deps-core 2.0.0

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

use crate::lsp_helpers::{
    EcosystemFormatter, LineOffsetTable, RequirementGate, RequirementStatus, VersionData,
    is_safe_version_string, literal_span_matches, requirement_is_oversized,
    requirement_len_exceeds_cap, resolve_in_use_version, slice_for_range, strip_whitespace,
    warn_rejected_value,
};
use crate::{ConcreteVersion, Dependency, ParseResult, VersionReq};

/// Whether `current` — or `dep`'s own literal version span — is an unexpanded placeholder.
///
/// Checks both `current` (the requirement text a caller is about to consider rewriting) and
/// [`Dependency::version_literal`] (when present) rather than `current` alone, folding
/// `deps-swift`'s literal-vs-synthesized-comparator distinction (a `from: "\(v)"` declaration's
/// `current` is a synthesized `">=\(v), <1.0.0"` comparator, while `version_literal` is the raw
/// `\(v)` interpolation actually embedded in the manifest) into one shared check instead of a
/// per-ecosystem `format_version_replacing_for` override having to re-derive it.
///
/// This is the gate every central edit-planning call site
/// ([`collect_update_candidates`], [`plan_verified_fix`],
/// `crate::lsp_helpers::code_actions`'s unsatisfiable-requirement fix builder and REFACTOR
/// "Update to X" loop) checks before ever calling [`replacement_text`] — see that function's
/// doc for why the two are split into a boolean gate and a text-producing step rather than one
/// combined call.
///
/// # Examples
///
/// ```
/// use deps_core::edit::requirement_is_placeholder_for;
/// use deps_core::lsp_helpers::{DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering, RequirementResolution, SourcePolicy};
/// use deps_core::{ConcreteVersion, Dependency, PackageName, VersionReq};
///
/// struct PlainFormatter;
/// impl PackageNaming for PlainFormatter {}
/// impl PackageRendering for PlainFormatter {
///     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 PlainFormatter {}
/// impl DiagnosticMessages for PlainFormatter {}
/// impl DiagnosticPolicy for PlainFormatter {}
/// impl SourcePolicy for PlainFormatter {}
/// impl OsvNaming for PlainFormatter {}
///
/// struct PlainDependency(PackageName);
/// impl Dependency for PlainDependency {
///     fn name(&self) -> &PackageName {
///         &self.0
///     }
///     fn name_range(&self) -> deps_core::position::Range {
///         deps_core::position::Range::default()
///     }
///     fn version_requirement(&self) -> Option<&VersionReq> {
///         None
///     }
///     fn version_range(&self) -> Option<deps_core::position::Range> {
///         None
///     }
///     fn source(&self) -> deps_core::parser::DependencySource {
///         deps_core::parser::DependencySource::Registry
///     }
///     fn as_any(&self) -> &dyn std::any::Any {
///         self
///     }
/// }
///
/// let dep = PlainDependency(PackageName::new("example"));
/// assert!(!requirement_is_placeholder_for(&PlainFormatter, &dep, "^1.2"));
/// assert!(requirement_is_placeholder_for(&PlainFormatter, &dep, "{{ version }}"));
/// ```
#[must_use]
pub fn requirement_is_placeholder_for(
    formatter: &dyn EcosystemFormatter,
    dep: &dyn Dependency,
    current: &str,
) -> bool {
    formatter.requirement_is_placeholder(&VersionReq::new(current))
        || dep
            .version_literal()
            .is_some_and(|literal| formatter.requirement_is_placeholder(&VersionReq::new(literal)))
}

/// The only production path that rewrites a manifest's version-requirement text.
///
/// `None` when [`requirement_is_placeholder_for`] says `current`/`dep`'s literal is an
/// unexpanded placeholder, else `Some(formatter.format_version_replacing_for(dep, version,
/// current))`.
///
/// Centralizing the placeholder gate here — rather than leaving it to each ecosystem's
/// [`PackageRendering::format_version_replacing`](crate::lsp_helpers::PackageRendering::format_version_replacing)/
/// [`format_version_replacing_for`](crate::lsp_helpers::PackageRendering::format_version_replacing_for)
/// override to re-check — means a formatter implementation can never destructively rewrite a
/// placeholder no matter how it is reached: the 14 previously hand-rolled per-crate guards
/// inside those methods are gone (#1391), and this free function is the sole call site that
/// still invokes them in production. Every central edit-planning call site
/// ([`collect_update_candidates`], [`plan_verified_fix`],
/// `crate::lsp_helpers::code_actions`'s unsatisfiable-requirement fix builder and REFACTOR
/// "Update to X" loop) already checks [`requirement_is_placeholder_for`] as an early gate for
/// its own control-flow reasons (skip vs. `Err`/`None`/`continue` differ per caller) before
/// ever reaching this call — that earlier check makes this function's own `None` branch
/// unreachable in practice, and is kept anyway as a fail-closed defense-in-depth backstop
/// rather than relied upon as the only gate.
///
/// # Examples
///
/// ```
/// use deps_core::edit::replacement_text;
/// use deps_core::lsp_helpers::{DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering, RequirementResolution, SourcePolicy};
/// use deps_core::{ConcreteVersion, Dependency, PackageName, VersionReq};
///
/// struct PlainFormatter;
/// impl PackageNaming for PlainFormatter {}
/// impl PackageRendering for PlainFormatter {
///     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 PlainFormatter {}
/// impl DiagnosticMessages for PlainFormatter {}
/// impl DiagnosticPolicy for PlainFormatter {}
/// impl SourcePolicy for PlainFormatter {}
/// impl OsvNaming for PlainFormatter {}
///
/// struct PlainDependency(PackageName);
/// impl Dependency for PlainDependency {
///     fn name(&self) -> &PackageName {
///         &self.0
///     }
///     fn name_range(&self) -> deps_core::position::Range {
///         deps_core::position::Range::default()
///     }
///     fn version_requirement(&self) -> Option<&VersionReq> {
///         None
///     }
///     fn version_range(&self) -> Option<deps_core::position::Range> {
///         None
///     }
///     fn source(&self) -> deps_core::parser::DependencySource {
///         deps_core::parser::DependencySource::Registry
///     }
///     fn as_any(&self) -> &dyn std::any::Any {
///         self
///     }
/// }
///
/// let dep = PlainDependency(PackageName::new("example"));
/// assert_eq!(
///     replacement_text(&PlainFormatter, &dep, &ConcreteVersion::new("1.2.3"), "^1.0"),
///     Some("1.2.3".to_string())
/// );
/// assert_eq!(
///     replacement_text(&PlainFormatter, &dep, &ConcreteVersion::new("1.2.3"), "{{ version }}"),
///     None
/// );
/// ```
#[must_use]
pub fn replacement_text(
    formatter: &dyn EcosystemFormatter,
    dep: &dyn Dependency,
    version: &ConcreteVersion,
    current: &str,
) -> Option<String> {
    if requirement_is_placeholder_for(formatter, dep, current) {
        return None;
    }
    Some(formatter.format_version_replacing_for(dep, version, current))
}

/// Protocol-agnostic replacement for `ls_types::TextEdit` — a single manifest-text
/// replacement.
///
/// # Examples
///
/// ```
/// use deps_core::edit::ManifestEdit;
/// use deps_core::position::{Position, Range};
///
/// let edit = ManifestEdit {
///     range: Range::new(Position::new(0, 9), Position::new(0, 14)),
///     new_text: "1.2.0".to_string(),
/// };
/// assert_eq!(edit.new_text, "1.2.0");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManifestEdit {
    /// The span in the manifest source this edit replaces.
    pub range: crate::position::Range,
    /// The replacement text.
    pub new_text: String,
}

/// A manifest-edit plan with attribution — what makes ignore-rule/`--package` filtering
/// possible. The `ls_types::TextEdit` this generalizes discards everything but the edit
/// itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlannedUpdate {
    /// The dependency's declared (raw) name.
    pub name: String,
    /// [`crate::lsp_helpers::PackageNaming::normalize_package_name`]'s output for `name`.
    pub normalized_name: String,
    /// The dependency name's span in the manifest source.
    pub name_range: crate::position::Range,
    /// The version this dependency is currently pinned to, when it could be resolved (see
    /// [`collect_update_edits`]'s doc for exactly how). `None` covers two distinct cases: a
    /// genuinely unresolvable in-use version (`collect_update_candidates`) — a caller that
    /// classifies it via [`classify_update`] gets [`UpdateKind::Unknown`] for this case, the
    /// same as for any other string [`classify_update`] can't parse as a leading dotted-numeric
    /// version — and [`plan_verified_fix`], which never attempts to resolve this field at all
    /// and always leaves it `None` regardless of whether the in-use version is knowable.
    pub current: Option<ConcreteVersion>,
    /// The version this edit would move the dependency to.
    pub target: ConcreteVersion,
    /// The edit itself.
    pub edit: ManifestEdit,
}

/// A type with a `[start, end)` span, generalizing over [`ManifestEdit`] (this crate) and
/// `ls_types::TextEdit` (the `lsp-responses`-gated impl in [`crate::lsp_helpers`]).
///
/// Implemented locally for a foreign type (`ls_types::TextEdit`) in the gated module —
/// orphan-rule-clean since this trait is local to this crate.
pub trait EditSpan {
    /// The span's inclusive start, as `(line, character)`.
    fn start(&self) -> (u32, u32);
    /// The span's exclusive end, as `(line, character)`.
    fn end(&self) -> (u32, u32);
}

impl EditSpan for ManifestEdit {
    fn start(&self) -> (u32, u32) {
        (self.range.start.line, self.range.start.character)
    }

    fn end(&self) -> (u32, u32) {
        (self.range.end.line, self.range.end.character)
    }
}

impl EditSpan for PlannedUpdate {
    fn start(&self) -> (u32, u32) {
        self.edit.start()
    }

    fn end(&self) -> (u32, u32) {
        self.edit.end()
    }
}

/// Sorts `edits` by start position and drops any edit that overlaps the previous one.
///
/// A dropped edit's start falls before the previous (surviving) edit's end — an overlap no
/// LSP `WorkspaceEdit`/manifest rewrite can apply safely. Generic replacement for the
/// type-specific `TextEdit` version this crate carried before #1329 — see [`EditSpan`]'s doc.
///
/// **Breaking**: this is a breaking `pub` API change on `deps-core` (the old signature only
/// accepted `Vec<ls_types::TextEdit>`) — see `CHANGELOG.md`'s `[Unreleased]` section.
///
/// `caller` names the collector in the `tracing::warn!` emitted for each dropped edit.
///
/// # Examples
///
/// ```
/// use deps_core::edit::{ManifestEdit, dedup_overlapping_edits};
/// use deps_core::position::{Position, Range};
///
/// let edits = vec![
///     ManifestEdit {
///         range: Range::new(Position::new(0, 0), Position::new(0, 5)),
///         new_text: "a".to_string(),
///     },
///     ManifestEdit {
///         range: Range::new(Position::new(0, 2), Position::new(0, 7)),
///         new_text: "b".to_string(),
///     },
/// ];
/// let kept = dedup_overlapping_edits(edits, "test");
/// assert_eq!(kept.len(), 1);
/// ```
pub fn dedup_overlapping_edits<E: EditSpan>(mut edits: Vec<E>, caller: &str) -> Vec<E> {
    edits.sort_by_key(EditSpan::start);

    let mut non_overlapping: Vec<E> = Vec::with_capacity(edits.len());
    for edit in edits {
        let overlaps_prev = non_overlapping
            .last()
            .is_some_and(|prev: &E| edit.start() < prev.end());
        if overlaps_prev {
            tracing::warn!(
                start = ?edit.start(),
                end = ?edit.end(),
                caller,
                "dropping overlapping edit"
            );
            continue;
        }
        non_overlapping.push(edit);
    }

    non_overlapping
}

/// Applies `edits` to `content`, returning the rewritten manifest text.
///
/// `edits` must be non-overlapping (see [`dedup_overlapping_edits`]) — this function does not
/// itself check for overlap, it splices every edit's range in reverse start-position order so
/// an earlier edit's byte offsets are never invalidated by a later one's length change. Each
/// edit's `range.start` must not come after its own `range.end` (an inverted range); an edit
/// violating this precondition is skipped rather than applied — every current parser
/// produces structurally ordered ranges, so this is a defense-in-depth guard against a
/// future parser bug, not an expected code path (this function is `pub` `deps-core` API
/// consumed in-process by `deps-cli`, unlike its pre-#1329 callers, which only ever handed
/// equivalent ranges back to an LSP client as `TextEdit`s for the editor to apply).
///
/// # Examples
///
/// ```
/// use deps_core::edit::{ManifestEdit, apply_edits};
/// use deps_core::position::{Position, Range};
///
/// let content = "serde = \"1.0.0\"\n";
/// let edits = vec![ManifestEdit {
///     range: Range::new(Position::new(0, 9), Position::new(0, 14)),
///     new_text: "1.2.0".to_string(),
/// }];
/// assert_eq!(apply_edits(content, &edits), "serde = \"1.2.0\"\n");
/// ```
#[must_use]
pub fn apply_edits(content: &str, edits: &[ManifestEdit]) -> String {
    let table = LineOffsetTable::new(content);
    let mut byte_edits: Vec<(usize, usize, &str)> = edits
        .iter()
        .filter_map(|edit| {
            let start = table.position_to_byte_offset(content, edit.range.start);
            let end = table.position_to_byte_offset(content, edit.range.end);
            if start > end {
                tracing::warn!(range = ?edit.range, "dropping edit with an inverted range");
                return None;
            }
            Some((start, end, edit.new_text.as_str()))
        })
        .collect();
    byte_edits.sort_by_key(|&(start, ..)| start);

    let mut result = content.to_string();
    for &(start, end, new_text) in byte_edits.iter().rev() {
        result.replace_range(start..end, new_text);
    }
    result
}

/// Re-parses manifest text, abstracting over the production path.
///
/// [`EcosystemReparse`]/[`crate::ecosystem::parse_manifest_now`] is the production impl, so
/// [`crate::lsp_helpers::fallback_edit_excludes_newer`] (spec 076 FR-024) can be unit-tested
/// with a stub instead of a real ecosystem parser.
///
/// FR-024's guard validates the manifest's EFFECTIVE post-edit requirement, not the replacement
/// span's own text in isolation — some grammars (Swift's `from:`/`.exact`/`.upToNextMinor`
/// labels, Bundler's multi-constraint literals) build the effective requirement from context
/// outside the edited span, so only re-parsing the whole edited document proves what the edit
/// actually expresses.
///
/// # Examples
///
/// ```
/// use deps_core::edit::ManifestReparse;
///
/// let reparse = |_content: &str| None;
/// assert!(reparse.reparse("anything").is_none());
/// ```
pub trait ManifestReparse {
    /// Re-parses `content` (an edited scratch copy of a manifest), or `None` if it could not be
    /// parsed (fail closed).
    fn reparse(&self, content: &str) -> Option<Box<dyn ParseResult>>;
}

/// Blanket impl so a test can pass a plain closure as a [`ManifestReparse`] instead of defining
/// a stub type.
impl<F: Fn(&str) -> Option<Box<dyn ParseResult>>> ManifestReparse for F {
    fn reparse(&self, content: &str) -> Option<Box<dyn ParseResult>> {
        self(content)
    }
}

/// Production [`ManifestReparse`]: re-parses via [`crate::ecosystem::parse_manifest_now`].
///
/// That is the synchronous, dependency-count-capped sibling of
/// [`crate::ecosystem::parse_manifest_blocking`] (spec 076 FR-024).
///
/// # Examples
///
/// ```
/// use deps_core::edit::{EcosystemReparse, ManifestReparse};
/// use deps_core::Ecosystem;
/// use url::Url;
///
/// # fn example(ecosystem: &dyn Ecosystem, uri: Url) {
/// let reparse = EcosystemReparse {
///     ecosystem,
///     uri: &uri,
/// };
/// let _ = reparse.reparse("content");
/// # }
/// ```
pub struct EcosystemReparse<'a> {
    /// The ecosystem to re-parse through.
    pub ecosystem: &'a dyn crate::Ecosystem,
    /// The manifest document's URI, for position tracking.
    pub uri: &'a url::Url,
}

impl ManifestReparse for EcosystemReparse<'_> {
    fn reparse(&self, content: &str) -> Option<Box<dyn ParseResult>> {
        crate::ecosystem::parse_manifest_now(self.ecosystem, content, self.uri)
    }
}

/// The magnitude of a version bump, per semver-shaped leading-numeric-segment comparison.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpdateKind {
    /// The leading numeric segment (major) differs.
    Major,
    /// Major is equal, minor differs.
    Minor,
    /// Major and minor are equal (only patch, or nothing, differs).
    Patch,
    /// `from`/`to` could not both be classified as a version with an unambiguous leading
    /// dotted-numeric segment (a SHA pin, a Go pseudo-version, a range/comparator string,
    /// `*`/`latest`/`workspace:*`, Gradle's `{strictly}!!{preferred}`, ...).
    Unknown,
}

/// Classifies the version bump from `from` to `to`.
///
/// Returns [`UpdateKind::Unknown`] unless **both** strings have an unambiguous leading
/// dotted-numeric segment (an optional `v`/`V` prefix, then one or more all-digit
/// dot-separated components, then either nothing or a `-`/`+` suffix) — deliberately not
/// built on [`crate::lsp_helpers::is_same_major_minor`], whose permissive `_ => true`
/// fallback arm is wrong for this purpose. A Go pseudo-version
/// (`v0.0.0-20210101000000-abcdef123456`) would otherwise parse as a plain leading version
/// (`0.0.0`) by accident, so it is rejected by an explicit shape check before the general
/// parse runs.
///
/// # Examples
///
/// ```
/// use deps_core::edit::{UpdateKind, classify_update};
///
/// assert_eq!(classify_update("1.2.3", "2.0.0"), UpdateKind::Major);
/// assert_eq!(classify_update("1.2.3", "1.3.0"), UpdateKind::Minor);
/// assert_eq!(classify_update("1.2.3", "1.2.4"), UpdateKind::Patch);
/// assert_eq!(classify_update("*", "1.0.0"), UpdateKind::Unknown);
/// assert_eq!(
///     classify_update("v0.0.0-20210101000000-abcdef123456", "v1.0.0"),
///     UpdateKind::Unknown
/// );
/// ```
#[must_use]
pub fn classify_update(from: &str, to: &str) -> UpdateKind {
    match (
        parse_leading_dotted_numeric(from),
        parse_leading_dotted_numeric(to),
    ) {
        (Some(f), Some(t)) => {
            if f.0 != t.0 {
                UpdateKind::Major
            } else if f.1 != t.1 {
                UpdateKind::Minor
            } else {
                UpdateKind::Patch
            }
        }
        _ => UpdateKind::Unknown,
    }
}

/// Whether `s` has the shape of a Go pseudo-version: an optional `v`/`V` prefix, then a
/// component ending in a hyphen-separated 14-digit timestamp and a 12-hex-digit commit hash
/// (`vX.Y.Z-yyyymmddhhmmss-abcdefabcdef`, or the pre-release-shaped
/// `vX.Y.Z-0.yyyymmddhhmmss-abcdefabcdef`, whose timestamp segment carries a `0.` prefix).
///
/// Checked before [`parse_leading_dotted_numeric`] runs its general parse, since a pseudo-
/// version's leading `vX.Y.Z` would otherwise parse as an ordinary version by accident.
fn is_go_pseudo_version(s: &str) -> bool {
    let body = s.strip_prefix(['v', 'V']).unwrap_or(s);
    let mut parts = body.rsplitn(3, '-');
    let Some(hash) = parts.next() else {
        return false;
    };
    let Some(timestamp) = parts.next() else {
        return false;
    };
    if parts.next().is_none() {
        return false;
    }
    let timestamp = timestamp.strip_prefix("0.").unwrap_or(timestamp);
    hash.len() == 12
        && hash.bytes().all(|b| b.is_ascii_hexdigit())
        && timestamp.len() == 14
        && timestamp.bytes().all(|b| b.is_ascii_digit())
}

/// Parses `s`'s leading `(major, minor, patch)` dotted-numeric segment, or `None` when `s` is
/// not unambiguously one (see [`classify_update`]'s doc). A component beyond the third is
/// still required to be all-digit (so a 4-component version like NuGet's assembly-version
/// style is accepted), but only the first three are returned.
fn parse_leading_dotted_numeric(s: &str) -> Option<(u64, u64, u64)> {
    if is_go_pseudo_version(s) {
        return None;
    }
    let stripped = s.strip_prefix(['v', 'V']).unwrap_or(s);
    let core = match stripped.find(['-', '+']) {
        Some(idx) => stripped.get(..idx)?,
        None => stripped,
    };
    if core.is_empty() {
        return None;
    }

    let mut major = 0u64;
    let mut minor = 0u64;
    let mut patch = 0u64;
    let mut count = 0usize;
    for part in core.split('.') {
        if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        let n: u64 = part.parse().ok()?;
        match count {
            0 => major = n,
            1 => minor = n,
            2 => patch = n,
            _ => {}
        }
        count += 1;
    }
    if count == 0 {
        return None;
    }
    Some((major, minor, patch))
}

/// Default-mode planner: every dependency [`RequirementStatus::Outdated`] would report, as a
/// [`PlannedUpdate`].
///
/// Verbatim move of the logic `lsp_helpers::code_lenses::collect_update_all_edits` used to
/// implement directly (moved here for #1329/spec 068's `deps_core::edit` extraction; that
/// function is now a thin adapter over this one — see this crate's `lib.rs` "LSP type
/// stability" doc section) — the literal-span guard, the `is_safe_version_string` check, the
/// `requirement_status_for == Outdated` filter, the no-op guard, and overlap dedup are
/// unchanged. See that function's historical doc (preserved in git history) for the full
/// per-guard rationale.
///
/// [`PlannedUpdate::current`] is the dependency's resolved in-use version
/// ([`resolve_in_use_version`], **per occurrence**, never the collapsed per-name map — spec
/// 050's fix), when `versions` carries an [`crate::EcosystemId`]
/// ([`VersionData::with_ecosystem`]) and resolution succeeds; empty otherwise, which
/// [`classify_update`] always reports as [`UpdateKind::Unknown`] against any target.
///
/// # Examples
///
/// ```
/// use deps_core::edit::collect_update_edits;
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     PackageVersions, RequirementResolution, SourcePolicy, VersionData,
/// };
/// use deps_core::{ConcreteVersion, Dependency, ParseResult, PackageName, VersionReq};
/// use std::any::Any;
/// use std::collections::HashMap;
/// use deps_core::position::{Position, Range};
///
/// struct MockFormatter;
/// impl PackageNaming for MockFormatter {}
/// impl PackageRendering for MockFormatter {
///     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 MockFormatter {}
/// impl DiagnosticMessages for MockFormatter {}
/// impl DiagnosticPolicy for MockFormatter {}
/// impl SourcePolicy for MockFormatter {}
/// impl OsvNaming for MockFormatter {}
///
/// struct MockDep {
///     name: PackageName,
///     version_req: VersionReq,
///     version_range: Range,
///     name_range: Range,
/// }
/// impl Dependency for MockDep {
///     fn name(&self) -> &PackageName { &self.name }
///     fn name_range(&self) -> Range { self.name_range }
///     fn version_requirement(&self) -> Option<&VersionReq> { Some(&self.version_req) }
///     fn version_range(&self) -> Option<Range> { Some(self.version_range) }
///     fn source(&self) -> deps_core::parser::DependencySource {
///         deps_core::parser::DependencySource::Registry
///     }
///     fn as_any(&self) -> &dyn Any { self }
/// }
///
/// struct MockParseResult { deps: Vec<MockDep>, uri: url::Url }
/// impl 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 { &self.uri }
///     fn as_any(&self) -> &dyn Any { self }
/// }
///
/// let content = r#"serde = "1.0.0""#;
/// let parse_result = MockParseResult {
///     deps: vec![MockDep {
///         name: PackageName::new("serde"),
///         version_req: VersionReq::new("1.0.0"),
///         version_range: Range::new(Position::new(0, 9), Position::new(0, 14)),
///         name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
///     }],
///     uri: deps_core::test_util::test_uri("/test/Cargo.toml"),
/// };
///
/// let mut cached = HashMap::new();
/// cached.insert("serde".into(), PackageVersions::latest_only("1.2.0"));
/// let resolved = HashMap::new();
///
/// let planned = collect_update_edits(
///     &parse_result,
///     content,
///     VersionData::new(&cached, &resolved),
///     &MockFormatter,
/// );
///
/// assert_eq!(planned.len(), 1);
/// assert_eq!(planned[0].edit.new_text, "1.2.0");
/// assert_eq!(planned[0].name, "serde");
/// ```
#[must_use]
pub fn collect_update_edits(
    parse_result: &dyn ParseResult,
    content: &str,
    versions: VersionData<'_>,
    formatter: &dyn EcosystemFormatter,
) -> Vec<PlannedUpdate> {
    let planned: Vec<PlannedUpdate> =
        collect_update_candidates(parse_result, content, versions, formatter)
            .into_iter()
            .filter_map(|candidate| match candidate {
                UpdateCandidate::Planned(planned) => Some(planned),
                UpdateCandidate::Unplannable { .. } => None,
            })
            .collect();

    dedup_overlapping_edits(planned, "collect_update_edits")
}

/// Why a dependency [`crate::lsp_helpers::RequirementStatus::Outdated`] could not become a
/// writable [`PlannedUpdate`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnplannableReason {
    /// The registry's cached `latest` value failed the [`is_safe_version_string`] gate.
    UnsafeLatestVersion,
    /// The declared span does not hold the literal requirement text — a Maven
    /// `${property}` reference, a Gradle DSL variable/version-catalog alias, or similar.
    NonLiteralSpan,
    /// The formatter's rewrite would be a no-op (no single unambiguous rewrite exists, e.g.
    /// `deps-gradle`'s `{strictly}!!{preferred}` shorthand).
    NoOpRewrite,
    /// Issue #1517: OSV checked this exact `latest` version and found it affected by a
    /// non-informational advisory (or a confirmed-malicious record) —
    /// [`crate::lsp_helpers::LatestVerdict::Flagged`]. Writing this version into the manifest
    /// would be the exact supply-chain exposure this variant exists to prevent; the shared
    /// planner this variant lives in ([`collect_update_candidates`]) is used by both the LSP
    /// code lens and `deps-cli update`'s default mode, so both refuse it identically.
    LatestFlaggedByOsv,
    /// Issue #1517: `latest`'s OSV status could not be verified —
    /// [`crate::lsp_helpers::LatestVerdict::Unverified`] (never checked, a transient
    /// failure/timeout, or the checked version has since diverged from what's now cached as
    /// `latest`). Fails closed the same way [`Self::LatestFlaggedByOsv`] does: an unverified
    /// version is never distinguishable from a flagged one at write time, so neither is ever
    /// planned.
    LatestUnverified,
}

/// One [`crate::lsp_helpers::RequirementStatus::Outdated`] dependency's planning outcome.
#[derive(Debug, Clone)]
pub enum UpdateCandidate {
    /// A safe edit was planned.
    Planned(PlannedUpdate),
    /// The dependency is `Outdated` but no edit could be safely produced — callers that
    /// report per-dependency outcomes (`deps-cli update`) must surface this rather than
    /// silently dropping the dependency; [`collect_update_edits`] (the LSP-facing planner,
    /// which only needs the writable subset) drops it instead.
    Unplannable {
        /// The dependency's declared (raw) name.
        name: String,
        /// [`crate::lsp_helpers::PackageNaming::normalize_package_name`]'s output for `name`.
        normalized_name: String,
        /// The dependency name's span in the manifest source.
        name_range: crate::position::Range,
        /// Why no edit could be planned.
        reason: UnplannableReason,
    },
}

/// Every [`crate::lsp_helpers::RequirementStatus::Outdated`] dependency, classified into
/// [`UpdateCandidate::Planned`] or [`UpdateCandidate::Unplannable`].
///
/// [`collect_update_edits`] is a thin filter over this function (only the `Planned` subset,
/// deduped) — this is the richer form `deps-cli update`'s default-mode planner consumes so an
/// `Unplannable` dependency can be reported to the operator instead of vanishing from the
/// plan with no signal (spec 068 S4).
///
/// A dependency that never reaches `Outdated` status at all (no `version_range`, unknown to
/// the registry, no declared requirement, an empty requirement, or genuinely up to date) is
/// not a candidate and produces no entry here — reporting those would be noise, not signal
/// (most manifest dependencies are exactly this case on any given run). An unexpanded
/// placeholder ([`crate::lsp_helpers::RequirementResolution::bounded_requirement_is_placeholder`],
/// #1370) is checked and skipped the same way, independent of whatever status an ecosystem's
/// own classification logic reports for it — this is one of the four central edit-planning
/// gates that predicate consults.
#[must_use]
pub fn collect_update_candidates(
    parse_result: &dyn ParseResult,
    content: &str,
    versions: VersionData<'_>,
    formatter: &dyn EcosystemFormatter,
) -> Vec<UpdateCandidate> {
    let deps = parse_result.dependencies();
    let mut candidates: Vec<UpdateCandidate> = Vec::with_capacity(deps.len());
    // Built once and reused for every dependency below (matches the pre-extraction
    // `collect_update_all_edits`'s own rationale for doing so).
    let line_offsets = LineOffsetTable::new(content);
    // Issue #1517: shared by both the LSP code lens (`collect_update_edits`) and `deps-cli
    // update`'s default mode planner — the single gate neither can bypass.
    let vuln_keys = versions.ecosystem.map(|ecosystem| {
        crate::osv::vulnerability_keys(
            parse_result,
            versions.resolved,
            versions.resolved_version_candidates,
            formatter,
            ecosystem,
        )
    });

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

        let normalized_name = formatter.normalize_package_name(dep.name());
        let Some(latest) = versions
            .cached
            .get(normalized_name.as_str())
            .or_else(|| versions.cached.get(dep.name()))
            .map(|v| &v.latest)
        else {
            continue;
        };

        let Some(version_req) = dep.version_requirement() else {
            continue;
        };
        if version_req.as_str().is_empty() {
            // Defense-in-depth: an empty requirement would trivially satisfy the literal-span
            // guard below (both sides normalize to "") and could anchor an edit on a
            // non-literal span.
            continue;
        }
        // #1370: central placeholder gate, checked independently of `requirement_status_for`'s
        // own classification — a placeholder is never a rewrite candidate regardless of what
        // status an ecosystem's own (possibly still-buggy) classification logic reports for it,
        // the same defense-in-depth reasoning as the other three central edit-planning gates.
        if requirement_is_placeholder_for(formatter, dep, version_req.as_str()) {
            continue;
        }
        if formatter.requirement_status_for(dep, version_req, latest) != RequirementStatus::Outdated
        {
            continue;
        }

        // From here, `dep` is a confirmed `Outdated` candidate — every remaining guard below
        // must surface as `UpdateCandidate::Unplannable`, not a silent `continue`.
        let name = dep.name().as_str().to_string();
        let name_range = dep.name_range();

        if !is_safe_version_string(latest.as_str()) {
            warn_rejected_value(
                "is_safe_version_string",
                "update edit plan",
                latest.as_str(),
            );
            candidates.push(UpdateCandidate::Unplannable {
                name,
                normalized_name,
                name_range,
                reason: UnplannableReason::UnsafeLatestVersion,
            });
            continue;
        }

        // Issue #1517: never plan an edit that writes a flagged/unverified `latest` into the
        // manifest — the exact live-exploitable gap this issue closes (`deps-cli update`'s
        // default mode previously wrote a known-malicious version straight into the manifest).
        // Checked before the literal-span/no-op guards below: those are about *whether* an
        // edit can be produced at all, this is about whether the edit's *target* is safe to
        // write, and the latter must never be skipped just because the former also failed.
        match crate::lsp_helpers::latest_verdict(
            versions.latest_status,
            dep,
            vuln_keys.as_ref(),
            &normalized_name,
            latest.as_str(),
            formatter,
        ) {
            crate::lsp_helpers::LatestVerdict::Verified
            | crate::lsp_helpers::LatestVerdict::NotApplicable => {}
            crate::lsp_helpers::LatestVerdict::Flagged { .. } => {
                candidates.push(UpdateCandidate::Unplannable {
                    name,
                    normalized_name,
                    name_range,
                    reason: UnplannableReason::LatestFlaggedByOsv,
                });
                continue;
            }
            crate::lsp_helpers::LatestVerdict::Unverified => {
                candidates.push(UpdateCandidate::Unplannable {
                    name,
                    normalized_name,
                    name_range,
                    reason: UnplannableReason::LatestUnverified,
                });
                continue;
            }
        }

        // Intentionally not calling `dependency_version_range_is_literal` (#919) —
        // empty-requirement semantics differ (edit: nothing to update; completion: everything
        // to offer).
        let slice = slice_for_range(content, &line_offsets, version_range);
        let literal_target = dep
            .version_literal()
            .unwrap_or_else(|| version_req.as_str());
        if !literal_span_matches(slice, literal_target) {
            candidates.push(UpdateCandidate::Unplannable {
                name,
                normalized_name,
                name_range,
                reason: UnplannableReason::NonLiteralSpan,
            });
            continue;
        }

        // Unreachable after the gate above; fails closed rather than unwrapping.
        let Some(new_text) = replacement_text(formatter, dep, latest, version_req.as_str()) else {
            continue;
        };
        if strip_whitespace(&new_text) == strip_whitespace(literal_target) {
            candidates.push(UpdateCandidate::Unplannable {
                name,
                normalized_name,
                name_range,
                reason: UnplannableReason::NoOpRewrite,
            });
            continue;
        }

        // FR-003: per occurrence, never the collapsed per-name map — a renamed/aliased
        // dependency (spec 050) must classify against its own resolved pin. `None` here means
        // genuinely unresolvable (not, as for `plan_verified_fix`, simply never attempted) — a
        // caller that classifies this field via `classify_update` gets `UpdateKind::Unknown`
        // for it, since there is no version string to pass in.
        let current = versions.ecosystem.and_then(|ecosystem| {
            resolve_in_use_version(
                dep,
                &normalized_name,
                versions.resolved,
                versions.resolved_version_candidates,
                formatter,
                ecosystem,
            )
        });

        candidates.push(UpdateCandidate::Planned(PlannedUpdate {
            name,
            normalized_name,
            name_range,
            current,
            target: latest.clone(),
            edit: ManifestEdit {
                range: version_range,
                new_text,
            },
        }));
    }

    candidates
}

/// Why [`plan_vulnerability_fix`] could not produce a [`PlannedUpdate`] for a dependency
/// already known to be [`crate::osv::ScanOutcome::Vulnerable`].
///
/// Mirrors [`UnplannableReason`]'s role for the default-mode planner (spec 068's typed-skip
/// convention) — before this type existed, every one of these six causes collapsed into a
/// single `None`, forcing `deps-cli update --security-only`'s
/// `classify_vulnerable_dependency` to re-run [`resolve_recommended_fix`]'s and
/// `fix_target_is_verified`'s own chain itself just to tell `NoVerifiedFix` apart from
/// `RequiresLockfileUpdate` (#1350).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VulnFixSkip {
    /// No advisory on `dv` has a claimable fix — [`crate::osv::DependencyVulnerabilities::recommended_fix`]
    /// returned `None`.
    NoRecommendedFix,
    /// The recommended fix's version, converted to this ecosystem's native namespace, failed
    /// [`is_safe_version_string`].
    UnsafeVersion,
    /// The internal fix-target verification gate could not confirm the fix target F against
    /// OSV — F was never live-checked, or the live check found F still vulnerable to an
    /// advisory this recommendation claims to resolve.
    UnverifiedTarget,
    /// The dependency's declared requirement, left unedited, already resolves forward to the
    /// fix target under this ecosystem's own resolution rules — nothing to rewrite (#1344).
    RequirementAlreadyResolves,
    /// The formatter's rewrite would be textually identical to the declared literal — no edit
    /// to make.
    NoOpRewrite,
    /// `current` is an unexpanded placeholder/interpolation
    /// ([`crate::lsp_helpers::RequirementResolution::bounded_requirement_is_placeholder`]) — there is
    /// no concrete version text to replace, so the requirement is never rewritten regardless
    /// of what any other resolution predicate or the formatter's own rewrite logic would do
    /// with it (#1370).
    UnresolvedPlaceholder,
    /// `current`, the dependency's requirement, or its version literal exceeds
    /// [`crate::lsp_helpers::MAX_REQUIREMENT_LEN`] — unmodellable text is never rewritten,
    /// fail-closed and distinct from a placeholder so a caller can report the size cause.
    OversizedRequirement,
}

/// Resolves and validates the OSV-recommended fix for `dv`.
///
/// The common prefix every vulnerability-fix caller needs before it can decide what to do
/// next: is there a fix, and is its version string safe to act on. Shared by
/// [`plan_vulnerability_fix`] and `deps-engine`'s phase-B fix-target verification
/// (`classify::osv::resolve_fix_target`), which independently ran the same two steps before
/// this was extracted (#1350).
///
/// # Errors
///
/// Returns [`VulnFixSkip::NoRecommendedFix`] when `dv.recommended_fix(latest)` is `None`, or
/// [`VulnFixSkip::UnsafeVersion`] when the fix's version fails [`is_safe_version_string`].
///
/// # Arguments
///
/// * `latest` - This dependency's entry in the shared [`crate::osv::LatestStatusMap`] (issue
///   #1517), forwarded verbatim to [`crate::osv::DependencyVulnerabilities::recommended_fix`] —
///   see that method's doc for its effect.
///
/// # Examples
///
/// ```
/// use deps_core::edit::{VulnFixSkip, resolve_recommended_fix};
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy,
/// };
/// use deps_core::osv::{Advisory, Capped, DependencyVulnerabilities, VulnSeverity};
/// use deps_core::{ConcreteVersion, PackageName};
/// use std::sync::Arc;
///
/// struct MockFormatter;
/// impl PackageNaming for MockFormatter {}
/// impl PackageRendering for MockFormatter {
///     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 MockFormatter {}
/// impl DiagnosticMessages for MockFormatter {}
/// impl DiagnosticPolicy for MockFormatter {}
/// impl SourcePolicy for MockFormatter {}
/// impl OsvNaming for MockFormatter {}
///
/// let dv = DependencyVulnerabilities::new(Capped::new(Vec::<Arc<Advisory>>::new(), 0));
/// assert_eq!(
///     resolve_recommended_fix(&dv, None, &MockFormatter),
///     Err(VulnFixSkip::NoRecommendedFix)
/// );
/// ```
pub fn resolve_recommended_fix(
    dv: &crate::osv::DependencyVulnerabilities,
    latest: Option<&crate::osv::UpgradeStatus>,
    formatter: &dyn EcosystemFormatter,
) -> Result<(crate::osv::FixRecommendation, String), VulnFixSkip> {
    let fix = dv
        .recommended_fix(latest)
        .ok_or(VulnFixSkip::NoRecommendedFix)?;
    let version_native = formatter.osv_version_to_native(&fix.version).into_string();
    if !is_safe_version_string(&version_native) {
        warn_rejected_value(
            "is_safe_version_string",
            "vulnerability fix plan",
            &version_native,
        );
        return Err(VulnFixSkip::UnsafeVersion);
    }
    Ok((fix, version_native))
}

/// Whether `dv.fix_target_status` clears `fix`'s target version as an honest, presentable fix
/// (#462 FR-003) — verbatim move of `lsp_helpers::code_actions`'s private helper of the same
/// name and doc.
///
/// `CandidateClean { version: F }` always clears it. A `CandidateVulnerable { version: F,
/// advisory_ids }` result can also clear it — F may legitimately still be affected by
/// advisories `recommended_fix()` never claimed to resolve in the first place — but is
/// suppressed the moment `advisory_ids` names either a *claimed* advisory or one this
/// dependency's own `advisories` never recorded at all. Any other state means F was never
/// actually verified, so it is rejected too. `known_ids` is built from `dv.advisories`, the
/// fix-computation set capped at [`crate::osv::MAX_ADVISORY_RECORDS`] — not the smaller,
/// render-only [`crate::osv::DependencyVulnerabilities::advisories_for_display`] — so this gate
/// sees the same advisory set `recommended_fix()` itself claimed against (#1422).
///
/// `pub(crate)`: `deps-cli update --security-only` (#1329) used to call this directly to
/// distinguish "no verified fix target" from [`plan_vulnerability_fix`]'s other `None` cause,
/// but now matches on [`VulnFixSkip`] directly (#1350), so this no longer needs to be `pub`.
#[must_use]
pub(crate) fn fix_target_is_verified(
    dv: &crate::osv::DependencyVulnerabilities,
    fix: &crate::osv::FixRecommendation,
    version_native: &str,
) -> bool {
    use crate::osv::UpgradeStatus;
    use std::collections::HashSet;

    match &dv.fix_target_status {
        UpgradeStatus::CandidateClean { version } => version == version_native,
        UpgradeStatus::CandidateVulnerable {
            version,
            advisory_ids,
            ..
        } => {
            if version != version_native || !advisory_ids.is_complete() {
                return false;
            }
            let known_ids: HashSet<&str> = dv
                .advisories
                .items()
                .iter()
                .map(|a| a.id.as_str())
                .collect();
            advisory_ids
                .items()
                .iter()
                .all(|id| known_ids.contains(id.as_str()) && !fix.advisory_ids.contains(id))
        }
        UpgradeStatus::NotChecked
        | UpgradeStatus::CandidateUnverified { .. }
        | UpgradeStatus::StructurallyUnchecked(_) => false,
    }
}

/// [`resolve_recommended_fix`] plus the internal `fix_target_is_verified` gate — resolves the
/// OSV-recommended fix for `dv` AND confirms its target version's own OSV status.
///
/// Callers that need to know "is there a *usable* fix" (not just "is there *a* fix") call
/// this instead of [`resolve_recommended_fix`] alone — see [`plan_vulnerability_fix`] and
/// `deps-cli`'s `classify_vulnerable_dependency` (#1350 S1 regression fix: that caller must
/// run this check *before* any other requirement/range/yanked-status decision, exactly as it
/// did when it held its own copy of the `fix_target_is_verified` call, or an unverified fix
/// target gets misreported as `RequiresLockfileUpdate`/`Unfixable(Yanked)` instead of
/// `Unfixable(NoVerifiedFix)`).
///
/// `deps-engine`'s phase-B fix-target verification (`classify::osv::resolve_fix_target`) is
/// the producer of `dv.fix_target_status` in the first place, so it calls
/// [`resolve_recommended_fix`] directly instead of this function — gating on a status it has
/// not computed yet would be circular.
///
/// # Errors
///
/// Returns anything [`resolve_recommended_fix`] can return, plus
/// [`VulnFixSkip::UnverifiedTarget`] when the internal `fix_target_is_verified` gate rejects
/// the fix target.
///
/// # Examples
///
/// ```
/// use deps_core::edit::{VulnFixSkip, resolve_verified_fix};
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy,
/// };
/// use deps_core::osv::{
///     Advisory, Capped, DependencyVulnerabilities, OsvVersion, UpgradeStatus, VulnSeverity,
/// };
/// use deps_core::{ConcreteVersion, PackageName};
/// use std::sync::Arc;
///
/// struct MockFormatter;
/// impl PackageNaming for MockFormatter {}
/// impl PackageRendering for MockFormatter {
///     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 MockFormatter {}
/// impl DiagnosticMessages for MockFormatter {}
/// impl DiagnosticPolicy for MockFormatter {}
/// impl SourcePolicy for MockFormatter {}
/// impl OsvNaming for MockFormatter {}
///
/// 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")]),
/// );
/// // `fix_target_status` left at its `NotChecked` default — never live-checked yet.
/// let unverified = DependencyVulnerabilities::new(Capped::new(vec![advisory.clone()], 1));
/// assert_eq!(
///     resolve_verified_fix(&unverified, None, &MockFormatter),
///     Err(VulnFixSkip::UnverifiedTarget)
/// );
///
/// let verified = DependencyVulnerabilities::new(Capped::new(vec![advisory], 1))
///     .with_fix_target_status(UpgradeStatus::CandidateClean { version: ConcreteVersion::new("1.2.0") });
/// assert!(resolve_verified_fix(&verified, None, &MockFormatter).is_ok());
/// ```
pub fn resolve_verified_fix(
    dv: &crate::osv::DependencyVulnerabilities,
    latest: Option<&crate::osv::UpgradeStatus>,
    formatter: &dyn EcosystemFormatter,
) -> Result<(crate::osv::FixRecommendation, String), VulnFixSkip> {
    let (fix, version_native) = resolve_recommended_fix(dv, latest, formatter)?;
    if !fix_target_is_verified(dv, &fix, &version_native) {
        return Err(VulnFixSkip::UnverifiedTarget);
    }
    Ok((fix, version_native))
}

/// Security-mode planner: plans the vulnerability-fix edit for one dependency.
///
/// The dependency must already be known to be [`crate::osv::ScanOutcome::Vulnerable`]; this
/// targets [`crate::osv::DependencyVulnerabilities::recommended_fix`] rather than `latest`.
///
/// Originally a verbatim move of `lsp_helpers::code_actions::build_vulnerability_fix_action`'s
/// planning core (the no-op guard, `is_safe_version_string`, `osv_version_to_native`,
/// `format_version_replacing_for`, and the `fix_target_is_verified` gate) — yank/timeout
/// filtering is deliberately **not** moved: both `deps-lsp` and `deps-cli` apply their own
/// source and policy for that (see `lsp_helpers::code_actions::generate_code_actions`'s
/// yank-filtering block and `deps-cli`'s `update::security` module).
///
/// #1344: also gated on whether `dep`'s own declared requirement, left unedited, already
/// *resolves forward* to the fix target under this ecosystem's own resolution rules
/// (`formatter.requirement_already_resolves_to(..)`) — not just the textual no-op guard below
/// (which only catches the declared literal already *spelling* the fix version verbatim).
/// `serde = "1"` with fix `1.0.2` must not be rewritten to `serde = "1.0.2"`: the declared
/// range already accepts `1.0.2`, so re-resolving already gets there without a manifest edit
/// (a `cargo update`/lock-file refresh, for an ecosystem that has one — not every ecosystem
/// does: Maven and Gradle have none, and a NuGet project's is opt-in. For those, suppression
/// is instead because the requirement already structurally expresses the fix — e.g. a Maven
/// dynamic range/`LATEST`/`SNAPSHOT` resolves it at build time — not because of any lock
/// file). `bounded_requirement_already_resolves_to`'s default asks only "is the fix a member of the
/// requirement's accepted set", correct for a requirement a resolver picks its *newest*
/// admissible member from, but wrong for one a resolver instead pins to its *lowest*
/// admissible member (NuGet's bare `Version="1.0.0"` floor, #1344) — ecosystems with that
/// resolution shape override the method rather than relying on the default; see
/// `deps-nuget`'s override. Ecosystems with no `compile_bounded_requirement` override (GitHub Actions,
/// GitLab CI — SHA/tag pins, not version ranges) fall through to the textual no-op guard as
/// the only available signal. Originally only checked by `deps-cli update --security-only`'s
/// `classify_vulnerable_dependency` (#1329); moved here so `deps-lsp`'s vulnerability-fix code
/// action shares the same decision instead of reimplementing it.
///
/// `dv` and `current` are supplied by the caller rather than resolved internally — the
/// pre-extraction function rebuilt `crate::osv::vulnerability_keys` per call, tolerable for
/// one position-driven LSP request but O(n²) for a planner iterating every dependency in a
/// manifest; both call sites now build that map once and look up each dependency's key
/// themselves.
///
/// # Examples
///
/// ```
/// use deps_core::edit::plan_vulnerability_fix;
/// use deps_core::lsp_helpers::{
///     DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
///     RequirementResolution, SourcePolicy,
/// };
/// use deps_core::osv::{
///     Advisory, Capped, DependencyVulnerabilities, OsvVersion, UpgradeStatus, VulnSeverity,
/// };
/// use deps_core::{ConcreteVersion, Dependency, PackageName, VersionReq};
/// use deps_core::position::{Position, Range};
/// use std::any::Any;
/// use std::sync::Arc;
///
/// struct MockFormatter;
/// impl PackageNaming for MockFormatter {}
/// impl PackageRendering for MockFormatter {
///     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 MockFormatter {}
/// impl DiagnosticMessages for MockFormatter {}
/// impl DiagnosticPolicy for MockFormatter {}
/// impl SourcePolicy for MockFormatter {}
/// impl OsvNaming for MockFormatter {}
///
/// struct MockDep {
///     name: PackageName,
///     version_req: VersionReq,
///     version_range: Range,
///     name_range: Range,
/// }
/// impl Dependency for MockDep {
///     fn name(&self) -> &PackageName { &self.name }
///     fn name_range(&self) -> Range { self.name_range }
///     fn version_requirement(&self) -> Option<&VersionReq> { Some(&self.version_req) }
///     fn version_range(&self) -> Option<Range> { Some(self.version_range) }
///     fn source(&self) -> deps_core::parser::DependencySource {
///         deps_core::parser::DependencySource::Registry
///     }
///     fn as_any(&self) -> &dyn Any { self }
/// }
///
/// let dep = MockDep {
///     name: PackageName::new("serde"),
///     version_req: VersionReq::new("1.0.0"),
///     version_range: Range::new(Position::new(0, 9), Position::new(0, 14)),
///     name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
/// };
///
/// 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 dv = DependencyVulnerabilities::new(Capped::new(vec![advisory], 1))
///     .with_fix_target_status(UpgradeStatus::CandidateClean { version: ConcreteVersion::new("1.2.0") });
///
/// let planned =
///     plan_vulnerability_fix(&dep, dep.version_range, "1.0.0", &dv, None, &MockFormatter);
/// assert_eq!(planned.unwrap().edit.new_text, "1.2.0");
/// ```
///
/// # Errors
///
/// Returns [`VulnFixSkip`] for any of the six causes that make an edit impossible or
/// unnecessary — see that type's variants.
pub fn plan_vulnerability_fix(
    dep: &dyn Dependency,
    version_range: crate::position::Range,
    current: &str,
    dv: &crate::osv::DependencyVulnerabilities,
    latest: Option<&crate::osv::UpgradeStatus>,
    formatter: &dyn EcosystemFormatter,
) -> Result<PlannedUpdate, VulnFixSkip> {
    let (_fix, version_native) = resolve_verified_fix(dv, latest, formatter)?;
    plan_verified_fix(dep, version_range, current, &version_native, formatter)
}

/// The remainder of [`plan_vulnerability_fix`]'s decision, for a fix target already resolved
/// and verified via [`resolve_verified_fix`].
///
/// Split out for a caller that already holds `version_native` because it needed it for its
/// own decision (e.g. a yank check) before ever reaching this point —
/// [`plan_vulnerability_fix`] itself calls [`resolve_verified_fix`] internally, so calling
/// that first and then [`plan_vulnerability_fix`] would run the same resolve-and-verify chain
/// twice per dependency (code review finding, #1350). `deps-cli`'s
/// `classify_vulnerable_dependency` is this function's only caller outside
/// [`plan_vulnerability_fix`] itself.
///
/// # Errors
///
/// Returns [`VulnFixSkip::OversizedRequirement`], [`VulnFixSkip::UnresolvedPlaceholder`],
/// [`VulnFixSkip::RequirementAlreadyResolves`], or [`VulnFixSkip::NoOpRewrite`] — the causes
/// that can still make an edit unnecessary once the fix is already known resolved and verified.
pub fn plan_verified_fix(
    dep: &dyn Dependency,
    version_range: crate::position::Range,
    current: &str,
    version_native: &str,
    formatter: &dyn EcosystemFormatter,
) -> Result<PlannedUpdate, VulnFixSkip> {
    // Checked before the placeholder gate: that gate reports oversized text as a placeholder,
    // which would misattribute a size-based skip to `UnresolvedPlaceholder`.
    if requirement_len_exceeds_cap(current)
        || dep
            .version_requirement()
            .is_some_and(requirement_is_oversized)
        || dep
            .version_literal()
            .is_some_and(requirement_len_exceeds_cap)
    {
        return Err(VulnFixSkip::OversizedRequirement);
    }

    // #1370: central placeholder gate, checked first — an unexpanded placeholder has no
    // concrete version text to replace, independent of whether `bounded_requirement_already_resolves_to`
    // or the formatter's own rewrite logic would coincidentally treat it as safe. Checked
    // against `current` (the exact text a caller is about to consider rewriting), not
    // `dep.version_requirement()`, since a caller may reach this with `current` derived from
    // somewhere other than the dependency's own preserved requirement field.
    if requirement_is_placeholder_for(formatter, dep, current) {
        return Err(VulnFixSkip::UnresolvedPlaceholder);
    }

    let fix_concrete = ConcreteVersion::new(version_native);
    let requirement_already_resolves_to_fix =
        dep.version_requirement().is_some_and(|version_req| {
            formatter.requirement_already_resolves_to(version_req, &fix_concrete)
        });
    if requirement_already_resolves_to_fix {
        return Err(VulnFixSkip::RequirementAlreadyResolves);
    }

    // Unreachable after the gate above; fails closed rather than unwrapping.
    let Some(new_text) = replacement_text(formatter, dep, &fix_concrete, current) else {
        return Err(VulnFixSkip::UnresolvedPlaceholder);
    };
    let literal_target = dep.version_literal().unwrap_or(current);
    if strip_whitespace(literal_target) == strip_whitespace(&new_text) {
        return Err(VulnFixSkip::NoOpRewrite);
    }

    let normalized_name = formatter.normalize_package_name(dep.name());
    Ok(PlannedUpdate {
        name: dep.name().as_str().to_string(),
        normalized_name,
        name_range: dep.name_range(),
        // `current` here is the requirement text passed in for placeholder/no-op checks
        // above, not a resolved pinned version — `PlannedUpdate::current` documents only the
        // latter, so this caller has none to report.
        current: None,
        target: ConcreteVersion::new(version_native),
        edit: ManifestEdit {
            range: version_range,
            new_text,
        },
    })
}

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

    fn range(sl: u32, sc: u32, el: u32, ec: u32) -> crate::position::Range {
        crate::position::Range::new(Position::new(sl, sc), Position::new(el, ec))
    }

    // --- classify_update / UpdateKind ---

    #[test]
    fn test_classify_update_major() {
        assert_eq!(classify_update("1.2.3", "2.0.0"), UpdateKind::Major);
    }

    #[test]
    fn test_classify_update_minor() {
        assert_eq!(classify_update("1.2.3", "1.3.0"), UpdateKind::Minor);
    }

    #[test]
    fn test_classify_update_patch() {
        assert_eq!(classify_update("1.2.3", "1.2.4"), UpdateKind::Patch);
    }

    #[test]
    fn test_classify_update_v_prefix() {
        assert_eq!(classify_update("v1.2.3", "v2.0.0"), UpdateKind::Major);
    }

    #[test]
    fn test_classify_update_prerelease_and_build_suffix_ignored() {
        assert_eq!(
            classify_update("1.2.3-alpha.1", "1.2.3+build.5"),
            UpdateKind::Patch
        );
    }

    #[test]
    fn test_classify_update_github_actions_sha_pin_is_unknown() {
        assert_eq!(
            classify_update(
                "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
                "b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3"
            ),
            UpdateKind::Unknown
        );
    }

    #[test]
    fn test_classify_update_go_pseudo_version_is_unknown() {
        assert_eq!(
            classify_update("v0.0.0-20210101000000-abcdef123456", "v1.0.0"),
            UpdateKind::Unknown
        );
        assert_eq!(
            classify_update(
                "v1.2.3-0.20210101000000-abcdef123456",
                "v1.2.3-0.20210102000000-abcdef654321"
            ),
            UpdateKind::Unknown
        );
    }

    #[test]
    fn test_classify_update_maven_nuget_range_syntax_is_unknown() {
        assert_eq!(classify_update("[1.0,2.0)", "2.0.0"), UpdateKind::Unknown);
        assert_eq!(classify_update("1.0.0", "[1.0,2.0)"), UpdateKind::Unknown);
    }

    #[test]
    fn test_classify_update_wildcard_latest_workspace_star_is_unknown() {
        assert_eq!(classify_update("*", "1.0.0"), UpdateKind::Unknown);
        assert_eq!(classify_update("latest", "1.0.0"), UpdateKind::Unknown);
        assert_eq!(classify_update("workspace:*", "1.0.0"), UpdateKind::Unknown);
    }

    #[test]
    fn test_classify_update_gradle_strictly_preferred_syntax_is_unknown() {
        assert_eq!(
            classify_update("{strictly 1.0}!!1.2", "1.3.0"),
            UpdateKind::Unknown
        );
    }

    #[test]
    fn test_classify_update_equal_versions_is_patch() {
        assert_eq!(classify_update("1.2.3", "1.2.3"), UpdateKind::Patch);
    }

    #[test]
    fn test_classify_update_four_component_version() {
        assert_eq!(classify_update("1.0.0.0", "1.0.1.0"), UpdateKind::Patch);
    }

    // --- dedup_overlapping_edits<ManifestEdit> ---

    #[test]
    fn test_dedup_overlapping_manifest_edits_drops_the_later_overlap() {
        let edits = vec![
            ManifestEdit {
                range: range(0, 0, 0, 5),
                new_text: "a".to_string(),
            },
            ManifestEdit {
                range: range(0, 2, 0, 7),
                new_text: "b".to_string(),
            },
        ];
        let kept = dedup_overlapping_edits(edits, "test");
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].new_text, "a");
    }

    #[test]
    fn test_dedup_non_overlapping_manifest_edits_keeps_both() {
        let edits = vec![
            ManifestEdit {
                range: range(0, 0, 0, 5),
                new_text: "a".to_string(),
            },
            ManifestEdit {
                range: range(1, 0, 1, 5),
                new_text: "b".to_string(),
            },
        ];
        let kept = dedup_overlapping_edits(edits, "test");
        assert_eq!(kept.len(), 2);
    }

    // --- apply_edits ---

    #[test]
    fn test_apply_edits_single_line() {
        let content = "serde = \"1.0.0\"\n";
        let edits = vec![ManifestEdit {
            range: range(0, 9, 0, 14),
            new_text: "1.2.0".to_string(),
        }];
        assert_eq!(apply_edits(content, &edits), "serde = \"1.2.0\"\n");
    }

    #[test]
    fn test_apply_edits_multiple_lines_reverse_splice() {
        let content = "serde = \"1.0.0\"\ntokio = \"1.0.0\"\n";
        let edits = vec![
            ManifestEdit {
                range: range(0, 9, 0, 14),
                new_text: "1.2.0".to_string(),
            },
            ManifestEdit {
                range: range(1, 9, 1, 14),
                new_text: "1.3.0".to_string(),
            },
        ];
        assert_eq!(
            apply_edits(content, &edits),
            "serde = \"1.2.0\"\ntokio = \"1.3.0\"\n"
        );
    }

    #[test]
    fn test_apply_edits_empty_slice_is_a_no_op() {
        let content = "serde = \"1.0.0\"\n";
        assert_eq!(apply_edits(content, &[]), content);
    }

    /// Security-S2 regression: an inverted range (`start > end`) must be dropped, not panic
    /// `replace_range`. `apply_edits` splices ranges in-process now (deps-cli), unlike its
    /// pre-#1329 callers, which only ever handed ranges back to an LSP client.
    #[test]
    fn test_apply_edits_drops_inverted_range_instead_of_panicking() {
        let content = "serde = \"1.0.0\"\n";
        let edits = vec![ManifestEdit {
            range: range(0, 14, 0, 9),
            new_text: "evil".to_string(),
        }];
        assert_eq!(apply_edits(content, &edits), content);
    }

    #[test]
    fn test_apply_edits_valid_edit_still_applies_alongside_a_dropped_inverted_one() {
        let content = "serde = \"1.0.0\"\ntokio = \"1.0.0\"\n";
        let edits = vec![
            ManifestEdit {
                range: range(0, 14, 0, 9),
                new_text: "evil".to_string(),
            },
            ManifestEdit {
                range: range(1, 9, 1, 14),
                new_text: "1.3.0".to_string(),
            },
        ];
        assert_eq!(
            apply_edits(content, &edits),
            "serde = \"1.0.0\"\ntokio = \"1.3.0\"\n"
        );
    }

    #[test]
    fn test_apply_edits_non_ascii_line_with_several_edits() {
        let content = "h\u{e9}llo \u{1f600} a = \"1.0.0\", b = \"2.0.0\"\n";
        let edit = |sc, ec, text: &str| ManifestEdit {
            range: range(0, sc, 0, ec),
            new_text: text.to_string(),
        };
        let edits = vec![
            edit(27, 32, "2.2.2"),
            edit(6, 8, "X"),
            edit(14, 19, "1.1.0"),
        ];
        assert_eq!(
            apply_edits(content, &edits),
            "h\u{e9}llo X a = \"1.1.0\", b = \"2.2.2\"\n"
        );
    }

    #[test]
    fn test_apply_edits_many_edits_on_one_long_non_ascii_line() {
        const UNITS: usize = 5000;
        const UNIT_UTF16_LEN: u32 = 18;
        const VERSION_COL: u32 = 10;
        let unit = |version: &str| format!("\u{e9}\u{1f600}dep = \"{version}\", ");
        let content = "\u{e9}\u{1f600}dep = \"1.0.0\", ".repeat(UNITS);
        let edits: Vec<ManifestEdit> = (0..UNITS)
            .filter(|i| i % 30 == 0)
            .map(|i| {
                let start = VERSION_COL + UNIT_UTF16_LEN * u32::try_from(i).unwrap();
                ManifestEdit {
                    range: range(0, start, 0, start + 5),
                    new_text: "9.9.9".to_string(),
                }
            })
            .collect();
        assert!(edits.len() >= 100);
        let expected: String = (0..UNITS)
            .map(|i| unit(if i % 30 == 0 { "9.9.9" } else { "1.0.0" }))
            .collect();
        assert_eq!(apply_edits(&content, &edits), expected);
    }

    // --- collect_update_edits / collect_update_candidates ---

    mod collect_update_tests {
        use super::*;
        use crate::lsp_helpers::PackageVersions;
        use crate::lsp_helpers::test_support::{MOCK_FORMATTER, MockDep, MockParseResult, pkg};
        use crate::{EcosystemId, PackageName};
        use std::collections::HashMap;

        fn dep(name: &str, req: &str, version_range: crate::position::Range) -> MockDep {
            MockDep {
                name: pkg(name),
                version_req: crate::VersionReq::new(req),
                version_range,
                name_range: crate::position::Range::default(),
            }
        }

        fn parse_result(deps: Vec<MockDep>) -> MockParseResult {
            MockParseResult {
                deps,
                uri: crate::test_util::test_uri("/test/Cargo.toml"),
            }
        }

        /// spec 050 (T002): a renamed/aliased dependency's two occurrences must each
        /// classify `current` against their own resolved pin, never the collapsed per-name
        /// map.
        #[test]
        fn test_collect_update_edits_renamed_occurrence_resolves_its_own_pin() {
            let content = "serde = \"0.9\"\nserde = \"1.0\"\n";
            let pr = parse_result(vec![
                dep("serde", "0.9", range(0, 9, 0, 12)),
                dep("serde", "1.0", range(1, 9, 1, 12)),
            ]);
            let mut cached = HashMap::new();
            cached.insert("serde".into(), PackageVersions::latest_only("1.2.0"));
            let resolved_versions: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            let mut candidates = HashMap::new();
            candidates.insert(
                pkg("serde"),
                vec![
                    ConcreteVersion::from("0.9.15"),
                    ConcreteVersion::from("1.0.219"),
                ],
            );
            let versions = VersionData::new(&cached, &resolved_versions)
                .with_resolved_version_candidates(&candidates)
                .with_ecosystem(EcosystemId::Cargo);

            let mut planned = collect_update_edits(&pr, content, versions, &MOCK_FORMATTER);
            planned.sort_by_key(|p| p.edit.range.start.line);

            assert_eq!(planned.len(), 2);
            assert_eq!(planned[0].current, Some(ConcreteVersion::from("0.9.15")));
            assert_eq!(planned[1].current, Some(ConcreteVersion::from("1.0.219")));
        }

        #[test]
        fn test_collect_update_candidates_non_literal_span_is_unplannable() {
            // Mirrors the Maven `${property}` class: `version_range` spans a reference, not
            // the literal requirement text.
            let content = "<version>${slf4j.version}</version>";
            let pr = parse_result(vec![dep("slf4j-api", "2.0.16", range(0, 9, 0, 25))]);
            let mut cached = HashMap::new();
            cached.insert("slf4j-api".into(), PackageVersions::latest_only("2.1.0"));
            let resolved: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            let versions = VersionData::new(&cached, &resolved);

            let candidates = collect_update_candidates(&pr, content, versions, &MOCK_FORMATTER);
            assert_eq!(candidates.len(), 1);
            assert!(matches!(
                candidates[0],
                UpdateCandidate::Unplannable {
                    reason: UnplannableReason::NonLiteralSpan,
                    ..
                }
            ));
            assert!(
                collect_update_edits(&pr, content, versions, &MOCK_FORMATTER).is_empty(),
                "an unplannable candidate must never reach collect_update_edits's writable subset"
            );
        }

        /// Issue #1517 (the P0 this fix addresses): OSV flagged the registry's "latest" as
        /// malicious — `collect_update_candidates` (shared by the LSP code lens and
        /// `deps-cli update`'s default mode) must never plan writing it into the manifest.
        #[test]
        fn test_collect_update_candidates_osv_flagged_latest_is_unplannable() {
            let content = "feed-widget-helper = \"1.0.4\"\n";
            let pr = parse_result(vec![dep(
                "feed-widget-helper",
                "1.0.4",
                range(0, 22, 0, 29),
            )]);
            let mut cached = HashMap::new();
            cached.insert(
                "feed-widget-helper".into(),
                PackageVersions::latest_only("1.0.8"),
            );
            let resolved: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            let mut latest_status = crate::osv::LatestStatusMap::new();
            latest_status.insert(
                crate::test_util::vuln_key("feed-widget-helper"),
                crate::osv::UpgradeStatus::CandidateVulnerable {
                    version: ConcreteVersion::new("1.0.8"),
                    advisory_ids: crate::osv::Capped::new(vec!["MAL-2026-16332".to_string()], 1),
                    worst_severity: Some(crate::osv::VulnSeverity::Malicious),
                },
            );
            let versions = VersionData::new(&cached, &resolved).with_latest_status(&latest_status);

            let candidates = collect_update_candidates(&pr, content, versions, &MOCK_FORMATTER);
            assert_eq!(candidates.len(), 1, "{candidates:?}");
            assert!(matches!(
                candidates[0],
                UpdateCandidate::Unplannable {
                    reason: UnplannableReason::LatestFlaggedByOsv,
                    ..
                }
            ));
            assert!(
                collect_update_edits(&pr, content, versions, &MOCK_FORMATTER).is_empty(),
                "a flagged latest must never reach collect_update_edits's writable subset"
            );
        }

        /// Issue #1517 AC4: a `latest_status` map with no entry for this dependency (the
        /// pre-phase-B window, or a transient skip) must fail closed, never be planned as if
        /// verified safe.
        #[test]
        fn test_collect_update_candidates_unverified_latest_is_unplannable() {
            let content = "pkg = \"1.0.0\"\n";
            let pr = parse_result(vec![dep("pkg", "1.0.0", range(0, 6, 0, 13))]);
            let mut cached = HashMap::new();
            cached.insert("pkg".into(), PackageVersions::latest_only("2.0.0"));
            let resolved: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            // Empty map, not `None`: the pre-phase-B window attaches `Some(&empty_map)`.
            let latest_status = crate::osv::LatestStatusMap::new();
            let versions = VersionData::new(&cached, &resolved).with_latest_status(&latest_status);

            let candidates = collect_update_candidates(&pr, content, versions, &MOCK_FORMATTER);
            assert_eq!(candidates.len(), 1, "{candidates:?}");
            assert!(matches!(
                candidates[0],
                UpdateCandidate::Unplannable {
                    reason: UnplannableReason::LatestUnverified,
                    ..
                }
            ));
        }

        #[test]
        fn test_collect_update_candidates_no_op_rewrite_is_unplannable() {
            struct NoOpFormatter;
            impl crate::lsp_helpers::PackageNaming for NoOpFormatter {}
            impl crate::lsp_helpers::PackageRendering for NoOpFormatter {
                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()
                }
                fn format_version_replacing(
                    &self,
                    _version: &ConcreteVersion,
                    current: &str,
                ) -> String {
                    current.to_string()
                }
            }
            impl crate::lsp_helpers::RequirementResolution for NoOpFormatter {
                fn is_bounded_requirement_up_to_date(
                    &self,
                    _requirement: crate::lsp_helpers::BoundedVersionReq<'_>,
                    _latest: &ConcreteVersion,
                ) -> bool {
                    false
                }
            }
            impl crate::lsp_helpers::DiagnosticMessages for NoOpFormatter {}
            impl crate::lsp_helpers::DiagnosticPolicy for NoOpFormatter {}
            impl crate::lsp_helpers::SourcePolicy for NoOpFormatter {}
            impl crate::lsp_helpers::OsvNaming for NoOpFormatter {}

            let content = "pkg = \"1.0.0\"\n";
            let pr = parse_result(vec![dep("pkg", "1.0.0", range(0, 7, 0, 12))]);
            let mut cached = HashMap::new();
            cached.insert("pkg".into(), PackageVersions::latest_only("1.2.0"));
            let resolved: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            let versions = VersionData::new(&cached, &resolved);

            let candidates = collect_update_candidates(&pr, content, versions, &NoOpFormatter);
            assert_eq!(candidates.len(), 1);
            assert!(matches!(
                candidates[0],
                UpdateCandidate::Unplannable {
                    reason: UnplannableReason::NoOpRewrite,
                    ..
                }
            ));
        }

        #[test]
        fn test_collect_update_candidates_unsafe_latest_is_unplannable() {
            let content = "serde = \"1.0.0\"\n";
            let pr = parse_result(vec![dep("serde", "1.0.0", range(0, 8, 0, 15))]);
            let mut cached = HashMap::new();
            cached.insert(
                "serde".into(),
                PackageVersions::latest_only("1.2.0\", \"evil\": \"true"),
            );
            let resolved: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            let versions = VersionData::new(&cached, &resolved);

            let candidates = collect_update_candidates(&pr, content, versions, &MOCK_FORMATTER);
            assert_eq!(candidates.len(), 1);
            assert!(matches!(
                candidates[0],
                UpdateCandidate::Unplannable {
                    reason: UnplannableReason::UnsafeLatestVersion,
                    ..
                }
            ));
        }

        #[test]
        fn test_collect_update_candidates_up_to_date_dependency_produces_no_candidate() {
            // A dependency that is not `Outdated` at all must produce no entry — reporting
            // every up-to-date dependency as a "candidate" would be noise, not signal.
            let content = "serde = \"^1.0\"\n";
            let pr = parse_result(vec![dep("serde", "^1.0", range(0, 8, 0, 14))]);
            let mut cached = HashMap::new();
            cached.insert("serde".into(), PackageVersions::latest_only("1.2.0"));
            let resolved: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            let versions = VersionData::new(&cached, &resolved);

            let candidates = collect_update_candidates(&pr, content, versions, &MOCK_FORMATTER);
            assert!(candidates.is_empty());
        }

        /// #1556 N3 (review): `current` in `collect_update_candidates` — the value
        /// `deps-cli update --update-types` feeds into `classify_update` — now flows through
        /// `resolve_in_use_version`, so a GitHub Actions SHA pin whose `resolved_pin_version`
        /// hook resolves to a full-semver tag now classifies as a real `UpdateKind` instead of
        /// `Unknown`. This is a genuine, user-visible CLI behavior change introduced by this
        /// PR's core fix that had zero coverage before: `test_classify_update_github_actions_
        /// sha_pin_is_unknown` only calls `classify_update` directly on two raw SHA strings and
        /// never goes through `resolve_in_use_version`/`resolved_pin_version` at all — that test
        /// still covers the unresolved case (the hook returning nothing) and must keep passing
        /// unchanged.
        #[test]
        fn test_collect_update_candidates_github_actions_sha_pin_current_resolves_via_hook() {
            struct ShaPinResolvedFormatter;
            impl crate::lsp_helpers::PackageNaming for ShaPinResolvedFormatter {}
            impl crate::lsp_helpers::PackageRendering for ShaPinResolvedFormatter {
                fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
                    version.to_string()
                }
                fn package_url(&self, name: &PackageName) -> String {
                    name.as_str().to_string()
                }
            }
            impl crate::lsp_helpers::RequirementResolution for ShaPinResolvedFormatter {
                fn is_bounded_requirement_up_to_date(
                    &self,
                    _requirement: crate::lsp_helpers::BoundedVersionReq<'_>,
                    _latest: &ConcreteVersion,
                ) -> bool {
                    false
                }
                fn resolved_pin_version(
                    &self,
                    _dep: &dyn Dependency,
                ) -> Option<crate::lsp_helpers::ResolvedPin> {
                    Some(crate::lsp_helpers::ResolvedPin::most_specific(
                        ConcreteVersion::new("v1.3.0"),
                    ))
                }
            }
            impl crate::lsp_helpers::DiagnosticMessages for ShaPinResolvedFormatter {}
            impl crate::lsp_helpers::DiagnosticPolicy for ShaPinResolvedFormatter {}
            impl crate::lsp_helpers::SourcePolicy for ShaPinResolvedFormatter {}
            impl crate::lsp_helpers::OsvNaming for ShaPinResolvedFormatter {}

            let sha = "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2";
            let content = format!("actions/checkout = \"{sha}\"\n");
            let sha_start = u32::try_from(content.find(sha).unwrap()).unwrap();
            let sha_end = sha_start + u32::try_from(sha.len()).unwrap();
            let pr = parse_result(vec![dep(
                "actions/checkout",
                sha,
                range(0, sha_start, 0, sha_end),
            )]);
            let mut cached = HashMap::new();
            cached.insert(
                "actions/checkout".into(),
                PackageVersions::latest_only("v1.4.0"),
            );
            let resolved: HashMap<PackageName, ConcreteVersion> = HashMap::new();
            let versions =
                VersionData::new(&cached, &resolved).with_ecosystem(EcosystemId::GithubActions);

            let candidates =
                collect_update_candidates(&pr, &content, versions, &ShaPinResolvedFormatter);

            assert_eq!(candidates.len(), 1, "{candidates:?}");
            let UpdateCandidate::Planned(planned) = &candidates[0] else {
                panic!("expected a planned update, got {:?}", candidates[0]);
            };
            assert_eq!(planned.current, Some(ConcreteVersion::from("v1.3.0")));
            assert_eq!(
                classify_update(
                    planned.current.as_ref().unwrap().as_str(),
                    planned.target.as_str()
                ),
                UpdateKind::Minor
            );
        }
    }

    // --- plan_vulnerability_fix: #1344 requirement-already-admits-fix gate, #1347
    // requirement_is_unresolved hardening ---

    mod plan_vulnerability_fix_tests {
        use super::*;
        use crate::PackageName;
        use crate::VersionReq;
        use crate::lsp_helpers::test_support::{
            MOCK_FORMATTER, MockDep, StrictSemverFormatter, pkg,
        };
        use crate::lsp_helpers::{
            DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
            RequirementMatcher, RequirementResolution, SourcePolicy,
        };
        use crate::osv::{
            Advisory, Capped, DependencyVulnerabilities, OsvVersion, UpgradeStatus, VulnSeverity,
        };

        fn dep(name: &str, req: &str, version_range: crate::position::Range) -> MockDep {
            MockDep {
                name: PackageName::new(name),
                version_req: crate::VersionReq::new(req),
                version_range,
                name_range: crate::position::Range::default(),
            }
        }

        fn verified_dv(fixed_version: &str) -> DependencyVulnerabilities {
            let advisory = std::sync::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(fixed_version)]),
            );
            DependencyVulnerabilities::new(Capped::new(vec![advisory], 1)).with_fix_target_status(
                UpgradeStatus::CandidateClean {
                    version: ConcreteVersion::new(fixed_version),
                },
            )
        }

        /// Reproduces `GithubActionsFormatter`'s real semantics: `requirement_is_unresolved`
        /// is `true` for a full-SHA pin (it means "not decidable from text alone", not
        /// "unexpanded placeholder"), yet `format_version_replacing_for` still produces a
        /// legitimate SHA-preserving rewrite for it. Guards against reintroducing #1347's C1
        /// regression (gating `plan_vulnerability_fix` on `requirement_is_unresolved`, which
        /// would silently drop this ecosystem's working vulnerability remediation) — a real
        /// cross-crate `GithubActionsFormatter` can't be used here (`deps-core` cannot depend
        /// on `deps-github-actions`), so this mock reproduces its documented override shape
        /// instead.
        struct ShaPinFormatter;
        impl PackageNaming for ShaPinFormatter {}
        impl PackageRendering for ShaPinFormatter {
            fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
                version.to_string()
            }
            fn package_url(&self, name: &crate::PackageName) -> String {
                name.as_str().to_string()
            }
            fn format_version_replacing(
                &self,
                version: &ConcreteVersion,
                _current: &str,
            ) -> String {
                format!("{version} # v-resolved")
            }
        }
        impl RequirementResolution for ShaPinFormatter {
            fn bounded_requirement_is_unresolved(
                &self,
                _requirement: crate::lsp_helpers::BoundedVersionReq<'_>,
            ) -> bool {
                true
            }
        }
        impl DiagnosticMessages for ShaPinFormatter {}
        impl DiagnosticPolicy for ShaPinFormatter {}
        impl SourcePolicy for ShaPinFormatter {}
        impl OsvNaming for ShaPinFormatter {}

        /// A caret range ("^1" is what Cargo/npm-shaped bare "1" compiles to) that already
        /// admits the fix target must suppress the edit — the declared requirement needs no
        /// manifest change, only a lock-file update.
        #[test]
        fn test_requirement_already_admitting_fix_returns_none() {
            let d = dep("serde", "1", range(0, 8, 0, 9));
            let dv = verified_dv("1.0.2");

            let planned =
                plan_vulnerability_fix(&d, d.version_range, "1", &dv, None, &StrictSemverFormatter);
            assert_eq!(planned, Err(VulnFixSkip::RequirementAlreadyResolves));
        }

        /// #1472 defense-in-depth: an oversized requirement must not trip
        /// `RequirementAlreadyResolves`, even when `bounded_requirement_already_resolves_to` would
        /// otherwise report `true` — proven via `ExactMatchFormatter`'s exact string-equality
        /// matcher, so an oversized requirement identical to the fix target trivially "already
        /// resolves" without the gate. With the gate, planning stops earlier with the distinct
        /// `OversizedRequirement` skip (#1665) — not `UnresolvedPlaceholder`, which the
        /// placeholder gate's fail-closed `true` for oversized text would otherwise report; the
        /// at-cap control proves the size check is a strict `>`, not `>=`.
        #[test]
        fn test_oversized_requirement_does_not_report_already_resolves() {
            use crate::lsp_helpers::MAX_REQUIREMENT_LEN;
            use crate::lsp_helpers::test_support::ExactMatchFormatter;

            let at_cap = "1".repeat(MAX_REQUIREMENT_LEN);
            let d = dep(
                "serde",
                &at_cap,
                range(0, 8, 0, 8 + u32::try_from(at_cap.len()).unwrap()),
            );
            assert_eq!(
                plan_verified_fix(&d, d.version_range, &at_cap, &at_cap, &ExactMatchFormatter),
                Err(VulnFixSkip::RequirementAlreadyResolves)
            );

            let oversized = "1".repeat(MAX_REQUIREMENT_LEN + 1);
            let d = dep(
                "serde",
                &oversized,
                range(0, 8, 0, 8 + u32::try_from(oversized.len()).unwrap()),
            );

            let planned = plan_verified_fix(
                &d,
                d.version_range,
                &oversized,
                &oversized,
                &ExactMatchFormatter,
            );

            assert_eq!(planned, Err(VulnFixSkip::OversizedRequirement));
        }

        /// #1665: the oversized check also covers the dependency's own requirement and version
        /// literal, not only the `current` text a caller passes in — each arm alone must yield
        /// `OversizedRequirement` rather than a placeholder or rewrite verdict.
        #[test]
        fn test_oversized_dependency_requirement_or_literal_is_oversized_skip() {
            use crate::lsp_helpers::MAX_REQUIREMENT_LEN;
            use crate::lsp_helpers::test_support::ExactMatchFormatter;

            struct LiteralDep {
                inner: MockDep,
                literal: String,
            }
            impl Dependency for LiteralDep {
                fn name(&self) -> &PackageName {
                    self.inner.name()
                }
                fn name_range(&self) -> crate::position::Range {
                    self.inner.name_range()
                }
                fn version_requirement(&self) -> Option<&VersionReq> {
                    self.inner.version_requirement()
                }
                fn version_range(&self) -> Option<crate::position::Range> {
                    self.inner.version_range()
                }
                fn version_literal(&self) -> Option<&str> {
                    Some(&self.literal)
                }
                fn source(&self) -> crate::parser::DependencySource {
                    self.inner.source()
                }
                fn as_any(&self) -> &dyn std::any::Any {
                    self
                }
            }

            let oversized = "1".repeat(MAX_REQUIREMENT_LEN + 1);

            let oversized_requirement = dep("serde", &oversized, range(0, 8, 0, 9));
            assert_eq!(
                plan_verified_fix(
                    &oversized_requirement,
                    oversized_requirement.version_range,
                    "1",
                    "2",
                    &ExactMatchFormatter,
                ),
                Err(VulnFixSkip::OversizedRequirement)
            );

            let oversized_literal = LiteralDep {
                inner: dep("serde", "1", range(0, 8, 0, 9)),
                literal: oversized,
            };
            assert_eq!(
                plan_verified_fix(
                    &oversized_literal,
                    range(0, 8, 0, 9),
                    "1",
                    "2",
                    &ExactMatchFormatter,
                ),
                Err(VulnFixSkip::OversizedRequirement)
            );
        }

        /// A requirement the comparator confirms does NOT admit the fix target must still
        /// produce a rewrite — the #1344 gate must not suppress legitimate fixes.
        #[test]
        fn test_requirement_not_admitting_fix_returns_planned_edit() {
            let d = dep("serde", "0.9", range(0, 8, 0, 11));
            let dv = verified_dv("1.0.2");

            let planned = plan_vulnerability_fix(
                &d,
                d.version_range,
                "0.9",
                &dv,
                None,
                &StrictSemverFormatter,
            )
            .expect("0.9 does not admit 1.0.2, so an edit must be planned");
            assert_eq!(planned.edit.new_text, "1.0.2");
            assert_eq!(planned.target.as_str(), "1.0.2");
        }

        /// An ecosystem with no `compile_bounded_requirement` override (e.g. GitHub Actions/GitLab CI)
        /// has no comparator to consult, so the gate is inert and the textual no-op guard is
        /// the only available signal — a genuinely different target must still be planned.
        #[test]
        fn test_no_compile_requirement_override_falls_back_to_no_op_guard() {
            let d = dep("serde", "1", range(0, 8, 0, 9));
            let dv = verified_dv("1.0.2");

            let planned =
                plan_vulnerability_fix(&d, d.version_range, "1", &dv, None, &MOCK_FORMATTER)
                    .unwrap();
            assert_eq!(planned.edit.new_text, "\"1.0.2\"");
        }

        /// A malformed `fixed_versions` entry (as if it somehow reached this dependency's
        /// `advisories` despite OSV's own wire-boundary validation) must be rejected before
        /// any other gate runs — `VulnFixSkip::UnsafeVersion`, not a planned edit.
        #[test]
        fn test_unsafe_fix_version_is_rejected() {
            let d = dep("serde", "0.9", range(0, 8, 0, 11));
            // A space is not in `is_safe_version_string`'s allowlist.
            let dv = verified_dv("1.2.0 evil");

            let planned =
                plan_vulnerability_fix(&d, d.version_range, "0.9", &dv, None, &MOCK_FORMATTER);
            assert_eq!(planned, Err(VulnFixSkip::UnsafeVersion));
        }

        /// A genuine textual no-op — the formatter's rewrite is byte-identical to the literal
        /// fallback `current` text — must be `VulnFixSkip::NoOpRewrite`, distinct from
        /// `RequirementAlreadyResolves` above (no `compile_bounded_requirement` override here, so that
        /// gate never fires; this is the plain textual guard alone).
        #[test]
        fn test_true_no_op_rewrite_is_rejected() {
            let d = dep("serde", "1", range(0, 8, 0, 9));
            let dv = verified_dv("1.0.2");

            // `MOCK_FORMATTER.format_version_for_text_edit` quotes its input, so the
            // already-quoted literal fallback below is byte-identical to the planned rewrite.
            let planned = plan_vulnerability_fix(
                &d,
                d.version_range,
                "\"1.0.2\"",
                &dv,
                None,
                &MOCK_FORMATTER,
            );
            assert_eq!(planned, Err(VulnFixSkip::NoOpRewrite));
        }

        /// #1422 regression: a dependency with more than `ADVISORY_DISPLAY_CAP` advisories must
        /// still resolve and verify a fix computed from an advisory beyond that display cap —
        /// `resolve_recommended_fix`/`fix_target_is_verified` must read the full
        /// `MAX_ADVISORY_RECORDS`-capped `advisories` set, not the render-only
        /// `advisories_for_display` truncation.
        #[test]
        fn test_plan_vulnerability_fix_uses_advisory_beyond_display_cap() {
            use crate::osv::ADVISORY_DISPLAY_CAP;

            let mut advisories: Vec<std::sync::Arc<Advisory>> = (0..ADVISORY_DISPLAY_CAP + 3)
                .map(|i| {
                    std::sync::Arc::new(
                        Advisory::new(
                            format!("ADV-{i}"),
                            "2024-01-01T00:00:00Z".to_string(),
                            VulnSeverity::High,
                        )
                        .expect("valid osv id")
                        .with_fixed_versions(vec![OsvVersion::new("1.0.0")]),
                    )
                })
                .collect();
            // The true highest fix sits past ADVISORY_DISPLAY_CAP; every other advisory fixes
            // at a lower version.
            let beyond_cap_index = ADVISORY_DISPLAY_CAP + 1;
            advisories[beyond_cap_index] = std::sync::Arc::new(
                Advisory::new(
                    format!("ADV-{beyond_cap_index}"),
                    "2024-01-01T00:00:00Z".to_string(),
                    VulnSeverity::High,
                )
                .expect("valid osv id")
                .with_fixed_versions(vec![OsvVersion::new("2.0.0")]),
            );
            let total = advisories.len();
            let dv = DependencyVulnerabilities::new(Capped::new(advisories, total))
                .with_fix_target_status(UpgradeStatus::CandidateClean {
                    version: ConcreteVersion::new("2.0.0"),
                });

            let d = dep("serde", "0.9", range(0, 8, 0, 11));
            let planned =
                plan_vulnerability_fix(&d, d.version_range, "0.9", &dv, None, &MOCK_FORMATTER)
                    .expect("fix beyond the display cap must still be recommended and verified");
            assert_eq!(planned.edit.new_text, "\"2.0.0\"");
            assert_eq!(planned.target.as_str(), "2.0.0");
        }

        /// A synthetic formatter mimicking a resolver that pins a bare requirement to its
        /// *lowest* admissible member (NuGet's bare `Version="1.0.0"` floor, #1344 C1) rather
        /// than following forward to the newest one. Its raw `compile_bounded_requirement` matcher is
        /// deliberately permissive (matches any version at or above the floor, exactly like
        /// NuGet's lower-bound-only shape) so this test proves `plan_vulnerability_fix` consults
        /// `bounded_requirement_already_resolves_to`'s override — which correctly refuses to
        /// suppress — rather than the raw matcher alone.
        struct FloorFormatter;

        struct FloorMatcher(String);
        impl RequirementMatcher for FloorMatcher {
            fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
                Some(version.as_str() >= self.0.as_str())
            }

            fn strict_prerelease_exclusion(&self) -> bool {
                false
            }
        }

        impl PackageNaming for FloorFormatter {}
        impl PackageRendering for FloorFormatter {
            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 FloorFormatter {
            fn compile_bounded_requirement(
                &self,
                requirement: crate::lsp_helpers::BoundedVersionReq<'_>,
            ) -> Option<Box<dyn RequirementMatcher>> {
                Some(Box::new(FloorMatcher(requirement.as_str().to_string())))
            }

            fn bounded_requirement_already_resolves_to(
                &self,
                _requirement: crate::lsp_helpers::BoundedVersionReq<'_>,
                _target: &ConcreteVersion,
            ) -> bool {
                // A floor never auto-follows forward — leaving it unedited always keeps
                // resolving to the floor itself, never to a higher target.
                false
            }
        }
        impl DiagnosticMessages for FloorFormatter {}
        impl DiagnosticPolicy for FloorFormatter {}
        impl SourcePolicy for FloorFormatter {}
        impl OsvNaming for FloorFormatter {}

        /// #1344 C1 regression: a floor-shaped requirement must NOT be suppressed just
        /// because `compile_bounded_requirement`'s raw matcher admits the fix target — the resolver
        /// keeps pinning to the floor, so an edit is still the only way to actually apply the
        /// fix. See `deps-nuget`'s real `bounded_requirement_already_resolves_to` override for the
        /// concrete regression this mirrors.
        #[test]
        fn test_floor_shaped_requirement_still_returns_planned_edit() {
            let d = dep("nuget.pkg", "1.0.0", range(0, 8, 0, 15));
            let dv = verified_dv("1.0.2");

            // Sanity: the raw matcher alone would wrongly admit the fix, if the gate used it
            // directly instead of `bounded_requirement_already_resolves_to`.
            assert_eq!(
                FloorFormatter
                    .compile_requirement(&crate::VersionReq::new("1.0.0"))
                    .unwrap()
                    .matches(&ConcreteVersion::new("1.0.2")),
                Some(true)
            );

            let planned =
                plan_vulnerability_fix(&d, d.version_range, "1.0.0", &dv, None, &FloorFormatter)
                    .expect("a floor-shaped requirement must not suppress the fix");
            assert_eq!(planned.edit.new_text, "1.0.2");
        }

        #[test]
        fn test_plan_vulnerability_fix_ignores_requirement_is_unresolved() {
            let action_dep = MockDep {
                name: pkg("some-action"),
                version_req: VersionReq::new("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
                version_range: range(0, 9, 0, 49),
                name_range: crate::position::Range::default(),
            };
            let dv = verified_dv("1.2.0");

            let planned = plan_vulnerability_fix(
                &action_dep,
                action_dep.version_range,
                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                &dv,
                None,
                &ShaPinFormatter,
            );

            assert_eq!(
                planned.expect("fix must still be planned").edit.new_text,
                "1.2.0 # v-resolved"
            );
        }
    }
}