deps-core 1.0.0

Core abstractions for deps-lsp: caching, errors, and traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
//! Shared LSP response builders.

use std::collections::HashMap;
use std::sync::Arc;
use tower_lsp_server::ls_types::{Position, Range, TextEdit, Uri};

use crate::error::DepsError;
use crate::licenses::LicensePolicy;
use crate::osv::VulnerabilityMap;
use crate::{
    ConcreteVersion, Dependency, Deprecation, DepsDevClient, EcosystemId, FetchFailure,
    LicenseSource, PackageName, RemovalStatus,
};

mod code_actions;
mod code_lenses;
mod diagnostics;
mod formatter;
mod git_ref;
mod hover;
mod in_use_version;
mod inlay_hints;
#[cfg(test)]
pub(crate) mod test_support;

pub use code_actions::generate_code_actions;
pub use code_lenses::{
    PIN_ALL_TO_SHA_COMMAND_ID, PinNoun, build_pin_all_to_sha_lens, collect_update_all_edits,
    dedup_overlapping_edits, generate_code_lenses,
};
pub use diagnostics::{
    DEPRECATED_DIAGNOSTIC_CODE, DiagnosticSeverities, LICENSE_POLICY_VIOLATION_DIAGNOSTIC_CODE,
    UNSATISFIABLE_DIAGNOSTIC_CODE, compile_requirement_unless, generate_diagnostics_from_cache,
    requirement_is_unsatisfiable, truncate_for_diagnostic,
};
pub use formatter::{
    DiagnosticMessages, DiagnosticPolicy, EcosystemFormatter, OsvNaming, PackageNaming,
    PackageRendering, RequirementResolution, SourcePolicy,
};
pub use git_ref::{
    MAX_FALLBACK_SCAN_BYTES, MarkedScalar, byte_span_to_range, is_full_sha,
    is_partial_semver_shaped, is_tag_shaped, locate_value_span, marker_byte_offset,
    match_v_prefix_style,
};
pub use hover::{CMD_DOT_FOOTER, generate_hover};
pub use in_use_version::{concrete_pin_version, is_full_semver_shape, resolve_in_use_version};
pub use inlay_hints::generate_inlay_hints;

/// Maximum number of recent versions hover's "Recent versions" section renders.
///
/// Also the walk target for registries (NuGet, npm) that must fetch publish times for
/// only the versions actually rendered, rather than the entire version history.
pub const HOVER_RECENT_VERSIONS: usize = 8;

/// Registry version data for one package, fetched together in a single round trip.
///
/// `latest` and `available` are deliberately asymmetric — this is load-bearing, not an
/// oversight:
/// - `latest` comes from this ecosystem's own `Registry::select_latest_matching(.., "*")`
///   pick, which excludes yanked (and, for semver/node-semver `*`, prerelease) versions —
///   the same value `get_latest_matching` returned before this type existed.
/// - `available` is the **unfiltered** `get_versions` output: every published version,
///   newest-first, yanked and prerelease entries included.
///
/// The unsatisfiable-requirement check (see `crate::lsp_helpers::requirement_is_unsatisfiable`)
/// scans `available` and deliberately does not filter it: a requirement that only matches a
/// yanked or prerelease version is still satisfied, so filtering `available` the same way
/// `latest` is filtered would produce false "no published version satisfies" warnings.
///
/// `yanked` is the subset of `available` (same version-string encoding) that the registry
/// reported as yanked/deprecated, paired with each entry's [`RemovalStatus`]. It exists
/// because `Registry::get_latest_matching` — the call that used to populate this cache —
/// filters yanked entries out by contract on every current registry implementation, so a
/// per-version yanked flag threaded through *that* call would always read `false` (see
/// #233). `available` now comes from the unfiltered `get_versions` instead, which does
/// observe yanked entries, so `yanked` is derived from that same fetch rather than
/// discarded.
///
/// The status rides alongside each version (rather than a bare membership list) so
/// [`crate::lsp_helpers::generate_diagnostics_from_cache`]'s #247 "requirement satisfiable
/// only by a yanked version" check can gate its own package-level-deprecation suppression
/// on `AdvisoryDeprecated` specifically, never on a genuine `Yanked` finding — mirroring
/// [`VersionData::outcomes`]'s D5 gate for the #263 in-use-version check (see #437).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageVersions {
    /// Latest usable version for this package.
    pub latest: ConcreteVersion,
    /// Every published version, newest-first, unfiltered.
    pub available: Arc<[ConcreteVersion]>,
    /// Subset of `available` reported as yanked/deprecated by the registry, each paired
    /// with its [`RemovalStatus`].
    pub yanked: Arc<[(ConcreteVersion, RemovalStatus)]>,
    /// When `latest` was published, if the registry exposes it. `None` when
    /// the ecosystem doesn't wire [`crate::Version::published_at`] or the fetch
    /// never ran.
    ///
    /// Deliberately a field on this single per-package struct rather than a
    /// second parallel map keyed alongside `latest` — the earlier two-map
    /// design (issue #227 critique C3) let `latest` and its age drift apart
    /// silently whenever one map was updated (e.g. lockfile-resolved
    /// overwrite) without the other. Bundling them here makes that
    /// desync impossible: whoever sets `latest` sets `published_at` too.
    pub published_at: Option<crate::freshness::PublishTime>,
}

impl PackageVersions {
    /// Constructs a `PackageVersions` from its two required fields, with [`Self::yanked`] and
    /// [`Self::published_at`] left empty/`None` — chain [`Self::with_yanked`] and/or
    /// [`Self::with_published_at`] to attach them.
    ///
    /// Needed because [`Self`] is `#[non_exhaustive]`: a struct literal only works inside
    /// this crate, so every other crate (including test code) must go through this
    /// constructor instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::{ConcreteVersion, PackageVersions};
    /// use std::sync::Arc;
    ///
    /// let versions = PackageVersions::new(
    ///     ConcreteVersion::new("2.0.0"),
    ///     Arc::from(vec![ConcreteVersion::new("2.0.0"), ConcreteVersion::new("1.0.0")]),
    /// );
    /// assert_eq!(versions.latest, "2.0.0");
    /// assert_eq!(versions.available.len(), 2);
    /// assert!(versions.yanked.is_empty());
    /// ```
    #[must_use]
    pub fn new(latest: ConcreteVersion, available: Arc<[ConcreteVersion]>) -> Self {
        Self {
            latest,
            available,
            yanked: Arc::from(Vec::new()),
            published_at: None,
        }
    }

    /// Attaches the registry's yanked/deprecated-version findings. See [`Self::yanked`].
    #[must_use]
    pub fn with_yanked(mut self, yanked: Arc<[(ConcreteVersion, RemovalStatus)]>) -> Self {
        self.yanked = yanked;
        self
    }

    /// Attaches when `latest` was published. See [`Self::published_at`].
    #[must_use]
    pub const fn with_published_at(mut self, published_at: crate::freshness::PublishTime) -> Self {
        self.published_at = Some(published_at);
        self
    }

    /// Builds a `PackageVersions` from only the "latest" version string, with `available`
    /// populated as the single-element list `[latest]`.
    ///
    /// **Test-only in intent.** The one-element `available` this produces is a real, if
    /// small, version list — it is not "empty/unknown", so `requirement_is_unsatisfiable`
    /// will evaluate a requirement against it. Do **not** use this for a lock-file-only
    /// population path that has no real version list to offer (use
    /// [`latest_without_list`](Self::latest_without_list) there instead, which leaves
    /// `available` genuinely empty) — that exact substitution is the false-positive N5 was
    /// written to prevent: it would let the unsatisfiable-requirement check produce a
    /// verdict against a fabricated one-entry list before any registry fetch has run. Real
    /// registry fetches always populate `available` from the full `get_versions` result
    /// instead of using either constructor.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::{ConcreteVersion, PackageVersions};
    ///
    /// let versions = PackageVersions::latest_only("1.0.214");
    /// assert_eq!(versions.latest, "1.0.214");
    /// assert_eq!(&*versions.available, &[ConcreteVersion::new("1.0.214")]);
    /// ```
    pub fn latest_only(latest: impl Into<ConcreteVersion>) -> Self {
        let latest = latest.into();
        let available = Arc::from(vec![latest.clone()]);
        Self {
            latest,
            available,
            yanked: Arc::from(Vec::new()),
            published_at: None,
        }
    }

    /// Builds a `PackageVersions` with no version list — used where only the "latest" value
    /// is known and probing further would be misleading, notably the lock-file population
    /// path (`crates/deps-lsp/src/document/lifecycle.rs`), which must not populate a
    /// plausible-looking one-element `available` list before any registry fetch has run: the
    /// unsatisfiable-requirement check treats an empty `available` as "still loading, skip".
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageVersions;
    ///
    /// let versions = PackageVersions::latest_without_list("1.0.195");
    /// assert_eq!(versions.latest, "1.0.195");
    /// assert!(versions.available.is_empty());
    /// ```
    pub fn latest_without_list(latest: impl Into<ConcreteVersion>) -> Self {
        Self {
            latest: latest.into(),
            available: Arc::from(Vec::new()),
            yanked: Arc::from(Vec::new()),
            published_at: None,
        }
    }
}

/// Everything the lifecycle fetch learned about one package, keyed by its normalized name.
///
/// All three channels can hold simultaneously for the same package — this is load-bearing,
/// not an incidental shape. The D5 status gate in
/// [`generate_diagnostics_from_cache`] reads the [`Self::deprecation`] and [`Self::yanked`]
/// entries for the same normalized name together and compares their [`RemovalStatus`], and on
/// the didChange path a surviving deprecation can coexist with a later fetch failure. A single
/// enum variant per package could not express that overlap.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DependencyOutcome {
    /// The version found yanked (the in-use version, or `latest` when only `latest` itself is
    /// yanked), paired with its [`RemovalStatus`]. See [`VersionData::outcomes`]'s prior
    /// semantics (#233/#263).
    pub yanked: Option<(ConcreteVersion, RemovalStatus)>,
    /// Package-level deprecation finding (#205). See [`Deprecation`].
    pub deprecation: Option<Deprecation>,
    /// Registry fetch errored, timed out, or was never attempted (#267). See [`FetchFailure`].
    pub fetch_failure: Option<FetchFailure>,
    /// The registry fetch succeeded (no [`Self::fetch_failure`]) but produced zero
    /// comparable versions — e.g. a real GitHub repository whose only tags don't parse
    /// as full `major.minor.patch` semver (`dtolnay/rust-toolchain`'s sole tag `v1`,
    /// issue #550). Distinct from both an absent [`DependencyOutcome`] entry ("never
    /// fetched") and [`Self::fetch_failure`] ("couldn't be asked"): this package
    /// demonstrably exists, so [R5](crate::lsp_helpers::generate_diagnostics_from_cache)
    /// must not claim it is unknown.
    pub no_comparable_versions: bool,
}

impl DependencyOutcome {
    /// True when none of the four channels are set.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.yanked.is_none()
            && self.deprecation.is_none()
            && self.fetch_failure.is_none()
            && !self.no_comparable_versions
    }
}

/// Normalized-package-name -> [`DependencyOutcome`] map.
///
/// A newtype rather than a bare `HashMap` so the empty-entry pruning invariant (an entry is
/// removed once all three of its channels are cleared) lives in one place, and so test
/// fixtures get chainable `with_*` constructors instead of building three ad-hoc `HashMap`s.
/// Mirrors the existing [`crate::osv::VulnerabilityMap`] convention of a `String`-keyed map by
/// normalized name.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DependencyOutcomes(HashMap<String, DependencyOutcome>);

impl DependencyOutcomes {
    /// Creates an empty map.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Looks up the full outcome recorded for `name`.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&DependencyOutcome> {
        self.0.get(name)
    }

    /// Looks up the yanked-version finding for `name`.
    #[must_use]
    pub fn yanked(&self, name: &str) -> Option<&(ConcreteVersion, RemovalStatus)> {
        self.0.get(name)?.yanked.as_ref()
    }

    /// Looks up the package-level deprecation finding for `name`.
    #[must_use]
    pub fn deprecation(&self, name: &str) -> Option<&Deprecation> {
        self.0.get(name)?.deprecation.as_ref()
    }

    /// Looks up the fetch-failure finding for `name`.
    #[must_use]
    pub fn fetch_failure(&self, name: &str) -> Option<&FetchFailure> {
        self.0.get(name)?.fetch_failure.as_ref()
    }

    /// True when the registry fetch for `name` succeeded but produced zero comparable
    /// versions (#550). See [`DependencyOutcome::no_comparable_versions`].
    #[must_use]
    pub fn no_comparable_versions(&self, name: &str) -> bool {
        self.0.get(name).is_some_and(|o| o.no_comparable_versions)
    }

    /// Records a yanked-version finding for `name`, creating the entry if absent.
    pub fn set_yanked(&mut self, name: String, yanked: (ConcreteVersion, RemovalStatus)) {
        self.0.entry(name).or_default().yanked = Some(yanked);
    }

    /// Records a package-level deprecation finding for `name`, creating the entry if absent.
    pub fn set_deprecation(&mut self, name: String, deprecation: Deprecation) {
        self.0.entry(name).or_default().deprecation = Some(deprecation);
    }

    /// Records a fetch-failure finding for `name`, creating the entry if absent.
    pub fn set_fetch_failure(&mut self, name: String, failure: FetchFailure) {
        self.0.entry(name).or_default().fetch_failure = Some(failure);
    }

    /// Records a fetch-failure finding for `name` only if one is not already recorded,
    /// creating the entry if absent.
    pub fn set_fetch_failure_if_absent(&mut self, name: String, failure: FetchFailure) {
        self.0
            .entry(name)
            .or_default()
            .fetch_failure
            .get_or_insert(failure);
    }

    /// Records that `name`'s registry fetch succeeded but produced zero comparable
    /// versions (#550), creating the entry if absent.
    pub fn set_no_comparable_versions(&mut self, name: String) {
        self.0.entry(name).or_default().no_comparable_versions = true;
    }

    /// Clears the no-comparable-versions channel for `name`, pruning the entry if it
    /// becomes empty.
    pub fn clear_no_comparable_versions(&mut self, name: &str) {
        if let Some(entry) = self.0.get_mut(name) {
            entry.no_comparable_versions = false;
            self.prune(name);
        }
    }

    /// Clears the yanked-version channel for `name`, pruning the entry if it becomes empty.
    pub fn clear_yanked(&mut self, name: &str) {
        if let Some(entry) = self.0.get_mut(name) {
            entry.yanked = None;
            self.prune(name);
        }
    }

    /// Clears the deprecation channel for `name`, pruning the entry if it becomes empty.
    pub fn clear_deprecation(&mut self, name: &str) {
        if let Some(entry) = self.0.get_mut(name) {
            entry.deprecation = None;
            self.prune(name);
        }
    }

    /// Clears the fetch-failure channel for `name`, pruning the entry if it becomes empty.
    pub fn clear_fetch_failure(&mut self, name: &str) {
        if let Some(entry) = self.0.get_mut(name) {
            entry.fetch_failure = None;
            self.prune(name);
        }
    }

    /// Removes the whole entry for `name`, regardless of which channels are set.
    pub fn remove(&mut self, name: &str) {
        self.0.remove(name);
    }

    /// Clears the fetch-failure channel for every entry, pruning any that become empty.
    ///
    /// Used when a forced re-fetch (e.g. a live-reloaded registry-routing setting, deps-lsp
    /// issue #592) makes every previously recorded fetch-failure finding untrustworthy: the
    /// routing itself changed, so a failure recorded under the old routing must not survive
    /// to be merged with results fetched under the new one.
    pub fn clear_all_fetch_failures(&mut self) {
        let names: Vec<String> = self.0.keys().cloned().collect();
        for name in names {
            self.clear_fetch_failure(&name);
        }
    }

    fn prune(&mut self, name: &str) {
        if self.0.get(name).is_some_and(DependencyOutcome::is_empty) {
            self.0.remove(name);
        }
    }

    /// Number of entries currently stored.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// True when no entries are stored.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Number of entries with a yanked-version finding, for logging/`Debug`.
    #[must_use]
    pub fn yanked_count(&self) -> usize {
        self.0.values().filter(|o| o.yanked.is_some()).count()
    }

    /// Number of entries with a deprecation finding, for logging/`Debug`.
    #[must_use]
    pub fn deprecation_count(&self) -> usize {
        self.0.values().filter(|o| o.deprecation.is_some()).count()
    }

    /// Number of entries with a fetch-failure finding, for logging/`Debug`.
    #[must_use]
    pub fn fetch_failure_count(&self) -> usize {
        self.0
            .values()
            .filter(|o| o.fetch_failure.is_some())
            .count()
    }

    /// Chainable builder recording a yanked-version finding. Test/fixture ergonomics.
    #[must_use]
    pub fn with_yanked(
        mut self,
        name: impl Into<String>,
        yanked: (ConcreteVersion, RemovalStatus),
    ) -> Self {
        self.set_yanked(name.into(), yanked);
        self
    }

    /// Chainable builder recording a package-level deprecation finding. Test/fixture
    /// ergonomics.
    #[must_use]
    pub fn with_deprecation(mut self, name: impl Into<String>, deprecation: Deprecation) -> Self {
        self.set_deprecation(name.into(), deprecation);
        self
    }

    /// Chainable builder recording a fetch-failure finding. Test/fixture ergonomics.
    #[must_use]
    pub fn with_fetch_failure(mut self, name: impl Into<String>, failure: FetchFailure) -> Self {
        self.set_fetch_failure(name.into(), failure);
        self
    }

    /// Chainable builder recording a no-comparable-versions finding (#550). Test/fixture
    /// ergonomics.
    #[must_use]
    pub fn with_no_comparable_versions(mut self, name: impl Into<String>) -> Self {
        self.set_no_comparable_versions(name.into());
        self
    }
}

/// Bundles the two per-package version maps (`cached`, `resolved`) that LSP handlers pass
/// together everywhere.
///
/// Grouping them prevents accidentally swapping the two map arguments at a call site, since
/// the compiler can no longer typecheck them positionally.
///
/// # Examples
///
/// ```
/// use deps_core::{ConcreteVersion, PackageName, PackageVersions, VersionData};
/// use std::collections::HashMap;
///
/// let mut cached = HashMap::new();
/// cached.insert(PackageName::new("serde"), PackageVersions::latest_only("1.0.214"));
///
/// let mut resolved = HashMap::new();
/// resolved.insert(PackageName::new("serde"), ConcreteVersion::new("1.0.200"));
///
/// let versions = VersionData::new(&cached, &resolved);
///
/// assert_eq!(versions.cached.get("serde").map(|v| v.latest.as_str()), Some("1.0.214"));
/// assert_eq!(versions.resolved.get("serde").map(ConcreteVersion::as_str), Some("1.0.200"));
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub struct VersionData<'a> {
    /// Latest known versions and full version lists from the registry, keyed by package name.
    pub cached: &'a HashMap<PackageName, PackageVersions>,
    /// Versions actually resolved in the lock file, keyed by package name.
    pub resolved: &'a HashMap<PackageName, ConcreteVersion>,
    /// Every lock-file-resolved version for a package name, when more than one is retained
    /// (issue #649) — additive alongside [`Self::resolved`], which stays the single
    /// collapsed value for the common case. `None` by default (most call sites have no such
    /// map); [`crate::lsp_helpers::resolve_in_use_version`] and [`crate::osv::vulnerability_keys`]
    /// consult it to disambiguate two manifest occurrences of one resolved name (e.g. a
    /// Cargo `package = "..."` rename pinning an older major) by each occurrence's own
    /// `version_requirement()`, falling back to [`Self::resolved`] when a name has at most
    /// one candidate.
    pub resolved_version_candidates: Option<&'a HashMap<PackageName, Vec<ConcreteVersion>>>,
    /// OSV scan results, keyed by normalized package name. `None` when no
    /// scan has run yet (e.g. the feature is disabled) — distinct from an
    /// empty map, which would mean "scanned, nothing found".
    pub vulnerabilities: Option<&'a VulnerabilityMap>,
    /// Yanked, deprecation, and fetch-failure findings from the most recent lifecycle fetch,
    /// keyed by normalized package name — see [`DependencyOutcome`] for what each channel
    /// means and why they must stay readable together off one lookup (D5 in
    /// [`generate_diagnostics_from_cache`], #233/#263/#205/#267). `None` when no fetch has run
    /// yet — distinct from an empty map, which would mean "checked, nothing found".
    pub outcomes: Option<&'a DependencyOutcomes>,
    /// This document's ecosystem, when the caller has one to give. `None` in
    /// most test fixtures and a handful of ecosystem-crate self-tests that
    /// predate this field.
    ///
    /// Enables two occurrence-aware refinements added for #394 (duplicate
    /// dependency names no longer collapsing into one shared finding):
    /// [`generate_diagnostics_from_cache`] only emits a yanked-version
    /// diagnostic on the occurrence whose own in-use version actually
    /// matches the recorded finding (S1), and the vulnerability lookups in
    /// `generate_diagnostics_from_cache`, [`generate_hover`], and
    /// `generate_code_actions` prefer a version-qualified
    /// [`crate::osv::VulnerabilityMap`] key over the plain name when more
    /// than one occurrence of a name has a distinct in-use version (S2).
    /// When `None`, both fall back to their pre-#394 name-only behavior.
    pub ecosystem: Option<EcosystemId>,
    /// Whether `network.offline` is set (issue #483). When `true`, [`generate_hover`]
    /// appends a footer stating that version *and vulnerability* data were not checked —
    /// deliberately more specific than a bare "showing cached data" notice, since
    /// `hover.rs`'s `Some(ScanOutcome::Skipped(_)) | None` arm renders nothing for an
    /// offline OSV skip, which would otherwise look identical to a scanned-and-clean
    /// dependency.
    pub offline: bool,
    /// The deps.dev client to fetch a supply-chain trust signal through
    /// (spec 037), when the caller wants hover to attempt one. `None` by
    /// default and left `None` by every surface but `handlers/hover.rs`
    /// (deps-lsp) — diagnostics, code actions, inlay hints, and code lenses
    /// never set this, which is what makes FR-010's hover-only scope
    /// structural rather than convention: those surfaces cannot reach
    /// deps.dev because they are never handed a client. `&'a Arc<..>`, not
    /// `&'a DepsDevClient`, so [`generate_hover`] can clone the `Arc` into a
    /// detached background task.
    pub trust: Option<&'a Arc<DepsDevClient>>,
    /// Background-pre-fetched license data for ecosystems `deps_dev_system` doesn't
    /// cover and whose hot-path registry response carries no license field — Dart,
    /// Swift, Gradle, Deno (issue #660, spec 010 plan §1 tier 3), keyed by raw
    /// (unnormalized) package name. `None` by default. Populated from `DocumentState`'s
    /// per-document pre-fetch cache (`document::osv_scan::run_license_prefetch` on
    /// document open/change — mirrors [`Self::vulnerabilities`]'s "populated by a
    /// background task, read synchronously here" shape) by `handlers/hover.rs` (deps-lsp)
    /// for hover, and by `handlers/diagnostics.rs`'s `textDocument/diagnostic` pull path
    /// for [`generate_diagnostics_from_cache`]'s license-policy rule (issue #661) — see
    /// [`Self::license_policy`].
    ///
    /// **What version this actually reflects is per-ecosystem, not uniformly the
    /// resolved version** (critic S1 — corrects a previous blanket claim here that it
    /// "only ever covers the resolved version"): Gradle's Maven Central POM fetch and
    /// Deno's JSR per-version API are genuinely fetched at the dependency's resolved/
    /// in-use version. Dart's pub.dev `/score` endpoint is per-*package*, not
    /// per-version — it reflects pana's detection on whatever pub.dev most recently
    /// scored, unrelated to which version is resolved. Swift's GitHub
    /// `GET /repos/{owner}/{repo}` reflects the repository's default branch, not the
    /// resolved version's tag. Every source here is still a background pre-fetch gated
    /// on a version having been resolved at all (no in-use version means nothing to
    /// look up), but only Gradle/Deno are actually version-*specific* in what they
    /// return.
    pub license_prefetch: Option<&'a HashMap<PackageName, Vec<String>>>,
    /// How [`Self::license_prefetch`]'s (and, for a resolved-version match, the
    /// registry-declared) license strings are sourced (issue #688), consulted by
    /// [`generate_hover`] for the "(detected)" qualifier and by
    /// [`generate_diagnostics_from_cache`]'s license-policy rule to decide whether
    /// [`crate::licenses::resolve_license_entries`] must normalize free text before
    /// evaluation. `None` in most test fixtures and any handler that doesn't go through
    /// [`crate::Ecosystem::generate_hover`]/[`crate::Ecosystem::generate_diagnostics`]'s
    /// default implementation, which is what actually attaches this field via
    /// `self.license_source()` — falls back to
    /// [`LicenseSource::RegistryDeclaredSpdx`] (`Default`) wherever consumed.
    pub license_source: Option<LicenseSource>,
    /// SPDX allow-list/deny-list license policy (issue #661, spec 010 Phase 2), when the
    /// caller wants diagnostics evaluated against one. `None` by default.
    ///
    /// Unlike [`Self::trust`], this is **not** hover-only-scoped: `deps-lsp`'s
    /// `handlers/diagnostics.rs::generate_diagnostics_internal` attaches the currently
    /// configured policy (cached on `ServerState`, kept live-updated by
    /// `Backend::initialize`/`did_change_configuration`) unconditionally, so every
    /// diagnostics-generation call site — the `textDocument/diagnostic` pull path *and*
    /// every push-path background refresh (fetch-completion, watched-config reparse,
    /// lock-file change) — evaluates the same policy. An earlier revision scoped this
    /// field to the pull path only, following `Self::trust`'s hover-only precedent; that
    /// was a false analogy (issue #660/#661 critic C1) — `trust` is safe hover-only
    /// because hover has exactly one producer per request, but diagnostics has multiple
    /// producers all replacing the same client-visible `publish_diagnostics` set, so a
    /// caller-scoped policy meant the license diagnostic flickered in and out on every
    /// edit and was invisible to push-only clients.
    /// [`generate_diagnostics_from_cache`]'s license-policy rule reads this alongside
    /// [`Self::license_prefetch`] — so today it only actually fires for tier-3 ecosystems
    /// (Dart/Swift/Deno; Gradle is explicitly excluded, see that rule's doc comment), the
    /// only ones `license_prefetch` covers; this field and the rule are otherwise
    /// ecosystem-agnostic and need no change as `license_prefetch`'s coverage widens.
    pub license_policy: Option<&'a LicensePolicy>,
}

impl<'a> VersionData<'a> {
    /// Creates a new `VersionData` from the cached and resolved version maps.
    ///
    /// `vulnerabilities` starts `None`; chain [`Self::with_vulnerabilities`]
    /// to attach a scan result.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionData;
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let versions = VersionData::new(&cached, &resolved);
    /// assert!(versions.cached.is_empty());
    /// assert!(versions.vulnerabilities.is_none());
    /// ```
    pub fn new(
        cached: &'a HashMap<PackageName, PackageVersions>,
        resolved: &'a HashMap<PackageName, ConcreteVersion>,
    ) -> Self {
        Self {
            cached,
            resolved,
            resolved_version_candidates: None,
            vulnerabilities: None,
            outcomes: None,
            ecosystem: None,
            offline: false,
            trust: None,
            license_prefetch: None,
            license_source: None,
            license_policy: None,
        }
    }

    /// Attaches the per-name lock-file candidates map, enabling the per-occurrence
    /// disambiguation described on [`Self::resolved_version_candidates`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionData;
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let candidates = HashMap::new();
    /// let versions =
    ///     VersionData::new(&cached, &resolved).with_resolved_version_candidates(&candidates);
    /// assert!(versions.resolved_version_candidates.is_some());
    /// ```
    #[must_use]
    pub const fn with_resolved_version_candidates(
        mut self,
        candidates: &'a HashMap<PackageName, Vec<ConcreteVersion>>,
    ) -> Self {
        self.resolved_version_candidates = Some(candidates);
        self
    }

    /// Attaches an OSV scan result to this `VersionData`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionData;
    /// use deps_core::osv::VulnerabilityMap;
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let vulns = VulnerabilityMap::new();
    /// let versions = VersionData::new(&cached, &resolved).with_vulnerabilities(&vulns);
    /// assert!(versions.vulnerabilities.is_some());
    /// ```
    #[must_use]
    pub fn with_vulnerabilities(mut self, vulnerabilities: &'a VulnerabilityMap) -> Self {
        self.vulnerabilities = Some(vulnerabilities);
        self
    }

    /// Attaches yanked, deprecation, and fetch-failure findings to this `VersionData`. See
    /// [`Self::outcomes`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionData;
    /// use deps_core::lsp_helpers::DependencyOutcomes;
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let outcomes = DependencyOutcomes::new();
    /// let versions = VersionData::new(&cached, &resolved).with_outcomes(&outcomes);
    /// assert!(versions.outcomes.is_some());
    /// ```
    #[must_use]
    pub fn with_outcomes(mut self, outcomes: &'a DependencyOutcomes) -> Self {
        self.outcomes = Some(outcomes);
        self
    }

    /// Attaches this document's ecosystem, enabling the occurrence-aware
    /// refinements described on [`Self::ecosystem`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::{EcosystemId, VersionData};
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let versions = VersionData::new(&cached, &resolved).with_ecosystem(EcosystemId::Cargo);
    /// assert_eq!(versions.ecosystem, Some(EcosystemId::Cargo));
    /// ```
    #[must_use]
    pub const fn with_ecosystem(mut self, ecosystem: EcosystemId) -> Self {
        self.ecosystem = Some(ecosystem);
        self
    }

    /// Marks this `VersionData` as built while `network.offline` was set, so
    /// [`generate_hover`] appends its offline footer.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionData;
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let versions = VersionData::new(&cached, &resolved).with_offline(true);
    /// assert!(versions.offline);
    /// ```
    #[must_use]
    pub const fn with_offline(mut self, offline: bool) -> Self {
        self.offline = offline;
        self
    }

    /// Attaches a deps.dev client, enabling [`generate_hover`] to attempt a
    /// supply-chain trust signal for the hovered dependency. See
    /// [`Self::trust`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::{DepsDevClient, HttpCache, VersionData};
    /// use std::collections::HashMap;
    /// use std::sync::Arc;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let client = Arc::new(DepsDevClient::new(Arc::new(HttpCache::new())));
    /// let versions = VersionData::new(&cached, &resolved).with_trust(&client);
    /// assert!(versions.trust.is_some());
    /// ```
    #[must_use]
    pub const fn with_trust(mut self, client: &'a Arc<DepsDevClient>) -> Self {
        self.trust = Some(client);
        self
    }

    /// Attaches tier-3 pre-fetched license data. See [`Self::license_prefetch`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionData;
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let licenses = HashMap::new();
    /// let versions = VersionData::new(&cached, &resolved).with_license_prefetch(&licenses);
    /// assert!(versions.license_prefetch.is_some());
    /// ```
    #[must_use]
    pub const fn with_license_prefetch(
        mut self,
        licenses: &'a HashMap<PackageName, Vec<String>>,
    ) -> Self {
        self.license_prefetch = Some(licenses);
        self
    }

    /// Attaches this ecosystem's license source. See [`Self::license_source`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::{LicenseSource, VersionData};
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let versions =
    ///     VersionData::new(&cached, &resolved).with_license_source(LicenseSource::PomFreeText);
    /// assert_eq!(versions.license_source, Some(LicenseSource::PomFreeText));
    /// ```
    #[must_use]
    pub const fn with_license_source(mut self, source: LicenseSource) -> Self {
        self.license_source = Some(source);
        self
    }

    /// Attaches a license policy for diagnostics evaluation. See [`Self::license_policy`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::{LicensePolicy, VersionData};
    /// use std::collections::HashMap;
    ///
    /// let cached = HashMap::new();
    /// let resolved = HashMap::new();
    /// let policy = LicensePolicy::new(vec!["MIT".to_string()], vec![]);
    /// let versions = VersionData::new(&cached, &resolved).with_license_policy(&policy);
    /// assert!(versions.license_policy.is_some());
    /// ```
    #[must_use]
    pub const fn with_license_policy(mut self, policy: &'a LicensePolicy) -> Self {
        self.license_policy = Some(policy);
        self
    }
}

/// Checks whether a cursor position falls within an LSP range (inclusive on both ends).
pub fn position_in_range(pos: Position, range: Range) -> bool {
    if pos.line < range.start.line || pos.line > range.end.line {
        return false;
    }
    if pos.line == range.start.line && pos.character < range.start.character {
        return false;
    }
    if pos.line == range.end.line && pos.character > range.end.character {
        return false;
    }
    true
}

/// Converts byte offsets in source text to LSP `Position` values.
///
/// Precomputes line-start byte offsets once, then maps any byte offset to a
/// `(line, character)` position. Characters are counted as UTF-16 code units
/// as required by the LSP specification.
///
/// Also precomputes, per line, whether that line is pure ASCII (`line_is_ascii`): for an
/// ASCII-only line, byte offset and UTF-16 code-unit
/// offset are always equal, so [`byte_offset_to_position`](Self::byte_offset_to_position)
/// can skip the `chars().map(char::len_utf16).sum()` scan entirely and compute the
/// character offset in O(1). This matters because a single minified manifest line (e.g. a
/// `package.json` with hundreds of dependencies on one line) turns per-offset lookups into
/// an O(n) scan each, and O(n) lookups across the line's length make the whole document
/// O(n^2) (#742) — the common case of an ASCII-only line now stays O(1) per lookup; a
/// non-ASCII line still takes an O(1) lookup too, via a lazily-built per-line index (#882) —
/// see `with_non_ascii_line_index`.
///
/// Interior mutability: this type is `Send` but not `Sync` (the non-ASCII line index cache
/// uses a `RefCell`). Build one per document parse and never share it across threads.
pub struct LineOffsetTable {
    line_starts: Vec<usize>,
    line_is_ascii: Vec<bool>,
    // Lazily populated for non-ASCII lines, keyed by 0-indexed line number. A `HashMap` rather
    // than a `Vec` sized to the line count so the cost is proportional to lines actually
    // queried non-ASCII — every other `LineOffsetTable` consumer (JSON/TOML ecosystems, code
    // lens, code actions) never touches a non-ASCII line's index and pays nothing beyond one
    // empty `HashMap::new()` (#882).
    non_ascii_line_index_cache:
        std::cell::RefCell<std::collections::HashMap<usize, NonAsciiLineIndex>>,
}

/// A non-ASCII line's char-boundary index, lazily built and cached by
/// `LineOffsetTable::with_non_ascii_line_index`.
///
/// `entries[i]` is `(byte_offset, utf16_units_before)` for the line's `i`-th char boundary
/// (`byte_offset` relative to the line's own start, `utf16_units_before` the cumulative UTF-16
/// code-unit count of every char *before* it). A final sentinel entry for the end of the line
/// (`byte_offset == line.len()`, `utf16_units_before` = the line's total UTF-16 length) makes
/// end-of-line byte offsets resolvable the same way as any other char boundary.
///
/// Serves both directions #882 needs on a non-ASCII line, from one build pass: char index ->
/// byte offset (`entries.get(col)`, what [`marker_byte_offset`] needs) and byte offset ->
/// UTF-16 units (`entries.binary_search_by_key`, what
/// [`byte_offset_to_position`](LineOffsetTable::byte_offset_to_position) needs) — a second,
/// independent cache would duplicate the exact `char_indices()` walk this one pass already
/// performs.
struct NonAsciiLineIndex {
    entries: Vec<(u32, u32)>,
}

impl NonAsciiLineIndex {
    /// Builds the index for one line's text via a single `char_indices()` walk.
    fn build(line_text: &str) -> Self {
        let mut entries = Vec::with_capacity(line_text.len() + 1);
        let mut utf16_units = 0u32;
        for (byte_offset, c) in line_text.char_indices() {
            entries.push((u32::try_from(byte_offset).unwrap_or(u32::MAX), utf16_units));
            utf16_units = utf16_units.saturating_add(u32::try_from(c.len_utf16()).unwrap_or(2));
        }
        entries.push((
            u32::try_from(line_text.len()).unwrap_or(u32::MAX),
            utf16_units,
        ));
        // The initial `line_text.len() + 1` capacity over-reserves 3-4x on a multi-byte-heavy
        // line (CJK, Devanagari, ...): it reserves per byte but pushes one entry per char.
        entries.shrink_to_fit();
        Self { entries }
    }
}

impl LineOffsetTable {
    /// Builds the table for `content`.
    pub fn new(content: &str) -> Self {
        let mut line_starts = vec![0];
        let mut line_is_ascii = Vec::new();
        let mut current_ascii = true;
        for (i, c) in content.char_indices() {
            if !c.is_ascii() {
                current_ascii = false;
            }
            if c == '\n' {
                line_starts.push(i + 1);
                line_is_ascii.push(current_ascii);
                current_ascii = true;
            }
        }
        line_is_ascii.push(current_ascii);
        debug_assert_eq!(
            line_starts.len(),
            line_is_ascii.len(),
            "line_starts and line_is_ascii must stay in lockstep — one entry per line"
        );
        Self {
            line_starts,
            line_is_ascii,
            non_ascii_line_index_cache: std::cell::RefCell::new(std::collections::HashMap::new()),
        }
    }

    /// Runs `f` against the cached (building it on first call) [`NonAsciiLineIndex`] for the
    /// non-ASCII line starting at `line0` (0-indexed), given that line's own text.
    ///
    /// Callers must pass the exact text of line `line0` as sliced from the same `content` this
    /// table was built from — the cache trusts its first-seen `line_text` for every later
    /// lookup of the same `line0` and never re-validates it. Building a line's index the first
    /// time it is looked up is still O(line length) (one `char_indices()` walk); only repeat
    /// lookups on an already-cached line become O(1) — a huge non-ASCII line's *first* lookup
    /// is not free, it is the same one-time cost `LineOffsetTable::new` always paid.
    ///
    /// Takes a closure rather than returning a `Ref` so the `RefCell` borrow never outlives one
    /// call — a caller cannot accidentally hold it open across an unrelated later borrow.
    // `borrow_mut()` below is dropped before `borrow()` runs (single-threaded, no reentrancy
    // between the two statements), and the entry it inserts is never removed, so the lookup
    // always succeeds.
    #[allow(clippy::expect_used)]
    fn with_non_ascii_line_index<R>(
        &self,
        line0: usize,
        line_text: &str,
        f: impl FnOnce(&NonAsciiLineIndex) -> R,
    ) -> R {
        self.non_ascii_line_index_cache
            .borrow_mut()
            .entry(line0)
            .or_insert_with(|| NonAsciiLineIndex::build(line_text));
        let cache = self.non_ascii_line_index_cache.borrow();
        let index = cache
            .get(&line0)
            .expect("just inserted above if it was missing");
        f(index)
    }

    /// Byte offset (relative to the line's own start) of the `col`-th char boundary within the
    /// non-ASCII line starting at `line0`, given that line's text. Clamps to `line_text.len()`
    /// if `col` is past the line's char count, matching a plain `char_indices().nth(col)` walk.
    fn non_ascii_char_byte_offset(&self, line0: usize, line_text: &str, col: usize) -> usize {
        self.with_non_ascii_line_index(line0, line_text, |index| {
            index
                .entries
                .get(col)
                .map_or(line_text.len(), |&(byte_offset, _)| byte_offset as usize)
        })
    }

    /// UTF-16 code-unit count preceding `byte_offset` (relative to the line's own start) within
    /// the non-ASCII line starting at `line0`, given that line's text.
    ///
    /// `byte_offset` must be a char boundary within the line (guaranteed by
    /// [`byte_offset_to_position`](Self::byte_offset_to_position)'s `floor_char_boundary` clamp
    /// before calling this) — every char boundary, including end-of-line, has an exact entry in
    /// the index, so this never needs to interpolate between two boundaries.
    fn non_ascii_utf16_units_before(
        &self,
        line0: usize,
        line_text: &str,
        byte_offset: usize,
    ) -> u32 {
        self.with_non_ascii_line_index(line0, line_text, |index| {
            let byte_offset = u32::try_from(byte_offset).unwrap_or(u32::MAX);
            let found = index
                .entries
                .binary_search_by_key(&byte_offset, |&(b, _)| b);
            // Not a recorded char boundary on `Err` — shouldn't happen given the caller's
            // `floor_char_boundary` guarantee, but falls back to the nearest preceding entry's
            // cumulative count rather than panicking.
            let i = found.unwrap_or_else(|i| i.saturating_sub(1));
            index.entries.get(i).map_or(0, |&(_, units)| units)
        })
    }

    /// Absolute byte offset where `line` (0-indexed) starts, or `None` if
    /// `line` is out of range.
    ///
    /// Prefer this over re-deriving a line's start via cursor arithmetic
    /// (`cursor += line.len() + 1`): `str::lines()` strips a trailing `\r`,
    /// so that approach under-counts by one byte per CRLF line and corrupts
    /// every subsequent offset in the file. This table is built by scanning
    /// `char_indices()` for `\n` (see [`new`](Self::new)), which counts the
    /// `\r`, so it stays correct for LF, CRLF and mixed line endings alike.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::LineOffsetTable;
    ///
    /// let table = LineOffsetTable::new("a\r\nb\r\nc");
    /// assert_eq!(table.line_start(0), Some(0));
    /// assert_eq!(table.line_start(1), Some(3));
    /// assert_eq!(table.line_start(2), Some(6));
    /// assert_eq!(table.line_start(3), None);
    /// ```
    pub fn line_start(&self, line: usize) -> Option<usize> {
        self.line_starts.get(line).copied()
    }

    /// Converts a byte offset into an LSP `Position`.
    // `offset` is floor_char_boundary-clamped just below before slicing `content`.
    #[allow(clippy::string_slice)]
    pub fn byte_offset_to_position(&self, content: &str, offset: usize) -> Position {
        let offset = offset.min(content.len());
        // `offset` is not always a toml-span offset (boundary-safe by
        // construction) — the requirements.txt line parser derives offsets
        // via hand-rolled byte arithmetic, which can land inside a
        // multi-byte character (e.g. a non-ASCII comment or marker string
        // combined with an off-by-a-byte cut). Clamp down to the nearest
        // char boundary rather than panicking on the slice below.
        let offset = content.floor_char_boundary(offset);
        let line = self
            .line_starts
            .partition_point(|&start| start <= offset)
            .saturating_sub(1);
        // `line_starts` always has at least one element (`vec![0]` at construction), so
        // `partition_point().saturating_sub(1)` is always a valid index into it.
        #[allow(clippy::indexing_slicing)]
        let line_start = self.line_starts[line];
        // #673 M1: `line`/`character` are NOT bounded by `fs_probe::read_to_string_capped`
        // or `HttpCache`'s body caps for a `textDocument/didChange` full-document-sync
        // text sent directly by the editor, so this saturates rather than assuming an
        // upstream cap that doesn't universally hold (mirrors
        // `completion::byte_to_utf16_offset`'s identical fix).
        //
        // #742: an ASCII-only line has 1 UTF-16 unit per byte, so the character offset is
        // just the byte delta — no need to walk the line's `chars()` to sum `len_utf16`.
        let character = if self.line_is_ascii.get(line).copied().unwrap_or(false) {
            u32::try_from(offset - line_start).unwrap_or(u32::MAX)
        } else {
            // #882: a naive `chars().map(len_utf16).sum()` per call is O(line length); N
            // lookups on the same wide non-ASCII line (e.g. N dependency values sharing a
            // minified manifest line) made this O(N x line length). The cached per-line
            // index (shared with `marker_byte_offset`'s identical cost, see
            // `with_non_ascii_line_index`) makes every lookup after the first on a given line
            // O(1).
            let line_end = self
                .line_starts
                .get(line + 1)
                .copied()
                .unwrap_or(content.len());
            let line_text = content.get(line_start..line_end).unwrap_or_default();
            self.non_ascii_utf16_units_before(line, line_text, offset - line_start)
        };
        Position::new(u32::try_from(line).unwrap_or(u32::MAX), character)
    }

    /// Converts an LSP `Position` back into a byte offset — the inverse of
    /// [`byte_offset_to_position`](Self::byte_offset_to_position). Out-of-range lines or
    /// UTF-16 characters clamp to `content.len()` rather than panicking, matching the
    /// forward conversion's `.min(content.len())` guard.
    // `line_start`/`line_end` come from `line_starts` (post-newline offsets, always char
    // boundaries) or `content.len()`.
    #[allow(clippy::string_slice)]
    pub fn position_to_byte_offset(&self, content: &str, position: Position) -> usize {
        let Some(&line_start) = self.line_starts.get(position.line as usize) else {
            return content.len();
        };
        let line_end = self
            .line_starts
            .get(position.line as usize + 1)
            .copied()
            .unwrap_or(content.len());
        let line = &content[line_start..line_end];
        crate::completion::utf16_to_byte_offset(line, position.character)
            .map_or(line_end, |offset| line_start + offset)
            .min(content.len())
    }
}

/// Escapes Markdown syntax characters so untrusted text cannot break out of the
/// Markdown structure it is embedded in.
///
/// Applied to manifest-controlled text (dependency names) before it is written into
/// hover markdown link labels, and to registry-controlled completion metadata
/// (package name/version, description, repository/documentation URLs) before it is
/// written into completion-item link labels and link destinations. Every ASCII
/// punctuation character is backslash-escaped (CommonMark's full escapable set — not
/// just brackets/parens, which would still leave e.g. `<https://evil.example>`
/// autolinks live), and control characters (including newlines) are replaced with a
/// space so the text cannot terminate the single-line block it is embedded in and
/// splice in new content.
///
/// Backslash-escaping is valid in link destinations as well as regular text, so this
/// also neutralizes `)`/`]` breakout attempts in a `[label](destination)` URL. It does
/// *not* block dangerous URI schemes (e.g. `javascript:`) in a destination — that is a
/// separate concern from breaking out of the surrounding Markdown structure.
///
/// Backslash-escaping does *not* work inside inline code spans (CommonMark §6.1) —
/// use [`markdown_code_span`] for text embedded in `` `...` `` instead.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::escape_markdown;
///
/// assert_eq!(escape_markdown("pkg](evil)[pkg"), r"pkg\]\(evil\)\[pkg");
/// assert_eq!(escape_markdown("a\nb"), "a b");
/// ```
pub fn escape_markdown(s: &str) -> String {
    let mut escaped = String::with_capacity(s.len());
    for c in s.chars() {
        if c.is_control() {
            escaped.push(' ');
            continue;
        }
        if c.is_ascii_punctuation() {
            escaped.push('\\');
        }
        escaped.push(c);
    }
    escaped
}

/// Wraps `content` in a Markdown inline code span (backticks included) that safely
/// contains arbitrary untrusted text, regardless of embedded backticks.
///
/// Backslash-escaping does not work inside code spans (CommonMark §6.1), so instead
/// this fences with one more backtick than the longest run found in `content`, and
/// pads with a single space on each side when `content` starts or ends with a
/// backtick or space (required by CommonMark to keep the fence unambiguous). Control
/// characters (including newlines) are replaced with a space first, since the raw
/// hover string is otherwise free to merge into an adjacent Markdown block.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::markdown_code_span;
///
/// assert_eq!(markdown_code_span("1.0.0"), "`1.0.0`");
/// assert_eq!(markdown_code_span("a`b"), "``a`b``");
/// ```
pub fn markdown_code_span(content: &str) -> String {
    let sanitized: String = content
        .chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect();

    let max_backtick_run = sanitized
        .split(|c| c != '`')
        .map(str::len)
        .max()
        .unwrap_or(0);
    let fence = "`".repeat(max_backtick_run + 1);

    if sanitized.is_empty() {
        format!("{fence} {fence}")
    } else if sanitized.starts_with(['`', ' ']) || sanitized.ends_with(['`', ' ']) {
        format!("{fence} {sanitized} {fence}")
    } else {
        format!("{fence}{sanitized}{fence}")
    }
}

/// Checks if two version strings have the same major and minor version.
pub fn is_same_major_minor(v1: &str, v2: &str) -> bool {
    if v1.is_empty() || v2.is_empty() {
        return false;
    }

    let mut parts1 = v1.split('.');
    let mut parts2 = v2.split('.');

    if parts1.next() != parts2.next() {
        return false;
    }

    match (parts1.next(), parts2.next()) {
        (Some(m1), Some(m2)) => m1 == m2,
        _ => true,
    }
}

/// Result of checking whether a dependency's declared requirement is already satisfied by
/// the latest known version.
///
/// Diagnostics and inlay hints read this result differently: diagnostics only need to know
/// whether it is safe to skip the "Newer version available" warning, so both `UpToDate` and
/// `Unresolved` suppress it. Inlay hints additionally need to distinguish `Unresolved` from
/// `UpToDate`, since an unresolved requirement (e.g. a dangling Gradle version-catalog
/// `version.ref` alias, or an unexpanded Maven `${property}`) must not render an "up to
/// date" badge that was never actually verified.
// Exhaustive: closed 3-way satisfies-check answer — a wildcard arm at any consuming match
// site would silently render the wrong label for a new variant instead of failing to
// compile (issue #769).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequirementStatus {
    /// The latest version satisfies the declared requirement.
    UpToDate,
    /// The latest version does not satisfy the declared requirement — a newer version is
    /// available.
    Outdated,
    /// The requirement could not be resolved to a concrete constraint, so no comparison
    /// could be made.
    Unresolved,
}

/// A `requirement` compiled by one ecosystem, ready to test candidate versions against.
///
/// Produced by [`formatter::RequirementResolution::compile_requirement`]. Kept as a separate object
/// (rather than a single "does any version match" function) so the requirement is parsed
/// once per dependency, and so the scanning loop — including the empty-list guard, the
/// early-exit on first match, and the "skip an unparseable candidate" rule — lives once in
/// [`requirement_is_unsatisfiable`] instead of being reimplemented by all eleven ecosystems.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::RequirementMatcher;
/// use deps_core::ConcreteVersion;
///
/// struct ExactMatch(String);
///
/// impl RequirementMatcher for ExactMatch {
///     fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
///         Some(version.as_str() == self.0)
///     }
/// }
///
/// let matcher = ExactMatch("1.0.0".to_string());
/// assert_eq!(matcher.matches(&ConcreteVersion::new("1.0.0")), Some(true));
/// assert_eq!(matcher.matches(&ConcreteVersion::new("2.0.0")), Some(false));
/// ```
pub trait RequirementMatcher: Send + Sync {
    /// Tests one candidate version string against the compiled requirement.
    ///
    /// `Some(true)` / `Some(false)`: this candidate provably does / does not satisfy the
    /// requirement. `None`: this candidate *string* could not be parsed by this ecosystem's
    /// version format (e.g. a PyPI legacy release identifier, a Maven timestamped snapshot
    /// qualifier) — the caller skips it and keeps scanning the rest of the list. Never
    /// return `None` to mean "the requirement itself is unusable"; that is
    /// [`formatter::RequirementResolution::compile_requirement`]'s job, via returning `None` from that
    /// method instead of constructing a matcher at all.
    fn matches(&self, version: &ConcreteVersion) -> Option<bool>;
}

/// Whether `segment` is exactly `.` or `..`.
///
/// Unlike ordinary path characters, a literal `.`/`..` segment is not neutralized by
/// percent-encoding: `.` is an unreserved character (RFC 3986), so `urlencoding::encode`
/// leaves it untouched, and the URL parser's dot-segment removal (RFC 3986 §5.2.4) still
/// collapses it after encoding — `%2E` decodes back to `.` before that normalization runs.
/// A registry-fetch URL built as `{base}/{prefix}/{name}` (no fixed suffix after `name`)
/// must reject a `name`/path segment satisfying this predicate rather than encode it,
/// since encoding alone does not stop the collapse (#341, #349).
///
/// Shared by `deps-npm`'s scope/package segment guard and `deps-dart`'s package-name
/// guard — both ecosystems' registry APIs key a fetch on a bare, suffix-less path segment.
///
/// **Scope**: this predicate (and the `#365` regression sweep built around it) guards
/// registry-*fetch* URL builders — the sink is a request this process actually
/// dereferences, so a retargeted URL can make it fetch attacker-chosen data. It
/// deliberately does *not* extend to a "docs link"/`package_url`-style builder (the
/// per-ecosystem hover/display link, e.g. `deps_cargo::crate_url`, `deps_go::package_url`):
/// those interpolate the name into a link rendered in hover text and never fetched by
/// this process, so an unrejected `.`/`..` name there produces at worst a misleading
/// same-host link (the registry's package-listing root), not a traversal off-host (#379).
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::is_dot_segment;
///
/// assert!(is_dot_segment(".."));
/// assert!(is_dot_segment("."));
/// assert!(!is_dot_segment("left-pad"));
/// ```
pub fn is_dot_segment(segment: &str) -> bool {
    segment == "." || segment == ".."
}

/// Whether `version` is safe to embed in a manifest [`TextEdit`] or completion item.
///
/// Guards every call into
/// [`formatter::PackageRendering::format_version_replacing`]/[`formatter::PackageRendering::format_version_for_text_edit`]
/// and every completion item's `insert_text`/`text_edit`.
///
/// Must be applied to the raw version string *before* formatting, never to a
/// formatter's output: some formatters legitimately produce structural
/// characters in their output from an already-validated version plus fixed,
/// trusted operators (e.g. PyPI's `>=1.2.3,<2`), so validating the output
/// would wrongly reject those.
///
/// An allowlist, not a denylist: `version` must be non-empty, at most 64
/// bytes, and contain only `[A-Za-z0-9.+_~:*^!-]` — the character set real
/// version strings use across every ecosystem this workspace supports
/// (SemVer, PEP 440 including epochs like `1!2.0`, Maven qualifiers, npm's
/// `^`/`~`/`*` range tokens, Go's `+incompatible` suffix). A denylist here
/// would need to anticipate every dangerous token a target manifest format
/// (or a build tool evaluating it, e.g. Gradle's Kotlin/Groovy DSL
/// interpolating `${...}` inside a version literal) could ever act on;
/// failing closed on an unrecognized character is cheaper and safer.
///
/// This is the single validation chokepoint shared by every producer of a
/// version-derived `TextEdit`/completion item in this workspace, including
/// OSV advisory data (an `Advisory.fixed_versions` entry is exactly as
/// untrusted as a registry-reported version).
///
/// # Examples
///
/// ```
/// use deps_core::is_safe_version_string;
///
/// assert!(is_safe_version_string("1.2.3-alpha.1+build"));
/// assert!(!is_safe_version_string("1.2.3\", git = \"https://evil"));
/// ```
pub fn is_safe_version_string(version: &str) -> bool {
    !version.is_empty()
        && version.len() <= 64
        && version.chars().all(|c| {
            c.is_ascii_alphanumeric()
                || matches!(c, '.' | '+' | '_' | '~' | ':' | '*' | '^' | '!' | '-')
        })
}

/// Whether `segment` is safe to embed as a Maven `groupId`/`artifactId` value in a
/// pom.xml [`TextEdit`] or completion item.
///
/// Guards Maven's group/artifact completion producer, which builds a completion item's
/// `insert_text`/`text_edit` from one field of a Maven Central search result — a value
/// type distinct from a version string (see [`is_safe_version_string`]'s doc comment for
/// why version-derived and non-version-derived sinks each get their own allowlist).
///
/// An allowlist, not a denylist: `segment` must be non-empty, at most 128 bytes, not
/// exactly `.`/`..` (see [`is_dot_segment`]), and contain only `[A-Za-z0-9._-]` — the
/// character set real Maven Central group ids (reverse-DNS style, e.g.
/// `org.apache.commons`) and artifact ids (hyphen/underscore separated, e.g.
/// `commons-lang3`) use. Deliberately excludes `:` — the `groupId:artifactId` separator —
/// because this validates one already-split coordinate field at a time, never the joined
/// pair. Failing closed on an unrecognized character (e.g. `<`, `"`, a newline) keeps a
/// malicious/compromised search result from restructuring the pom.xml it's inserted into;
/// the dedicated `.`/`..` rejection closes the same dot-segment URL-normalization gap
/// [`is_dot_segment`] guards elsewhere (`artifactId` reaches a registry-fetch URL as a bare
/// path segment in `deps-maven::registry::metadata_urls`, unlike `groupId`, whose `.`→`/`
/// expansion can never itself produce a literal `..` component).
///
/// # Examples
///
/// ```
/// use deps_core::is_safe_maven_coordinate_segment;
///
/// assert!(is_safe_maven_coordinate_segment("org.apache.commons"));
/// assert!(is_safe_maven_coordinate_segment("commons-lang3"));
/// assert!(!is_safe_maven_coordinate_segment("commons</artifactId><parent>"));
/// assert!(!is_safe_maven_coordinate_segment(".."));
/// ```
pub fn is_safe_maven_coordinate_segment(segment: &str) -> bool {
    !segment.is_empty()
        && segment.len() <= 128
        && !is_dot_segment(segment)
        && segment
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
}

/// Builds the Maven repository URL path (`"group/path/segments/artifact"`) for a
/// `groupId`/`artifactId` coordinate pair, or `None` if either fails validation.
///
/// The single shared home for `groupId:artifactId` -> URL-path construction (#702):
/// validates `group_id` and `artifact_id` as whole strings via
/// [`is_safe_maven_coordinate_segment`] (preserving its 128-byte total-length cap per
/// segment) *and* validates every `.`-separated component of `group_id` individually,
/// rejecting an empty component outright. The whole-string check alone is not enough —
/// it permits internal `.` characters, so a naive `group_id.replace('.', "/")` on a
/// coordinate like `"com..evil"` would produce the empty path segment `"com//evil"`; the
/// per-component check closes that gap without dropping the whole-string length bound a
/// pure per-segment `split('.')` validation would lose (a 10-segment, 128-byte-each group
/// would otherwise pass at 1280 bytes total).
///
/// # Examples
///
/// ```
/// use deps_core::maven_coordinate_path;
///
/// assert_eq!(
///     maven_coordinate_path("com.example", "artifact").as_deref(),
///     Some("com/example/artifact")
/// );
/// assert_eq!(
///     maven_coordinate_path("junit", "junit").as_deref(),
///     Some("junit/junit")
/// );
/// assert_eq!(maven_coordinate_path("com..evil", "artifact"), None);
/// ```
pub fn maven_coordinate_path(group_id: &str, artifact_id: &str) -> Option<String> {
    if !is_safe_maven_coordinate_segment(group_id) || !is_safe_maven_coordinate_segment(artifact_id)
    {
        return None;
    }
    let group_segments: Vec<&str> = group_id.split('.').collect();
    if group_segments
        .iter()
        .any(|segment| !is_safe_maven_coordinate_segment(segment))
    {
        return None;
    }
    Some(format!("{}/{artifact_id}", group_segments.join("/")))
}

/// Whether `url` is safe to embed as a Swift Package Manager repository URL in a
/// Package.swift [`TextEdit`] or completion item.
///
/// Guards Swift's URL-completion producer, which builds a `.package(url: "...")`
/// string-literal replacement from a package registry search result's URL — a value
/// type distinct from a version string (see [`is_safe_version_string`]'s doc comment for
/// why version-derived and non-version-derived sinks each get their own allowlist).
///
/// An allowlist, not a denylist: `url` must be non-empty, at most 2048 bytes, start with
/// `https://` — every real Swift package registry response is HTTPS (GitHub's `html_url`
/// never downgrades), so accepting plain `http://` would only hand a
/// compromised/malicious registry a transport-downgrade lever for zero legitimate
/// benefit — and otherwise contain only RFC 3986 URL characters (`A-Za-z0-9` plus
/// `` -._~:/?#[]@!$&'()*+,;=% ``). Deliberately excludes `"`, `\`, control characters,
/// and whitespace — none of those are valid unencoded URL characters, and any of them
/// could close the surrounding Swift string literal or otherwise corrupt the manifest.
/// Failing closed on an unrecognized character keeps a malicious/compromised search
/// result from breaking out of the string it's inserted into.
///
/// # Examples
///
/// ```
/// use deps_core::is_safe_registry_url;
///
/// assert!(is_safe_registry_url("https://github.com/apple/swift-nio"));
/// assert!(!is_safe_registry_url("https://evil.example\", .exact(\"1\")) // "));
/// ```
pub fn is_safe_registry_url(url: &str) -> bool {
    !url.is_empty()
        && url.len() <= 2048
        && url.starts_with("https://")
        && url.chars().all(|c| {
            c.is_ascii_alphanumeric()
                || matches!(
                    c,
                    '-' | '.'
                        | '_'
                        | '~'
                        | ':'
                        | '/'
                        | '?'
                        | '#'
                        | '['
                        | ']'
                        | '@'
                        | '!'
                        | '$'
                        | '&'
                        | '\''
                        | '('
                        | ')'
                        | '*'
                        | '+'
                        | ','
                        | ';'
                        | '='
                        | '%'
                )
        })
}

/// Whether `name` is safe to embed as a package name in a manifest [`TextEdit`] or
/// completion item.
///
/// Guards every arm of `create_package_completion_item`
/// (`crates/deps-lsp/src/handlers/completion.rs`) as a single upfront check, applied
/// before the raw `name` reaches any ecosystem-specific snippet — including Maven and
/// Swift, which additionally validate a *derived* value on top of this gate
/// ([`is_safe_maven_coordinate_segment`] on each split coordinate segment,
/// [`is_safe_registry_url`] on the constructed URL) because a value type distinct from
/// the raw name needs its own allowlist — see [`is_safe_version_string`]'s doc comment
/// for why version-derived and non-version-derived sinks each get their own allowlist.
/// [`PackageName::new`](crate::PackageName::new) is documented as never validating or
/// modifying its input, so this predicate is the first gate a registry-reported name
/// passes through before reaching a manifest. Two sinks that key a bare TOML/YAML
/// entry by `name` (Cargo/PyPI, Dart) additionally quote that key in the snippet, since
/// `.` and `@` are legal here but would otherwise be read as TOML's dotted-key
/// separator or break a YAML plain scalar.
///
/// An allowlist, not a denylist: `name` must be non-empty, at most 256 bytes, and
/// contain only `[A-Za-z0-9._@:/~-]` — the character set real package names use across
/// every ecosystem this predicate guards: Cargo/PyPI/Dart/NuGet/Bundler
/// (alphanumeric, `-`, `_`, `.`), npm/Deno scoped names (`@scope/name`, adding `@` and
/// `/`), Composer (`vendor/package`, `/`), Go module paths (domain-qualified paths like
/// `github.com/org/repo`, `/`, `.`, and `~` — legal in a Go path element and already
/// allowed by [`is_safe_version_string`]/[`is_safe_registry_url`]), and Gradle's
/// colon-delimited `group:artifact` short form (`:`). A denylist here would need to
/// anticipate every dangerous token a target manifest format (TOML/JSON/YAML/XML
/// string literals, a live Kotlin/Groovy build-script DSL) could ever act on; failing
/// closed on an unrecognized character — notably `"`, `'`, `<`, `>`, `` ` ``, and all
/// control characters/newlines — is cheaper and safer.
///
/// # Examples
///
/// ```
/// use deps_core::is_safe_package_name;
///
/// assert!(is_safe_package_name("serde"));
/// assert!(is_safe_package_name("@scope/name"));
/// assert!(is_safe_package_name("org.apache.commons:commons-lang3"));
/// assert!(!is_safe_package_name("evil\"\nbackdoor = \"9.9.9"));
/// ```
pub fn is_safe_package_name(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= 256
        && name.chars().all(|c| {
            c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '@' | ':' | '/' | '-' | '~')
        })
}

/// Logs a `tracing::warn!` for a value rejected by an `is_safe_*` predicate (or an
/// equivalent value-rejecting gate) before it reaches a manifest edit or registry URL.
///
/// Deliberately logs only `value`'s byte length, never its content: `value` is
/// registry-controlled and, by construction, already failed an allowlist — logging it
/// verbatim at `warn` would let a malicious/compromised registry response inject arbitrary
/// content into this project's own log stream (a second-order log-injection concern),
/// mirroring why `deps-pypi`'s `truncate_for_log` bounds a logged excerpt instead of
/// logging a value verbatim. This is this helper's own contract, not a claim that every
/// `tracing` call site in the workspace avoids logging a raw value — e.g. `deps-lsp`'s
/// `deps-lsp.updateVersion` handler and an OSV malformed-`fixed`-version warning predate
/// this helper and log their rejected value directly; they are unrelated call sites, not a
/// place this helper is used.
///
/// `gate` names the predicate/guard that rejected `value` (e.g.
/// `"is_safe_maven_coordinate_segment"`); `context` is a short description of the call site
/// (e.g. `"maven groupId completion"`).
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::warn_rejected_value;
///
/// warn_rejected_value("is_safe_version_string", "code lens latest version", "1.0.0\"; evil");
/// ```
pub fn warn_rejected_value(gate: &str, context: &str, value: &str) {
    tracing::warn!(
        gate,
        context,
        len = value.len(),
        "rejected unsafe value before manifest/registry sink"
    );
}

/// Logs a [`warn_rejected_value`] warning and builds the [`DepsError::PackageNotFound`] a
/// caller returns after its own `is_dot_segment`/`has_dot_segment` predicate rejects `name`.
///
/// Extracted from four equivalent `warn_rejected_value` + `PackageNotFound`
/// constructions in `deps-dart`, `deps-composer`, `deps-nuget`, and `deps-npm`
/// (deps-lsp#929 item 2) — `deps-npm`'s `gate` label was `"npm_dot_segment_guard"` rather
/// than the other three's `"is_dot_segment"` before this extraction normalized it. Each
/// crate keeps its own dot-segment *predicate* and the call to it exactly where it is
/// today; only this trailing boilerplate is shared. Deliberately does **not** fold in
/// `deps-go`'s guard, which returns `DepsError::InvalidVersionReq`, not `PackageNotFound`.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::dot_segment_rejection_error;
/// use deps_core::DepsError;
///
/// let err = dot_segment_rejection_error(
///     "is_dot_segment",
///     "example package metadata request URL",
///     "..",
///     "example",
/// );
/// assert!(matches!(err, DepsError::PackageNotFound { .. }));
/// ```
#[must_use]
pub fn dot_segment_rejection_error(
    gate: &str,
    context: &str,
    name: &str,
    registry: &'static str,
) -> DepsError {
    warn_rejected_value(gate, context, name);
    DepsError::PackageNotFound {
        package: name.to_string(),
        registry,
    }
}

/// Builds a single-entry [`tower_lsp_server::ls_types::WorkspaceEdit::changes`] map replacing `range` in `uri`
/// with `new_text`.
///
/// Shared by every quickfix/refactor code action in `code_actions` that edits exactly
/// one span in the current document (`build_vulnerability_fix_action`,
/// `build_unsatisfiable_fix_action`, and the plain "update to `<version>`" loop in
/// [`generate_code_actions`]).
fn single_file_edit(uri: &Uri, range: Range, new_text: String) -> HashMap<Uri, Vec<TextEdit>> {
    let mut edits = HashMap::new();
    edits.insert(uri.clone(), vec![TextEdit { range, new_text }]);
    edits
}

/// Strips every whitespace character from `s`, so two textually-equivalent strings that
/// differ only in spacing compare equal.
///
/// Shared by every no-op/literal-match guard across `code_actions` and `code_lenses`
/// (`build_vulnerability_fix_action`'s N1 guard, `generate_code_actions`'s REFACTOR-loop
/// guard, `literal_span_matches`, and `collect_update_all_edits`'s no-op guard), all of
/// which compare a declared requirement
/// string against a differently-normalized counterpart — e.g. pep508's `>=1.7, <2.0` vs. a
/// formatter's `>=1.7,<2.0`.
fn strip_whitespace(s: &str) -> String {
    s.chars().filter(|c| !c.is_whitespace()).collect()
}

/// Slices `content` over an LSP `Range` using a pre-built `LineOffsetTable`, returning
/// `""` for an inverted or out-of-bounds range instead of panicking.
///
/// `table` is document-invariant — callers iterating over multiple dependencies in the
/// same document must build it once and reuse it, rather than rebuilding it (an O(n)
/// scan of `content`) per dependency.
fn slice_for_range<'a>(content: &'a str, table: &LineOffsetTable, range: Range) -> &'a str {
    let start = table.position_to_byte_offset(content, range.start);
    let end = table.position_to_byte_offset(content, range.end);
    if start > end {
        return "";
    }
    content.get(start..end).unwrap_or("")
}

/// Checks whether `slice` — `content` sliced over a dependency's `version_range` — still
/// holds the literal version text declared by `requirement`.
///
/// Whitespace is stripped from both sides before comparison, since pep508's normalized
/// requirement string can diverge from the original source spacing (PyPI's `>=1.7,<2.0`
/// renders as `>=1.7, <2.0`) while `version_range` still spans the un-normalized source.
///
/// The second branch accepts `slice` wrapped in brackets matching `requirement` — the
/// exact inverse of NuGet's parser wrapping a bare source version as `format!("[{v}]")`
/// (`crates/deps-nuget/src/parser.rs`). This is deliberately **not** a symmetric bracket
/// strip: NuGet's `Version="1.0.0"` produces requirement `[1.0.0]` over a bare-literal
/// span, so a *symmetric* strip (stripping one bracket pair from both operands) would
/// compare `1.0.0` against `1.0.0` — coincidentally correct there, but the same strip
/// applied to `Version="[1.0.0]"` (requirement `[[1.0.0]]`, a spelling
/// `crates/deps-nuget/src/formatter.rs` explicitly supports) leaves `[1.0.0]` vs
/// `1.0.0` and **falsely rejects** an editable dependency. Wrapping only the slice side
/// handles both spellings without that false reject.
fn literal_span_matches(slice: &str, requirement: &str) -> bool {
    let norm_slice = strip_whitespace(slice);
    let norm_req = strip_whitespace(requirement);
    norm_slice == norm_req || format!("[{norm_slice}]") == norm_req
}

/// Whether `version_range`'s slice of `content` still holds `dep`'s own declared literal
/// version text.
///
/// The same literal-span discipline [`generate_code_actions`] and
/// `collect_update_all_edits` already apply before writing a `TextEdit` there, generalized
/// (issue #919) for any caller about to treat `version_range` as an editable literal: a
/// completion context, or a raw-text-scanning ecosystem's own completion dispatch (Maven,
/// Gradle) that never goes through [`crate::completion::detect_completion_context`] at all.
///
/// Returns `false` — not editable — when `dep` has no [`Dependency::version_requirement`], the
/// slice is syntactically reference-shaped (see below), or the slice doesn't textually match
/// the declared literal.
///
/// The reference-shape check runs **independently** of the text comparison (#919 C1): an
/// *unresolved* Maven `${property}` or Gradle `$var`/`${var}` interpolation is left by its
/// parser exactly as-is in both `version_range`'s slice and `version_requirement` (there is
/// nothing else to put there), so the two would otherwise textually agree and wrongly pass —
/// this is precisely the corruption #919 was filed over, and the dominant real-world Maven
/// case (a version inherited from a parent/BOM POM this crate cannot resolve) always lands
/// here. A slice containing `$` anywhere is rejected up front, before ever comparing text —
/// this single check subsumes both a whole-value `$var`/`${var}` interpolation and a Gradle
/// GString with the reference embedded mid-string (`1.0.$patch`), which `resolve_variable_ref`
/// only ever resolves in its whole-value form, leaving the mid-string case byte-identical
/// between slice and requirement and otherwise invisible to a `starts_with`-only check. A
/// slice that starts with `*` is rejected the same way *unless* [`crate::is_existence_wildcard_str`]
/// recognizes it as the project-wide existence-wildcard spelling (synthesized by `deps-npm`,
/// `deps-composer`, ...) — that case must keep offering a full version list at the exact
/// moment a user wants to replace the wildcard with a pin, while a `*anchor` YAML alias (any
/// other leading-`*` shape) still gets rejected.
///
/// An empty `version_requirement` is deliberately **not** special-cased here (unlike
/// `generate_code_actions`'s "nothing to update" early return, which does not apply to
/// completion): `serde = ""` / `"lodash": ""` — what an editor's auto-closing quotes produce
/// the instant the opening quote is typed — must still offer the full version list.
/// `literal_span_matches` alone already handles this correctly: `("", "")` matches (empty
/// slice, empty requirement — admitted), while a non-empty non-literal slice against an empty
/// requirement still fails to match (rejected).
///
/// Compares against [`Dependency::version_literal`] when the ecosystem provides one, falling
/// back to `version_requirement` otherwise (see that method's doc for why).
///
/// Builds its own [`LineOffsetTable`] for `content` on every call rather than accepting a
/// caller-built one — unlike `slice_for_range`'s multi-dependency callers (`generate_code_actions`,
/// `code_lenses`), every current call site invokes this at most once per request (a single
/// matched dependency), so a table-accepting overload would add API surface with no caller to
/// exercise it.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::dependency_version_range_is_literal;
/// use deps_core::{Dependency, PackageName, VersionReq};
/// use std::any::Any;
/// use tower_lsp_server::ls_types::{Position, Range};
///
/// struct MockDep {
///     name: PackageName,
///     version_req: VersionReq,
///     version_range: Range,
/// }
/// impl Dependency for MockDep {
///     fn name(&self) -> &PackageName {
///         &self.name
///     }
///     fn name_range(&self) -> Range {
///         Range::default()
///     }
///     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
///     }
/// }
///
/// // A plain literal version is admitted.
/// let content = r#"serde = "1.0.0""#;
/// 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)),
/// };
/// assert!(dependency_version_range_is_literal(&dep, content, dep.version_range));
///
/// // A Maven `${property}` interpolation is rejected even when unresolved — slice and
/// // requirement are byte-identical raw reference text, which the shape check catches
/// // independently of the (otherwise-matching) text comparison.
/// let content = r"<version>${slf4j.version}</version>";
/// let dep = MockDep {
///     name: PackageName::new("slf4j-api"),
///     version_req: VersionReq::new("${slf4j.version}"),
///     version_range: Range::new(Position::new(0, 9), Position::new(0, 25)),
/// };
/// assert!(!dependency_version_range_is_literal(&dep, content, dep.version_range));
/// ```
#[must_use]
pub fn dependency_version_range_is_literal(
    dep: &dyn Dependency,
    content: &str,
    version_range: Range,
) -> bool {
    let Some(version_req) = dep.version_requirement() else {
        return false;
    };
    let table = LineOffsetTable::new(content);
    let slice = slice_for_range(content, &table, version_range);
    let trimmed = slice.trim();
    if trimmed.contains('$')
        || (trimmed.starts_with('*') && !crate::is_existence_wildcard_str(trimmed))
    {
        return false;
    }
    let literal_target = dep
        .version_literal()
        .unwrap_or_else(|| version_req.as_str());
    literal_span_matches(slice, literal_target)
}

#[cfg(test)]
// Fixtures are single-line ASCII literals with hand-computed byte offsets.
#[allow(clippy::string_slice)]
mod tests {
    use super::*;
    use crate::lsp_helpers::test_support::*;
    use crate::{PackageName, VersionReq};

    /// #919: a plain literal version — `version_range`'s slice equals the declared
    /// requirement exactly — must be admitted as editable.
    #[test]
    fn test_dependency_version_range_is_literal_plain_literal_admitted() {
        let content = r#"serde = "1.0.0""#;
        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)),
        };

        assert!(dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// #919: a Maven-style `${property}` interpolation — `version_range` slices to the raw
    /// placeholder text while the parser resolves `version_requirement` to the property's
    /// value (a different string) — must be rejected, since a completion/edit there would
    /// splice text into the interpolation instead of updating a version.
    #[test]
    fn test_dependency_version_range_is_literal_rejects_property_interpolation() {
        let content = r"<version>${slf4j.version}</version>";
        let dep = MockDep {
            name: PackageName::new("slf4j-api"),
            version_req: VersionReq::new("2.0.16"), // resolved property value
            version_range: Range::new(Position::new(0, 9), Position::new(0, 25)), // "${slf4j.version}"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// #919: a YAML alias-shaped value (`*anchor`, e.g. GitLab CI/GitHub Actions `ref: *pin`
    /// job reuse) never textually equals a declared literal requirement — rejected the same
    /// way as the property-interpolation case.
    #[test]
    fn test_dependency_version_range_is_literal_rejects_yaml_alias() {
        let content = "ref: *pin";
        let dep = MockDep {
            name: PackageName::new("job"),
            version_req: VersionReq::new("1.0.0"),
            version_range: Range::new(Position::new(0, 5), Position::new(0, 9)), // "*pin"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// S1 (critic follow-up): an empty `version_requirement` over an equally-empty slice —
    /// exactly what an editor's auto-closing quotes produce the instant `serde = "` is typed
    /// — must be **admitted**, not rejected. `generate_code_actions`'s "nothing to update"
    /// semantics for an empty requirement do not apply to completion, where an empty value is
    /// the single most common moment to offer the full version list.
    #[test]
    fn test_dependency_version_range_is_literal_admits_empty_requirement_with_empty_slice() {
        let content = r#"serde = """#;
        let dep = MockDep {
            name: PackageName::new("serde"),
            version_req: VersionReq::new(""),
            version_range: Range::new(Position::new(0, 9), Position::new(0, 9)),
            name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
        };

        assert!(dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// S1 (critic follow-up): an empty `version_requirement` paired with a *non-empty*
    /// non-literal slice must still be rejected — dropping the old `is_empty()` early return
    /// must not also drop this case, which the plain text comparison already handles on its
    /// own (`"1.0" != ""`).
    #[test]
    fn test_dependency_version_range_is_literal_rejects_empty_requirement_with_mismatched_slice() {
        let content = r#"x = "1.0""#;
        let dep = MockDep {
            name: PackageName::new("x"),
            version_req: VersionReq::new(""),
            version_range: Range::new(Position::new(0, 5), Position::new(0, 8)), // "1.0"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 1)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// C1 (critic finding): the headline #919 case — an *unresolved* Maven `${property}`
    /// reference. The parser leaves an unresolved property as-is in both `version_range`'s
    /// slice and `version_requirement` (there is nothing else to put there), so the two
    /// textually agree — `literal_span_matches` alone would wrongly admit this. The
    /// reference-shape check must reject it independently of that text comparison.
    #[test]
    fn test_dependency_version_range_is_literal_rejects_unresolved_maven_property() {
        let content = r"<version>${slf4j.version}</version>";
        let dep = MockDep {
            name: PackageName::new("slf4j-api"),
            version_req: VersionReq::new("${slf4j.version}"), // left unresolved by the parser
            version_range: Range::new(Position::new(0, 9), Position::new(0, 25)), // "${slf4j.version}"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// C1 (critic finding): the Gradle sibling of the unresolved-property case — a `$var`
    /// reference `resolve_variable_ref` could not resolve, left as raw text in both the slice
    /// and `version_requirement`.
    #[test]
    fn test_dependency_version_range_is_literal_rejects_unresolved_gradle_variable() {
        let content = "implementation 'com.example:lib:$libVersion'";
        let dep = MockDep {
            name: PackageName::new("com.example:lib"),
            version_req: VersionReq::new("$libVersion"), // left unresolved by the parser
            version_range: Range::new(Position::new(0, 32), Position::new(0, 43)), // "$libVersion"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// C1 (critic finding): a partial interpolation embedded mid-string (`1.0-${suffix}`)
    /// does not start with `$`, but must still be rejected — the `contains("${")` arm of the
    /// reference-shape check, not just the `starts_with` arms.
    #[test]
    fn test_dependency_version_range_is_literal_rejects_embedded_interpolation() {
        let content = r#"x = "1.0-${suffix}""#;
        let dep = MockDep {
            name: PackageName::new("x"),
            version_req: VersionReq::new("1.0-${suffix}"),
            version_range: Range::new(Position::new(0, 5), Position::new(0, 18)), // "1.0-${suffix}"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 1)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// M2 (critic follow-up): `"*"` — the project-wide existence-wildcard spelling
    /// (`deps_core::registry::is_existence_wildcard`, synthesized by `deps-npm`,
    /// `deps-composer`, ...) — must be **admitted**, not caught by the `*`-prefix arm meant
    /// for a `*anchor` YAML alias. Rejecting it would silently disable version completion at
    /// the exact moment a user wants to replace `"lodash": "*"` with a pinned version.
    #[test]
    fn test_dependency_version_range_is_literal_admits_existence_wildcard() {
        let content = r#"x = "*""#;
        let dep = MockDep {
            name: PackageName::new("x"),
            version_req: VersionReq::new("*"),
            version_range: Range::new(Position::new(0, 5), Position::new(0, 6)), // "*"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 1)),
        };

        assert!(dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// M3 (critic follow-up): a `*anchor`-shaped slice that is *not exactly* `"*"` — e.g. a
    /// multi-char alias name — must still be rejected. Distinguishes the wildcard exemption
    /// above from a genuine leading-`*` reference.
    #[test]
    fn test_dependency_version_range_is_literal_rejects_multi_char_alias_despite_wildcard_exemption()
     {
        let content = "ref: *pinned-anchor";
        let dep = MockDep {
            name: PackageName::new("job"),
            version_req: VersionReq::new("1.0.0"),
            version_range: Range::new(Position::new(0, 5), Position::new(0, 19)), // "*pinned-anchor"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// M3 (critic follow-up): a Gradle GString with a `$var` reference embedded mid-string
    /// (`1.0.$patch`, no braces, not at the start) is not resolved by
    /// `resolve_variable_ref` (whole-value only) — the slice stays byte-identical to the raw
    /// `version_requirement`, so only the shape check (not the text comparison) can reject
    /// it. This is #919 C1 in a narrower spelling than the whole-value `$var`/`${var}` case.
    #[test]
    fn test_dependency_version_range_is_literal_rejects_gradle_mid_string_variable() {
        let content = r#"implementation "com.example:lib:1.0.$patch""#;
        let dep = MockDep {
            name: PackageName::new("com.example:lib"),
            version_req: VersionReq::new("1.0.$patch"), // left unresolved by the parser
            version_range: Range::new(Position::new(0, 32), Position::new(0, 42)), // "1.0.$patch"
            name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
        };

        assert!(!dependency_version_range_is_literal(
            &dep,
            content,
            dep.version_range,
        ));
    }

    /// The empty-entry pruning invariant: an entry is removed once its last set channel
    /// is cleared, one channel at a time, in every order — never left behind as a
    /// vacuous `Some(DependencyOutcome::default())` that would inflate `len()`.
    #[test]
    fn test_dependency_outcomes_prunes_entry_once_all_channels_cleared() {
        let mut outcomes = DependencyOutcomes::new()
            .with_yanked("pkg", ("1.0.0".into(), RemovalStatus::Yanked))
            .with_deprecation(
                "pkg",
                Deprecation {
                    reason: None,
                    replacement: None,
                },
            )
            .with_fetch_failure("pkg", FetchFailure::Transient);
        assert_eq!(outcomes.len(), 1);

        outcomes.clear_yanked("pkg");
        assert!(
            outcomes.get("pkg").is_some(),
            "entry must survive while other channels are still set"
        );

        outcomes.clear_deprecation("pkg");
        assert!(
            outcomes.get("pkg").is_some(),
            "entry must survive while the fetch-failure channel is still set"
        );

        outcomes.clear_fetch_failure("pkg");
        assert!(
            outcomes.is_empty(),
            "entry must be pruned once its last channel is cleared, not left as a vacuous Some"
        );
        assert_eq!(outcomes.len(), 0);
    }

    /// Clearing a channel that was never set on an existing entry must not spuriously
    /// prune channels that ARE still set (each `clear_*` only nulls its own field).
    #[test]
    fn test_dependency_outcomes_clear_on_unset_channel_is_a_no_op_for_others() {
        let mut outcomes = DependencyOutcomes::new()
            .with_yanked("pkg", ("1.0.0".into(), RemovalStatus::AdvisoryDeprecated));

        outcomes.clear_deprecation("pkg");
        outcomes.clear_fetch_failure("pkg");

        assert!(
            outcomes.yanked("pkg").is_some(),
            "clearing unset channels must not touch the still-set yanked channel"
        );
        assert_eq!(outcomes.len(), 1);
    }

    /// `remove` drops the whole entry regardless of which channels are set, unlike the
    /// per-channel `clear_*` methods.
    #[test]
    fn test_dependency_outcomes_remove_drops_entry_with_multiple_channels_set() {
        let mut outcomes = DependencyOutcomes::new()
            .with_yanked("pkg", ("1.0.0".into(), RemovalStatus::Yanked))
            .with_fetch_failure("pkg", FetchFailure::Transient);

        outcomes.remove("pkg");

        assert!(outcomes.get("pkg").is_none());
        assert!(outcomes.is_empty());
    }

    /// `clear_all_fetch_failures` (deps-lsp issue #592) drops the fetch-failure channel for
    /// every entry, pruning an entry that becomes empty, while leaving other channels
    /// (yanked/deprecation/no-comparable-versions) on a still-mixed entry untouched.
    #[test]
    fn test_dependency_outcomes_clear_all_fetch_failures() {
        let mut outcomes = DependencyOutcomes::new()
            .with_fetch_failure("only-failure", FetchFailure::Transient)
            .with_yanked("mixed", ("1.0.0".into(), RemovalStatus::Yanked))
            .with_fetch_failure("mixed", FetchFailure::Transient);

        outcomes.clear_all_fetch_failures();

        assert!(
            outcomes.get("only-failure").is_none(),
            "an entry whose only channel was fetch-failure must be pruned"
        );
        assert!(outcomes.fetch_failure("mixed").is_none());
        assert!(
            outcomes.yanked("mixed").is_some(),
            "clearing fetch-failure must not touch a mixed entry's other channels"
        );
    }

    /// `clear_all_fetch_failures` on an empty map is a no-op, not a panic.
    #[test]
    fn test_dependency_outcomes_clear_all_fetch_failures_on_empty_map() {
        let mut outcomes = DependencyOutcomes::new();
        outcomes.clear_all_fetch_failures();
        assert!(outcomes.is_empty());
    }

    /// `set_fetch_failure_if_absent` (impl-critic M2) must never clobber a genuine
    /// `Actionable`/`Transient` failure already recorded for the name — only `set_fetch_failure`
    /// unconditionally overwrites.
    #[test]
    fn test_dependency_outcomes_set_fetch_failure_if_absent_does_not_clobber_existing() {
        let mut outcomes = DependencyOutcomes::new().with_fetch_failure(
            "pkg",
            FetchFailure::Actionable("set GITHUB_TOKEN".to_string()),
        );

        outcomes.set_fetch_failure_if_absent("pkg".to_string(), FetchFailure::NotAttempted);

        assert_eq!(
            outcomes.fetch_failure("pkg"),
            Some(&FetchFailure::Actionable("set GITHUB_TOKEN".to_string())),
            "an existing genuine failure must survive a collided-name NotAttempted marker"
        );
    }

    /// The mirror case: when no failure is recorded yet, `set_fetch_failure_if_absent` does
    /// populate the entry.
    #[test]
    fn test_dependency_outcomes_set_fetch_failure_if_absent_populates_when_unset() {
        let mut outcomes = DependencyOutcomes::new();

        outcomes.set_fetch_failure_if_absent("pkg".to_string(), FetchFailure::NotAttempted);

        assert_eq!(
            outcomes.fetch_failure("pkg"),
            Some(&FetchFailure::NotAttempted)
        );
    }

    #[test]
    fn test_line_offset_table_line_start_crlf() {
        let table = LineOffsetTable::new("a\r\nbb\r\nc");
        assert_eq!(table.line_start(0), Some(0));
        assert_eq!(table.line_start(1), Some(3));
        assert_eq!(table.line_start(2), Some(7));
        assert_eq!(table.line_start(3), None);
    }

    #[test]
    fn test_byte_offset_to_position_clamps_to_char_boundary_instead_of_panicking() {
        // "é" is a 2-byte UTF-8 sequence; offset 1 lands inside it.
        let content = "é";
        let table = LineOffsetTable::new(content);
        // Must not panic; clamps down to the nearest boundary (offset 0).
        let pos = table.byte_offset_to_position(content, 1);
        assert_eq!(pos, Position::new(0, 0));
    }

    #[test]
    fn test_byte_offset_to_position_multi_byte_boundary_in_longer_line() {
        let content = "ab é cd";
        let table = LineOffsetTable::new(content);
        // Byte 3 is 'é's leading byte (boundary); byte 4 is its continuation
        // byte (not a boundary) and must clamp back to 3 rather than panic.
        assert!(content.is_char_boundary(3));
        assert!(!content.is_char_boundary(4));
        let pos = table.byte_offset_to_position(content, 4);
        assert_eq!(pos, table.byte_offset_to_position(content, 3));
    }

    /// Covers the ASCII/non-ASCII fast-path split introduced for #742: an ASCII-only line
    /// (line 0), a non-ASCII line mixing a BMP accented character with a surrogate-pair
    /// emoji (line 1), and a mixed line (line 2) must all still resolve to the same
    /// `Position`s as the original `chars().map(char::len_utf16).sum()` scan would produce.
    #[test]
    fn test_byte_offset_to_position_ascii_and_non_ascii_lines_agree() {
        let content = "abcde\nhéllo 😀\nab café end";
        let table = LineOffsetTable::new(content);

        // Line 0 ("abcde"): ASCII fast path, byte offset == UTF-16 character offset.
        assert_eq!(
            table.byte_offset_to_position(content, 3),
            Position::new(0, 3)
        );
        assert_eq!(
            table.byte_offset_to_position(content, 5),
            Position::new(0, 5)
        );

        // Line 1 ("héllo 😀"): non-ASCII scan path.
        // Offset after "h\u{e9}" (1 + 2 bytes into the line): 'h' + 'é' = 2 UTF-16 units.
        assert_eq!(
            table.byte_offset_to_position(content, 6 + 3),
            Position::new(1, 2)
        );
        // Offset at the end of the line: "héllo 😀" = 8 UTF-16 units (emoji is a surrogate pair).
        assert_eq!(
            table.byte_offset_to_position(content, 6 + 11),
            Position::new(1, 8)
        );

        // Line 2 ("ab café end"): mixed line, still takes the non-ASCII scan path.
        // Offset after "ab café" (8 bytes into the line): 7 UTF-16 units ('é' is 1 BMP unit).
        assert_eq!(
            table.byte_offset_to_position(content, 18 + 8),
            Position::new(2, 7)
        );
    }

    /// Regression guard for #742: `byte_offset_to_position` on a large single-line
    /// (minified) manifest must stay near-instant. The pre-fix implementation rescanned
    /// the line from its start on every call, making repeated lookups over such a line
    /// O(n^2) in the line's length (~350ms for 8000 calls on an ~180KB line on the
    /// reporter's machine); the ASCII fast path makes each call O(1), so this generous
    /// wall-clock bound leaves wide margin without being flaky.
    #[test]
    fn test_byte_offset_to_position_minified_line_stays_fast() {
        let mut content = String::from("{\"dependencies\":{");
        for i in 0..8000 {
            content.push_str(&format!("\"dep{i}\":\"1.0.{i}\","));
        }
        content.push_str("}}");

        let table = LineOffsetTable::new(&content);
        let step = (content.len() / 8000).max(1);
        let start = std::time::Instant::now();
        for offset in (0..content.len()).step_by(step) {
            std::hint::black_box(table.byte_offset_to_position(&content, offset));
        }
        let elapsed = start.elapsed();

        assert!(
            elapsed < std::time::Duration::from_millis(100),
            "8000 byte_offset_to_position calls on a minified line took {elapsed:?}, expected < 100ms"
        );
    }

    /// Regression guard for #882 (widened scope): `byte_offset_to_position`'s non-ASCII branch
    /// used to walk `chars().map(len_utf16).sum()` from the line's start on every call, so N
    /// lookups on the same wide non-ASCII line cost O(N x line length) — the same shape #882
    /// reported for `marker_byte_offset`, and, per the #882 review, ~300x its cost since
    /// `make_range` calls this twice per dependency. The shared per-line index makes every
    /// lookup after the first on a given line O(1).
    #[test]
    fn test_byte_offset_to_position_non_ascii_line_cache_stays_fast_on_a_huge_single_line() {
        let filler = "x".repeat(200 * 1024);
        let content = format!("{filler}\u{2014}{filler}");
        let table = LineOffsetTable::new(&content);
        let step = (content.len() / 5000).max(1);
        let start = std::time::Instant::now();
        for offset in (0..content.len()).step_by(step) {
            std::hint::black_box(table.byte_offset_to_position(&content, offset));
        }
        assert!(
            start.elapsed() < std::time::Duration::from_secs(1),
            "byte_offset_to_position took {:?} for ~5000 lookups on a huge non-ASCII line, \
             expected well under 1s",
            start.elapsed()
        );
    }

    /// Differential test: the cached non-ASCII path must agree with a plain reimplemented
    /// `chars().map(len_utf16).sum()` walk for every char-boundary offset on a non-ASCII line,
    /// including offsets on more than one non-ASCII line in the same document (cache isolation
    /// across lines, sharing the same underlying index `marker_byte_offset` populates).
    #[test]
    fn test_byte_offset_to_position_non_ascii_cache_matches_char_sum_result_across_lines() {
        fn slow_path(content: &str, line_start: usize, offset: usize) -> u32 {
            u32::try_from(
                content[line_start..offset]
                    .chars()
                    .map(char::len_utf16)
                    .sum::<usize>(),
            )
            .unwrap_or(u32::MAX)
        }

        let content = "\u{1f680}rocket \u{2014} dash\nascii line\n\u{3000}ideographic \u{e9}nd";
        let table = LineOffsetTable::new(content);
        let line_starts = [
            table.line_start(0).unwrap(),
            table.line_start(1).unwrap(),
            table.line_start(2).unwrap(),
        ];
        let line_ends = [line_starts[1] - 1, line_starts[2] - 1, content.len()];

        for (line, (&line_start, &line_end)) in line_starts.iter().zip(&line_ends).enumerate() {
            let line_text = &content[line_start..line_end];
            for (byte_offset, _) in line_text
                .char_indices()
                .chain(std::iter::once((line_text.len(), '\0')))
            {
                let offset = line_start + byte_offset;
                assert_eq!(
                    table.byte_offset_to_position(content, offset).character,
                    slow_path(content, line_start, offset),
                    "line {line} byte offset {byte_offset} desynced from the char-sum walk"
                );
            }
        }
    }

    #[test]
    fn test_position_in_range_inside() {
        let range = Range::new(Position::new(5, 10), Position::new(5, 20));
        let position = Position::new(5, 15);
        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_at_start() {
        let range = Range::new(Position::new(5, 10), Position::new(5, 20));
        let position = Position::new(5, 10);
        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_at_end() {
        let range = Range::new(Position::new(5, 10), Position::new(5, 20));
        let position = Position::new(5, 20);
        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_before() {
        let range = Range::new(Position::new(5, 10), Position::new(5, 20));
        let position = Position::new(5, 5);
        assert!(!position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_after() {
        let range = Range::new(Position::new(5, 10), Position::new(5, 20));
        let position = Position::new(5, 25);
        assert!(!position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_different_line_before() {
        let range = Range::new(Position::new(5, 10), Position::new(5, 20));
        let position = Position::new(4, 15);
        assert!(!position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_different_line_after() {
        let range = Range::new(Position::new(5, 10), Position::new(5, 20));
        let position = Position::new(6, 15);
        assert!(!position_in_range(position, range));
    }

    #[test]
    fn test_position_in_range_multiline() {
        let range = Range::new(Position::new(5, 10), Position::new(7, 5));
        let position = Position::new(6, 0);
        assert!(position_in_range(position, range));
    }

    #[test]
    fn test_escape_markdown_link_breakout_payload() {
        let payload = "real-pkg](https://legit-looking-typosquat.example/download)[real-pkg";
        let escaped = escape_markdown(payload);
        assert_eq!(
            escaped,
            r"real\-pkg\]\(https\:\/\/legit\-looking\-typosquat\.example\/download\)\[real\-pkg"
        );
        assert!(!escaped.contains("]("));
    }

    #[test]
    fn test_escape_markdown_backslash_and_backtick() {
        assert_eq!(escape_markdown(r"a\b`c"), r"a\\b\`c");
    }

    #[test]
    fn test_escape_markdown_autolink_angle_brackets() {
        // `<...>` around a bare URL is a CommonMark autolink; `<`/`>` must be escaped
        // so it cannot render as a live link independent of the `[]`/`()` escaping.
        let escaped = escape_markdown("pkg <https://evil.example>");
        assert_eq!(escaped, r"pkg \<https\:\/\/evil\.example\>");
        assert!(!escaped.contains('<') || escaped.contains(r"\<"));
    }

    #[test]
    fn test_escape_markdown_control_chars_become_spaces() {
        assert_eq!(escape_markdown("a\nb"), "a b");
        assert_eq!(escape_markdown("a\r\nb"), "a  b");
        assert_eq!(escape_markdown("a\tb"), "a b");
        assert_eq!(escape_markdown("a\0b"), "a b");
    }

    #[test]
    fn test_escape_markdown_newline_cannot_break_out_of_heading() {
        // A raw newline used to terminate the ATX heading line early, letting the
        // rest of the name (potentially another "# [...](...)" sequence) render as
        // separate, unescaped Markdown blocks.
        let escaped = escape_markdown("react\n# [fake](https://evil.example)");
        assert!(!escaped.contains('\n'));
    }

    #[test]
    fn test_escape_markdown_hyphenated_name_round_trips_visually() {
        // Escaping a hyphen (ASCII punctuation) is visually inert on render — CommonMark
        // renders `\-` as a literal `-` — so common package names are unaffected in
        // practice even though the raw Markdown source now escapes them.
        assert_eq!(escape_markdown("tokio-util"), r"tokio\-util");
    }

    #[test]
    fn test_markdown_code_span_plain_content() {
        assert_eq!(markdown_code_span("1.0.0"), "`1.0.0`");
    }

    #[test]
    fn test_markdown_code_span_widens_fence_for_embedded_backticks() {
        assert_eq!(markdown_code_span("a`b"), "``a`b``");
        assert_eq!(markdown_code_span("``double``"), "``` ``double`` ```");
    }

    #[test]
    fn test_markdown_code_span_pads_when_content_starts_or_ends_with_backtick() {
        let span = markdown_code_span("`leading");
        assert!(span.starts_with("`` `"));
    }

    #[test]
    fn test_markdown_code_span_replaces_control_chars() {
        let span = markdown_code_span("1.0\n[evil](https://evil.example)");
        assert!(!span.contains('\n'));
    }

    #[test]
    fn test_markdown_code_span_empty_content() {
        assert_eq!(markdown_code_span(""), "` `");
    }

    #[test]
    fn test_markdown_code_span_backtick_payload_cannot_break_span() {
        // A payload attempting to close the code span early and splice in a live
        // link must not succeed regardless of backtick count in the content.
        let payload = "1.0` <https://evil.example>` more";
        let span = markdown_code_span(payload);
        // The fence must be strictly longer than any backtick run in the (sanitized)
        // content, so no substring of `span` after the opening fence can act as a
        // closing fence before the real one.
        let opening_fence_len = span.chars().take_while(|&c| c == '`').count();
        let inner = &span[opening_fence_len..span.len() - opening_fence_len];
        assert!(
            !inner.contains(&"`".repeat(opening_fence_len)),
            "content contains a run of backticks as long as the fence: {span}"
        );
    }

    #[test]
    fn test_is_same_major_minor_full_match() {
        assert!(is_same_major_minor("1.2.3", "1.2.9"));
    }

    #[test]
    fn test_is_same_major_minor_exact_match() {
        assert!(is_same_major_minor("1.2.3", "1.2.3"));
    }

    #[test]
    fn test_is_same_major_minor_major_only_match() {
        assert!(is_same_major_minor("1", "1.2.3"));
        assert!(is_same_major_minor("1.2.3", "1"));
    }

    #[test]
    fn test_is_same_major_minor_no_match_different_minor() {
        assert!(!is_same_major_minor("1.2.3", "1.3.0"));
    }

    #[test]
    fn test_is_same_major_minor_no_match_different_major() {
        assert!(!is_same_major_minor("1.2.3", "2.2.3"));
    }

    #[test]
    fn test_is_same_major_minor_empty_strings() {
        assert!(!is_same_major_minor("", ""));
        assert!(!is_same_major_minor("1.2.3", ""));
        assert!(!is_same_major_minor("", "1.2.3"));
    }

    #[test]
    fn test_is_safe_version_string_accepts_ordinary_versions() {
        assert!(is_safe_version_string("1.2.3"));
        assert!(is_safe_version_string("1.2.3-beta.1+build"));
        assert!(is_safe_version_string("v1.2.3"));
    }

    #[test]
    fn test_is_safe_version_string_rejects_empty_or_whitespace() {
        assert!(!is_safe_version_string(""));
        assert!(!is_safe_version_string("   "));
        assert!(!is_safe_version_string("\t\n"));
    }

    #[test]
    fn test_is_safe_version_string_rejects_control_and_structural_characters() {
        for bad in [
            "1.2.3\n",
            "1.2.3\t",
            "1.2.3\"",
            "1.2.3'",
            "1.2.3<",
            "1.2.3>",
            "1.2.3&",
            "1.2.3\\",
            "1.0.0\", \"malicious\": \"true",
        ] {
            assert!(
                !is_safe_version_string(bad),
                "expected {bad:?} to be rejected"
            );
        }
    }

    #[test]
    fn test_is_safe_version_string_rejects_gradle_interpolation_payload() {
        // Regression (critic S2): `$`/`{`/`}` are outside the allowlist, so a
        // Gradle Kotlin/Groovy `${...}` interpolation payload written into
        // build.gradle(.kts) can never reach a version literal via this gate.
        for bad in ["1.0${System.getenv(\"X\")}", "1.0$var", "${evil}"] {
            assert!(
                !is_safe_version_string(bad),
                "expected {bad:?} to be rejected"
            );
        }
    }

    #[test]
    fn test_is_safe_version_string_rejects_invisible_unicode() {
        // Regression (critic M1): `char::is_control()` alone only covers
        // category Cc — format/separator characters like the bidi override
        // U+202E, zero-width space U+200B, and the JS/JSON5 line terminators
        // U+2028/U+2029 must also be rejected by the allowlist.
        for bad in ["1.2.3\u{202E}", "1.2.3\u{200B}", "1.2.3\u{2028}"] {
            assert!(
                !is_safe_version_string(bad),
                "expected {bad:?} to be rejected"
            );
        }
    }

    #[test]
    fn test_is_safe_version_string_accepts_pep440_epoch() {
        // PEP 440 epochs (`1!2.0`) are legitimate PyPI versions.
        assert!(is_safe_version_string("1!2.0"));
    }

    #[test]
    fn test_is_safe_version_string_length_cap() {
        assert!(is_safe_version_string(&"1".repeat(64)));
        assert!(!is_safe_version_string(&"1".repeat(65)));
    }

    #[test]
    fn test_is_safe_maven_coordinate_segment_accepts_real_ids() {
        assert!(is_safe_maven_coordinate_segment("org.apache.commons"));
        assert!(is_safe_maven_coordinate_segment("commons-lang3"));
        assert!(is_safe_maven_coordinate_segment("jackson-core_2.13"));
    }

    #[test]
    fn test_is_safe_maven_coordinate_segment_rejects_empty() {
        assert!(!is_safe_maven_coordinate_segment(""));
    }

    #[test]
    fn test_is_safe_maven_coordinate_segment_rejects_xml_structural_characters() {
        for bad in [
            "commons</artifactId><parent>",
            "commons\"",
            "commons'",
            "commons&amp;",
            "commons\nlang3",
            "commons\tlang3",
        ] {
            assert!(
                !is_safe_maven_coordinate_segment(bad),
                "expected {bad:?} to be rejected"
            );
        }
    }

    #[test]
    fn test_is_safe_maven_coordinate_segment_rejects_group_artifact_colon() {
        assert!(!is_safe_maven_coordinate_segment(
            "org.apache.commons:commons-lang3"
        ));
    }

    #[test]
    fn test_is_safe_maven_coordinate_segment_length_cap() {
        assert!(is_safe_maven_coordinate_segment(&"a".repeat(128)));
        assert!(!is_safe_maven_coordinate_segment(&"a".repeat(129)));
    }

    #[test]
    fn test_is_safe_registry_url_accepts_real_urls() {
        assert!(is_safe_registry_url("https://github.com/apple/swift-nio"));
        assert!(is_safe_registry_url(
            "https://github.com/apple/swift-nio.git"
        ));
        assert!(is_safe_registry_url("https://github.com/apple/swift%2Dnio"));
    }

    #[test]
    fn test_is_safe_registry_url_rejects_non_https_scheme() {
        // Every real Swift package registry response is HTTPS; accepting `http://` would
        // only hand a compromised registry a transport-downgrade lever.
        assert!(!is_safe_registry_url("http://example.com/repo"));
        assert!(!is_safe_registry_url("file:///etc/passwd"));
        assert!(!is_safe_registry_url("javascript:alert(1)"));
        assert!(!is_safe_registry_url("ftp://example.com/repo"));
        assert!(!is_safe_registry_url(""));
    }

    #[test]
    fn test_is_safe_registry_url_rejects_swift_string_literal_breakout() {
        for bad in [
            "https://evil.example\", .exact(\"1.0.0\")), .package(url: \"https://real",
            "https://evil.example\\",
            "https://evil.example\nlet x = 1",
            "https://evil.example`echo`",
            "https://evil.example<script>",
        ] {
            assert!(
                !is_safe_registry_url(bad),
                "expected {bad:?} to be rejected"
            );
        }
    }

    #[test]
    fn test_is_safe_registry_url_length_cap() {
        let prefix = "https://example.com/";
        let at_cap = format!("{prefix}{}", "a".repeat(2048 - prefix.len()));
        assert_eq!(at_cap.len(), 2048);
        assert!(is_safe_registry_url(&at_cap));

        let over_cap = format!("{at_cap}a");
        assert_eq!(over_cap.len(), 2049);
        assert!(!is_safe_registry_url(&over_cap));
    }

    #[test]
    fn test_is_safe_package_name_accepts_real_names_across_ecosystems() {
        for good in [
            "serde",                            // Cargo
            "requests",                         // PyPI
            "@scope/name",                      // npm/Deno scoped
            "monolog/monolog",                  // Composer vendor/package
            "github.com/org/repo",              // Go module path
            "path",                             // Dart
            "org.apache.commons:commons-lang3", // Gradle group:artifact
            "Newtonsoft.Json",                  // NuGet
            "rails",                            // Bundler
            "npm:react",                        // Deno npm-scheme specifier
            "jsr:@std/fs",                      // Deno jsr-scheme specifier
            "github.com/foo/bar~compat",        // Go path element with `~`
        ] {
            assert!(
                is_safe_package_name(good),
                "expected {good:?} to be accepted"
            );
        }
    }

    #[test]
    fn test_is_safe_package_name_rejects_empty() {
        assert!(!is_safe_package_name(""));
    }

    #[test]
    fn test_is_safe_package_name_rejects_non_ascii() {
        // Deliberately excluded: the allowlist is ASCII-only, so a legacy non-ASCII
        // npm package name (a handful exist, e.g. Unicode-normalized scopes) is
        // rejected rather than risking homograph/normalization tricks in a manifest.
        assert!(!is_safe_package_name("café"));
        assert!(!is_safe_package_name("пакет"));
    }

    #[test]
    fn test_is_safe_package_name_accepts_dot_dot_shapes() {
        // `.`/`/` are individually legal (PyPI dotted names, npm/Composer scopes), so
        // `..`/`../..` pass the charset too. This is not a path-traversal risk: every
        // sink treats `name` as manifest text (a TOML/JSON/YAML/XML value or a
        // string-literal argument), never as a filesystem path.
        assert!(is_safe_package_name(".."));
        assert!(is_safe_package_name("../.."));
    }

    #[test]
    fn test_is_safe_package_name_rejects_structural_breakout_characters() {
        for bad in [
            "evil\"\nbackdoor = \"9.9.9",
            "evil\", git = \"https://evil",
            "evil\\",
            "evil'",
            "evil<script>",
            "evil`echo`",
            "evil\ninjected = true",
            "evil\tname",
        ] {
            assert!(
                !is_safe_package_name(bad),
                "expected {bad:?} to be rejected"
            );
        }
    }

    #[test]
    fn test_is_safe_package_name_length_cap() {
        assert!(is_safe_package_name(&"a".repeat(256)));
        assert!(!is_safe_package_name(&"a".repeat(257)));
    }

    #[test]
    fn test_is_same_major_minor_partial_versions() {
        assert!(is_same_major_minor("1.2", "1.2.3"));
        assert!(is_same_major_minor("1.2.3", "1.2"));
    }

    #[test]
    fn test_ecosystem_formatter_defaults() {
        let formatter = MockFormatter;
        assert_eq!(
            formatter.normalize_package_name(&pkg("test-pkg")),
            "test-pkg"
        );
        assert_eq!(formatter.yanked_message(), "This version has been yanked");
        assert_eq!(formatter.yanked_label(), "*(yanked)*");
    }

    #[test]
    fn test_format_version_replacing_for_default_delegates_to_format_version_replacing() {
        let formatter = MockFormatter;
        let dep = MockDep {
            name: pkg("test-pkg"),
            version_req: VersionReq::new("1.0.0"),
            version_range: Range::default(),
            name_range: Range::default(),
        };
        assert_eq!(
            formatter.format_version_replacing_for(&dep, &ConcreteVersion::new("1.2.3"), "1.0.0"),
            formatter.format_version_replacing(&ConcreteVersion::new("1.2.3"), "1.0.0")
        );
    }

    #[test]
    fn test_ecosystem_formatter_version_satisfies() {
        let formatter = MockFormatter;

        assert!(formatter.version_satisfies_requirement(&ConcreteVersion::new("1.2.3"), "1.2.3"));

        assert!(formatter.version_satisfies_requirement(&ConcreteVersion::new("1.2.3"), "^1.2"));
        assert!(formatter.version_satisfies_requirement(&ConcreteVersion::new("1.2.3"), "~1.2"));

        assert!(formatter.version_satisfies_requirement(&ConcreteVersion::new("1.2.3"), "1"));
        assert!(formatter.version_satisfies_requirement(&ConcreteVersion::new("1.2.3"), "1.2"));

        assert!(!formatter.version_satisfies_requirement(&ConcreteVersion::new("1.2.3"), "2.0.0"));
        assert!(!formatter.version_satisfies_requirement(&ConcreteVersion::new("1.2.3"), "1.3"));
    }

    #[test]
    fn test_ecosystem_formatter_custom_normalize() {
        struct PyPIFormatter;

        impl PackageNaming for PyPIFormatter {
            fn normalize_package_name(&self, name: &PackageName) -> String {
                name.as_str().to_lowercase().replace('-', "_")
            }
        }

        impl PackageRendering for PyPIFormatter {
            fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
                format!(
                    ">={},<{}",
                    version,
                    version.as_str().split('.').next().unwrap_or("0")
                )
            }

            fn package_url(&self, name: &PackageName) -> String {
                format!("https://pypi.org/project/{}", name)
            }
        }

        impl RequirementResolution for PyPIFormatter {}

        impl DiagnosticMessages for PyPIFormatter {}

        impl DiagnosticPolicy for PyPIFormatter {}

        impl SourcePolicy for PyPIFormatter {}

        impl OsvNaming for PyPIFormatter {}

        let formatter = PyPIFormatter;
        assert_eq!(
            formatter.normalize_package_name(&pkg("Test-Package")),
            "test_package"
        );
        assert_eq!(
            formatter.format_version_for_text_edit(&ConcreteVersion::new("1.2.3")),
            ">=1.2.3,<1"
        );
        assert_eq!(
            formatter.package_url(&pkg("requests")),
            "https://pypi.org/project/requests"
        );
    }
}