deps-core 3.0.0

Core abstractions for deps-lsp: caching, errors, and traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
//! Shared git-tags-datasource parser scaffolding, extracted from
//! `deps-github-actions`'s originally crate-private `parser.rs`/`formatter.rs` helpers so a
//! second git-tags-shaped ecosystem (GitLab CI) can reuse the same hardened span/text
//! plumbing instead of forking it. `deps-github-actions` now imports these instead of
//! defining them locally.

use super::{
    BoundedVersionReq, CommentTag, LineOffsetTable, RequirementStatus, concrete_pin_version,
};
use crate::EcosystemId;
use crate::pagination::ListCoverage;
use crate::position::Range;
use yaml_rust2::parser::Tag;
use yaml_rust2::scanner::{Marker, TScalarStyle};

#[cfg(feature = "lsp-responses")]
use super::diagnostics::MAX_VERSION_DIAGNOSTIC_CHARS;
#[cfg(feature = "lsp-responses")]
use super::{EcosystemFormatter, markdown_code_span, single_file_edit};
#[cfg(feature = "lsp-responses")]
use crate::{Dependency, ParseResult};
#[cfg(feature = "lsp-responses")]
use tower_lsp_server::ls_types::{CodeAction, CodeActionKind, Position, TextEdit, WorkspaceEdit};

/// Length of a full, lowercase-or-not hex commit SHA (git's SHA-1 object id).
pub(super) const SHA_LEN: usize = 40;

/// The conventional 7-character display prefix of a commit SHA (the whole string when shorter).
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::short_sha;
///
/// assert_eq!(short_sha(&"a".repeat(40)), "aaaaaaa");
/// assert_eq!(short_sha("abc"), "abc");
/// ```
#[must_use]
pub fn short_sha(sha: &str) -> &str {
    sha.get(..7).unwrap_or(sha)
}

/// Whether `s` is a 40-character hex string — a git commit SHA shape, shared by every
/// ecosystem resolving refs against a git-tags-datasource API (GitHub, GitLab).
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::is_full_sha;
///
/// assert!(is_full_sha(&"a".repeat(40)));
/// assert!(!is_full_sha(&"a".repeat(39)));
/// assert!(!is_full_sha("not-a-sha"));
/// ```
#[must_use]
pub fn is_full_sha(s: &str) -> bool {
    s.len() == SHA_LEN && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// A validated, lowercase-canonical, full 40-hex-character git commit SHA.
///
/// Equality and hashing are therefore independent of the case a pin was written in:
/// registries report lowercase hex, while a manifest may spell the SHA in uppercase. The
/// only constructor is [`CommitSha::parse`], which routes every value through
/// [`is_full_sha`] — the shared allowlist gate for the one registry-controlled string in
/// each git-tags-datasource ecosystem (GitHub Actions, GitLab CI) that is later spliced
/// verbatim into a manifest text edit and a hover string with no other validation (security
/// S-3). Once constructed, a caller holding a `CommitSha` never needs to re-check it.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct CommitSha(String);

impl CommitSha {
    /// Validates `s` as a full 40-hex-character commit SHA via [`is_full_sha`].
    ///
    /// The text is stored lowercased: [`is_full_sha`] accepts uppercase hex, and registries
    /// report lowercase, so the canonical form is what makes `CommitSha` values comparable.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::CommitSha;
    ///
    /// assert!(CommitSha::parse(&"a".repeat(40)).is_some());
    /// assert!(CommitSha::parse("not-a-sha").is_none());
    /// assert_eq!(CommitSha::parse(&"A".repeat(40)), CommitSha::parse(&"a".repeat(40)));
    /// ```
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        is_full_sha(s).then(|| Self(s.to_ascii_lowercase()))
    }

    /// The validated SHA text, lowercase.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for CommitSha {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// Per-repository/per-route tag/SHA cross-reference, shared by every git-tags-datasource
/// ecosystem (GitHub Actions, GitLab CI).
///
/// Populated on every successful tags/releases fetch (the response already carries the
/// commit SHA — zero extra requests). Read by each ecosystem's formatter to resolve a
/// SHA-pin edit's replacement text and by a hover override to resolve a tag or SHA's
/// counterpart for display.
///
/// [`Self::from_tags`] fills both directions together, so an index built that way never
/// disagrees with itself about a published tag. A cross-crate integration test that exercises
/// the shared `deps_core::collect_update_all_edits`/hover machinery — which never itself drives
/// a live registry fetch — seeds a repository's entry with it. [`Self::insert_sha_pin`] is the
/// one explicit override: it writes the SHA -> tag direction alone, for a caller that must
/// state a SHA's alias classification itself, and so can make the two directions differ.
#[non_exhaustive]
#[derive(Debug, Default)]
pub struct TagIndex {
    /// Tag/release text (as published) -> the commit SHA it points at.
    tag_to_sha: std::collections::HashMap<String, CommitSha>,
    /// Commit SHA -> the tag/release it corresponds to, classified at insertion time so a
    /// tag can never be read back without knowing whether it is a moving alias.
    sha_to_tag: std::collections::HashMap<CommitSha, ResolvedPin>,
    canonical_repo_name: Option<crate::github::CanonicalRepoName>,
    coverage: ListCoverage,
}

/// Which release tags on a commit [`TagIndex::resolved_release`] reports as siblings of its
/// primary tag.
///
/// Ordered from narrowest to widest; an ecosystem merging several readings of one key keeps the
/// widest.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::SiblingScope;
///
/// assert!(SiblingScope::SameMajor < SiblingScope::WholeCommit);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SiblingScope {
    /// Only tags of the primary's own major line, as for an exact-tag pin.
    SameMajor,
    /// Every release tag on the commit, as for a SHA pin that names the commit itself.
    WholeCommit,
}

/// Other release tags sharing a commit with a [`ResolvedPin`]'s primary tag.
///
/// Each has the same specificity class as the primary (a full-semver release next to a
/// full-semver release, or a `major.minor` release that no other tag extends next to another),
/// so each is as valid a name for the commit as the primary. Pre-release and non-semver tags
/// are never siblings. The list is sorted deterministically (lowest version first) and
/// excludes the primary and spelling duplicates (`4.8.0` next to `v4.8.0`). It can only be
/// built inside `deps-core` from a [`TagIndex`]; a scan receives it only through
/// [`crate::lsp_helpers::InUseVersions`]. [`Default`] is the empty list.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{CommitSha, SiblingTags, TagIndex};
///
/// assert!(SiblingTags::default().is_empty());
///
/// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
/// let index = TagIndex::from_tags([("v4.8.0", &sha), ("v4.9.0", &sha), ("v4.9.1-rc1", &sha)]);
/// let pin = index.resolved_pin(&sha).unwrap();
/// let siblings: Vec<&str> = pin.siblings().iter().map(|t| t.as_str()).collect();
/// assert_eq!(siblings, ["v4.9.0"]);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SiblingTags(Vec<crate::ConcreteVersion>);

impl SiblingTags {
    pub(crate) fn from_candidates<'a>(
        primary: &str,
        names: impl IntoIterator<Item = &'a str>,
    ) -> Self {
        let class = tag_specificity_rank(primary).0;
        let (kind, _, is_release) = class;
        if !is_release || !matches!(kind, FULL_SEMVER_KIND | PARTIAL_SEMVER_KIND) {
            return Self::default();
        }
        let primary_normalized = crate::github::normalize_tag(primary);
        let mut ranked: Vec<(TagRank<'a>, &'a str)> = names
            .into_iter()
            .map(|n| (tag_specificity_rank(n), n))
            .collect();
        let all: Vec<&str> = ranked.iter().map(|(_, n)| *n).collect();
        ranked.retain(|(rank, n)| {
            rank.0 == class
                && crate::github::normalize_tag(n) != primary_normalized
                && (kind == FULL_SEMVER_KIND
                    || (tag_components(n).all(|c| c.parse::<u64>().is_ok())
                        && !all.iter().any(|other| extends_tag(other, n))))
        });
        ranked.sort_by(|a, b| b.0.cmp(&a.0));
        ranked.dedup_by(|a, b| {
            crate::github::normalize_tag(a.1) == crate::github::normalize_tag(b.1)
        });
        Self(
            ranked
                .into_iter()
                .map(|(_, n)| crate::ConcreteVersion::new(n))
                .collect(),
        )
    }

    /// The sibling tags, lowest version first.
    pub fn iter(&self) -> std::slice::Iter<'_, crate::ConcreteVersion> {
        self.0.iter()
    }

    /// Whether the primary tag is the only release name on its commit.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// The number of sibling tags.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.0.len()
    }
}

impl<'a> IntoIterator for &'a SiblingTags {
    type Item = &'a crate::ConcreteVersion;
    type IntoIter = std::slice::Iter<'a, crate::ConcreteVersion>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// A tag resolved from a commit SHA, classified by whether it names a release or is a
/// moving alias of a more specific tag on the same commit.
///
/// Produced by [`TagIndex::resolved_pin`]; consumed by
/// [`crate::lsp_helpers::resolve_in_use_version`], which is the only place that decides
/// whether the tag is precise enough to query a vulnerability database with. Both variants
/// carry the other release tags on the same commit ([`SiblingTags`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedPin {
    /// No other tag on the same commit extends this one, so it is the most specific name the
    /// repository published for the commit (`v2.9` next to `v2`, but also a lone `v2`).
    MostSpecific {
        /// The tag text, verbatim as published.
        tag: crate::ConcreteVersion,
        /// Other release tags on the same commit.
        siblings: SiblingTags,
    },
    /// Another tag on the same commit extends this one (`v2` next to `v2.9`): a moving alias.
    Alias {
        /// The tag text, verbatim as published.
        tag: crate::ConcreteVersion,
        /// Other release tags on the same commit.
        siblings: SiblingTags,
    },
}

impl ResolvedPin {
    /// A [`Self::MostSpecific`] pin without siblings.
    #[must_use]
    pub fn most_specific(tag: crate::ConcreteVersion) -> Self {
        Self::MostSpecific {
            tag,
            siblings: SiblingTags::default(),
        }
    }

    /// An [`Self::Alias`] pin without siblings.
    #[must_use]
    pub fn alias(tag: crate::ConcreteVersion) -> Self {
        Self::Alias {
            tag,
            siblings: SiblingTags::default(),
        }
    }

    /// The tag text, verbatim as published.
    #[must_use]
    pub const fn version(&self) -> &crate::ConcreteVersion {
        match self {
            Self::MostSpecific { tag, .. } | Self::Alias { tag, .. } => tag,
        }
    }

    /// Other release tags on the same commit as [`Self::version`].
    #[must_use]
    pub const fn siblings(&self) -> &SiblingTags {
        match self {
            Self::MostSpecific { siblings, .. } | Self::Alias { siblings, .. } => siblings,
        }
    }
}

/// [`tag_specificity_rank`] class kind of a full `major.minor.patch` semver name.
const FULL_SEMVER_KIND: u8 = 2;
/// [`tag_specificity_rank`] class kind of a partial numeric name (`v2`, `v2.9`).
const PARTIAL_SEMVER_KIND: u8 = 1;

/// Sort key of [`tag_specificity_rank`]: class, then numeric version order (lower wins), then name.
type TagRank<'a> = (
    (u8, usize, bool),
    std::cmp::Reverse<Option<semver::Version>>,
    std::cmp::Reverse<Vec<u64>>,
    std::cmp::Reverse<&'a str>,
);

/// Specificity rank of a tag name when several share one commit: a full semver name beats a
/// partial numeric one (more components wins), which beats any non-semver name; within a
/// rank a release beats a pre-release of it, the numerically lower version wins (`v4.9.0`
/// over `v4.10.0`), and the lexicographically smaller name breaks any remaining tie so the
/// choice never depends on fetch order.
///
/// The winner is the commit's primary tag; the other names of its class become its
/// [`SiblingTags`], which the OSV scan evaluates as well.
fn tag_specificity_rank(name: &str) -> TagRank<'_> {
    let normalized = crate::github::normalize_tag(name);
    let is_release = !normalized.contains(['-', '+']);
    let (class, semver, numeric) = if let Ok(v) = semver::Version::parse(normalized) {
        ((FULL_SEMVER_KIND, 0, is_release), Some(v), Vec::new())
    } else if is_partial_semver_shaped(name) {
        let numeric = normalized
            .split(['-', '+'])
            .next()
            .unwrap_or_default()
            .split('.')
            .map(|c| c.parse().unwrap_or(u64::MAX))
            .collect();
        (
            (
                PARTIAL_SEMVER_KIND,
                tag_components(name).count(),
                is_release,
            ),
            None,
            numeric,
        )
    } else {
        ((0, 0, false), None, Vec::new())
    };
    (
        class,
        std::cmp::Reverse(semver),
        std::cmp::Reverse(numeric),
        std::cmp::Reverse(name),
    )
}

fn tag_components(name: &str) -> impl Iterator<Item = &str> {
    crate::github::normalize_tag(name).split('.')
}

/// Whether `longer` extends `shorter` by at least one more dot-separated component.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::extends_tag;
///
/// assert!(extends_tag("v4.2.2", "v4"));
/// assert!(!extends_tag("v5.0.0", "v4"));
/// assert!(!extends_tag("v4", "v4"));
/// ```
#[must_use]
pub fn extends_tag(longer: &str, shorter: &str) -> bool {
    let mut longer = tag_components(longer);
    tag_components(shorter).all(|c| longer.next() == Some(c)) && longer.next().is_some()
}

/// How a partial release tag (`v4`, `v4.2`) written in a manifest is judged against the newest
/// release by [`tag_pin_is_up_to_date`].
///
/// Exhaustive so each ecosystem states which reading its ref syntax has.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartialTagPolicy {
    /// A partial tag names a moving line that follows the newest release of that line
    /// (GitHub Actions `uses: owner/repo@v4`).
    MovingLine,
    /// A partial tag is just a literal tag name, current only when it is the newest tag.
    Exact,
}

/// Pre-release labels a partial release core may carry (`v2-beta`) and still be ordered.
const PRERELEASE_LABELS: [&str; 10] = [
    "alpha", "beta", "rc", "pre", "preview", "dev", "canary", "next", "nightly", "snapshot",
];

/// Whether `suffix` (starting at `-` or `+`) reads as a pre-release or build marker rather than
/// a variant name such as `-node20`.
fn is_prerelease_suffix(suffix: &str) -> bool {
    let Some(rest) = suffix.strip_prefix('-') else {
        return true;
    };
    let rest = rest.to_ascii_lowercase();
    let (label, tail) = rest.split_at(
        rest.find(|c: char| !c.is_ascii_alphabetic())
            .unwrap_or(rest.len()),
    );
    PRERELEASE_LABELS.contains(&label) && tail.chars().all(|c| c.is_ascii_digit() || c == '.')
}

/// Whether `tag` is a bare partial release: one or two all-digit components, no suffix. A
/// ref without a `v` prefix (`@4`) is one too, unlike a free-text comment token.
fn is_bare_partial_release(tag: &str) -> bool {
    tag_components(tag).count() < 3
        && tag_components(tag).all(|c| !c.is_empty() && c.bytes().all(|b| b.is_ascii_digit()))
}

/// A bare partial release zero-padded to a full version (`v4` -> `4.0.0`).
fn padded_release(tag: &str) -> Option<semver::Version> {
    if !is_bare_partial_release(tag) {
        return None;
    }
    let normalized = crate::github::normalize_tag(tag);
    let padding = ".0".repeat(3usize.checked_sub(tag_components(tag).count())?);
    semver::Version::parse(&format!("{normalized}{padding}")).ok()
}

/// Parses a full-semver `tag` (optional `v`/`V` prefix) with build metadata dropped.
fn comparable_version(tag: &str) -> Option<semver::Version> {
    let mut version = semver::Version::parse(crate::github::normalize_tag(tag)).ok()?;
    version.build = semver::BuildMetadata::EMPTY;
    Some(version)
}

/// Parses `tag` into a precedence-comparable semver version, build metadata dropped.
///
/// A partial release core with a recognized pre-release suffix (`v2-beta`, `v2.1-rc`) is padded
/// to three components (`2.0.0-beta`, `2.1.0-rc`); a bare partial release (`v4`) has no
/// precedence of its own and yields `None`, as does a variant suffix (`v3-node20`).
fn orderable_tag(tag: &str) -> Option<semver::Version> {
    let normalized = crate::github::normalize_tag(tag);
    let mut version = match semver::Version::parse(normalized) {
        Ok(version) => version,
        Err(_) if is_partial_semver_shaped(tag) => {
            let (core, suffix) = normalized.split_at(normalized.find(['-', '+'])?);
            if !is_prerelease_suffix(suffix) {
                return None;
            }
            let padding = ".0".repeat(3usize.checked_sub(core.split('.').count())?);
            semver::Version::parse(&format!("{core}{padding}{suffix}")).ok()?
        }
        Err(_) => return None,
    };
    version.build = semver::BuildMetadata::EMPTY;
    Some(version)
}

/// Whether [`tag_pin_is_up_to_date`] can place `tag` on the version line at all.
///
/// `false` for a tag-shaped ref that is no version (`v1.x`, a release-line branch) or carries a
/// variant suffix (`v3-node20`); an ecosystem whose refs may be branches treats those as
/// unknown rather than outdated.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::tag_has_precedence;
///
/// assert!(tag_has_precedence("v4"));
/// assert!(tag_has_precedence("v2-beta"));
/// assert!(tag_has_precedence("v4.2.0"));
/// assert!(!tag_has_precedence("v1.x"));
/// assert!(!tag_has_precedence("v3-node20"));
/// ```
#[must_use]
pub fn tag_has_precedence(tag: &str) -> bool {
    is_bare_partial_release(tag) || orderable_tag(tag).is_some()
}

/// Where a version tag written in a manifest sits relative to the newest release `latest`, as
/// decided by [`tag_pin_position`].
///
/// Exhaustive so a consumer must decide what each position means: only [`Self::Behind`] is
/// outdated, and only [`Self::Ahead`] is a claim a complete tag index can disprove.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TagPinPosition {
    /// The same tag as `latest` (ignoring a `v` prefix), or the same version by precedence.
    Equal,
    /// A partial release (`v4`) that follows the line `latest` belongs to, or a tag extending a
    /// less precise `latest`.
    MovingLine,
    /// A version above `latest` by precedence: a pre-release of a newer line, or a bare partial
    /// release whose zero-padded version is strictly higher. Such a tag may not exist at all.
    Ahead,
    /// Below `latest`, or placed on no version line.
    Behind,
}

/// Positions a version tag written in a manifest relative to the newest release `latest`.
///
/// Rules, in order: the same tag (ignoring a `v` prefix) is [`TagPinPosition::Equal`]; under
/// [`PartialTagPolicy::MovingLine`] a partial release (`v4`, `v4.2`) that `latest` extends, and a
/// written tag that extends a less precise `latest`, are [`TagPinPosition::MovingLine`];
/// otherwise both tags are compared by semver precedence, so a pre-release of an older line
/// (`v2-beta` against `v7.0.0`) is [`TagPinPosition::Behind`] while a pin above `latest` is
/// [`TagPinPosition::Ahead`]. A bare partial release whose zero-padded version is strictly
/// ahead of `latest` (`v5` against `v4.9.0`) is `Ahead` too. Anything else without precedence
/// (`v4.x`, a bare partial release under [`PartialTagPolicy::Exact`]) is `Behind`.
#[must_use]
pub(crate) fn tag_pin_position(
    written: &str,
    latest: &str,
    policy: PartialTagPolicy,
) -> TagPinPosition {
    use crate::github::normalize_tag;

    if normalize_tag(written) == normalize_tag(latest) {
        return TagPinPosition::Equal;
    }
    if policy == PartialTagPolicy::MovingLine
        && ((is_bare_partial_release(written) && extends_tag(latest, written))
            || extends_tag(written, latest))
    {
        return TagPinPosition::MovingLine;
    }
    let latest_version = orderable_tag(latest);
    if matches!(
        (padded_release(written), &latest_version),
        (Some(written), Some(latest)) if written > *latest
    ) {
        return TagPinPosition::Ahead;
    }
    match (orderable_tag(written), latest_version) {
        (Some(written), Some(latest)) => match written.cmp(&latest) {
            std::cmp::Ordering::Greater => TagPinPosition::Ahead,
            std::cmp::Ordering::Equal => TagPinPosition::Equal,
            std::cmp::Ordering::Less => TagPinPosition::Behind,
        },
        _ => TagPinPosition::Behind,
    }
}

/// Whether a version tag written in a manifest is at least as new as the newest release `latest`.
///
/// `true` unless `written` is behind `latest`: the same tag, a moving line, or a pin ahead of
/// `latest` (which is not offered a downgrade).
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{PartialTagPolicy, tag_pin_is_up_to_date};
///
/// assert!(tag_pin_is_up_to_date("v4", "v4.3.1", PartialTagPolicy::MovingLine));
/// assert!(!tag_pin_is_up_to_date("v4", "v4.3.1", PartialTagPolicy::Exact));
/// assert!(!tag_pin_is_up_to_date("v2-beta", "v7.0.0", PartialTagPolicy::MovingLine));
/// assert!(tag_pin_is_up_to_date("v5.0.0-rc.1", "v4.9.0", PartialTagPolicy::Exact));
/// ```
#[must_use]
pub fn tag_pin_is_up_to_date(written: &str, latest: &str, policy: PartialTagPolicy) -> bool {
    tag_pin_position(written, latest, policy) != TagPinPosition::Behind
}

impl TagIndex {
    /// Builds a `TagIndex` from `(name, sha)` pairs, preferring the most specific name when
    /// several entries share one SHA.
    ///
    /// A bare-major moving tag like `v3`/`v4` (or a non-semver release name) is a less
    /// specific name than the precise release the SHA was actually cut from, and the fetch
    /// API's ordering is undocumented, so "first in the response" is not a reliable proxy for
    /// "most specific". The SHA -> tag map therefore ranks the names sharing a SHA: a full
    /// semver name first, then a partial numeric one with more components (`v2.9` over `v2`),
    /// then anything else; a release beats a pre-release of it, and remaining ties resolve
    /// to the smaller name. The chosen name is stored as [`ResolvedPin::Alias`] when another
    /// name on the same SHA still extends it, else as [`ResolvedPin::MostSpecific`].
    /// The tag -> SHA direction has no such ambiguity (keyed by the caller's own literal ref
    /// text), so it stays a plain first-wins index over `entries`' order.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, TagIndex};
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// // "v1" (a bare-major moving tag) is listed before "v0.1.0" (the precise release) —
    /// // the SHA -> tag map must still prefer the more specific name.
    /// let index = TagIndex::from_tags([("v1", &sha), ("v0.1.0", &sha)]);
    /// assert_eq!(index.tag_for_sha(&sha), Some("v0.1.0"));
    /// assert_eq!(index.sha_for_tag("v1"), Some(&sha));
    /// ```
    #[must_use]
    pub fn from_tags<'a, I>(entries: I) -> Self
    where
        I: IntoIterator<Item = (&'a str, &'a CommitSha)>,
    {
        let mut index = Self::default();
        let mut names_by_sha: std::collections::HashMap<&CommitSha, Vec<&str>> =
            std::collections::HashMap::new();
        for (name, sha) in entries {
            names_by_sha.entry(sha).or_default().push(name);
            index
                .tag_to_sha
                .entry(name.to_string())
                .or_insert_with(|| sha.clone());
        }
        for (sha, names) in names_by_sha {
            let Some(best) = names
                .iter()
                .copied()
                .max_by_key(|n| tag_specificity_rank(n))
            else {
                continue;
            };
            let siblings = SiblingTags::from_candidates(best, names.iter().copied());
            let tag = crate::ConcreteVersion::new(best);
            let pin = if names.iter().any(|other| extends_tag(other, best)) {
                ResolvedPin::Alias { tag, siblings }
            } else {
                ResolvedPin::MostSpecific { tag, siblings }
            };
            index.sha_to_tag.insert(sha.clone(), pin);
        }
        index
    }

    /// The commit SHA the tag or release text `tag` points at, keyed by the literal text as
    /// published (`v4`, not a normalized spelling).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, TagIndex};
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4", &sha)]);
    /// assert_eq!(index.sha_for_tag("v4"), Some(&sha));
    /// assert_eq!(index.sha_for_tag("v5"), None);
    /// ```
    #[must_use]
    pub fn sha_for_tag(&self, tag: &str) -> Option<&CommitSha> {
        self.tag_to_sha.get(tag)
    }

    /// Resolves the exact tag `written` (`v4.8.0`) to a pin whose primary is that tag itself,
    /// with the other release tags of the same major line on its commit as siblings.
    ///
    /// Shorthand for [`Self::resolved_release`] with [`SiblingScope::SameMajor`]. Unlike
    /// [`Self::resolved_pin`] the primary is never re-picked: the user wrote that tag. `None`
    /// when `written` is not in the index.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, TagIndex};
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4.8.0", &sha), ("v4.9.0", &sha), ("v5.0.0", &sha)]);
    /// let pin = index.resolved_exact_tag("v4.8.0").unwrap();
    /// assert_eq!(pin.version().as_str(), "v4.8.0");
    /// assert_eq!(pin.siblings().len(), 1);
    /// assert!(index.resolved_exact_tag("v9.9.9").is_none());
    /// ```
    #[must_use]
    pub fn resolved_exact_tag(&self, written: &str) -> Option<ResolvedPin> {
        self.resolved_release(written, SiblingScope::SameMajor)
    }

    /// Resolves the tag `tag` (exact key text) to a pin whose primary is that tag, with the
    /// other release tags on its commit that `scope` admits as siblings.
    ///
    /// `None` when `tag` is not a key of the index.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, SiblingScope, TagIndex};
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4.8.0", &sha), ("v4.9.0", &sha), ("v5.0.0", &sha)]);
    /// let same_major = index.resolved_release("v4.8.0", SiblingScope::SameMajor).unwrap();
    /// assert_eq!(same_major.siblings().len(), 1);
    /// let whole_commit = index.resolved_release("v4.8.0", SiblingScope::WholeCommit).unwrap();
    /// assert_eq!(whole_commit.siblings().len(), 2);
    /// ```
    #[must_use]
    pub fn resolved_release(&self, tag: &str, scope: SiblingScope) -> Option<ResolvedPin> {
        let sha = self.tag_to_sha.get(tag)?;
        let major = tag_components(tag).next();
        let names: Vec<&str> = self
            .tag_to_sha
            .iter()
            .filter(|(name, other)| {
                *other == sha
                    && match scope {
                        SiblingScope::SameMajor => tag_components(name).next() == major,
                        SiblingScope::WholeCommit => true,
                    }
            })
            .map(|(name, _)| name.as_str())
            .collect();
        let siblings = SiblingTags::from_candidates(tag, names.iter().copied());
        let primary = crate::ConcreteVersion::new(tag);
        Some(if names.iter().any(|other| extends_tag(other, tag)) {
            ResolvedPin::Alias {
                tag: primary,
                siblings,
            }
        } else {
            ResolvedPin::MostSpecific {
                tag: primary,
                siblings,
            }
        })
    }

    /// The index key naming the release `version`, tolerating a `v`/`V` prefix mismatch.
    ///
    /// Every key equal to `version` after [`crate::github::normalize_tag`] is considered. `None`
    /// when there is none, or when they point at different commits, an exact key included: an
    /// ambiguous spelling is never resolved by ranking, because the text a later edit writes may
    /// be spelled differently from `version`. Otherwise the exact key if present, else the
    /// smallest matching key.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, TagIndex};
    ///
    /// let a = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let b = CommitSha::parse(&"b".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4.1.3", &a), ("v5.0.0", &a), ("5.0.0", &b)]);
    /// assert_eq!(index.release_tag("v4.1.3"), Some("v4.1.3"));
    /// assert_eq!(index.release_tag("4.1.3"), Some("v4.1.3"));
    /// assert_eq!(index.release_tag("5.0.0"), None);
    /// assert_eq!(index.release_tag("v5.0.0"), None);
    /// assert_eq!(index.release_tag("v9.9.9"), None);
    /// ```
    #[must_use]
    pub fn release_tag(&self, version: &str) -> Option<&str> {
        let normalized = crate::github::normalize_tag(version);
        let mut matches = self
            .tag_to_sha
            .iter()
            .filter(|(key, _)| crate::github::normalize_tag(key) == normalized);
        let (first_key, first_sha) = matches.next()?;
        let mut chosen = first_key.as_str();
        for (key, sha) in matches {
            if sha != first_sha {
                return None;
            }
            chosen = chosen.min(key.as_str());
        }
        Some(
            self.tag_to_sha
                .get_key_value(version)
                .map_or(chosen, |(key, _)| key.as_str()),
        )
    }

    /// The index key naming the release `version` and the commit it points at, for rewriting a
    /// SHA pin to that release (`<sha> # <key>`).
    ///
    /// An exact key wins even when a differently spelled twin (`4.1.3` beside `v4.1.3`) points
    /// elsewhere: git resolves the written text exactly, so that is the tag the user meant.
    /// Without an exact key this is [`Self::release_tag`], so a fix version `4.1.3` finds
    /// `v4.1.3` and the comment is written in the key's own spelling, while conflicting twins
    /// yield `None`.
    ///
    /// Callers rewriting a pin to an OSV fix version must first verify that version through
    /// [`Self::release_tag`] (the sibling lookup of a fix-target check does): the exact-key
    /// preference alone would bind `4.1.3` to a twin spelling's commit.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, TagIndex};
    ///
    /// let a = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let b = CommitSha::parse(&"b".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4.1.3", &a), ("5.0.0", &a), ("v5.0.0", &b)]);
    /// let (tag, sha) = index.release_commit("4.1.3").unwrap();
    /// assert_eq!((tag.as_str(), &sha), ("v4.1.3", &a));
    /// assert_eq!(index.release_commit("5.0.0").unwrap().1, a);
    /// assert!(index.release_commit("v9.9.9").is_none());
    /// ```
    #[must_use]
    pub fn release_commit(&self, version: &str) -> Option<(crate::ConcreteVersion, CommitSha)> {
        let (key, sha) = self.tag_to_sha.get_key_value(version).or_else(|| {
            let key = self.release_tag(version)?;
            self.tag_to_sha.get_key_value(key)
        })?;
        Some((crate::ConcreteVersion::new(key), sha.clone()))
    }

    /// Attaches the repository's canonical casing as reported by GitHub.
    #[must_use]
    pub fn with_canonical_repo_name(
        mut self,
        name: Option<crate::github::CanonicalRepoName>,
    ) -> Self {
        self.canonical_repo_name = name;
        self
    }

    /// Records whether the fetch that built this index reached the end of the tag list.
    ///
    /// [`Self::default`] and [`Self::from_tags`] start as [`ListCoverage::Complete`].
    #[must_use]
    pub const fn with_coverage(mut self, coverage: ListCoverage) -> Self {
        self.coverage = coverage;
        self
    }

    /// Whether the index covers every tag of the repository, so absence of a SHA is meaningful.
    #[must_use]
    pub const fn coverage(&self) -> ListCoverage {
        self.coverage
    }

    /// The repository's canonical `owner/repo` casing, `None` when no fetched tag confirmed it.
    #[must_use]
    pub const fn canonical_repo_name(&self) -> Option<&crate::github::CanonicalRepoName> {
        self.canonical_repo_name.as_ref()
    }

    /// Records `pin` as the tag resolved for `sha`, replacing any previous entry.
    ///
    /// For callers that build an index by hand (e.g. cross-crate tests) instead of via
    /// [`Self::from_tags`], and so must state the alias classification explicitly.
    pub fn insert_sha_pin(&mut self, sha: CommitSha, pin: ResolvedPin) {
        self.sha_to_tag.insert(sha, pin);
    }

    /// The tag published at `sha`, classified as a release name or a moving alias.
    ///
    /// `None` when no tag points at `sha`.
    #[must_use]
    pub fn resolved_pin(&self, sha: &CommitSha) -> Option<ResolvedPin> {
        self.sha_to_tag.get(sha).cloned()
    }

    /// The tag text published at `sha`, without its alias classification.
    #[must_use]
    pub fn tag_for_sha(&self, sha: &CommitSha) -> Option<&str> {
        self.sha_to_tag.get(sha).map(|pin| pin.version().as_str())
    }

    /// What the index proves about `sha`: the tag naming it, that no release tag names it, that
    /// the comment beside it names another commit, or nothing.
    ///
    /// [`PinResolution::Untagged`] requires a populated, [`ListCoverage::Complete`] index that
    /// lacks `sha`; an empty index is [`PinResolution::Unresolved`]. A populated
    /// [`ListCoverage::Truncated`] index which lacks `sha` is [`PinResolution::Unlisted`],
    /// except that one which maps the full-version `comment` to a different commit is
    /// [`PinResolution::CommentContradicted`]. A moving-alias comment (`# v4`) is never
    /// contradicted, since such a tag legitimately drifts.
    ///
    /// A comment naming a full version the truncated index does not list at all (a forged
    /// `# v99.0.0`) is [`PinResolution::Unlisted`], not trusted.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, PinResolution, TagIndex};
    /// use deps_core::pagination::ListCoverage;
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let other = CommitSha::parse(&"b".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v1.0.0", &sha)]);
    /// assert!(matches!(index.pin_resolution(&sha, None), PinResolution::Resolved { .. }));
    /// assert_eq!(index.pin_resolution(&other, None), PinResolution::Untagged);
    /// assert_eq!(TagIndex::default().pin_resolution(&other, None), PinResolution::Unresolved);
    /// let truncated = TagIndex::from_tags([("v1.0.0", &sha)]).with_coverage(ListCoverage::Truncated);
    /// assert_eq!(truncated.pin_resolution(&other, None), PinResolution::Unlisted);
    /// ```
    #[must_use]
    pub fn pin_resolution(&self, sha: &CommitSha, comment: Option<&CommentTag>) -> PinResolution {
        if let Some(pin) = self.sha_to_tag.get(sha) {
            return PinResolution::Resolved {
                pin: pin.clone(),
                sibling_coverage: self.coverage,
            };
        }
        if self.is_empty() {
            return PinResolution::Unresolved;
        }
        match self.coverage {
            ListCoverage::Complete => PinResolution::Untagged,
            ListCoverage::Truncated if self.comment_names_other_commit(sha, comment) => {
                PinResolution::CommentContradicted
            }
            ListCoverage::Truncated => PinResolution::Unlisted,
        }
    }

    /// What the index proves about a pin written as the exact tag `written` (`v4.8.0`).
    ///
    /// [`PinResolution::Resolved`] when the tag is listed, with [`Self::resolved_exact_tag`]'s
    /// siblings. A tag missing from a populated [`ListCoverage::Truncated`] index is
    /// [`PinResolution::Unlisted`], since the list may simply not reach it; missing from a
    /// complete index it is [`PinResolution::Unpublished`] when the ref has a full release shape
    /// ([`UnpublishedRef::Release`]), otherwise, like on an empty index, [`PinResolution::Unresolved`].
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, PinResolution, TagIndex};
    /// use deps_core::pagination::ListCoverage;
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let complete = TagIndex::from_tags([("v4.8.0", &sha)]);
    /// assert!(matches!(complete.exact_tag_resolution("v4.8.0"), PinResolution::Resolved { .. }));
    /// assert_eq!(complete.exact_tag_resolution("v4.9.0"), PinResolution::Unpublished);
    /// assert_eq!(TagIndex::default().exact_tag_resolution("v4.9.0"), PinResolution::Unresolved);
    /// let truncated = TagIndex::from_tags([("v4.8.0", &sha)]).with_coverage(ListCoverage::Truncated);
    /// assert_eq!(truncated.exact_tag_resolution("v4.9.0"), PinResolution::Unlisted);
    /// ```
    #[must_use]
    pub fn exact_tag_resolution(&self, written: &str) -> PinResolution {
        match self.resolved_exact_tag(written) {
            Some(pin) => PinResolution::Resolved {
                pin,
                sibling_coverage: self.coverage,
            },
            None => match self.unpublished_tag_ref(written) {
                Some(UnpublishedRef::Release) => PinResolution::Unpublished,
                Some(UnpublishedRef::Partial) | None => self.unlisted_or_unresolved(),
            },
        }
    }

    /// What the index proves about a pin written as the floating tag `written` (`v4`, `v4.1`).
    ///
    /// Resolves through the commit `written` currently points at, to the most specific release
    /// that equals or extends `written` on that commit: a commit that also carries an unrelated
    /// `v5.0.0` is not reported as that version. [`PinResolution::Unresolved`] when `written`
    /// names no release on its commit. A `written` that a populated [`ListCoverage::Truncated`]
    /// index does not list is [`PinResolution::Unlisted`], and an unlisted one on a complete
    /// index [`PinResolution::Unresolved`]. The sub-selection never narrows
    /// [`PinResolution::Resolved`]'s `sibling_coverage`: it is this index's own.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, PinResolution, TagIndex};
    /// use deps_core::pagination::ListCoverage;
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4", &sha), ("v4.2.0", &sha), ("v5.0.0", &sha)])
    ///     .with_coverage(ListCoverage::Truncated);
    /// let PinResolution::Resolved { pin, sibling_coverage } = index.floating_tag_resolution("v4")
    /// else {
    ///     panic!("v4 resolves");
    /// };
    /// assert_eq!(pin.version().as_str(), "v4.2.0");
    /// assert_eq!(sibling_coverage, ListCoverage::Truncated);
    /// ```
    #[must_use]
    pub fn floating_tag_resolution(&self, written: &str) -> PinResolution {
        let Some(commit) = self.tag_to_sha.get(written) else {
            return self.unlisted_or_unresolved();
        };
        let candidates = self
            .tag_to_sha
            .iter()
            .filter(|(tag, sha)| {
                *sha == commit && (tag.as_str() == written || extends_tag(tag, written))
            })
            .map(|(tag, sha)| (tag.as_str(), sha));
        Self::from_tags(candidates)
            .resolved_pin(commit)
            .map_or(PinResolution::Unresolved, |pin| PinResolution::Resolved {
                pin,
                sibling_coverage: self.coverage,
            })
    }

    /// What the index proves about a pin written as the tag `written` of `ecosystem`: an exact
    /// release ([`Self::exact_tag_resolution`]) when `written` is concrete under
    /// [`concrete_pin_version`], a floating major/minor ([`Self::floating_tag_resolution`]) when
    /// it is a partial semver shape, and [`PinResolution::Unresolved`] for any other text (a
    /// branch name, a date, free text).
    ///
    /// The one classification both git-tags ecosystems (GitHub Actions, GitLab CI) share, so a
    /// tag pin resolves the same way in each.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::EcosystemId;
    /// use deps_core::lsp_helpers::{CommitSha, PinResolution, TagIndex};
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4", &sha), ("v4.8.0", &sha)]);
    /// let resolve = |written| index.tag_pin_resolution(written, EcosystemId::GitlabCi);
    /// assert!(matches!(resolve("v4.8.0"), PinResolution::Resolved { .. }));
    /// assert_eq!(resolve("v4.9.0"), PinResolution::Unpublished);
    /// assert!(matches!(resolve("v4"), PinResolution::Resolved { .. }));
    /// assert_eq!(resolve("main"), PinResolution::Unresolved);
    /// ```
    #[must_use]
    pub fn tag_pin_resolution(&self, written: &str, ecosystem: EcosystemId) -> PinResolution {
        if concrete_pin_version(written, ecosystem).is_some() {
            self.exact_tag_resolution(written)
        } else if is_partial_semver_shaped(written) {
            self.floating_tag_resolution(written)
        } else {
            PinResolution::Unresolved
        }
    }

    /// Caps an up-to-date status read from the text of a tag pin `written` that this index
    /// proves unpublished (see [`Self::unpublished_tag_ref`] and [`UnpublishedRef::cap_status`]):
    /// a full release at any position, a partial shape only when ahead of `latest`. Any other
    /// pin, and an index that cannot prove absence, leave `status`.
    #[must_use]
    pub fn cap_status_if_unpublished(
        &self,
        written: &str,
        latest: &str,
        policy: PartialTagPolicy,
        status: RequirementStatus,
    ) -> RequirementStatus {
        self.unpublished_tag_ref(written).map_or(status, |kind| {
            kind.cap_status(written, latest, policy, status)
        })
    }

    /// Caps a status read from the text of the tag pin `written` to never up to date when a
    /// populated [`ListCoverage::Truncated`] index does not list that exact tag (#1769): the
    /// list may simply not reach it, so the text cannot prove it current. Any other index leaves
    /// `status`; an outdated status stays outdated.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, RequirementStatus, TagIndex};
    /// use deps_core::pagination::ListCoverage;
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let truncated = TagIndex::from_tags([("v4.8.0", &sha)]).with_coverage(ListCoverage::Truncated);
    /// let up = RequirementStatus::UpToDate;
    /// assert_eq!(truncated.cap_status_if_tag_unlisted("v9.0.0", up), RequirementStatus::Unresolved);
    /// assert_eq!(truncated.cap_status_if_tag_unlisted("v4.8.0", up), up);
    /// let complete = TagIndex::from_tags([("v4.8.0", &sha)]);
    /// assert_eq!(complete.cap_status_if_tag_unlisted("v9.0.0", up), up);
    /// ```
    #[must_use]
    pub fn cap_status_if_tag_unlisted(
        &self,
        written: &str,
        status: RequirementStatus,
    ) -> RequirementStatus {
        if matches!(self.unlisted_or_unresolved(), PinResolution::Unlisted)
            && !self.tag_to_sha.contains_key(written)
        {
            status.never_up_to_date()
        } else {
            status
        }
    }

    /// [`PinResolution::Unlisted`] for a populated truncated index, else
    /// [`PinResolution::Unresolved`].
    fn unlisted_or_unresolved(&self) -> PinResolution {
        match self.coverage {
            ListCoverage::Truncated if !self.is_empty() => PinResolution::Unlisted,
            ListCoverage::Truncated | ListCoverage::Complete => PinResolution::Unresolved,
        }
    }

    /// Whether `comment` is a full version that this index maps to a commit other than `sha`.
    ///
    /// Tags are matched by version (`v` prefix and build metadata ignored), so a spelling
    /// variant (`# 2.87.22`, `# V2.87.22`) cannot dodge the check. A comment is contradicted
    /// only when no tag of that version points at `sha`.
    fn comment_names_other_commit(&self, sha: &CommitSha, comment: Option<&CommentTag>) -> bool {
        let Some(wanted) = comment
            .filter(|tag| tag.is_full_version())
            .and_then(|tag| comparable_version(tag.as_str()))
        else {
            return false;
        };
        let mut named_elsewhere = false;
        for (name, commit) in &self.tag_to_sha {
            if comparable_version(name).as_ref() == Some(&wanted) {
                if commit == sha {
                    return false;
                }
                named_elsewhere = true;
            }
        }
        named_elsewhere
    }

    /// What the index proves about a tag-shaped ref `written` (`4.3.1`, `v40`) that no tag of
    /// that exact text matches: `None` when the ref is listed, is not tag-shaped, or the index
    /// cannot speak for absence (empty or [`ListCoverage::Truncated`]).
    ///
    /// Git refs are exact, so `4.3.1` is missing from a repository that only tags `v4.3.1`. The
    /// [`UnpublishedRef`] says how plausible a branch of that name is; see its variants.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, TagIndex, UnpublishedRef};
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4.3.1", &sha)]);
    /// assert_eq!(index.unpublished_tag_ref("4.3.1"), Some(UnpublishedRef::Release));
    /// assert_eq!(index.unpublished_tag_ref("v40"), Some(UnpublishedRef::Partial));
    /// assert_eq!(index.unpublished_tag_ref("v4.3.1"), None);
    /// ```
    #[must_use]
    pub fn unpublished_tag_ref(&self, written: &str) -> Option<UnpublishedRef> {
        if self.coverage != ListCoverage::Complete
            || self.is_empty()
            || !is_tag_shaped(written)
            || self.tag_to_sha.contains_key(written)
        {
            return None;
        }
        Some(if is_release_shaped(written) {
            UnpublishedRef::Release
        } else {
            UnpublishedRef::Partial
        })
    }

    /// Whether a SHA pin can be rewritten to the release `version` using this index (#1779).
    ///
    /// [`CommitRewrite::NoReleaseTag`] only when the index is populated and
    /// [`ListCoverage::Complete`] yet names no release `version`: absence is then proven.
    /// An empty or truncated index cannot prove it, so that is
    /// [`CommitRewrite::IndexUnavailable`] (as is a missing index, which the caller reports
    /// itself).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitRewrite, CommitSha, TagIndex};
    /// use deps_core::pagination::ListCoverage;
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v4.1.3", &sha)]);
    /// assert_eq!(index.commit_rewrite_to("4.1.3"), CommitRewrite::Resolved);
    /// assert_eq!(index.commit_rewrite_to("9.9.9"), CommitRewrite::NoReleaseTag);
    /// let truncated = TagIndex::from_tags([("v4.1.3", &sha)]).with_coverage(ListCoverage::Truncated);
    /// assert_eq!(truncated.commit_rewrite_to("9.9.9"), CommitRewrite::IndexUnavailable);
    /// assert_eq!(TagIndex::default().commit_rewrite_to("9.9.9"), CommitRewrite::IndexUnavailable);
    /// ```
    #[must_use]
    pub fn commit_rewrite_to(&self, version: &str) -> CommitRewrite {
        if self.release_commit(version).is_some() {
            CommitRewrite::Resolved
        } else if self.coverage == ListCoverage::Complete && !self.is_empty() {
            CommitRewrite::NoReleaseTag
        } else {
            CommitRewrite::IndexUnavailable
        }
    }

    /// Whether the index holds no tag in either direction.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.tag_to_sha.is_empty() && self.sha_to_tag.is_empty()
    }

    /// Whether `other` differs from `self` in anything a finding is derived from: the
    /// tag-to-commit mapping, the list coverage, or the canonical repository name.
    ///
    /// Drives [`crate::TagIndexRefreshSender`]: a refetch that changes none of these cannot
    /// change a finding, so it must not trigger a rescan.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{CommitSha, TagIndex};
    /// use deps_core::pagination::ListCoverage;
    ///
    /// let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let complete = TagIndex::from_tags([("v1", &sha)]);
    /// let same = TagIndex::from_tags([("v1", &sha)]);
    /// let truncated = TagIndex::from_tags([("v1", &sha)]).with_coverage(ListCoverage::Truncated);
    /// assert!(!complete.observably_differs(&same));
    /// assert!(complete.observably_differs(&truncated));
    /// ```
    #[must_use]
    pub fn observably_differs(&self, other: &Self) -> bool {
        self.tag_to_sha != other.tag_to_sha
            || self.coverage != other.coverage
            || self.canonical_repo_name != other.canonical_repo_name
    }
}

/// Whether a dependency's commit pin can be rewritten to a given release version, as returned
/// by [`super::RequirementResolution::commit_rewrite_for`] (#1779).
///
/// Exhaustive so each consumer decides what every state means: only
/// [`Self::NoReleaseTag`] is proof that the fix version has no release tag.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::CommitRewrite;
///
/// assert_ne!(CommitRewrite::NoReleaseTag, CommitRewrite::IndexUnavailable);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommitRewrite {
    /// The dependency is not a commit pin: its rewrite does not depend on a tag index.
    NotACommitPin,
    /// A release tag exists, so the pin can be rewritten to its commit.
    Resolved,
    /// A complete tag list proves no release tag names this version.
    NoReleaseTag,
    /// The tag list is missing, cold, empty or truncated, so the pin's rewrite cannot be
    /// confirmed.
    IndexUnavailable,
}

/// What a repository's [`TagIndex`] proves about a pinned commit, as returned by
/// [`TagIndex::pin_resolution`].
///
/// The variants are exhaustive so a consumer must decide what each means for it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PinResolution {
    /// No out-of-band evidence (empty index, or a pin the index cannot speak about): manifest
    /// text may stand in for the pin's version.
    Unresolved,
    /// The repository's tag list has not been fetched yet (cold cache) or its fetch failed, so
    /// the index cannot speak about a tag pin at all. Manifest text may stand in for the pin's
    /// version, but its sibling tags are unknown: a clean OSV answer is not trustworthy until
    /// a later fetch populates the index.
    NotYetIndexed,
    /// A [`ListCoverage::Truncated`] index does not list the pinned commit or exact tag, so a
    /// tag beyond the fetched list may name it. Manifest text may stand in for the pin's
    /// version, but nothing derived from that text is authoritative: a clean OSV answer is
    /// not trustworthy and a status read from the text never reads as up to date.
    Unlisted,
    /// A truncated index lacks the commit but maps the comment's full-version tag to another
    /// commit, so the comment is provably wrong and must not stand in for the pin's version.
    CommentContradicted,
    /// A tag names the commit.
    Resolved {
        /// The resolved tag and the other release tags on its commit.
        pin: ResolvedPin,
        /// Whether `pin`'s siblings were read from a complete tag list; a truncated one may
        /// have hidden further sibling tags.
        sibling_coverage: ListCoverage,
    },
    /// The index proves no release tag names the commit, so manifest text (a trailing
    /// comment) must not stand in for its version.
    Untagged,
    /// A complete index lists no tag of this exact text for a full-release-shaped tag pin
    /// (`4.2.2` when only `v4.2.2` is published): the ref names no release, so manifest text
    /// must not stand in for its version and a vulnerability answer for that text is not
    /// about this pin.
    Unpublished,
}

/// How plausible it is that a tag-shaped ref no published tag matches is a branch instead, as
/// reported by [`TagIndex::unpublished_tag_ref`].
///
/// Exhaustive so each consumer decides what every shape means. Top actions document branch pins
/// that look like tags (`ruby/setup-ruby@v1`, `pnpm/action-setup@v3`,
/// `aws-actions/configure-aws-credentials@v3-node20`, `codecov/codecov-action@v5.x`), so only a
/// full release shape is reported as unknown.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{PartialTagPolicy, RequirementStatus, UnpublishedRef};
///
/// let capped = |kind: UnpublishedRef, written| {
///     kind.cap_status(written, "v4.3.1", PartialTagPolicy::MovingLine, RequirementStatus::UpToDate)
/// };
/// assert_eq!(capped(UnpublishedRef::Release, "4.3.1"), RequirementStatus::Unresolved);
/// assert_eq!(capped(UnpublishedRef::Partial, "v40"), RequirementStatus::Unresolved);
/// assert_eq!(capped(UnpublishedRef::Partial, "v1"), RequirementStatus::UpToDate);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnpublishedRef {
    /// A full release (`4.3.1`, `v4.3.10`, `v5.0.0-rc.1`: a plain `major.minor.patch` core, or one
    /// with a recognized pre-release label): a branch with that name is implausible, so the ref
    /// names nothing and is unknown at any position.
    Release,
    /// Any other tag-shaped ref (`v1`, `v5.x`, `v3-node20`, `v40`, `v3.4.0-working`): it may be a
    /// branch, so only a ref ahead of the newest release is distrusted, and it is not reported.
    Partial,
}

impl UnpublishedRef {
    /// Caps a status read from the text of an unpublished ref: it never reads as up to date when
    /// the ref is a [`Self::Release`], or a [`Self::Partial`] ahead of `latest`. An outdated
    /// status stays outdated, since the bump target is valid either way.
    #[must_use]
    pub fn cap_status(
        self,
        written: &str,
        latest: &str,
        policy: PartialTagPolicy,
        status: RequirementStatus,
    ) -> RequirementStatus {
        if status != RequirementStatus::UpToDate {
            return status;
        }
        match self {
            Self::Release => RequirementStatus::Unresolved,
            Self::Partial => {
                if tag_pin_position(written, latest, policy) == TagPinPosition::Ahead {
                    RequirementStatus::Unresolved
                } else {
                    status
                }
            }
        }
    }
}

/// Whether `tag` is a full release: a plain `major.minor.patch` core, optionally with a
/// recognized pre-release label (`rc`, `beta`, ...); a branch named like it is implausible.
fn is_release_shaped(tag: &str) -> bool {
    comparable_version(tag).is_some_and(|version| {
        version.pre.is_empty() || is_prerelease_suffix(&format!("-{}", version.pre.as_str()))
    })
}

/// Where a tag that names a pinned commit sits relative to the newest release, by version.
///
/// Decided by [`tag_pin_is_up_to_date`] under [`PartialTagPolicy::Exact`]: a commit tagged only
/// by a moving alias (`v1`, `1.1`) is not `latest`'s commit, so the alias counts as
/// [`Self::BelowLatest`] unless its zero-padded version is strictly ahead of `latest`
/// (`v1.10` over `v1.9.0`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TagPosition {
    /// The tag is at or above `latest`: a pre-release of a newer line (`v2.0.0-rc1` over
    /// `1.9.0`) counts, as semver orders it above the older release.
    AtOrAboveLatest,
    /// The tag is below `latest`, or has no version order (`cargo-deny`, `v3-node20`).
    BelowLatest,
}

impl TagPosition {
    /// Positions `tag` relative to `latest`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::TagPosition;
    ///
    /// assert_eq!(TagPosition::of("v1", "v1.5.0"), TagPosition::BelowLatest);
    /// assert_eq!(TagPosition::of("v1.10", "v1.9.0"), TagPosition::AtOrAboveLatest);
    /// assert_eq!(TagPosition::of("cargo-deny", "v1.5.0"), TagPosition::BelowLatest);
    /// ```
    #[must_use]
    pub fn of(tag: &str, latest: &str) -> Self {
        if tag_pin_is_up_to_date(tag, latest, PartialTagPolicy::Exact) {
            Self::AtOrAboveLatest
        } else {
            Self::BelowLatest
        }
    }
}

/// Outcome of looking a full-SHA pin up in a repository's [`TagIndex`] against the newest
/// release, shared by every tags-datasource ecosystem (GitHub Actions, GitLab CI).
///
/// Callers map each variant to their own status policy; the variants are exhaustive so a
/// new outcome forces every consumer to decide.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShaPinLookup {
    /// The SHA is the commit of `latest`, whatever other tags name it.
    LatestCommit,
    /// A tag other than `latest` names the SHA.
    Indexed {
        /// The tag published at the SHA, verbatim.
        tag: crate::ConcreteVersion,
        /// Where `tag` sits relative to `latest` by version.
        position: TagPosition,
    },
    /// The repository's index is populated, [`ListCoverage::Complete`], and no tag points at
    /// the SHA.
    NotIndexed,
    /// No populated index yet (cold cache): the index says nothing about the SHA, so manifest
    /// text may stand in for its status.
    Unverifiable,
    /// A [`ListCoverage::Truncated`] index lacks the SHA: a tag beyond the fetched list may
    /// name it. Manifest text may stand in for its status, except that it never reads as up to
    /// date.
    Unlisted,
    /// A [`ListCoverage::Truncated`] index lacks the SHA but maps the comment's full-version
    /// tag to another commit: the comment is provably wrong, so neither it nor the SHA vouches
    /// for a status. Its [`Self::status_or_text`] is `Unresolved`, never the text status,
    /// because the comment must not be used as the status fallback.
    CommentContradicted,
}

impl ShaPinLookup {
    /// Looks `sha` up in `index` relative to `latest`.
    ///
    /// A missing or empty `index` yields [`Self::Unverifiable`], and a SHA absent from a
    /// truncated one [`Self::Unlisted`], never [`Self::NotIndexed`], so a cold cache or a capped
    /// tag list is not mistaken for proof that the pin is stale. The one exception is a
    /// full-version `comment` that the truncated index maps to a different commit
    /// ([`Self::CommentContradicted`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    /// use deps_core::lsp_helpers::{CommitSha, ShaPinLookup, TagIndex};
    ///
    /// let sha = CommitSha::parse(&"A".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v1.0.0", &sha)]);
    /// let latest = ConcreteVersion::new("v1.0.0");
    /// assert_eq!(
    ///     ShaPinLookup::resolve(Some(&index), &sha, &latest, None),
    ///     ShaPinLookup::LatestCommit
    /// );
    /// assert_eq!(
    ///     ShaPinLookup::resolve(None, &sha, &latest, None),
    ///     ShaPinLookup::Unverifiable
    /// );
    /// ```
    #[must_use]
    pub fn resolve(
        index: Option<&TagIndex>,
        sha: &CommitSha,
        latest: &crate::ConcreteVersion,
        comment: Option<&CommentTag>,
    ) -> Self {
        let Some(index) = index.filter(|index| !index.is_empty()) else {
            return Self::Unverifiable;
        };
        if index.tag_to_sha.get(latest.as_str()) == Some(sha) {
            return Self::LatestCommit;
        }
        match index.pin_resolution(sha, comment) {
            PinResolution::Resolved { pin, .. } => Self::Indexed {
                tag: pin.version().clone(),
                position: TagPosition::of(pin.version().as_str(), latest.as_str()),
            },
            PinResolution::Untagged => Self::NotIndexed,
            PinResolution::Unresolved
            | PinResolution::Unpublished
            | PinResolution::NotYetIndexed => Self::Unverifiable,
            PinResolution::Unlisted => Self::Unlisted,
            PinResolution::CommentContradicted => Self::CommentContradicted,
        }
    }

    /// Maps the lookup to a [`RequirementStatus`], asking `text` for the manifest-text status
    /// only when the index cannot rule it out.
    ///
    /// [`Self::LatestCommit`] is up to date. [`Self::Indexed`] is up to date only when its
    /// tag is [`TagPosition::AtOrAboveLatest`]: a commit named
    /// only by an outdated moving tag (`v1`) or by a non-version tag (`cargo-deny`) is not
    /// `latest`'s commit and never reads as current by text; an oversized tag is
    /// `Unresolved`. [`Self::NotIndexed`] is `Outdated`: `latest` comes from the same fetch,
    /// so the pin is provably not `latest`'s commit, whatever a trailing `# tag` comment
    /// claims. [`Self::CommentContradicted`] is `Unresolved`: the comment is wrong, so it must
    /// not be trusted, yet the pin's own age is unknown. [`Self::Unverifiable`] is `text()`.
    /// [`Self::Unlisted`] is `text()` with `UpToDate` capped to `Unresolved`: a pin the truncated
    /// list does not reach may be older than any comment claims, whatever the comment's shape
    /// (`# v99.0.0`, `# v99`, a moving `# v4`); an `Outdated` text stays `Outdated`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    /// use deps_core::lsp_helpers::{CommitSha, RequirementStatus, ShaPinLookup, TagIndex};
    ///
    /// let old = CommitSha::parse(&"a".repeat(40)).unwrap();
    /// let new = CommitSha::parse(&"b".repeat(40)).unwrap();
    /// let index = TagIndex::from_tags([("v1", &old), ("v1.5.0", &new)]);
    /// let latest = ConcreteVersion::new("v1.5.0");
    /// let lookup = ShaPinLookup::resolve(Some(&index), &old, &latest, None);
    /// let text = || RequirementStatus::UpToDate;
    /// assert_eq!(lookup.status_or_text(text), RequirementStatus::Outdated);
    /// assert_eq!(ShaPinLookup::LatestCommit.status_or_text(text), RequirementStatus::UpToDate);
    /// assert_eq!(ShaPinLookup::Unverifiable.status_or_text(text), RequirementStatus::UpToDate);
    /// assert_eq!(ShaPinLookup::Unlisted.status_or_text(text), RequirementStatus::Unresolved);
    /// assert_eq!(
    ///     ShaPinLookup::CommentContradicted.status_or_text(text),
    ///     RequirementStatus::Unresolved
    /// );
    /// ```
    #[must_use]
    pub fn status_or_text(self, text: impl FnOnce() -> RequirementStatus) -> RequirementStatus {
        match self {
            Self::LatestCommit => RequirementStatus::UpToDate,
            Self::Indexed { tag, position } => {
                let tag = crate::VersionReq::new(tag.as_str());
                if BoundedVersionReq::new(&tag).is_none() {
                    RequirementStatus::Unresolved
                } else {
                    match position {
                        TagPosition::AtOrAboveLatest => RequirementStatus::UpToDate,
                        TagPosition::BelowLatest => RequirementStatus::Outdated,
                    }
                }
            }
            Self::NotIndexed => RequirementStatus::Outdated,
            Self::CommentContradicted => RequirementStatus::Unresolved,
            Self::Unverifiable => text(),
            Self::Unlisted => text().never_up_to_date(),
        }
    }
}

/// Whether `s` has the shape of a tag ref: an optional leading `v`/`V` followed by a digit.
///
/// Anything else (that isn't an [`is_full_sha`] SHA) is treated as a branch name — the
/// "honest unknown" side, since a branch cannot be resolved to a concrete version without
/// registry access.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::is_tag_shaped;
///
/// assert!(is_tag_shaped("v4"));
/// assert!(is_tag_shaped("4.2.0"));
/// assert!(!is_tag_shaped("main"));
/// assert!(!is_tag_shaped(&"a".repeat(40)));
/// ```
#[must_use]
pub fn is_tag_shaped(s: &str) -> bool {
    if is_full_sha(s) {
        return false;
    }
    let stripped = s.strip_prefix(['v', 'V']).unwrap_or(s);
    stripped.starts_with(|c: char| c.is_ascii_digit())
}

/// Whether `s` has the shape of a version safe to trust from free-text context.
///
/// Unlike [`is_tag_shaped`] (safe for a constrained git-ref domain GitHub itself
/// resolves), this is meant for text a human wrote by hand — e.g. a YAML comment.
///
/// An optional leading `v`/`V`, 1-3 dot-separated all-digit components, and an optional
/// `-`/`+` prerelease/build suffix (accepted, not itself validated) — but, unlike
/// `is_tag_shaped`, a bare all-digit token with **no** `v`/`V` prefix and **no** dot
/// (`1234`, `20240501`, `0`) is rejected: nothing in the shape alone distinguishes an
/// unprefixed integer from an arbitrary numeric annotation a human might write in a
/// comment (a ticket number, a date), whereas `owner/repo@1234` as an actual git *ref* has
/// no such ambiguity — GitHub either has a ref named `1234` or it doesn't (issue #907
/// review finding S1: `deps-github-actions`'s SHA-pin trailing-comment parser had used
/// `is_tag_shaped` and silently treated a genuine non-version annotation as a version).
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::is_partial_semver_shaped;
///
/// assert!(is_partial_semver_shaped("v4"));
/// assert!(is_partial_semver_shaped("v2.9"));
/// assert!(is_partial_semver_shaped("4.2.0"));
/// assert!(is_partial_semver_shaped("v4.2.0-beta.1"));
/// assert!(!is_partial_semver_shaped("1234"));
/// assert!(!is_partial_semver_shaped("20240501"));
/// assert!(!is_partial_semver_shaped("0"));
/// assert!(!is_partial_semver_shaped("2024-01-15"));
/// assert!(!is_partial_semver_shaped("main"));
/// ```
#[expect(
    clippy::string_slice,
    reason = "idx comes from str::find(['-', '+']), both ASCII bytes, so it is always a char \
              boundary; strip_prefix(['v', 'V']) likewise only ever removes a single ASCII byte"
)]
#[must_use]
pub fn is_partial_semver_shaped(s: &str) -> bool {
    let has_v_prefix = s.starts_with(['v', 'V']);
    let stripped = s.strip_prefix(['v', 'V']).unwrap_or(s);
    let core = match stripped.find(['-', '+']) {
        Some(idx) => &stripped[..idx],
        None => stripped,
    };
    let parts: Vec<&str> = core.split('.').collect();
    if parts.len() > 3 || (!has_v_prefix && parts.len() < 2) {
        return false;
    }
    parts
        .iter()
        .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
}

/// Rewrites `tag` to match `current`'s leading `v`/`V` prefix style (or lack of one).
///
/// A repository/project can change its tagging convention over time (`4.0.0` -> `v5.0.0`);
/// a formatted replacement should still read naturally against the user's existing pin
/// style rather than silently flipping it.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::match_v_prefix_style;
///
/// assert_eq!(match_v_prefix_style("v4", "5.0.0"), "v5.0.0");
/// assert_eq!(match_v_prefix_style("4", "v5.0.0"), "5.0.0");
/// ```
#[expect(
    clippy::string_slice,
    reason = "tag[1..] only runs when tag_has_v (an ASCII 'v'/'V' prefix check), so index 1 \
              is always a char boundary"
)]
#[must_use]
pub fn match_v_prefix_style(current: &str, tag: &str) -> String {
    let current_has_v = current.starts_with(['v', 'V']);
    let tag_has_v = tag.starts_with(['v', 'V']);
    match (current_has_v, tag_has_v) {
        (true, false) => format!("v{tag}"),
        (false, true) => tag[1..].to_string(),
        _ => tag.to_string(),
    }
}

/// Whether a plain (unquoted) scalar's text denotes an absent value.
///
/// A completely empty plain scalar (`ref:` with nothing after the colon — the normal
/// mid-typing state in a live editor) is *always* absent, regardless of any tag: `!!str` on
/// no text still means no text was given, not the literal empty string (which needs an
/// actual quoted `""` to express — see the `style == Plain` guard below). For non-empty text
/// (`~`/`null`), an explicit tag matters: untagged or explicitly `tag:yaml.org,2002:null`
/// tagged text still resolves to absent, but any *other* explicit tag (e.g. `!!str`) forces
/// the scalar to that type instead — `!!str null` is the literal string `"null"`, not an
/// absent value.
///
/// The four spellings GitLab's Psych loader treats as null (verified against Ruby Psych
/// 5.3.1 — GitLab's own YAML loader and this function's binding oracle since
/// `deps-gitlab-ci`'s mapping-shaped container-anchor support (spec 058 FR-015) became this
/// function's second consumer): `~`, `null`, `Null`, `NULL`. This is a fixed enumeration, not
/// true case-insensitive matching — `nULL` or `nUll` do **not** match, mirroring Psych's own
/// behavior exactly. Gating on `"~" | "null"` alone (this function's original, `deps-dart`-only,
/// `yaml_rust2::YamlLoader`-mirroring behavior) let a merged-template `ref: NULL` resolve to
/// the literal version string `"NULL"` instead of absent — a plausible-looking wrong
/// version, worse than none (P0).
///
/// A *quoted* empty string (`ref: ""`) is a real, if unusual, explicit value and must not be
/// treated as absent — enforced by the `style == Plain` guard below, not by this list.
///
/// Promoted from `deps-dart/src/parser.rs` (originally private to that crate, and originally
/// scoped only to `yaml_rust2::YamlLoader`'s narrower `"" | "~" | "null"` rule) to
/// `deps-core` once `deps-gitlab-ci`'s mapping-shaped container-anchor support (spec 058
/// FR-015) became its second consumer; `deps-dart` now imports this shared version too,
/// rather than keeping its own duplicate.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::is_plain_null;
/// use yaml_rust2::scanner::TScalarStyle;
///
/// assert!(is_plain_null(TScalarStyle::Plain, None, ""));
/// assert!(is_plain_null(TScalarStyle::Plain, None, "~"));
/// assert!(is_plain_null(TScalarStyle::Plain, None, "null"));
/// assert!(is_plain_null(TScalarStyle::Plain, None, "Null"));
/// assert!(is_plain_null(TScalarStyle::Plain, None, "NULL"));
/// assert!(!is_plain_null(TScalarStyle::DoubleQuoted, None, ""));
/// assert!(!is_plain_null(TScalarStyle::Plain, None, "v1.0.0"));
/// ```
#[must_use]
pub fn is_plain_null(style: TScalarStyle, tag: Option<&Tag>, value: &str) -> bool {
    if style != TScalarStyle::Plain {
        return false;
    }
    if value.is_empty() {
        return true;
    }
    match tag {
        None => matches!(value, "~" | "null" | "Null" | "NULL"),
        Some(tag) => is_null_tag(tag) && matches!(value, "~" | "null" | "Null" | "NULL"),
    }
}

/// Whether `tag` is YAML's `null` tag, in either form `yaml-rust2`'s scanner produces.
///
/// The `!!null` shorthand resolves to `Tag { handle: "tag:yaml.org,2002:", suffix: "null"
/// }`, but the equivalent verbatim form `!<tag:yaml.org,2002:null>` resolves to `Tag {
/// handle: "", suffix: "tag:yaml.org,2002:null" }` — the whole URI lands in `suffix` with an
/// empty `handle`, since verbatim tags bypass handle resolution entirely.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::is_null_tag;
/// use yaml_rust2::parser::Tag;
///
/// assert!(is_null_tag(&Tag {
///     handle: "tag:yaml.org,2002:".to_string(),
///     suffix: "null".to_string(),
/// }));
/// assert!(!is_null_tag(&Tag {
///     handle: "tag:yaml.org,2002:".to_string(),
///     suffix: "str".to_string(),
/// }));
/// ```
#[must_use]
pub fn is_null_tag(tag: &Tag) -> bool {
    (tag.handle == "tag:yaml.org,2002:" && tag.suffix == "null")
        || (tag.handle.is_empty() && tag.suffix == "tag:yaml.org,2002:null")
}

/// Resolves a `yaml-rust2` scanner marker's `(line, col)` position into a byte offset in
/// `content`, via a shared, once-per-document [`LineOffsetTable`].
///
/// Deliberately does **not** use `yaml_rust2::scanner::Marker::index()` — despite its own
/// doc comment claiming a byte count, `Scanner::scan_block_scalar_content_line`
/// (`yaml-rust2` 0.12.0's `scanner.rs:1778-1779`) advances `mark.index` by the **byte**
/// length of each block-scalar (`|`/`>`) content line, not its char count, once the
/// scanner's internal 16-char lookahead buffer empties mid-line — which happens on
/// essentially every real content line. Every multi-byte UTF-8 character consumed this way
/// desyncs `index` permanently for the rest of the document (#879). `Marker::line()`/
/// `Marker::col()` are unaffected: `col` resets to `0` on every line break
/// (`Scanner::skip_nl`), so the corruption from one block-scalar content line never carries
/// into a later scalar's own `col` — safe for every value this crate resolves spans for
/// (`uses:`, `ref:`, `project:`, `include:`), none of which are themselves inside a block
/// scalar's own content.
///
/// This `line`/`col`-based resolver is a workaround for an upstream `yaml-rust2` 0.12.0 bug
/// (tracked in #880, not yet reported upstream). Do not simplify this back to
/// `Marker::index()`-based resolution without first checking whether the upstream bug has
/// been fixed.
///
/// `line` is 1-indexed and `col` a 0-indexed **char** count within that line, matching
/// `yaml-rust2`'s own `Marker::line()`/`Marker::col()` *behavior* — note that
/// `yaml_rust2::scanner::Marker::col()`'s own doc comment claims 1-indexed while its `Display`
/// impl prints `col + 1`, i.e. the doc is wrong the same way `index()`'s was; do not "fix" the
/// `col.min(...)`/`.nth(col)` arithmetic below to match that prose. Returns `content.len()` if
/// `line` is past the end of `content`. `line` must be `>= 1` (see `debug_assert!` below) —
/// every marker `yaml-rust2` actually emits satisfies this.
///
/// # Line-ending assumption
///
/// Like every other [`LineOffsetTable`] lookup, this counts only `\n` as a line break. A
/// document using bare `\r` (no `\n`) line endings is out of scope: `yaml-rust2` still
/// advances `mark.line` across such a break (`Scanner::skip_nl`), but `LineOffsetTable::new`
/// never splits on a lone `\r`, so `line` can run past the table's line count for any content
/// after the first line — this function then falls back to `content.len()`, and the caller's
/// [`locate_value_span`] fails to find the value, dropping the candidate (logged at `debug`
/// — see its own doc comment) the same way as any other fallback-scan miss.
/// Bare-`\r` YAML is not a realistic manifest shape; LF and CRLF, which `yaml-rust2` and this
/// crate both handle throughout, are unaffected.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{LineOffsetTable, marker_byte_offset};
///
/// let content = "a: b\nc: \u{2014}d\n";
/// let table = LineOffsetTable::new(content);
/// // Line 2 ("c: \u{2014}d"), char column 4 -> the 'd' right after the multi-byte em dash.
/// assert_eq!(marker_byte_offset(content, &table, 2, 4), content.find('d').unwrap());
/// ```
#[must_use]
pub fn marker_byte_offset(
    content: &str,
    table: &LineOffsetTable,
    line: usize,
    col: usize,
) -> usize {
    debug_assert!(line >= 1, "yaml-rust2 marker line is 1-indexed, got 0");
    let Some(line_start) = table.line_start(line.saturating_sub(1)) else {
        return content.len();
    };
    let line_end = table.line_start(line).unwrap_or(content.len());
    let line_text = content.get(line_start..line_end).unwrap_or_default();
    // #742-style fast path: an ASCII line has 1 byte per char, so `col` is already a byte
    // offset — skip the `char_indices()` walk, which made this O(line length) per call.
    let byte_in_line = if table
        .line_is_ascii
        .get(line.saturating_sub(1))
        .copied()
        .unwrap_or(false)
    {
        col.min(line_text.len())
    } else {
        // #882: a naive char_indices().nth(col) walk per call is O(line length); the
        // cached per-line index makes repeat lookups on the same line O(1).
        table.non_ascii_char_byte_offset(line.saturating_sub(1), line_text, col)
    };
    line_start + byte_in_line
}

/// Upper bound, in bytes past `search_from`, on how far [`locate_value_span`]'s fallback
/// scan will search.
///
/// The fallback exists only to correct for `yaml-rust2`'s marker-vs-value quoting offset —
/// a handful of bytes at most for any real manifest value. Leaving the scan unbounded made
/// it an `O(line_length x value_length)` scan over the *rest of the line* regardless of how
/// far away the real match could possibly be: a several-megabyte single-line manifest
/// (comfortably under the crate's YAML expansion-size gate) could cost whole minutes of
/// single-core CPU per `didOpen`/`didChange` (security S-2). Capping the window bounds the
/// fallback's cost independent of line length; a value that genuinely cannot be located
/// within this window is treated the same as any other unlocatable value — the candidate is
/// silently skipped, not an error.
pub const MAX_FALLBACK_SCAN_BYTES: usize = 1024;

/// Finds the byte offset in `content` (searching only within the line starting at
/// `search_from`) where the literal bytes of `value` occur.
///
/// The scanner-reported marker usually points exactly at the value's start for a plain
/// scalar, but may point at the opening quote for a quoted one — rather than
/// reverse-engineering `yaml-rust2`'s exact escaping/quoting byte accounting, this verifies
/// the direct-offset guess first and falls back to a bounded same-line search (see
/// [`MAX_FALLBACK_SCAN_BYTES`]), which is exact for the unescaped ASCII text most manifest
/// values are.
///
/// `is_quoted` disambiguates the empty-value case (see below) — pass
/// [`MarkedScalar::is_quoted`], or the equivalent for a hand-rolled scanner receiver.
///
/// Returns `None` if `search_from` is past the end of `content` (checked first, before the
/// `value.is_empty()` short-circuit below — #673 M2) or `value` cannot be located within
/// the bounded fallback scan — logged at `debug` (value length only, never the value text
/// itself, matching the `warn_rejected_value` convention) so a future resolver miss (e.g.
/// #879's class of bug, or [`marker_byte_offset`]'s documented bare-`\r` gap) is diagnosable
/// instead of vanishing the candidate with zero trace.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::locate_value_span;
///
/// let content = "prefix xxxxx actions/checkout@v4 suffix";
/// let (start, end) = locate_value_span(content, 0, "actions/checkout@v4", false).unwrap();
/// assert_eq!(&content[start..end], "actions/checkout@v4");
/// ```
#[must_use]
pub fn locate_value_span(
    content: &str,
    search_from: usize,
    value: &str,
    is_quoted: bool,
) -> Option<(usize, usize)> {
    let bytes = content.as_bytes();
    // #673: reject an out-of-bounds search_from before the value.is_empty() check below
    // (#673 M2: otherwise an empty value would return Some((search_from, search_from))).
    if search_from > bytes.len() {
        tracing::debug!(
            search_from,
            content_len = bytes.len(),
            "locate_value_span: search_from past end of content"
        );
        return None;
    }
    if value.is_empty() {
        // #1184: a quoted empty scalar (`""`/`''`) has no content bytes for a fallback
        // scan to anchor on, so the marker's own opening-quote-or-not shape is the only
        // signal available — advance past the quote when the raw marker lands on one.
        // Gated on `is_quoted` (a non-heuristic discriminator from the scanner's own
        // reported style — true only for `SingleQuoted`/`DoubleQuoted`, critic M2), not on
        // the marker byte alone and not on `!is_plain`: a `Plain` empty scalar's marker
        // points at the *next token*, not the value itself, and a `Literal`/`Folded`
        // block scalar's empty body is neither plain nor quoted — both cases have an
        // unrelated next token that can itself happen to be a quote byte, which
        // inferring "quoted" from `!is_plain` alone would incorrectly shift into.
        let corrected = if is_quoted {
            match bytes.get(search_from) {
                Some(b'"' | b'\'') => search_from + 1,
                _ => search_from,
            }
        } else {
            search_from
        };
        return Some((corrected, corrected));
    }
    #[expect(
        clippy::indexing_slicing,
        reason = "every slice/index in this block is bounds-checked by the search_from <= \
                  bytes.len() guard above combined with each expression's own <=/.min(...) clamp"
    )]
    {
        if search_from + value.len() <= bytes.len()
            && &bytes[search_from..search_from + value.len()] == value.as_bytes()
        {
            return Some((search_from, search_from + value.len()));
        }
    }
    // #885: bound the window *before* searching for '\n', not after — searching the whole
    // remainder first reintroduces O(remaining-document-length) cost on one huge line even
    // though the resulting scan_end value is the same either way (min is order-independent).
    let window_end = bytes
        .len()
        .min(search_from.saturating_add(MAX_FALLBACK_SCAN_BYTES));
    #[expect(
        clippy::indexing_slicing,
        reason = "window_end = bytes.len().min(...), and search_from <= bytes.len() from the \
                  guard above, so bytes[search_from..window_end] is always in bounds"
    )]
    let scan_end = bytes[search_from..window_end]
        .iter()
        .position(|&b| b == b'\n')
        .map_or(window_end, |p| search_from + p);
    #[expect(
        clippy::indexing_slicing,
        reason = "scan_end is derived from window_end or a position found within \
                  bytes[search_from..window_end], so it stays within [search_from, window_end]"
    )]
    let haystack = &bytes[search_from..scan_end];
    let needle = value.as_bytes();
    let found = haystack
        .windows(needle.len())
        .position(|w| w == needle)
        .map(|rel| (search_from + rel, search_from + rel + needle.len()));
    if found.is_none() {
        tracing::debug!(
            search_from,
            value_len = needle.len(),
            scan_bytes = scan_end - search_from,
            "locate_value_span: value not found within bounded fallback scan"
        );
    }
    found
}

/// Converts a byte span in `content` into an LSP [`Range`] via `table`.
///
/// `deps-gitlab-ci`'s `make_range` and `deps-github-actions`'s `make_range` closure each
/// defined this exact computation byte-for-byte identically before deps-lsp#908 extracted
/// it here. deps-lsp#927 later routed every other ecosystem crate's byte-span-to-`Range`
/// site through this same function: `deps-cargo`, `deps-pypi`, `deps-gradle`, and
/// `deps-nuget` each keep a thin local adapter for their own span shape (a
/// `toml_span::Span`, or a `(usize, usize)` tuple); `deps-swift` keeps its `make_range`
/// closure, which captures `content`/`line_table` to save two arguments across its ~15
/// call sites; `deps-bundler`, `deps-go`, `deps-maven`, `deps-deno`, and `deps-pypi`'s
/// `requirements.rs` call this directly at each bare inline site (`deps-deno` deleted its
/// own byte-identical `byte_range_to_lsp` rather than keep a pointless delegate); `deps-core`'s
/// own `json_ast` module calls it directly at two sites (`quoted_lsp_range`, plus
/// `dependency_position`'s `ObjectPropName::Word` arm). `deps-dart` is a full adopter as
/// well (see [`MarkedScalar::range`], added by deps-lsp#928) — it does not call this
/// function directly, but `MarkedScalar::range` does, on its behalf.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{LineOffsetTable, byte_span_to_range};
///
/// let content = "uses: actions/checkout@v4\n";
/// let table = LineOffsetTable::new(content);
/// let range = byte_span_to_range(content, &table, 6, 26);
/// assert_eq!(range.start.line, 0);
/// assert_eq!(range.start.character, 6);
/// ```
#[must_use]
pub fn byte_span_to_range(
    content: &str,
    table: &LineOffsetTable,
    start: usize,
    end: usize,
) -> Range {
    Range::new(
        table.byte_offset_to_position(content, start),
        table.byte_offset_to_position(content, end),
    )
}

/// A YAML scalar captured directly from `yaml-rust2`'s event stream.
///
/// Holds the scalar's resolved text, its scalar style, and the scanner's own
/// marker — the shape all three `MarkedEventReceiver`-based ecosystem parsers
/// (`deps-dart`, `deps-github-actions`, `deps-gitlab-ci`) build from an
/// `Event::Scalar` payload before resolving a byte span for it.
///
/// Always built via [`MarkedScalar::new`] from a real `&Marker`, never hand-assembled
/// from raw numbers: `line` is 1-indexed and `col` a 0-indexed **char** count, matching
/// `yaml-rust2`'s own `Marker::line()`/`Marker::col()` (see [`marker_byte_offset`]'s
/// docs for why — #879/#882 both trace back to conflating this with a byte count).
///
/// The marker does not always come from the same event as the text/style: `deps-dart`'s
/// `on_alias` (key position) builds a `MarkedScalar` whose marker is the *alias*
/// occurrence's own site but whose text and style are the *anchor* definition's — this is
/// deliberate (the anchor's style is what `is_plain_null` already checked to accept the
/// value), and safe because [`MarkedScalar::span`]/[`MarkedScalar::range`] never read
/// `style`, only `text`/`line`/`col`.
#[derive(Debug, Clone)]
pub struct MarkedScalar {
    text: String,
    style: TScalarStyle,
    line: usize,
    col: usize,
}

impl MarkedScalar {
    /// Builds a `MarkedScalar` from an `Event::Scalar`'s resolved value/style and the
    /// scanner marker it fired at.
    ///
    /// `yaml-rust2`'s `Marker` has no public constructor — a real one is only ever
    /// obtained from a live `MarkedEventReceiver::on_event` callback, as shown here.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::MarkedScalar;
    /// use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser};
    /// use yaml_rust2::scanner::{Marker, TScalarStyle};
    ///
    /// struct Scalars(Vec<(String, TScalarStyle, Marker)>);
    /// impl MarkedEventReceiver for Scalars {
    ///     fn on_event(&mut self, event: Event, marker: Marker) {
    ///         if let Event::Scalar(value, style, ..) = event {
    ///             self.0.push((value, style, marker));
    ///         }
    ///     }
    /// }
    ///
    /// let mut receiver = Scalars(Vec::new());
    /// Parser::new_from_str("uses: v4\n")
    ///     .load(&mut receiver, false)
    ///     .unwrap();
    /// let (value, style, marker) = receiver.0[1].clone(); // the value scalar
    /// let scalar = MarkedScalar::new(value, style, &marker);
    /// assert_eq!(scalar.text(), "v4");
    /// assert!(scalar.is_plain());
    /// ```
    #[must_use]
    pub fn new(text: String, style: TScalarStyle, marker: &Marker) -> Self {
        Self {
            text,
            style,
            line: marker.line(),
            col: marker.col(),
        }
    }

    /// The scalar's resolved (dequoted) text.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Consumes the scalar, returning its resolved text.
    #[must_use]
    pub fn into_text(self) -> String {
        self.text
    }

    /// The YAML scalar style (`Plain`, single/double-quoted, literal/folded block).
    #[must_use]
    pub const fn style(&self) -> TScalarStyle {
        self.style
    }

    /// Whether the scalar was written unquoted.
    #[must_use]
    pub fn is_plain(&self) -> bool {
        self.style == TScalarStyle::Plain
    }

    /// Whether the scalar was written with an explicit quote style
    /// (`SingleQuoted`/`DoubleQuoted`).
    ///
    /// Deliberately not `!is_plain()` (critic M2 on #1184): a `Literal`/`Folded` block
    /// scalar (`ref: |`/`ref: >`) is neither plain nor quoted, and its marker has the
    /// same "points at the next token, not the value" shape as a `Plain` scalar's — so
    /// [`Self::span`]'s empty-value quote-correction must key on this method, not on the
    /// negation of [`Self::is_plain`].
    #[must_use]
    pub fn is_quoted(&self) -> bool {
        matches!(
            self.style,
            TScalarStyle::SingleQuoted | TScalarStyle::DoubleQuoted
        )
    }

    /// The scanner marker's 1-indexed line.
    #[must_use]
    pub const fn line(&self) -> usize {
        self.line
    }

    /// The scanner marker's 0-indexed char column.
    #[must_use]
    pub const fn col(&self) -> usize {
        self.col
    }

    /// Resolves this scalar's **raw, untrimmed** byte span within `content`, via
    /// [`marker_byte_offset`] + [`locate_value_span`].
    ///
    /// This is the load-bearing primitive every caller needing a *sub*-span builds
    /// on: `deps-github-actions` needs `owner/repo@ref`'s ref sub-span
    /// (`span_start + before_at_len + 1`) and `deps-gitlab-ci` needs
    /// `component@version`'s name/version sub-spans (`raw_start + prefix.len()`), and
    /// both derive those from *this* span's start, never from a value this function
    /// re-trims itself.
    ///
    /// Deliberately does **not** trim leading/trailing whitespace off the located
    /// span — a caller with its own trim-aware offset arithmetic (`deps-github-actions`'s
    /// UTF-8-boundary guard for a quoted value with non-ASCII padding is the concrete
    /// case) depends on receiving the untrimmed span and re-anchoring its own
    /// downstream offsets to it; trimming here would silently desync that arithmetic.
    /// Returns `None` on the same misses [`locate_value_span`] does (e.g. a folded or
    /// multiline scalar it cannot locate within its bounded fallback scan).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{LineOffsetTable, MarkedScalar};
    /// use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser};
    /// use yaml_rust2::scanner::{Marker, TScalarStyle};
    ///
    /// struct Scalars(Vec<(String, TScalarStyle, Marker)>);
    /// impl MarkedEventReceiver for Scalars {
    ///     fn on_event(&mut self, event: Event, marker: Marker) {
    ///         if let Event::Scalar(value, style, ..) = event {
    ///             self.0.push((value, style, marker));
    ///         }
    ///     }
    /// }
    ///
    /// let content = "uses: actions/checkout@v4\n";
    /// let mut receiver = Scalars(Vec::new());
    /// Parser::new_from_str(content)
    ///     .load(&mut receiver, false)
    ///     .unwrap();
    /// let (value, style, marker) = receiver.0[1].clone(); // the value scalar
    /// let scalar = MarkedScalar::new(value, style, &marker);
    ///
    /// let table = LineOffsetTable::new(content);
    /// let (start, end) = scalar.span(content, &table).unwrap();
    /// assert_eq!(&content[start..end], "actions/checkout@v4");
    /// ```
    #[must_use]
    pub fn span(&self, content: &str, table: &LineOffsetTable) -> Option<(usize, usize)> {
        let start = marker_byte_offset(content, table, self.line, self.col);
        locate_value_span(content, start, &self.text, self.is_quoted())
    }

    /// Resolves this scalar's raw span (see [`MarkedScalar::span`]) into an LSP
    /// [`Range`] via [`byte_span_to_range`], or `None` on the same miss `span` can
    /// return.
    #[must_use]
    pub fn range(&self, content: &str, table: &LineOffsetTable) -> Option<Range> {
        self.span(content, table)
            .map(|(start, end)| byte_span_to_range(content, table, start, end))
    }
}

/// A successful static "pin to commit SHA" resolution: the dependency's display name, the
/// span of its current ref, and the commit-SHA replacement text for that span.
///
/// A named struct rather than a same-typed `(String, Range, String)` tuple (review finding
/// M3, #1138): `display_name` and `replacement` are both `String`, and a tuple return lets a
/// future [`ShaPinning`] implementor transpose them silently.
#[cfg(feature = "lsp-responses")]
#[derive(Clone, PartialEq, Eq, deps_core::redact_debug::RedactingDebug)]
pub struct ResolvedShaPin {
    /// The dependency's human-readable name, for the quickfix title ("Pin `{display_name}`
    /// to commit SHA").
    #[redact(key)]
    pub display_name: String,
    /// The span of the dependency's current ref — what the edit replaces.
    #[raw]
    pub version_range: Range,
    /// The commit-SHA text (plus any ecosystem-specific trailing comment, e.g. GitHub
    /// Actions' `{sha} # {tag}`) to splice into `version_range`.
    #[raw]
    pub replacement: String,
}

/// Resolves the *static* — warm-`TagIndex`-only, no live fetch — "pin a mutable ref to an
/// immutable commit SHA" quickfix shape.
///
/// Shared by every git-tags-datasource ecosystem (`deps-github-actions`'s `owner/repo@ref`,
/// `deps-gitlab-ci`'s `PinStyle::Tag` include) — see deps-lsp issue #1138. A resolution that
/// needs a live fetch instead of a warm tag index (e.g. GitLab's `component:`
/// `Latest`/`Partial` pin, resolved against a project's published releases) is out of this
/// trait's scope and stays ecosystem-specific.
#[cfg(feature = "lsp-responses")]
pub trait ShaPinning: Send + Sync {
    /// Attempts the static "pin to commit SHA" resolution for `dep`.
    ///
    /// Runs the eligibility check and `TagIndex` lookup in one step, since neither is
    /// meaningful without the other to this trait's callers.
    ///
    /// Returns a [`ResolvedShaPin`] on success. `None` if `dep` is not this ecosystem's own
    /// dependency type, is not a statically-pinnable occurrence (e.g. a mutable branch/SHA
    /// ref, or a non-editable alias token), has no ref span to anchor an edit on, or the
    /// `TagIndex` lookup misses (a registry fetch still in flight).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::lsp_helpers::{ResolvedShaPin, ShaPinning};
    /// use deps_core::parser::DependencySource;
    /// use deps_core::position::Range;
    /// use deps_core::{Dependency, PackageName, VersionReq};
    /// use std::any::Any;
    ///
    /// struct MockDep {
    ///     name: PackageName,
    /// }
    ///
    /// impl Dependency for MockDep {
    ///     fn name(&self) -> &PackageName {
    ///         &self.name
    ///     }
    ///     fn name_range(&self) -> Range {
    ///         Range::default()
    ///     }
    ///     fn version_requirement(&self) -> Option<&VersionReq> {
    ///         None
    ///     }
    ///     fn version_range(&self) -> Option<Range> {
    ///         Some(Range::default())
    ///     }
    ///     fn source(&self) -> DependencySource {
    ///         DependencySource::Registry
    ///     }
    ///     fn as_any(&self) -> &dyn Any {
    ///         self
    ///     }
    /// }
    ///
    /// struct MockPinning;
    ///
    /// impl ShaPinning for MockPinning {
    ///     fn resolve_static_sha_pin(&self, dep: &dyn Dependency) -> Option<ResolvedShaPin> {
    ///         Some(ResolvedShaPin {
    ///             display_name: dep.name().as_str().to_string(),
    ///             version_range: dep.version_range()?,
    ///             replacement: "a".repeat(40),
    ///         })
    ///     }
    /// }
    ///
    /// let dep = MockDep { name: PackageName::new("owner/repo") };
    /// let resolved = MockPinning.resolve_static_sha_pin(&dep).unwrap();
    /// assert_eq!(resolved.display_name, "owner/repo");
    /// assert_eq!(resolved.replacement.len(), 40);
    /// ```
    fn resolve_static_sha_pin(&self, dep: &dyn Dependency) -> Option<ResolvedShaPin>;
}

/// Maximum character count of the dependency name interpolated into
/// [`build_sha_pin_action`]'s CodeAction title, before truncation with an ellipsis marker.
/// Mirrors `diagnostics::MAX_DIAGNOSTIC_NAME_CHARS`'s and
/// `deps_core::lsp_helpers::MAX_DIAGNOSTIC_VALUE_CHARS`'s numeric bound (#1252 critic
/// follow-up C1) — a separate `= 128` literal, not derived from either, out of #1278's
/// scope (that issue's nine-constant list did not include this one): this is the
/// *primary* `PinStyle::Tag` quickfix title, shared by both `deps-github-actions` and
/// `deps-gitlab-ci`, so it needs the same cap as the diagnostic sinks it sits next to.
#[cfg(feature = "lsp-responses")]
const MAX_SHA_PIN_TITLE_NAME_CHARS: usize = 128;

/// Builds the "Pin `{name}` to commit SHA" [`CodeAction`] for the dependency at `position`.
///
/// The boilerplate `deps-github-actions`'s and `deps-gitlab-ci`'s own `build_sha_pin_action`
/// functions each re-derived byte-for-byte before deps-lsp#1138 moved it here: locate the
/// dependency at `position` through `formatter`'s shared
/// [`PackageRendering::is_position_on_dependency`](super::PackageRendering::is_position_on_dependency)
/// lookup, resolve it via [`ShaPinning::resolve_static_sha_pin`], and wrap the resulting edit
/// into a `WorkspaceEdit`-carrying quickfix tagged with `diagnostic_code` so a client can
/// later associate this action back to its diagnostic.
///
/// Takes a single `formatter: &F` bound by both [`EcosystemFormatter`] and [`ShaPinning`]
/// (review finding M4, #1138) rather than two separate parameters for the same value — every
/// real implementor is one type that implements both traits, and a two-parameter signature
/// let a caller pass mismatched formatters at the two call sites with no compile error.
#[cfg(feature = "lsp-responses")]
#[must_use]
pub fn build_sha_pin_action<F: EcosystemFormatter + ShaPinning>(
    parse_result: &dyn ParseResult,
    position: Position,
    uri: &url::Url,
    formatter: &F,
    diagnostic_code: &'static str,
) -> Option<CodeAction> {
    let dep = parse_result
        .dependencies()
        .into_iter()
        .find(|d| formatter.is_position_on_dependency(*d, position.into()))?;
    let resolved = formatter.resolve_static_sha_pin(dep)?;
    let changes = single_file_edit(uri, resolved.version_range, resolved.replacement);
    let display_name = super::diagnostics::sanitize_and_truncate_for_diagnostic(
        &resolved.display_name,
        MAX_SHA_PIN_TITLE_NAME_CHARS,
    );
    Some(CodeAction {
        title: format!("Pin {display_name} to commit SHA"),
        kind: Some(CodeActionKind::QUICKFIX),
        edit: Some(WorkspaceEdit {
            changes: Some(changes),
            ..Default::default()
        }),
        data: Some(serde_json::json!({
            "diagnostic_codes": [diagnostic_code],
            "diagnostic_range": tower_lsp_server::ls_types::Range::from(resolved.version_range),
        })),
        ..Default::default()
    })
}

/// Builds the [`TextEdit`] for `dep` via [`ShaPinning::resolve_static_sha_pin`].
///
/// The single-dependency step `deps-github-actions`'s and `deps-gitlab-ci`'s own bulk "pin
/// all to SHA" collectors both build on, one dependency at a time, before their own
/// `dedup_overlapping_edits` pass.
#[cfg(feature = "lsp-responses")]
#[must_use]
pub fn sha_pin_text_edit(pinning: &impl ShaPinning, dep: &dyn Dependency) -> Option<TextEdit> {
    let resolved = pinning.resolve_static_sha_pin(dep)?;
    Some(TextEdit {
        range: resolved.version_range.into(),
        new_text: resolved.replacement,
    })
}

/// Inserts a `**Resolved**: `tag` (`sha…`)` line immediately after the shared hover's
/// `**Current**`/`**Requirement**` line (whichever is present), falling back to append.
///
/// Falls back to appending only if neither anchor is found — the byte-for-byte-identical
/// helper `deps-github-actions` and `deps-gitlab-ci` each defined locally, before
/// deps-lsp#1138 moved it here.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::splice_resolved_line;
///
/// let markdown = "**Current**: `v3`\n\nSome body.";
/// let sha = deps_core::lsp_helpers::CommitSha::parse(&"a".repeat(40)).unwrap();
/// let out = splice_resolved_line(markdown, "v3.0.0", &sha);
/// assert!(out.contains("**Resolved**: `v3.0.0`"));
/// ```
#[cfg(feature = "lsp-responses")]
#[must_use]
pub fn splice_resolved_line(markdown: &str, resolved_tag: &str, sha: &CommitSha) -> String {
    let short_sha = short_sha(sha.as_str());
    // `resolved_tag` is tag-index/registry-controlled and unbounded (#1311), and — like
    // any git tag — has no legitimate use for an invisible/bidi character, so it gets
    // the same `sanitize_invisible`-then-truncate treatment `HoverMarkdown`'s
    // `Name`/`Version` field kinds apply (#1313), via the same combined helper
    // `build_sha_pin_action`'s `display_name` above already uses, at
    // `MAX_VERSION_DIAGNOSTIC_CHARS` (the version-shaped sibling cap).
    let line = format!(
        "**Resolved**: {} ({})",
        markdown_code_span(&super::diagnostics::sanitize_and_truncate_for_diagnostic(
            resolved_tag,
            MAX_VERSION_DIAGNOSTIC_CHARS
        )),
        markdown_code_span(&format!("{short_sha}…"))
    );
    splice_hover_line(markdown, &line)
}

/// Inserts one markdown `line` as its own paragraph after the last present hover anchor
/// (`**Resolved**`, else `**Current**`, else `**Requirement**`), falling back to append.
///
/// Anchoring on `**Resolved**` first keeps a warning line below a previously spliced
/// resolved-tag line. `line` must already be sanitized and contain no paragraph break.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::splice_hover_line;
///
/// let out = splice_hover_line("**Current**: `v3`\n\nBody.", "**Warning**: careful");
/// assert_eq!(out, "**Current**: `v3`\n\n**Warning**: careful\n\nBody.");
/// ```
#[cfg(feature = "lsp-responses")]
#[expect(
    clippy::string_slice,
    reason = "pos/rel_end/insert_at derive only from find() of ASCII anchors, so every slice \
              below is a char boundary"
)]
#[must_use]
pub fn splice_hover_line(markdown: &str, line: &str) -> String {
    for anchor in ["**Resolved**: ", "**Current**: ", "**Requirement**: "] {
        if let Some(pos) = markdown.find(anchor)
            && let Some(rel_end) = markdown[pos..].find("\n\n")
        {
            let insert_at = pos + rel_end + 2;
            let mut out = String::with_capacity(markdown.len() + line.len() + 2);
            out.push_str(&markdown[..insert_at]);
            out.push_str(line);
            out.push_str("\n\n");
            out.push_str(&markdown[insert_at..]);
            return out;
        }
    }
    format!("{markdown}{line}\n\n")
}

#[cfg(test)]
#[expect(
    clippy::string_slice,
    reason = "fixtures are single-line ASCII literals with hand-computed byte offsets"
)]
mod tests {
    use super::*;
    use std::assert_matches;

    #[test]
    fn test_is_full_sha_accepts_and_rejects() {
        assert!(is_full_sha(&"a".repeat(40)));
        assert!(!is_full_sha(&"a".repeat(39)));
        assert!(!is_full_sha(&"g".repeat(40)));
    }

    #[test]
    fn test_tag_pin_position_table() {
        use PartialTagPolicy::{Exact, MovingLine};
        use TagPinPosition::{Ahead, Behind, Equal, MovingLine as Moving};
        for (written, latest, policy, expected) in [
            ("v4.3.1", "v4.3.1", MovingLine, Equal),
            ("4.3.1", "v4.3.1", Exact, Equal),
            ("v4", "v4.3.1", MovingLine, Moving),
            ("v4", "v4.3.1", Exact, Behind),
            ("v4.3.1.1", "v4.3.1", MovingLine, Moving),
            ("v40", "v4.3.1", MovingLine, Ahead),
            ("v5", "v4.9.0", Exact, Ahead),
            ("v5.0.0-rc.1", "v4.9.0", Exact, Ahead),
            ("v4.3.1+build", "v4.3.1", Exact, Equal),
            ("v2-beta", "v7.0.0", MovingLine, Behind),
            ("v1.x", "v4.3.1", MovingLine, Behind),
            ("v3", "v4.3.1", MovingLine, Behind),
        ] {
            assert_eq!(
                tag_pin_position(written, latest, policy),
                expected,
                "{written} vs {latest} ({policy:?})"
            );
            assert_eq!(
                tag_pin_is_up_to_date(written, latest, policy),
                expected != Behind,
                "{written} vs {latest} ({policy:?})"
            );
        }
    }

    /// #1766: the shape of an unpublished ref decides how plausible a branch of that name is;
    /// an exact key match, a truncated or empty index, or a non-tag ref never reports one.
    #[test]
    fn test_unpublished_tag_ref_shape_table() {
        use UnpublishedRef::{Partial, Release};

        let sha = sha_of('a');
        let complete = TagIndex::from_tags([("v4.3.1", &sha), ("v4", &sha), ("v5.x", &sha)]);
        for (written, expected) in [
            ("4.3.1", Some(Release)),
            ("v4.3.10", Some(Release)),
            ("V4.3.2", Some(Release)),
            ("v5.0.0-rc.1", Some(Release)),
            ("v5.0.0-beta", Some(Release)),
            ("v1", Some(Partial)),
            ("v40", Some(Partial)),
            ("v5.0", Some(Partial)),
            ("v3-node20", Some(Partial)),
            ("v1.2.3-node20", Some(Partial)),
            ("v3.4.0-working", Some(Partial)),
            ("v4.3.1", None),
            ("v4", None),
            ("v5.x", None),
            ("main", None),
            ("", None),
        ] {
            assert_eq!(complete.unpublished_tag_ref(written), expected, "{written}");
        }

        let truncated =
            TagIndex::from_tags([("v4.3.1", &sha)]).with_coverage(ListCoverage::Truncated);
        let empty = TagIndex::default();
        for written in ["4.3.1", "v40", "v1"] {
            assert_eq!(truncated.unpublished_tag_ref(written), None, "{written}");
            assert_eq!(empty.unpublished_tag_ref(written), None, "{written}");
        }
    }

    /// #1766: a full release is unknown at any position; a partial shape only when ahead of
    /// `latest` (#1753), so a documented branch pin (`v1`) stays up to date; outdated stays so.
    #[test]
    fn test_unpublished_ref_cap_status_by_shape_and_position() {
        use RequirementStatus::{Outdated, Unresolved, UpToDate};
        use UnpublishedRef::{Partial, Release};

        let cap = |kind: UnpublishedRef, written, status| {
            kind.cap_status(written, "v4.3.1", PartialTagPolicy::MovingLine, status)
        };
        assert_eq!(cap(Release, "4.3.1", UpToDate), Unresolved);
        assert_eq!(cap(Release, "v9.0.0", UpToDate), Unresolved);
        assert_eq!(cap(Release, "v3.0.0", Outdated), Outdated);
        assert_eq!(cap(Partial, "v40", UpToDate), Unresolved);
        assert_eq!(cap(Partial, "v4", UpToDate), UpToDate);
        assert_eq!(cap(Partial, "v1", Outdated), Outdated);
        assert_eq!(cap(Partial, "v3-node20", UpToDate), UpToDate);
        assert_eq!(cap(Partial, "v40", Unresolved), Unresolved);
    }

    fn comment_tag(text: &str) -> CommentTag {
        CommentTag::parse(text).unwrap()
    }

    #[test]
    fn test_pin_resolution_comment_contradicted_only_on_truncated_index() {
        let (pinned, latest) = (sha_of('a'), sha_of('b'));
        let tags = [("v1.1.0", &latest), ("v1", &latest)];
        let index = TagIndex::from_tags(tags);
        let truncated = TagIndex::from_tags(tags).with_coverage(ListCoverage::Truncated);
        let full = comment_tag("v1.1.0");
        assert_eq!(
            truncated.pin_resolution(&pinned, Some(&full)),
            PinResolution::CommentContradicted
        );
        assert_eq!(
            index.pin_resolution(&pinned, Some(&full)),
            PinResolution::Untagged
        );
        for benign in ["v1", "v1.2.0"] {
            assert_eq!(
                truncated.pin_resolution(&pinned, Some(&comment_tag(benign))),
                PinResolution::Unlisted,
                "{benign}"
            );
        }
        assert_eq!(
            truncated.pin_resolution(&pinned, None),
            PinResolution::Unlisted
        );
        assert_eq!(
            truncated.pin_resolution(&latest, Some(&full)),
            truncated.pin_resolution(&latest, None),
            "a pin the index can place is resolved whatever its comment says"
        );
    }

    #[test]
    fn test_pin_resolution_comment_match_ignores_spelling_unless_a_variant_names_the_pin() {
        let (pinned, latest) = (sha_of('a'), sha_of('b'));
        let mut truncated =
            TagIndex::from_tags([("v1.1.0", &latest)]).with_coverage(ListCoverage::Truncated);
        for spelling in ["1.1.0", "V1.1.0", "v1.1.0+meta"] {
            assert_eq!(
                truncated.pin_resolution(&pinned, Some(&comment_tag(spelling))),
                PinResolution::CommentContradicted,
                "{spelling}"
            );
        }
        truncated.tag_to_sha.insert("1.1.0".into(), pinned.clone());
        assert_eq!(
            truncated.pin_resolution(&pinned, Some(&comment_tag("v1.1.0"))),
            PinResolution::Unlisted,
            "a variant tag pointing at the pin means the comment is not contradicted"
        );
    }

    #[test]
    fn test_sha_pin_lookup_comment_contradicted_has_unresolved_status() {
        let (pinned, latest) = (sha_of('a'), sha_of('b'));
        let truncated =
            TagIndex::from_tags([("v1.1.0", &latest)]).with_coverage(ListCoverage::Truncated);
        let comment = comment_tag("1.1.0");
        let newest = crate::ConcreteVersion::new("v1.2.0");
        let lookup = ShaPinLookup::resolve(Some(&truncated), &pinned, &newest, Some(&comment));
        assert_eq!(lookup, ShaPinLookup::CommentContradicted);
        assert_eq!(
            lookup.status_or_text(|| RequirementStatus::UpToDate),
            RequirementStatus::Unresolved
        );
        assert_eq!(
            ShaPinLookup::resolve(Some(&truncated), &pinned, &newest, None),
            ShaPinLookup::Unlisted
        );
    }

    /// #1766: a SHA the truncated list does not reach never reads as up to date from text, in
    /// whatever shape the comment is written; an outdated text status is kept.
    #[test]
    fn test_sha_pin_lookup_unlisted_caps_up_to_date_text() {
        for text in [
            RequirementStatus::UpToDate,
            RequirementStatus::Outdated,
            RequirementStatus::Unresolved,
        ] {
            let expected = if text == RequirementStatus::UpToDate {
                RequirementStatus::Unresolved
            } else {
                text
            };
            assert_eq!(ShaPinLookup::Unlisted.status_or_text(|| text), expected);
            assert_eq!(ShaPinLookup::Unverifiable.status_or_text(|| text), text);
        }
    }

    /// #1795: only the exact-tag lookup proves a tag ref unpublished; a commit lookup never
    /// does, so `ShaPinLookup` and the SHA comment check never see `Unpublished`.
    #[test]
    fn test_commit_lookup_never_yields_unpublished() {
        let sha = sha_of('a');
        let other = sha_of('b');
        for index in [
            TagIndex::from_tags([("v4.8.0", &sha)]),
            TagIndex::from_tags([("v4.8.0", &sha)]).with_coverage(ListCoverage::Truncated),
            TagIndex::default(),
        ] {
            assert_ne!(
                index.pin_resolution(&other, None),
                PinResolution::Unpublished
            );
        }
        let index = TagIndex::from_tags([("v4.8.0", &sha)]);
        assert_eq!(
            ShaPinLookup::resolve(
                Some(&index),
                &other,
                &crate::ConcreteVersion::new("v4.8.0"),
                None
            ),
            ShaPinLookup::NotIndexed
        );
    }

    #[test]
    fn test_exact_tag_resolution_listed_missing_complete_and_truncated() {
        let sha = sha_of('a');
        let complete = TagIndex::from_tags([("v4.8.0", &sha)]);
        assert_matches!(
            complete.exact_tag_resolution("v4.8.0"),
            PinResolution::Resolved {
                sibling_coverage: ListCoverage::Complete,
                ..
            }
        );
        assert_eq!(
            complete.exact_tag_resolution("v4.9.0"),
            PinResolution::Unpublished
        );
        let truncated =
            TagIndex::from_tags([("v4.8.0", &sha)]).with_coverage(ListCoverage::Truncated);
        assert_matches!(
            truncated.exact_tag_resolution("v4.8.0"),
            PinResolution::Resolved {
                sibling_coverage: ListCoverage::Truncated,
                ..
            }
        );
        assert_eq!(
            truncated.exact_tag_resolution("v4.9.0"),
            PinResolution::Unlisted
        );
        let empty = TagIndex::default().with_coverage(ListCoverage::Truncated);
        assert_eq!(
            empty.exact_tag_resolution("v4.9.0"),
            PinResolution::Unresolved
        );
    }

    /// The floating-tag sub-selection keeps the whole index's coverage.
    #[test]
    fn test_floating_tag_resolution_keeps_truncated_coverage() {
        let sha = sha_of('a');
        let index = TagIndex::from_tags([("v4", &sha), ("v4.2.0", &sha), ("v5.0.0", &sha)])
            .with_coverage(ListCoverage::Truncated);
        assert_matches!(
            index.floating_tag_resolution("v4"),
            PinResolution::Resolved { pin, sibling_coverage: ListCoverage::Truncated }
                if pin.version().as_str() == "v4.2.0"
        );
        assert_eq!(index.floating_tag_resolution("v9"), PinResolution::Unlisted);
        let complete = TagIndex::from_tags([("v4", &sha)]);
        assert_eq!(
            complete.floating_tag_resolution("v9"),
            PinResolution::Unresolved
        );
    }

    #[test]
    fn test_commit_sha_parse_accepts_and_rejects() {
        assert!(CommitSha::parse(&"a".repeat(40)).is_some());
        assert!(CommitSha::parse("not-a-sha").is_none());
    }

    #[test]
    fn test_commit_sha_parse_canonicalizes_to_lowercase() {
        let upper = CommitSha::parse(&"ABCDEF0123".repeat(4)).unwrap();
        let lower = CommitSha::parse(&"abcdef0123".repeat(4)).unwrap();
        assert_eq!(upper, lower);
        assert_eq!(upper.as_str(), "abcdef0123".repeat(4));
        assert_eq!(upper.to_string(), "abcdef0123".repeat(4));
    }

    #[test]
    fn test_commit_sha_hash_lookup_is_case_independent() {
        let mut map = std::collections::HashMap::new();
        map.insert(CommitSha::parse(&"a".repeat(40)).unwrap(), "v1.0.0");
        let upper = CommitSha::parse(&"A".repeat(40)).unwrap();
        assert_eq!(map.get(&upper), Some(&"v1.0.0"));
    }

    #[test]
    fn test_pin_resolution_variants() {
        let sha = sha_of('a');
        let other = sha_of('b');
        let index = TagIndex::from_tags([("v1.0.0", &sha)]);
        assert_matches!(
            index.pin_resolution(&sha, None),
            PinResolution::Resolved { pin, .. } if pin.version().as_str() == "v1.0.0"
        );
        assert_eq!(index.pin_resolution(&other, None), PinResolution::Untagged);

        let truncated =
            TagIndex::from_tags([("v1.0.0", &sha)]).with_coverage(ListCoverage::Truncated);
        assert_eq!(
            truncated.pin_resolution(&other, None),
            PinResolution::Unlisted
        );
        assert_matches!(
            truncated.pin_resolution(&sha, None),
            PinResolution::Resolved {
                sibling_coverage: ListCoverage::Truncated,
                ..
            }
        );
        assert_eq!(
            TagIndex::default().pin_resolution(&other, None),
            PinResolution::Unresolved
        );
    }

    #[test]
    fn test_tag_has_precedence() {
        for tag in [
            "v4",
            "v4.2",
            "4.2.0",
            "v2-beta",
            "v2.1-rc.1",
            "v3.0.0-rc.1",
            "v2+b5",
        ] {
            assert!(tag_has_precedence(tag), "{tag}");
        }
        for tag in [
            "v1.x",
            "v1.*",
            "v1_2",
            "v3-node20",
            "v1.2-stable",
            "v2-beta.01",
            "main",
        ] {
            assert!(!tag_has_precedence(tag), "{tag}");
        }
    }

    #[test]
    fn test_tag_pin_is_up_to_date_table() {
        use PartialTagPolicy::{Exact, MovingLine};
        let cases = [
            ("v2-beta", "v7.0.0", MovingLine, false),
            ("v3.0.0-rc.1", "v7.0.0", MovingLine, false),
            ("v3.0.0-rc.1", "v3.0.0-rc.1", MovingLine, true),
            ("v4", "v4.3.1", MovingLine, true),
            ("v4", "v4.3.1", Exact, false),
            ("v4.2", "v4.2.5", MovingLine, true),
            ("v4.2", "v4.3.0", MovingLine, false),
            ("v5.0.0-rc.1", "v4.9.0", MovingLine, true),
            ("v5.0.0-rc.1", "v4.9.0", Exact, true),
            ("v8-beta", "v7.0.0", MovingLine, true),
            ("4.2.0", "v4.2.0", MovingLine, true),
            ("v4.x", "v4.3.1", MovingLine, false),
            ("v5", "v4.9.0", MovingLine, true),
            ("v5", "v4.9.0", Exact, true),
            ("v4.10", "v4.9.0", Exact, true),
            ("v4", "v4.0.0", Exact, false),
            ("v3-node20", "v7.0.0", MovingLine, false),
            ("v2-beta.01", "v7.0.0", MovingLine, false),
            ("v4.2.0", "v4", MovingLine, true),
            ("v4.2.0", "v4.2.0+build.5", Exact, true),
            ("v2.1-rc", "v2.1.0", Exact, false),
            ("v1", "v1.3.0", Exact, false),
            ("v4.1.0", "v4.2.0", MovingLine, false),
        ];
        for (written, latest, policy, expected) in cases {
            assert_eq!(
                tag_pin_is_up_to_date(written, latest, policy),
                expected,
                "{written} vs {latest} ({policy:?})"
            );
        }
    }

    #[test]
    fn test_sha_for_tag_unknown_tag_is_none_and_lookup_is_exact() {
        let sha = sha_of('a');
        let index = TagIndex::from_tags([("v4", &sha)]);

        assert_eq!(index.sha_for_tag("v4"), Some(&sha));
        assert_eq!(index.sha_for_tag("v5"), None);
        assert_eq!(index.sha_for_tag("V4"), None, "no case or prefix folding");
        assert_eq!(index.sha_for_tag("4"), None);
        assert_eq!(index.sha_for_tag(""), None);
        assert_eq!(TagIndex::default().sha_for_tag("v4"), None);
    }

    #[test]
    fn test_tag_index_from_tags_dedupes_first_wins_for_tag_to_sha() {
        let sha_a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let sha_b = CommitSha::parse(&"b".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("v1.0.0", &sha_a), ("v1.0.0", &sha_b)]);
        assert_eq!(index.tag_to_sha.get("v1.0.0"), Some(&sha_a));
    }

    #[test]
    fn test_tag_index_from_tags_sha_to_tag_prefers_semver_over_bare_moving_tag() {
        let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
        // The moving tag ("v1") listed before the precise release ("v0.1.15") — sha_to_tag
        // must still resolve to the semver-parseable one, regardless of iteration order.
        let index = TagIndex::from_tags([("v1", &sha), ("v0.1.15", &sha)]);
        assert_eq!(index.tag_for_sha(&sha), Some("v0.1.15"));
        assert_eq!(index.tag_to_sha.get("v1"), Some(&sha));
        assert_eq!(index.tag_to_sha.get("v0.1.15"), Some(&sha));
    }

    fn sha_of(c: char) -> CommitSha {
        CommitSha::parse(&c.to_string().repeat(40)).unwrap()
    }

    fn lookup(index: Option<&TagIndex>, sha: &str, latest: &str) -> Option<ShaPinLookup> {
        let sha = CommitSha::parse(sha)?;
        Some(ShaPinLookup::resolve(
            index,
            &sha,
            &crate::ConcreteVersion::new(latest),
            None,
        ))
    }

    #[test]
    fn test_sha_pin_lookup_rejects_non_full_sha() {
        let index = TagIndex::from_tags([("v1.0.0", &sha_of('a'))]);
        for bad in [
            "a".repeat(39),
            "a".repeat(41),
            "g".repeat(40),
            "v1.0.0".to_string(),
        ] {
            assert_eq!(lookup(Some(&index), &bad, "v1.0.0"), None, "{bad}");
        }
        assert_eq!(
            lookup(Some(&index), &"A".repeat(40), "v1.0.0"),
            Some(ShaPinLookup::LatestCommit)
        );
    }

    #[test]
    fn test_sha_pin_lookup_variants() {
        let index = TagIndex::from_tags([
            ("v1.0.0", &sha_of('a')),
            ("v1.1.0", &sha_of('b')),
            ("v1.1", &sha_of('b')),
        ]);
        assert_eq!(
            lookup(Some(&index), &"a".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::Indexed {
                tag: crate::ConcreteVersion::new("v1.0.0"),
                position: TagPosition::BelowLatest,
            })
        );
        assert_eq!(
            lookup(Some(&index), &"c".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::NotIndexed)
        );
        assert_eq!(
            lookup(Some(&TagIndex::default()), &"a".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::Unverifiable)
        );
        assert_eq!(
            lookup(None, &"a".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::Unverifiable)
        );
        assert_eq!(
            lookup(Some(&index), &"b".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::LatestCommit)
        );
    }

    #[test]
    fn test_sha_pin_lookup_truncated_index_only_proves_presence() {
        let index = TagIndex::from_tags([("v1.0.0", &sha_of('a')), ("v1.1.0", &sha_of('b'))])
            .with_coverage(ListCoverage::Truncated);
        assert_eq!(
            lookup(Some(&index), &"c".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::Unlisted)
        );
        assert_eq!(
            lookup(Some(&index), &"a".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::Indexed {
                tag: crate::ConcreteVersion::new("v1.0.0"),
                position: TagPosition::BelowLatest,
            })
        );
        assert_eq!(
            lookup(Some(&index), &"b".repeat(40), "v1.1.0"),
            Some(ShaPinLookup::LatestCommit)
        );
    }

    #[test]
    fn test_tag_position_table() {
        use TagPosition::{AtOrAboveLatest as At, BelowLatest as Below};
        let cases = [
            ("v1", "v1.5.0", Below),
            ("1.1", "1.1.3", Below),
            ("v1.10", "v1.9.0", At),
            ("v2.0.0-rc1", "1.9.0", At),
            ("v2", "1.9.0", At),
            ("v1", "v1.0.0", Below),
            ("v1.0.0", "1.0.0", At),
            ("v1.2.3-rc1", "v1.2.3", Below),
            ("v1.2.4", "v1.2.3", At),
            ("v1.9.0", "v1.10.0", Below),
            ("cargo-deny", "v1.5.0", Below),
            ("v1-rc1", "v1.5.0", Below),
            ("v1.5.0", "stable", Below),
            ("v99999999999999999999", "v1.5.0", Below),
            ("1.1", "1.1.0", Below),
            ("v1.2", "v1.1.9", At),
            ("v1.2.3+build5", "v1.2.3", At),
            ("v1+build5", "v1.5.0", Below),
            ("v01.2", "v1.1.0", Below),
            ("v01.2.3", "v1.2.3", Below),
            ("v1.2.3", "v01.2.3", Below),
        ];
        for (tag, latest, expected) in cases {
            assert_eq!(TagPosition::of(tag, latest), expected, "{tag} vs {latest}");
        }
    }

    #[test]
    fn test_sha_pin_lookup_indexed_by_outdated_moving_tag_is_outdated() {
        let index = TagIndex::from_tags([("v1", &sha_of('a')), ("v1.5.0", &sha_of('b'))]);
        let found = lookup(Some(&index), &"a".repeat(40), "v1.5.0").unwrap();
        assert_eq!(
            found,
            ShaPinLookup::Indexed {
                tag: crate::ConcreteVersion::new("v1"),
                position: TagPosition::BelowLatest,
            }
        );
        assert_eq!(
            found.status_or_text(|| RequirementStatus::UpToDate),
            RequirementStatus::Outdated
        );
    }

    #[test]
    fn test_sha_pin_lookup_indexed_by_prerelease_of_newer_line_is_up_to_date() {
        let index = TagIndex::from_tags([("v2.0.0-rc1", &sha_of('a')), ("1.9.0", &sha_of('b'))]);
        let found = lookup(Some(&index), &"a".repeat(40), "1.9.0").unwrap();
        assert_eq!(
            found.status_or_text(|| RequirementStatus::Unresolved),
            RequirementStatus::UpToDate
        );
    }

    #[test]
    fn test_sha_pin_lookup_status_branches() {
        let indexed = |tag: &str, position| ShaPinLookup::Indexed {
            tag: crate::ConcreteVersion::new(tag),
            position,
        };
        let text = || RequirementStatus::Unresolved;
        assert_eq!(
            indexed("v2.0.0", TagPosition::AtOrAboveLatest).status_or_text(text),
            RequirementStatus::UpToDate
        );
        assert_eq!(
            indexed("cargo-deny", TagPosition::BelowLatest).status_or_text(text),
            RequirementStatus::Outdated
        );
        let oversized = "v".repeat(super::super::MAX_REQUIREMENT_LEN + 1);
        assert_eq!(
            indexed(&oversized, TagPosition::AtOrAboveLatest).status_or_text(text),
            RequirementStatus::Unresolved
        );
        assert_eq!(
            ShaPinLookup::LatestCommit.status_or_text(text),
            RequirementStatus::UpToDate
        );
        assert_eq!(
            ShaPinLookup::NotIndexed.status_or_text(text),
            RequirementStatus::Outdated
        );
        assert_eq!(
            ShaPinLookup::Unverifiable.status_or_text(|| RequirementStatus::Outdated),
            RequirementStatus::Outdated
        );
    }

    fn resolved_pin_for(tags: &[&str]) -> Option<ResolvedPin> {
        let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
        let index = TagIndex::from_tags(tags.iter().map(|t| (*t, &sha)));
        index.resolved_pin(&sha)
    }

    /// #1668: `v2.9` next to its moving alias `v2` is the most specific name, regardless of the
    /// order the fetch returned them in.
    #[test]
    fn test_tag_index_two_component_release_beats_moving_major_in_any_order() {
        for tags in [["v2.9", "v2"], ["v2", "v2.9"]] {
            assert_eq!(
                resolved_pin_for(&tags),
                Some(ResolvedPin::most_specific(crate::ConcreteVersion::new(
                    "v2.9"
                ))),
                "{tags:?}"
            );
        }
    }

    #[test]
    fn test_tag_index_full_semver_beats_two_component_and_major() {
        assert_eq!(
            resolved_pin_for(&["v2", "v2.9", "v2.9.1"]),
            Some(ResolvedPin::most_specific(crate::ConcreteVersion::new(
                "v2.9.1"
            )))
        );
    }

    #[test]
    fn test_tag_index_lone_major_is_most_specific_but_a_prefix_of_an_unranked_tag_is_alias() {
        assert_eq!(
            resolved_pin_for(&["v2"]),
            Some(ResolvedPin::most_specific(crate::ConcreteVersion::new(
                "v2"
            )))
        );
        // Four components rank below a partial-semver name but still extend it.
        assert_eq!(
            resolved_pin_for(&["v2.9", "v2.9.1.4"]),
            Some(ResolvedPin::alias(crate::ConcreteVersion::new("v2.9")))
        );
    }

    fn most_specific(tag: &str) -> Option<ResolvedPin> {
        Some(ResolvedPin::most_specific(crate::ConcreteVersion::new(tag)))
    }

    fn sibling_names(pin: &ResolvedPin) -> Vec<&str> {
        pin.siblings().iter().map(|t| t.as_str()).collect()
    }

    /// #1709: other release names on the commit become siblings of the primary, in any order.
    #[test]
    fn test_sibling_tags_collect_other_releases_in_any_order() {
        for tags in [["v4.8.0", "v4.9.0"], ["v4.9.0", "v4.8.0"]] {
            let pin = resolved_pin_for(&tags).unwrap();
            assert_eq!(pin.version().as_str(), "v4.8.0", "{tags:?}");
            assert_eq!(sibling_names(&pin), ["v4.9.0"], "{tags:?}");
        }
    }

    #[test]
    fn test_sibling_tags_are_sorted_lowest_first() {
        let pin = resolved_pin_for(&["v4.10.0", "v4.8.0", "v4.9.0", "v4.11.0"]).unwrap();
        assert_eq!(pin.version().as_str(), "v4.8.0");
        assert_eq!(sibling_names(&pin), ["v4.9.0", "v4.10.0", "v4.11.0"]);
    }

    /// #1709 (M4): aliases, pre-releases, other classes and spelling duplicates are never siblings.
    #[test]
    fn test_sibling_tags_exclude_aliases_prereleases_and_duplicates() {
        let pin = resolved_pin_for(&["v4", "v4.8", "v4.8.0", "v4.9.0-rc1", "4.8.0", "release-x"])
            .unwrap();
        assert_eq!(pin.version().as_str().trim_start_matches('v'), "4.8.0");
        assert!(pin.siblings().is_empty(), "{:?}", pin.siblings());
    }

    /// #1709: spelling duplicates among siblings collapse to one entry.
    #[test]
    fn test_sibling_tags_dedupe_spelling_variants_among_siblings() {
        let pin = resolved_pin_for(&["v4.8.0", "v4.9.0", "4.9.0"]).unwrap();
        assert_eq!(pin.version().as_str(), "v4.8.0");
        assert_eq!(pin.siblings().len(), 1);
    }

    /// #1709 (G7): two-component releases are siblings unless another tag extends them.
    #[test]
    fn test_sibling_tags_two_component_releases() {
        let pin = resolved_pin_for(&["v2.9", "v2.10"]).unwrap();
        assert_eq!(sibling_names(&pin), ["v2.10"]);
        let pin = resolved_pin_for(&["v2.9", "v2.10", "v2.10.0.1"]).unwrap();
        assert_eq!(pin.version().as_str(), "v2.9");
        assert!(pin.siblings().is_empty());
    }

    /// #1709: a prerelease primary has no siblings, not even other prereleases.
    #[test]
    fn test_sibling_tags_prerelease_primary_has_none() {
        let pin = resolved_pin_for(&["v4.9.0-rc1", "v4.9.0-rc2"]).unwrap();
        assert!(pin.siblings().is_empty());
    }

    /// #1709: an alias winner (extended by a non-semver 4-component name) keeps its siblings.
    #[test]
    fn test_sibling_tags_alias_winner_keeps_siblings() {
        let pin = resolved_pin_for(&["v1.2.3", "v1.2.4", "v1.2.3.1"]).unwrap();
        assert_matches!(pin, ResolvedPin::Alias { .. });
        assert_eq!(pin.version().as_str(), "v1.2.3");
        assert_eq!(sibling_names(&pin), ["v1.2.4"]);
    }

    /// #1709/#1719: the written exact tag stays primary; only its major line's releases on the
    /// same commit are siblings.
    #[test]
    fn test_resolved_exact_tag_keeps_written_primary_and_same_major_siblings() {
        let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
        let other = CommitSha::parse(&"b".repeat(40)).unwrap();
        let index = TagIndex::from_tags([
            ("v4.9.0", &sha),
            ("v4.8.0", &sha),
            ("v5.0.0", &sha),
            ("v4.7.0", &other),
        ]);
        let pin = index.resolved_exact_tag("v4.9.0").unwrap();
        assert_eq!(pin.version().as_str(), "v4.9.0");
        assert_eq!(sibling_names(&pin), ["v4.8.0"]);
        assert_eq!(index.resolved_exact_tag("v9.9.9"), None);
    }

    /// #1709: an exact tag extended by another name on its commit is an alias primary; a
    /// differently spelled twin on the commit is not a sibling.
    #[test]
    fn test_resolved_exact_tag_alias_and_spelling_twin() {
        let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("v4.8.0", &sha), ("v4.8.0.1", &sha), ("4.8.0", &sha)]);
        let pin = index.resolved_exact_tag("v4.8.0").unwrap();
        assert_matches!(pin, ResolvedPin::Alias { .. });
        assert!(pin.siblings().is_empty());
    }

    #[test]
    fn test_release_tag_exact_normalized_and_missing() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("v4.1.3", &a), ("4.2.0", &a)]);
        assert_eq!(index.release_tag("v4.1.3"), Some("v4.1.3"));
        assert_eq!(index.release_tag("4.1.3"), Some("v4.1.3"));
        assert_eq!(index.release_tag("V4.2.0"), Some("4.2.0"));
        assert_eq!(index.release_tag("v9.9.9"), None);
    }

    /// Any conflicting spelling makes the lookup ambiguous, an exact key included.
    #[test]
    fn test_release_tag_conflicting_spellings_are_none_even_with_an_exact_key() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let b = CommitSha::parse(&"b".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("4.1.3", &b), ("v4.1.3", &a)]);
        for version in ["4.1.3", "v4.1.3", "V4.1.3"] {
            assert_eq!(index.release_tag(version), None, "{version}");
        }
    }

    /// Spellings of one commit agree; the unprefixed request gets a deterministic key.
    #[test]
    fn test_release_tag_agreeing_spellings_resolve_deterministically() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("v4.1.3", &a), ("V4.1.3", &a)]);
        assert_eq!(index.release_tag("4.1.3"), Some("V4.1.3"));
        assert_eq!(index.release_tag("v4.1.3"), Some("v4.1.3"));
    }

    #[test]
    fn test_release_commit_exact_key_wins_over_a_conflicting_twin() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let b = CommitSha::parse(&"b".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("4.1.3", &b), ("v4.1.3", &a)]);
        let (tag, sha) = index.release_commit("4.1.3").unwrap();
        assert_eq!((tag.as_str(), sha), ("4.1.3", b));
        let (tag, sha) = index.release_commit("v4.1.3").unwrap();
        assert_eq!((tag.as_str(), sha), ("v4.1.3", a));
    }

    #[test]
    fn test_release_commit_unprefixed_version_finds_the_prefixed_key() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("v4.1.3", &a)]);
        let (tag, sha) = index.release_commit("4.1.3").unwrap();
        assert_eq!((tag.as_str(), sha), ("v4.1.3", a));
        assert!(index.release_commit("4.1.4").is_none());
    }

    #[test]
    fn test_release_commit_conflicting_twins_without_an_exact_key_are_none() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let b = CommitSha::parse(&"b".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("v4.1.3", &a), ("V4.1.3", &b)]);
        assert!(index.release_commit("4.1.3").is_none());
    }

    #[test]
    fn test_resolved_release_scope_same_major_vs_whole_commit() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let b = CommitSha::parse(&"b".repeat(40)).unwrap();
        let index = TagIndex::from_tags([
            ("v4.8.0", &a),
            ("v4.9.0", &a),
            ("v5.0.0", &a),
            ("v4.7.0", &b),
        ]);
        let same = index
            .resolved_release("v4.8.0", SiblingScope::SameMajor)
            .unwrap();
        assert_eq!(sibling_names(&same), ["v4.9.0"]);
        let whole = index
            .resolved_release("v4.8.0", SiblingScope::WholeCommit)
            .unwrap();
        assert_eq!(sibling_names(&whole), ["v4.9.0", "v5.0.0"]);
        assert_eq!(
            index.resolved_release("4.8.0", SiblingScope::WholeCommit),
            None,
            "exact key text only"
        );
    }

    /// A pre-release never beats its own release, in either fetch order (#1668 critic).
    #[test]
    fn test_tag_index_release_beats_prerelease_in_any_order() {
        for tags in [["v2.9-rc1", "v2.9"], ["v2.9", "v2.9-rc1"]] {
            assert_eq!(resolved_pin_for(&tags), most_specific("v2.9"), "{tags:?}");
        }
        for tags in [["v2.9.1-rc1", "v2.9.1"], ["v2.9.1", "v2.9.1-rc1"]] {
            assert_eq!(resolved_pin_for(&tags), most_specific("v2.9.1"), "{tags:?}");
        }
    }

    /// #1703: equally specific releases on one commit resolve to the numerically lowest one,
    /// not to whichever name sorts first as text (`v4.10.0` < `v4.9.0` textually).
    #[test]
    fn test_tag_index_lowest_semver_release_wins_in_any_order() {
        for (tags, expected) in [
            (["v4.9.0", "v4.10.0"], "v4.9.0"),
            (["v4.10.0", "v4.9.0"], "v4.9.0"),
            (["v2.9", "v2.10"], "v2.9"),
            (["v2.10", "v2.9"], "v2.9"),
            (["v4.8.0", "v4.9.0"], "v4.8.0"),
            (["v4.9.0", "v4.8.0"], "v4.8.0"),
        ] {
            let pin = resolved_pin_for(&tags).unwrap();
            assert_eq!(pin.version().as_str(), expected, "{tags:?}");
            assert_matches!(pin, ResolvedPin::MostSpecific { .. }, "{tags:?}");
        }
    }

    #[test]
    fn test_tag_index_prerelease_ordering_and_release_precedence() {
        for tags in [
            ["v1.0.0-rc.2", "v1.0.0-rc.10"],
            ["v1.0.0-rc.10", "v1.0.0-rc.2"],
        ] {
            assert_eq!(
                resolved_pin_for(&tags),
                most_specific("v1.0.0-rc.2"),
                "{tags:?}"
            );
        }
        assert_eq!(
            resolved_pin_for(&["v4.10.0-rc1", "v4.9.0"]),
            most_specific("v4.9.0")
        );
    }

    #[test]
    fn test_tag_index_non_semver_and_overflowing_components_stay_deterministic() {
        for tags in [["nightly", "edge"], ["edge", "nightly"]] {
            assert_eq!(resolved_pin_for(&tags), most_specific("edge"), "{tags:?}");
        }
        let huge = "v99999999999999999999999.1";
        for tags in [[huge, "v2.9"], ["v2.9", huge]] {
            assert_eq!(resolved_pin_for(&tags), most_specific("v2.9"), "{tags:?}");
        }
    }

    #[test]
    fn test_tag_index_full_semver_prerelease_beats_two_component() {
        assert_eq!(
            resolved_pin_for(&["v2.9", "v2.9.0-beta"]),
            most_specific("v2.9.0-beta")
        );
    }

    #[test]
    fn test_tag_index_unprefixed_tags_rank_like_prefixed() {
        for tags in [["2.9", "2"], ["2", "2.9"]] {
            assert_eq!(resolved_pin_for(&tags), most_specific("2.9"), "{tags:?}");
        }
        assert_eq!(resolved_pin_for(&["2"]), most_specific("2"));
    }

    #[test]
    fn test_tag_index_numeric_tag_beats_non_numeric_and_lone_non_numeric_wins() {
        assert_eq!(resolved_pin_for(&["cargo-deny", "v2"]), most_specific("v2"));
        assert_eq!(
            resolved_pin_for(&["nightly", "v2.9"]),
            most_specific("v2.9")
        );
        assert_eq!(resolved_pin_for(&["nightly"]), most_specific("nightly"));
    }

    #[test]
    fn test_tag_index_empty_input_yields_empty_index() {
        let index = TagIndex::from_tags(std::iter::empty());
        assert!(index.is_empty());
        assert_eq!(index.resolved_pin(&sha_of('a')), None);
    }

    #[test]
    fn test_tag_index_classifies_each_sha_independently() {
        let a = CommitSha::parse(&"a".repeat(40)).unwrap();
        let b = CommitSha::parse(&"b".repeat(40)).unwrap();
        let index = TagIndex::from_tags([("v2", &a), ("v2.9", &a), ("v3", &b)]);
        assert_eq!(index.resolved_pin(&a), most_specific("v2.9"));
        assert_eq!(index.resolved_pin(&b), most_specific("v3"));
    }

    #[test]
    fn test_tag_index_alias_is_classified_and_insert_sha_pin_overrides() {
        let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
        let mut index = TagIndex::from_tags([("v2.9", &sha), ("v2.9.1.4", &sha)]);
        assert_eq!(
            index.resolved_pin(&sha),
            Some(ResolvedPin::alias(crate::ConcreteVersion::new("v2.9")))
        );
        assert_eq!(index.tag_for_sha(&sha), Some("v2.9"));
        index.insert_sha_pin(
            sha.clone(),
            ResolvedPin::most_specific(crate::ConcreteVersion::new("v3.0")),
        );
        assert_eq!(index.resolved_pin(&sha), most_specific("v3.0"));
    }

    #[test]
    fn test_extends_tag() {
        assert!(extends_tag("v2.9", "v2"));
        assert!(extends_tag("2.9.1", "v2.9"));
        assert!(!extends_tag("v2.10", "v2.1"));
        assert!(!extends_tag("v2", "v2"));
        assert!(!extends_tag("v2", "v2.9"));
        assert!(!extends_tag("v3.9", "v2"));
    }

    #[test]
    fn test_tag_index_resolved_pin_none_for_unknown_sha() {
        assert_eq!(TagIndex::default().resolved_pin(&sha_of('b')), None);
    }

    #[test]
    fn test_is_tag_shaped() {
        assert!(is_tag_shaped("v4"));
        assert!(is_tag_shaped("4.2.0"));
        assert!(!is_tag_shaped("main"));
        assert!(!is_tag_shaped(&"a".repeat(40)));
    }

    #[test]
    fn test_is_partial_semver_shaped_accepts_v_prefixed_at_any_precision() {
        assert!(is_partial_semver_shaped("v4"));
        assert!(is_partial_semver_shaped("v2.9"));
        assert!(is_partial_semver_shaped("v4.2.0"));
        assert!(is_partial_semver_shaped("v4.2.0-beta.1"));
        assert!(is_partial_semver_shaped("v4.2.0+build.5"));
        assert!(is_partial_semver_shaped("V4"));
    }

    #[test]
    fn test_is_partial_semver_shaped_accepts_dotted_without_v_prefix() {
        assert!(is_partial_semver_shaped("2.9"));
        assert!(is_partial_semver_shaped("4.2.0"));
    }

    #[test]
    fn test_is_partial_semver_shaped_rejects_bare_unprefixed_integer() {
        // #907 review S1: a bare all-digit token (ticket number, date) is indistinguishable
        // from a version, so it must be rejected here unlike `is_tag_shaped`.
        assert!(!is_partial_semver_shaped("1234"));
        assert!(!is_partial_semver_shaped("20240501"));
        assert!(!is_partial_semver_shaped("0"));
    }

    #[test]
    fn test_is_partial_semver_shaped_rejects_dash_separated_date_and_branch_names() {
        assert!(!is_partial_semver_shaped("2024-01-15"));
        assert!(!is_partial_semver_shaped("main"));
        assert!(!is_partial_semver_shaped(&"a".repeat(40)));
    }

    #[test]
    fn test_is_partial_semver_shaped_rejects_too_many_components() {
        assert!(!is_partial_semver_shaped("v1.2.3.4"));
    }

    #[test]
    fn test_match_v_prefix_style() {
        assert_eq!(match_v_prefix_style("v4", "5.0.0"), "v5.0.0");
        assert_eq!(match_v_prefix_style("4", "v5.0.0"), "5.0.0");
        assert_eq!(match_v_prefix_style("v4", "v5.0.0"), "v5.0.0");
        assert_eq!(match_v_prefix_style("4", "5.0.0"), "5.0.0");
    }

    #[test]
    fn test_locate_value_span_finds_value_within_fallback_bound() {
        let content = "prefix xxxxx actions/checkout@v4 suffix";
        let value = "actions/checkout@v4";
        let (start, end) = locate_value_span(content, 0, value, false).unwrap();
        assert_eq!(&content[start..end], value);
    }

    #[test]
    fn test_locate_value_span_out_of_bounds_search_from_rejected_even_with_empty_value() {
        // #673 M2: the `search_from > bytes.len()` guard must run before the
        // `value.is_empty()` early return, or this returned `Some((usize::MAX, usize::MAX))`.
        let content = "short";
        assert_eq!(locate_value_span(content, usize::MAX, "", false), None);
        assert_eq!(
            locate_value_span(content, content.len() + 1, "", false),
            None
        );
    }

    #[test]
    fn test_locate_value_span_empty_value_corrects_past_opening_double_quote() {
        // #1180: the raw marker for `pkg: ""` lands on the opening `"`, one byte before the
        // actual (empty) value slot between the quotes.
        let content = r#"pkg: """#;
        let quote_offset = content.find('"').unwrap();
        let (start, end) = locate_value_span(content, quote_offset, "", true).unwrap();
        assert_eq!(start, quote_offset + 1);
        assert_eq!(end, quote_offset + 1);
    }

    #[test]
    fn test_locate_value_span_empty_value_corrects_past_opening_single_quote() {
        let content = "ref: ''";
        let quote_offset = content.find('\'').unwrap();
        let (start, end) = locate_value_span(content, quote_offset, "", true).unwrap();
        assert_eq!(start, quote_offset + 1);
        assert_eq!(end, quote_offset + 1);
    }

    #[test]
    fn test_locate_value_span_empty_value_at_non_quote_position_is_unchanged() {
        // A plain (unquoted) empty value has no opening quote to correct past — the marker
        // already points at the right (empty) slot, e.g. `ref:` with nothing after it.
        let content = "ref: ";
        let end_offset = content.len();
        let (start, end) = locate_value_span(content, end_offset, "", false).unwrap();
        assert_eq!(start, end_offset);
        assert_eq!(end, end_offset);
    }

    #[test]
    fn test_locate_value_span_plain_empty_value_never_shifts_past_a_next_token_quote() {
        // #1184 Gap 1: for a Plain empty scalar the marker points at the *next token*,
        // not the value itself — if that next token happens to start with a quote byte,
        // `is_quoted: false` must still suppress the quote-correction, unlike the quoted
        // case above where the byte-at-marker really is the value's own opening quote.
        let content = "ref: \n\"next-token\"";
        let marker_offset = content.find('\n').unwrap() + 1;
        assert_eq!(content.as_bytes()[marker_offset], b'"');
        let (start, end) = locate_value_span(content, marker_offset, "", false).unwrap();
        assert_eq!(start, marker_offset);
        assert_eq!(end, marker_offset);
    }

    #[test]
    fn test_locate_value_span_literal_style_empty_value_never_shifts_past_a_next_token_quote() {
        // #1184 critic M2: a `Literal`/`Folded` block scalar's empty body is neither
        // `Plain` nor quoted — the old `!is_plain` gate would have wrongly performed the
        // quote-correction here (`is_plain()` is `false` for `Literal` too). `is_quoted`
        // must be keyed on the actual quote styles, not the negation of `is_plain`.
        let content = "ref: |\n\"next-token\"";
        let marker_offset = content.find('\n').unwrap() + 1;
        assert_eq!(content.as_bytes()[marker_offset], b'"');
        let (start, end) = locate_value_span(content, marker_offset, "", false).unwrap();
        assert_eq!(start, marker_offset);
        assert_eq!(end, marker_offset);
    }

    #[test]
    fn test_marked_scalar_span_quoted_empty_value_anchors_after_opening_quote() {
        // End-to-end regression for #1180: `MarkedScalar::span` (via `locate_value_span`)
        // must anchor a quoted empty scalar's span at the actual value slot, not the
        // opening quote one column early — reproduces deps-dart's `pkg: ""` and
        // deps-gitlab-ci's `ref: ""`.
        use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser};

        struct Scalars(Vec<(String, TScalarStyle, Marker)>);
        impl MarkedEventReceiver for Scalars {
            fn on_event(&mut self, event: Event, marker: Marker) {
                if let Event::Scalar(value, style, ..) = event {
                    self.0.push((value, style, marker));
                }
            }
        }

        let content = "pkg: \"\"\n";
        let mut receiver = Scalars(Vec::new());
        Parser::new_from_str(content)
            .load(&mut receiver, false)
            .unwrap();
        // receiver.0[0] is the key scalar ("pkg"), receiver.0[1] is the value.
        let (value, style, marker) = receiver.0[1].clone();
        assert_eq!(value, "");
        let scalar = MarkedScalar::new(value, style, &marker);
        let table = LineOffsetTable::new(content);
        let (start, end) = scalar.span(content, &table).unwrap();
        let quote_offset = content.find("\"\"").unwrap();
        assert_eq!(
            (start, end),
            (quote_offset + 1, quote_offset + 1),
            "expected the empty value's span to anchor between the quotes, not on the \
             opening quote"
        );
    }

    #[test]
    fn test_marked_scalar_is_quoted_distinguishes_literal_from_plain_and_quoted() {
        // #1184 critic M2: `is_quoted()` must be `false` for `Literal`/`Folded`, same as
        // `Plain` — not the negation of `is_plain()`, which was `true` for `Literal` too.
        use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser};

        struct Scalars(Vec<(String, TScalarStyle, Marker)>);
        impl MarkedEventReceiver for Scalars {
            fn on_event(&mut self, event: Event, marker: Marker) {
                if let Event::Scalar(value, style, ..) = event {
                    self.0.push((value, style, marker));
                }
            }
        }

        let content = "ref: |\n";
        let mut receiver = Scalars(Vec::new());
        Parser::new_from_str(content)
            .load(&mut receiver, false)
            .unwrap();
        let (value, style, marker) = receiver.0[1].clone();
        assert_eq!(style, TScalarStyle::Literal);
        let scalar = MarkedScalar::new(value, style, &marker);
        assert!(!scalar.is_plain());
        assert!(
            !scalar.is_quoted(),
            "a Literal block scalar is neither plain nor quoted"
        );
    }

    #[test]
    fn test_locate_value_span_gives_up_beyond_fallback_bound_instead_of_hanging() {
        let filler = "x".repeat(MAX_FALLBACK_SCAN_BYTES + 100);
        let value = "actions/checkout@v4";
        let content = format!("{filler}{value}");
        assert_eq!(locate_value_span(&content, 0, value, false), None);
    }

    #[test]
    fn test_locate_value_span_bounded_scan_stays_fast_on_a_huge_line() {
        // Regression guard (security S-2): a several-megabyte single-line haystack must
        // resolve in milliseconds, not minutes, once the scan is bounded.
        let value = "not-present-in-filler@v4";
        let result = crate::test_util::scaling::assert_scaling(
            "locate_value_span on a huge line",
            crate::test_util::scaling::ExpectedGrowth::Bounded,
            6 * 1024 * 1024,
            |len| format!("{}\n", "y".repeat(len)),
            |content| locate_value_span(content, 0, value, false),
        );
        assert_eq!(result, None);
    }

    #[test]
    fn test_locate_value_span_many_fallback_scans_on_one_huge_line_stay_bounded() {
        // Regression for #885 (S2): each fallback-triggering call on one huge physical line
        // used to cost O(remaining-document-length) despite the cap. Simulates many
        // fallback-forcing lookups on one multi-megabyte single-line manifest.
        let value = "actions/checkout@v4";

        crate::test_util::scaling::assert_scaling(
            "locate_value_span fallback calls against a huge-tail single line",
            crate::test_util::scaling::ExpectedGrowth::Bounded,
            8 * 1024 * 1024,
            |tail_len| {
                let filler_segment = "z".repeat(64);
                let mut content = String::new();
                let mut offsets = Vec::new();
                for _ in 0..2000 {
                    offsets.push(content.len());
                    content.push_str(&filler_segment);
                }
                content.push_str(&"w".repeat(tail_len));
                (content, offsets)
            },
            |(content, offsets)| {
                for &offset in offsets {
                    std::hint::black_box(locate_value_span(content, offset, value, false));
                }
            },
        );
    }

    #[test]
    fn test_marker_byte_offset_ascii() {
        let content = "hello\nworld";
        let table = LineOffsetTable::new(content);
        assert_eq!(marker_byte_offset(content, &table, 1, 0), 0);
        assert_eq!(marker_byte_offset(content, &table, 2, 3), 9);
    }

    #[test]
    fn test_marker_byte_offset_multibyte() {
        let content = "\u{3000}a\nb";
        let table = LineOffsetTable::new(content);
        // U+3000 is 3 bytes; the second char ('a') on line 1 starts at byte 3.
        assert_eq!(marker_byte_offset(content, &table, 1, 1), 3);
        // Line 2 ('b') starts right after the '\n'.
        assert_eq!(marker_byte_offset(content, &table, 2, 0), 5);
    }

    #[test]
    fn test_marker_byte_offset_block_scalar_drift_regression() {
        // #879: a non-ASCII char inside a `|` block scalar must not desync the byte offset
        // resolved for a later scalar — reproduces the yaml-rust2 Marker::index() drift.
        let content = "run: |\n  echo \u{2014} hi\nuses: actions/checkout@v4\n";
        let table = LineOffsetTable::new(content);
        // Line 3, col 6 is where "actions/checkout@v4" starts (after "uses: ").
        let expected = content.find("actions/checkout@v4").unwrap();
        assert_eq!(marker_byte_offset(content, &table, 3, 6), expected);
    }

    #[test]
    fn test_marker_byte_offset_line_past_end_returns_content_len() {
        let content = "hello";
        let table = LineOffsetTable::new(content);
        assert_eq!(marker_byte_offset(content, &table, 5, 0), content.len());
    }

    #[test]
    fn test_marker_byte_offset_multiple_multibyte_chars_before_target_col() {
        // Each multi-byte char before the target col must count as one *char*, not its byte
        // length, when walking to `col` (#879's failure mode, direct on the resolver).
        let content = "\u{2014}\u{2014}\u{3000}target";
        let table = LineOffsetTable::new(content);
        // 3 leading multi-byte chars (3 + 3 + 3 = 9 bytes), then "target" starts at char
        // column 3.
        assert_eq!(marker_byte_offset(content, &table, 1, 3), 9);
    }

    #[test]
    fn test_marker_byte_offset_col_past_end_of_line_clamps_to_line_end() {
        let content = "ab\ncd";
        let table = LineOffsetTable::new(content);
        // Line 1 ("ab") has only 2 chars; a col past that clamps to the line span's byte
        // end (`table.line_start(1)`, i.e. right after the '\n', where the next line
        // starts), rather than panicking or reading past that into line 2's content.
        assert_eq!(marker_byte_offset(content, &table, 1, 100), 3);
    }

    #[test]
    fn test_marker_byte_offset_ascii_fast_path_matches_char_indices_result() {
        // Differential test: the `line_is_ascii` fast path must agree with the pre-S1
        // general `char_indices().nth(col)` walk (reimplemented here) for every column on
        // an ASCII line, including overshoot — the desync class S1's fix could introduce.
        fn slow_path(content: &str, table: &LineOffsetTable, line: usize, col: usize) -> usize {
            let Some(line_start) = table.line_start(line.saturating_sub(1)) else {
                return content.len();
            };
            let line_end = table.line_start(line).unwrap_or(content.len());
            let line_text = content.get(line_start..line_end).unwrap_or_default();
            let byte_in_line = line_text
                .char_indices()
                .nth(col)
                .map_or(line_text.len(), |(b, _)| b);
            line_start + byte_in_line
        }

        let content = "uses: actions/checkout@v4\nref: v1.0.0\n";
        let table = LineOffsetTable::new(content);
        for col in 0..=35 {
            assert_eq!(
                marker_byte_offset(content, &table, 1, col),
                slow_path(content, &table, 1, col),
                "ascii fast path desynced from the general char_indices() walk at col {col}"
            );
        }
    }

    #[test]
    fn test_marker_byte_offset_ascii_fast_path_stays_linear_on_a_huge_single_line() {
        // Regression guard (S1, impl-critic, #879 follow-up): without `line_is_ascii`,
        // this was O(line length) per call, reintroducing the O(n^2) shape.
        // Lookups scale with the line length, so a per-lookup O(line length) cost shows up as
        // quadratic growth rather than a constant factor.
        crate::test_util::scaling::assert_scaling(
            "marker_byte_offset on a huge ASCII line",
            crate::test_util::scaling::ExpectedGrowth::Linear,
            6 * 1024 * 1024,
            |len| {
                let filler = "x".repeat(len);
                let table = LineOffsetTable::new(&filler);
                (filler, table)
            },
            |(filler, table)| {
                for col in (0..filler.len()).step_by(1200) {
                    assert_eq!(marker_byte_offset(filler, table, 1, col), col);
                }
            },
        );
    }

    #[test]
    fn test_marker_byte_offset_non_ascii_line_cache_stays_fast_on_a_huge_single_line() {
        // Regression guard for #882: without the per-line char-boundary cache, N lookups on
        // the same non-ASCII line cost O(N x line length) — ~500ms for 5000 lookups on a
        // several-hundred-KB line in a release build.
        crate::test_util::scaling::assert_scaling(
            "marker_byte_offset on a huge non-ASCII line",
            crate::test_util::scaling::ExpectedGrowth::Linear,
            200 * 1024,
            |half_len| {
                let filler = "x".repeat(half_len);
                let content = format!("{filler}\u{2014}{filler}");
                let table = LineOffsetTable::new(&content);
                let char_count = content.chars().count();
                (content, table, char_count)
            },
            |(content, table, char_count)| {
                for col in (0..*char_count).step_by(80) {
                    let _ = marker_byte_offset(content, table, 1, col);
                }
            },
        );
    }

    #[test]
    fn test_marker_byte_offset_non_ascii_cache_matches_char_indices_result() {
        // Differential test: the cached char-boundary path must agree with a plain
        // reimplemented `char_indices().nth(col)` walk for every column on a non-ASCII line —
        // the exact class of desync a caching bug could silently introduce.
        fn slow_path(content: &str, table: &LineOffsetTable, line: usize, col: usize) -> usize {
            let Some(line_start) = table.line_start(line.saturating_sub(1)) else {
                return content.len();
            };
            let line_end = table.line_start(line).unwrap_or(content.len());
            let line_text = content.get(line_start..line_end).unwrap_or_default();
            let byte_in_line = line_text
                .char_indices()
                .nth(col)
                .map_or(line_text.len(), |(b, _)| b);
            line_start + byte_in_line
        }

        let content = "\u{1f680}rocket \u{2014} emoji then em dash \u{3000} and more";
        let table = LineOffsetTable::new(content);
        for col in 0..=(content.chars().count() + 5) {
            assert_eq!(
                marker_byte_offset(content, &table, 1, col),
                slow_path(content, &table, 1, col),
                "cached non-ASCII path desynced from the general char_indices() walk at col \
                 {col}"
            );
        }
    }

    #[test]
    fn test_marker_byte_offset_multiple_non_ascii_lines_cache_isolation() {
        // Coverage gap flagged by #882 review: the per-line cache must resolve two or more
        // non-ASCII lines independently regardless of query order, with no cross-line leak.
        fn slow_path(content: &str, table: &LineOffsetTable, line: usize, col: usize) -> usize {
            let Some(line_start) = table.line_start(line.saturating_sub(1)) else {
                return content.len();
            };
            let line_end = table.line_start(line).unwrap_or(content.len());
            let line_text = content.get(line_start..line_end).unwrap_or_default();
            let byte_in_line = line_text
                .char_indices()
                .nth(col)
                .map_or(line_text.len(), |(b, _)| b);
            line_start + byte_in_line
        }

        let content = "ascii only\n\u{2014}em dash line\n\u{1f680}rocket \u{3000}ideographic line\nascii again";
        let table = LineOffsetTable::new(content);

        // Query line 3 first, then line 2, then re-query line 3 and line 2 — deliberately out
        // of line order and with a repeat, to catch any cross-line contamination.
        let cases: &[(usize, usize)] = &[(3, 5), (2, 2), (3, 0), (2, 5), (3, 8), (2, 0)];
        for &(line, col) in cases {
            assert_eq!(
                marker_byte_offset(content, &table, line, col),
                slow_path(content, &table, line, col),
                "line {line} col {col} desynced after interleaved multi-line lookups"
            );
        }
    }

    #[test]
    fn test_marker_byte_offset_non_ascii_line_still_correct_without_fast_path() {
        // The fast path must only trigger for a genuinely ASCII line; a non-ASCII line still
        // takes the O(line) `char_indices()` walk, unchanged from before S1.
        let content = "\u{1f680}rocket \u{2014} emoji then em dash";
        let table = LineOffsetTable::new(content);
        let expected = content.char_indices().nth(3).unwrap().0;
        assert_eq!(marker_byte_offset(content, &table, 1, 3), expected);
    }

    #[test]
    fn test_marker_byte_offset_lone_cr_document_documented_limitation() {
        // S2 (impl-critic, #879 follow-up): a bare-`\r` document is out of scope per the
        // "Line-ending assumption" doc section, so this falls back to `content.len()`.
        // Locks in the documented behavior, not asserting it is desirable.
        let content = "on: push\rjobs:\r  build:\r    steps:\r      - uses: actions/checkout@v4\r";
        let table = LineOffsetTable::new(content);
        // yaml-rust2 would report line 5 for the `uses:` value here; only line 1 exists in
        // the table since it never splits on a lone `\r`.
        assert_eq!(marker_byte_offset(content, &table, 5, 14), content.len());
    }

    #[test]
    fn test_tag_index_coverage_defaults_to_complete() {
        assert_eq!(TagIndex::default().coverage(), ListCoverage::Complete);
        assert_eq!(
            TagIndex::from_tags(std::iter::empty()).coverage(),
            ListCoverage::Complete
        );
    }

    #[test]
    fn test_tag_index_with_coverage_records_truncation() {
        let index = TagIndex::default().with_coverage(ListCoverage::Truncated);
        assert_eq!(index.coverage(), ListCoverage::Truncated);
    }

    #[cfg(feature = "lsp-responses")]
    mod lsp_tests {
        use super::*;

        #[test]
        fn splice_hover_line_anchor_priority_resolved_then_current_then_requirement() {
            let with_resolved = "**Current**: `a`\n\n**Resolved**: `b`\n\nBody.";
            assert_eq!(
                splice_hover_line(with_resolved, "W"),
                "**Current**: `a`\n\n**Resolved**: `b`\n\nW\n\nBody."
            );
            assert_eq!(
                splice_hover_line("**Requirement**: `a`\n\nBody.", "W"),
                "**Requirement**: `a`\n\nW\n\nBody."
            );
            assert_eq!(splice_hover_line("Body.", "W"), "Body.W\n\n");
        }

        /// #1311: `resolved_tag` is tag-index/registry-controlled and unbounded — mirrors
        /// diagnostics.rs's `MAX_VERSION_DIAGNOSTIC_CHARS` truncation test pattern.
        #[test]
        fn splice_resolved_line_truncates_overlong_resolved_tag() {
            let long_tag = "9".repeat(5000);
            let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
            let out = splice_resolved_line("", &long_tag, &sha);
            assert!(out.len() < long_tag.len(), "got: {out}");
            assert!(out.contains('…'));
        }

        /// #1310 critic M2: boundary case using `MAX_VERSION_DIAGNOSTIC_CHARS` specifically,
        /// not just the 5000-char extreme.
        #[test]
        fn splice_resolved_line_boundary_at_and_over_cap() {
            let cap = MAX_VERSION_DIAGNOSTIC_CHARS;
            let sha = CommitSha::parse(&"a".repeat(40)).unwrap();

            // `short_sha` always renders with a trailing `…` of its own (it's a fixed
            // 7-char prefix of a 40-char SHA), so a blanket "no ellipsis anywhere"
            // assertion would be wrong here — check the tag's own code span exactly instead.
            let at_cap = "9".repeat(cap);
            let out = splice_resolved_line("", &at_cap, &sha);
            assert!(out.contains(&format!("`{at_cap}`")), "got: {out}");

            let over_cap = "9".repeat(cap + 1);
            let out = splice_resolved_line("", &over_cap, &sha);
            assert!(
                out.contains(&format!("`{}…`", "9".repeat(cap))),
                "got: {out}"
            );
        }

        /// #1311/#1313: `resolved_tag` is a git tag (name/version-shaped), so it must strip
        /// a `sanitize_invisible`-only codepoint (U+0600 ARABIC NUMBER SIGN) that
        /// `is_markdown_unsafe` alone does not catch — deliberately exempt per #1248/#1323
        /// — the same treatment `HoverMarkdown`'s `Name`/`Version` field kinds now apply.
        #[test]
        fn splice_resolved_line_strips_u0600_from_resolved_tag() {
            let sha = CommitSha::parse(&"a".repeat(40)).unwrap();
            let out = splice_resolved_line("", &format!("v1.0{}0", '\u{0600}'), &sha);
            assert!(
                !out.contains('\u{0600}'),
                "U+0600 must be stripped from resolved_tag; got: {out}"
            );
        }

        // --- #1138 review M5: direct coverage for `build_sha_pin_action`/`sha_pin_text_edit`,
        // which previously had only indirect coverage via ecosystem-crate wrapper tests.

        use crate::lsp_helpers::test_support::MOCK_FORMATTER;

        use crate::position::Position as CorePosition;

        use crate::test_util::StubFormatter;

        use crate::{PackageName, VersionReq};

        /// Resolves a dependency named `"resolvable"` to a fixed SHA; declines everything else
        /// — the minimal [`ShaPinning`] fixture these tests need, layered onto the shared
        /// [`MOCK_FORMATTER`] fixture (already implements every [`EcosystemFormatter`] sub-trait)
        /// rather than hand-rolling a second formatter mock.
        impl ShaPinning for StubFormatter {
            fn resolve_static_sha_pin(&self, dep: &dyn Dependency) -> Option<ResolvedShaPin> {
                if dep.name().as_str() != "resolvable" {
                    return None;
                }
                Some(ResolvedShaPin {
                    display_name: dep.name().as_str().to_string(),
                    version_range: dep.version_range()?,
                    replacement: "a".repeat(40),
                })
            }
        }

        #[expect(
            clippy::cast_possible_truncation,
            reason = "fixed short ASCII test-fixture names never approach u32::MAX"
        )]
        fn sha_pin_test_dep(name: &str) -> crate::lsp_helpers::test_support::MockDep {
            let range = Range::new(
                CorePosition::new(0, 6),
                CorePosition::new(0, 6 + name.len() as u32),
            );
            crate::lsp_helpers::test_support::MockDep {
                name: PackageName::new(name),
                version_req: VersionReq::new("v1"),
                version_range: range,
                name_range: range,
            }
        }

        #[test]
        fn test_build_sha_pin_action_resolves_at_position() {
            let dep = sha_pin_test_dep("resolvable");
            let uri = crate::test_util::test_uri("/repo/manifest.yml");
            let parse_result = crate::lsp_helpers::test_support::MockParseResult {
                deps: vec![dep],
                uri: uri.clone(),
            };
            let position = Position {
                line: 0,
                character: 7,
            };

            let action = build_sha_pin_action(
                &parse_result,
                position,
                &uri,
                &MOCK_FORMATTER,
                "TEST_DIAGNOSTIC_CODE",
            )
            .expect("resolvable dependency at position must produce a quickfix");

            assert_eq!(action.title, "Pin resolvable to commit SHA");
            let edits = action
                .edit
                .expect("quickfix must carry a WorkspaceEdit")
                .changes
                .expect("WorkspaceEdit must carry changes");
            let text_edits = edits.values().next().expect("one file's edits");
            assert_eq!(text_edits.len(), 1);
            assert_eq!(text_edits[0].new_text, "a".repeat(40));
        }

        #[test]
        fn test_build_sha_pin_action_none_when_pinning_declines() {
            let dep = sha_pin_test_dep("not-resolvable");
            let uri = crate::test_util::test_uri("/repo/manifest.yml");
            let parse_result = crate::lsp_helpers::test_support::MockParseResult {
                deps: vec![dep],
                uri: uri.clone(),
            };
            let position = Position {
                line: 0,
                character: 7,
            };

            assert!(
                build_sha_pin_action(
                    &parse_result,
                    position,
                    &uri,
                    &MOCK_FORMATTER,
                    "TEST_DIAGNOSTIC_CODE",
                )
                .is_none()
            );
        }

        #[test]
        fn test_build_sha_pin_action_none_when_position_off_dependency() {
            let dep = sha_pin_test_dep("resolvable");
            let uri = crate::test_util::test_uri("/repo/manifest.yml");
            let parse_result = crate::lsp_helpers::test_support::MockParseResult {
                deps: vec![dep],
                uri: uri.clone(),
            };
            let position = Position {
                line: 5,
                character: 0,
            };

            assert!(
                build_sha_pin_action(
                    &parse_result,
                    position,
                    &uri,
                    &MOCK_FORMATTER,
                    "TEST_DIAGNOSTIC_CODE",
                )
                .is_none()
            );
        }

        #[test]
        fn test_sha_pin_text_edit_resolves() {
            let dep = sha_pin_test_dep("resolvable");
            let edit = sha_pin_text_edit(&MOCK_FORMATTER, &dep)
                .expect("resolvable dependency must resolve");
            assert_eq!(edit.new_text, "a".repeat(40));
            assert_eq!(edit.range, dep.version_range.into());
        }

        #[test]
        fn test_sha_pin_text_edit_none_when_pinning_declines() {
            let dep = sha_pin_test_dep("not-resolvable");
            assert!(sha_pin_text_edit(&MOCK_FORMATTER, &dep).is_none());
        }

        crate::debug_redaction_conformance!(
            test_resolved_sha_pin_debug_redacts_credentials,
            1,
            ResolvedShaPin {
                display_name: crate::conformance::CREDENTIAL_PROBE_KEY.to_string(),
                version_range: Range::default(),
                replacement: "a".repeat(40),
            },
        );
    }
}