rumdl 0.2.76

A fast Markdown linter and formatter written in Rust
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
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
//!
//! Rule MD057: Existing relative links
//!
//! See [docs/md057.md](../../docs/md057.md) for full documentation, configuration, and examples.

use crate::rule::{
    CrossFileScope, Fix, FixCapability, LintError, LintResult, LintWarning, Rule, RuleCategory, Severity,
};
use crate::utils::frontmatter_values;
use crate::utils::range_utils::byte_to_char_count;
use crate::workspace_index::{
    FileIndex, LinkOrigin, Md057LinkTarget, URL_EXTRACT_ANGLE_BRACKET_REGEX, URL_EXTRACT_REGEX,
    extract_cross_file_links, normalize_relative_path,
};
use pulldown_cmark::LinkType;
use regex::Regex;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::env;
use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use unicode_normalization::UnicodeNormalization;

mod md057_config;
use crate::utils::mkdocs_config::resolve_docs_dir;
use crate::utils::obsidian_config::resolve_attachment_folder;
use crate::utils::project_root::project_root;
pub use md057_config::{AbsoluteLinksOption, MD057Config};

// Thread-safe cache for file existence checks to avoid redundant filesystem operations
static FILE_EXISTENCE_CACHE: LazyLock<Arc<Mutex<HashMap<PathBuf, bool>>>> =
    LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));

/// The shared map behind the directory cache. Each listing is an `Arc` so a
/// lookup clones the handle and releases the lock before reading the names.
type DirectoryListingCache = Arc<Mutex<HashMap<PathBuf, Arc<DirectoryListing>>>>;

/// Directory listings, keyed by directory. One listing answers for every link
/// naming an entry in that directory, and stands for as long as the
/// directory's modification time does.
static DIRECTORY_LISTING_CACHE: LazyLock<DirectoryListingCache> =
    LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));

/// Drops what one check learned about which paths exist, so the next check
/// asks the filesystem again.
///
/// The directory listings are not dropped. Each carries the modification time
/// it was read at and is read again once that time moves, which is a stat per
/// lookup rather than a read of the whole directory per file checked.
fn reset_file_existence_cache() {
    if let Ok(mut cache) = FILE_EXISTENCE_CACHE.lock() {
        cache.clear();
    }
}

/// The entry names of one directory, in the spelling the filesystem stores,
/// together with the moment they were read at.
struct DirectoryListing {
    /// The directory's modification time when the read began, or `None` where
    /// the directory's metadata could not be read. A lookup keeps this listing
    /// only while the directory still reports this time.
    modified: Option<SystemTime>,
    /// Whether the directory could be read in full. One that could not says
    /// nothing about how its entries are spelled.
    listed: bool,
    /// Every entry name, compared byte for byte.
    names: HashSet<OsString>,
    /// The composed form of each entry name holding a character outside ASCII.
    /// A macOS volume can store such a name decomposed while the link is typed
    /// composed, and the two spell the same name.
    composed: HashSet<String>,
}

impl DirectoryListing {
    /// A listing that says nothing about how the directory's entries are
    /// spelled, so every name under it is accepted.
    fn unlisted(modified: Option<SystemTime>) -> Self {
        Self {
            modified,
            listed: false,
            names: HashSet::new(),
            composed: HashSet::new(),
        }
    }

    fn read(directory: &Path) -> Self {
        // The time is taken before the entries are, so a change landing during
        // the read leaves this listing behind the directory's own time and the
        // next lookup reads again.
        let modified = std::fs::metadata(directory)
            .and_then(|metadata| metadata.modified())
            .ok();
        let mut names = HashSet::new();
        let mut composed = HashSet::new();
        let Ok(entries) = std::fs::read_dir(directory) else {
            return Self::unlisted(modified);
        };
        for entry in entries {
            let Ok(entry) = entry else {
                // A name the kernel could not return is missing from these
                // names, and a listing missing a name must not answer that the
                // name is absent.
                return Self::unlisted(modified);
            };
            let name = entry.file_name();
            if let Some(text) = name.to_str()
                && !text.is_ascii()
            {
                composed.insert(text.nfc().collect());
            }
            names.insert(name);
        }
        Self {
            modified,
            listed: true,
            names,
            composed,
        }
    }

    /// Whether the directory holds an entry that spells `name`: either the
    /// spelling as written, or the same name in composed form on one side or
    /// the other. A name outside ASCII can compose to one inside it (the
    /// Kelvin sign composes to the letter K), so an ASCII name is looked up
    /// among the composed forms as well, and a composed form is looked up
    /// among the entries as written as well as among their composed forms.
    fn holds(&self, name: &OsStr) -> bool {
        if !self.listed {
            return true;
        }
        if self.names.contains(name) {
            return true;
        }
        let Some(text) = name.to_str() else {
            return false;
        };
        if text.is_ascii() {
            return self.composed.contains(text);
        }
        let composed: String = text.nfc().collect();
        self.composed.contains(composed.as_str()) || self.names.contains(OsStr::new(composed.as_str()))
    }
}

/// The listing of `directory`, reused for every link naming an entry in it
/// until the directory's modification time moves.
///
/// A lookup stats the directory and keeps a stored listing only while the time
/// it recorded is the one the directory reports, so a directory of many
/// documents linking to their siblings is read once rather than once per
/// document. Creating, deleting or renaming an entry moves that time on APFS,
/// ext4 and NTFS, so a process that lints the same tree repeatedly sees the
/// change at its next lookup. Where the filesystem keeps the time coarsely,
/// one second on HFS+ and two on FAT, a change inside the same tick as the
/// read is seen once the directory next changes. A long-lived process holds
/// one listing per directory its links reach.
///
/// The read happens with no lock held, so one slow directory does not stop
/// other threads answering from the cache. Two threads reaching the same
/// directory both read it and store the same names.
fn directory_listing(directory: &Path) -> Arc<DirectoryListing> {
    let Ok(modified) = std::fs::metadata(directory).and_then(|metadata| metadata.modified()) else {
        // With no time to compare against, a stored listing cannot be told
        // from one the directory has outgrown.
        return Arc::new(DirectoryListing::read(directory));
    };
    match DIRECTORY_LISTING_CACHE.lock() {
        Ok(cache) => {
            if let Some(listing) = cache.get(directory)
                && listing.modified == Some(modified)
            {
                return Arc::clone(listing);
            }
        }
        Err(_) => return Arc::new(DirectoryListing::read(directory)), // Fallback to an uncached listing on mutex poison
    }
    let listing = Arc::new(DirectoryListing::read(directory));
    match DIRECTORY_LISTING_CACHE.lock() {
        Ok(mut cache) => {
            // Two threads that raced on an unchanged directory store the same
            // names. If the directory changed between their reads, the slower
            // thread can store the older listing over the newer one; the next
            // lookup's stat then finds a time that no longer matches and reads
            // again, so a stale insert costs one extra read and never a wrong
            // answer.
            cache.insert(directory.to_path_buf(), Arc::clone(&listing));
            listing
        }
        Err(_) => listing, // Fallback to an uncached listing on mutex poison
    }
}

// Check if a file exists with caching
fn file_exists_with_cache(path: &Path) -> bool {
    match FILE_EXISTENCE_CACHE.lock() {
        Ok(mut cache) => *cache.entry(path.to_path_buf()).or_insert_with(|| path.exists()),
        Err(_) => path.exists(), // Fallback to uncached check on mutex poison
    }
}

/// Whether every component of `path` below `anchor` is spelled the way the
/// filesystem stores it.
///
/// `anchor` is the directory the link resolves against, so everything above it
/// is the path to the project rather than anything the link author wrote and is
/// left alone. A `..` moves up without a listing check, and a directory that
/// cannot be listed is accepted, so the walk only ever rejects a spelling a
/// directory listing contradicts.
///
/// A `..` component moves the anchor up lexically, the way a URL resolver does,
/// so a link through a symlinked directory is judged by the path as written
/// rather than by the directory the symlink reaches.
fn has_exact_case_components(anchor: &Path, path: &Path) -> bool {
    let Ok(relative) = path.strip_prefix(anchor) else {
        return true;
    };
    let mut directory = if anchor.as_os_str().is_empty() {
        PathBuf::from(".")
    } else {
        anchor.to_path_buf()
    };
    for component in relative.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                // Only a named directory can be stepped out of by dropping it.
                // Above a root, or past a `..` already on the path, the step
                // has to be written out instead.
                if matches!(directory.components().next_back(), Some(Component::Normal(_))) {
                    directory.pop();
                } else {
                    directory.push("..");
                }
                // Dropping the only component of a relative path lands on the
                // directory the process runs in.
                if directory.as_os_str().is_empty() {
                    directory.push(".");
                }
            }
            Component::Normal(name) => {
                if !directory_listing(&directory).holds(name) {
                    return false;
                }
                directory.push(name);
            }
            // A relative path holds neither, and a path that does is not one
            // this rule resolved against the anchor.
            Component::RootDir | Component::Prefix(_) => return true,
        }
    }
    true
}

/// Whether `path` exists with exactly the spelling it is written in.
///
/// A case-insensitive volume answers `exists` for a spelling it does not store,
/// so macOS and Windows accept a link that 404s on every web server and breaks
/// the moment the project is checked out on Linux. The filesystem's own answer
/// is the cheap negative: a path that is not there is not there whatever its
/// case. A path that is there is confirmed against the directory listings below
/// `anchor`, which compare the stored name, as a server does.
fn exists_exact_case(anchor: &Path, path: &Path) -> bool {
    file_exists_with_cache(path) && has_exact_case_components(anchor, path)
}

/// Check if a file exists, also trying markdown extensions for extensionless links.
/// This supports wiki-style links like `[Link](page)` that resolve to `page.md`.
fn file_exists_or_markdown_extension(anchor: &Path, path: &Path) -> bool {
    resolve_existing_target(anchor, path).is_some()
}

/// The file a link path resolves to, or `None` when nothing is there.
///
/// An extensionless link is tried against the markdown extensions in turn, so
/// `[Link](page)` resolves to `page.md`. Callers that only need existence go
/// through `file_exists_or_markdown_extension`; the resolved path itself
/// matters when the answer has to be compared against another file.
fn resolve_existing_target(anchor: &Path, path: &Path) -> Option<PathBuf> {
    // First, check exact path
    if exists_exact_case(anchor, path) {
        return Some(path.to_path_buf());
    }

    // If the path has no extension, try adding markdown extensions
    if path.extension().is_none() {
        for ext in MARKDOWN_EXTENSIONS {
            // MARKDOWN_EXTENSIONS includes the dot, e.g., ".md"
            let path_with_ext = path.with_extension(&ext[1..]);
            if exists_exact_case(anchor, &path_with_ext) {
                return Some(path_with_ext);
            }
        }
    }

    None
}

/// Regex to detect URLs with explicit schemes (should not be checked as relative links)
/// Matches: scheme:// or scheme: (per RFC 3986)
/// This covers http, https, ftp, file, smb, mailto, tel, data, macappstores, etc.
static PROTOCOL_DOMAIN_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([a-zA-Z][a-zA-Z0-9+.-]*://|[a-zA-Z][a-zA-Z0-9+.-]*:|www\.)").unwrap());

// Current working directory
static CURRENT_DIR: LazyLock<PathBuf> = LazyLock::new(|| env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

/// Convert a hex digit (0-9, a-f, A-F) to its numeric value.
/// Returns None for non-hex characters.
#[inline]
fn hex_digit_to_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// Supported markdown file extensions
const MARKDOWN_EXTENSIONS: &[&str] = &[
    ".md",
    ".markdown",
    ".mdx",
    ".mkd",
    ".mkdn",
    ".mdown",
    ".mdwn",
    ".qmd",
    ".rmd",
];

/// A relative link that resolves to the file it is written in.
#[derive(Debug, PartialEq, Eq)]
enum SelfReferentialLink {
    /// The link addresses the whole file, so there is no shorter way to write
    /// the same destination.
    WholeFile,
    /// The link carries a fragment, which on its own reaches the same heading
    /// without leaving the page.
    Fragment(String),
}

#[cfg(feature = "blake3")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DependencyPathState {
    Missing,
    File,
    Directory,
    Other,
}

/// Rule MD057: Existing relative links should point to valid files or directories.
#[derive(Debug, Clone)]
pub struct MD057ExistingRelativeLinks {
    /// Base directory for resolving relative links. Behind an `Arc<Mutex<..>>`
    /// so it is shared across clones (the rule is cloned per config group and
    /// for inline-config overrides); the base is resolved from the file under
    /// check and consulted while validating that file's links.
    base_path: Arc<Mutex<Option<PathBuf>>>,
    /// Configuration for the rule
    config: MD057Config,
}

impl Default for MD057ExistingRelativeLinks {
    fn default() -> Self {
        Self {
            base_path: Arc::new(Mutex::new(None)),
            config: MD057Config::default(),
        }
    }
}

impl MD057ExistingRelativeLinks {
    /// Create a new instance with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the base path for resolving relative links
    pub fn with_path<P: AsRef<Path>>(self, path: P) -> Self {
        let path = path.as_ref();
        let dir_path = if path.is_file() {
            path.parent().map(std::path::Path::to_path_buf)
        } else {
            Some(path.to_path_buf())
        };

        if let Ok(mut guard) = self.base_path.lock() {
            *guard = dir_path;
        }
        self
    }

    pub fn from_config_struct(config: MD057Config) -> Self {
        Self {
            base_path: Arc::new(Mutex::new(None)),
            config,
        }
    }

    /// Resolve a config-supplied path string (from `roots` or `search-paths`)
    /// against the project root: absolute strings are taken verbatim, relative
    /// strings are joined onto `project_root`.
    fn resolve_against_project_root(path_str: &str, project_root: &Path) -> PathBuf {
        if Path::new(path_str).is_absolute() {
            PathBuf::from(path_str)
        } else {
            project_root.join(path_str)
        }
    }

    /// Check if a URL is external or should be skipped for validation.
    ///
    /// Returns `true` (skip validation) for:
    /// - URLs with protocols: `https://`, `http://`, `ftp://`, `mailto:`, etc.
    /// - Bare domains: `www.example.com`, `example.com`
    /// - Email addresses: `user@example.com` (without `mailto:`)
    /// - Template variables: `{{URL}}`, `{{% include %}}`
    /// - Absolute web URL paths: `/api/docs`, `/blog/post.html`
    ///
    /// Returns `false` (validate) for:
    /// - Relative filesystem paths: `./file.md`, `../parent/file.md`, `file.md`
    #[inline]
    fn is_external_url(&self, url: &str) -> bool {
        if url.is_empty() {
            return false;
        }

        // Quick checks for common external URL patterns
        if PROTOCOL_DOMAIN_REGEX.is_match(url) || url.starts_with("www.") {
            return true;
        }

        // Skip template variables (Handlebars/Mustache/Jinja2 syntax)
        // Examples: {{URL}}, {{#URL}}, {{> partial}}, {{% include %}}, {{ variable }}
        if url.starts_with("{{") || url.starts_with("{%") {
            return true;
        }

        // Simple check: if URL contains @, it's almost certainly an email address
        // File paths with @ are extremely rare, so this is a safe heuristic
        if url.contains('@') {
            return true; // It's an email address, skip it
        }

        // Bare domain check (e.g., "example.com")
        // Note: We intentionally DON'T skip all TLDs like .org, .net, etc.
        // Links like [text](nodejs.org/path) without a protocol are broken -
        // they'll be treated as relative paths by markdown renderers.
        // Flagging them helps users find missing protocols.
        // We only skip .com as a minimal safety net for the most common case.
        // Require the absence of a path separator so a relative file reference
        // that merely ends in ".com" (e.g. "../../vendor.com") is still
        // validated rather than assumed to be a bare domain.
        if !url.contains('/') && url.ends_with(".com") {
            return true;
        }

        // Framework path aliases (resolved by build tools like Vite, webpack, etc.)
        // These are not filesystem paths but module/asset aliases
        // Examples: ~/assets/image.png, @images/photo.jpg, @/components/Button.vue
        if url.starts_with('~') || url.starts_with('@') {
            return true;
        }

        // All other cases (relative paths, etc.) are not external
        false
    }

    /// External destinations and gh-aw output placeholders do not name files
    /// relative to the Markdown source.
    #[inline]
    fn is_non_file_destination(&self, url: &str, flavor: crate::config::MarkdownFlavor) -> bool {
        self.is_external_url(url)
            || (flavor == crate::config::MarkdownFlavor::GhAw && crate::utils::gh_aw::is_output_placeholder(url))
    }

    /// Check if the URL is a fragment-only link (internal document link)
    #[inline]
    fn is_fragment_only_link(&self, url: &str) -> bool {
        url.starts_with('#')
    }

    /// Check if the URL is an absolute path (starts with /)
    /// These are typically routes for published documentation sites.
    #[inline]
    fn is_absolute_path(url: &str) -> bool {
        url.starts_with('/')
    }

    /// Decode URL percent-encoded sequences in a path.
    /// Converts `%20` to space, `%2F` to `/`, etc.
    /// Returns the original string if decoding fails or produces invalid UTF-8.
    fn url_decode(path: &str) -> String {
        // Quick check: if no percent sign, return as-is
        if !path.contains('%') {
            return path.to_string();
        }

        let bytes = path.as_bytes();
        let mut result = Vec::with_capacity(bytes.len());
        let mut i = 0;

        while i < bytes.len() {
            if bytes[i] == b'%' && i + 2 < bytes.len() {
                // Try to parse the two hex digits following %
                let hex1 = bytes[i + 1];
                let hex2 = bytes[i + 2];
                if let (Some(d1), Some(d2)) = (hex_digit_to_value(hex1), hex_digit_to_value(hex2)) {
                    result.push(d1 * 16 + d2);
                    i += 3;
                    continue;
                }
            }
            result.push(bytes[i]);
            i += 1;
        }

        // Convert to UTF-8, falling back to original if invalid
        String::from_utf8(result).unwrap_or_else(|_| path.to_string())
    }

    /// Strip query parameters and fragments from a URL for file existence checking.
    /// URLs like `path/to/image.png?raw=true` or `file.md#section` should check
    /// for `path/to/image.png` or `file.md` respectively.
    ///
    /// Note: In standard URLs, query parameters (`?`) come before fragments (`#`),
    /// so we check for `?` first. If a URL has both, only the query is stripped here
    /// (fragments are handled separately by the regex in `contribute_to_index`).
    fn strip_query_and_fragment(url: &str) -> &str {
        // Find the first occurrence of '?' or '#', whichever comes first
        // This handles both standard URLs (? before #) and edge cases (# before ?)
        let query_pos = url.find('?');
        let fragment_pos = url.find('#');

        match (query_pos, fragment_pos) {
            (Some(q), Some(f)) => {
                // Both exist - strip at whichever comes first
                &url[..q.min(f)]
            }
            (Some(q), None) => &url[..q],
            (None, Some(f)) => &url[..f],
            (None, None) => url,
        }
    }

    /// Resolve a relative link against a provided base path
    fn resolve_link_path_with_base(link: &str, base_path: &Path) -> PathBuf {
        base_path.join(link)
    }

    /// Compute additional search paths for fallback link resolution.
    ///
    /// Combines Obsidian attachment folder auto-detection (when flavor is Obsidian)
    /// with explicitly configured `search-paths`.
    fn compute_search_paths(
        &self,
        flavor: crate::config::MarkdownFlavor,
        source_file: Option<&Path>,
        base_path: &Path,
        project_root: &Path,
    ) -> Vec<PathBuf> {
        let mut paths = Vec::new();

        // Auto-detect Obsidian attachment folder
        if flavor == crate::config::MarkdownFlavor::Obsidian
            && let Some(attachment_dir) = resolve_attachment_folder(source_file.unwrap_or(base_path), base_path)
            && attachment_dir != *base_path
        {
            paths.push(attachment_dir);
        }

        // Add explicitly configured search paths. Resolved relative to the
        // discovered project root so paths are stable regardless of which
        // subdirectory rumdl is invoked from.
        for search_path in &self.config.search_paths {
            let resolved = Self::resolve_against_project_root(search_path, project_root);
            if resolved != *base_path && !paths.contains(&resolved) {
                paths.push(resolved);
            }
        }

        paths
    }

    /// Record every filesystem destination this rule may validate.
    ///
    /// The index keeps frontmatter inputs regardless of the current rule config
    /// because a content-matched entry can be reused by another config group.
    fn contribute_dependency_targets(&self, ctx: &crate::lint_context::LintContext, index: &mut FileIndex) {
        for destination in body_link_destinations(ctx) {
            let url = destination.url;
            if url.is_empty()
                || (url.starts_with('`') && url.ends_with('`'))
                || self.is_non_file_destination(url, ctx.flavor)
                || self.is_fragment_only_link(url)
            {
                continue;
            }
            index.add_md057_link_target(Md057LinkTarget {
                target: url.to_string(),
                origin: LinkOrigin::Body,
            });
        }

        for image in ctx.images() {
            if ctx
                .line_info(image.line)
                .is_some_and(|info| info.in_front_matter || info.in_pymdown_block)
                || matches!(image.link_type, LinkType::WikiLink { .. })
                || ctx.is_in_shortcode(image.byte_offset)
            {
                continue;
            }
            let url = image.url.as_ref();
            if url.is_empty() || self.is_non_file_destination(url, ctx.flavor) || self.is_fragment_only_link(url) {
                continue;
            }
            index.add_md057_link_target(Md057LinkTarget {
                target: url.to_string(),
                origin: LinkOrigin::Body,
            });
        }

        for reference in ctx.reference_definitions() {
            if ctx.line_info(reference.line).is_some_and(|info| info.in_front_matter) {
                continue;
            }
            let url = reference.url.as_str();
            if url.is_empty() || self.is_non_file_destination(url, ctx.flavor) || self.is_fragment_only_link(url) {
                continue;
            }
            index.add_md057_link_target(Md057LinkTarget {
                target: url.to_string(),
                origin: LinkOrigin::Body,
            });
        }

        for link in frontmatter_values::link_destinations(ctx) {
            let line = ctx.lines[link.line - 1].content(ctx.content);
            let url = &line[link.range];
            if self.is_non_file_destination(url, ctx.flavor) || self.is_fragment_only_link(url) {
                continue;
            }
            index.add_md057_link_target(Md057LinkTarget {
                target: url.to_string(),
                origin: LinkOrigin::FrontMatter { field: link.field },
            });
        }
    }

    /// Check if a link target exists in any of the additional search paths.
    fn exists_in_search_paths(
        decoded_path: &str,
        search_paths: &[PathBuf],
        policy: Option<&crate::lint_context::LinkTargetPolicy>,
    ) -> bool {
        search_paths.iter().any(|dir| {
            let candidate = dir.join(decoded_path);
            Self::target_exists(dir, &candidate, policy)
        })
    }

    fn target_exists(anchor: &Path, path: &Path, policy: Option<&crate::lint_context::LinkTargetPolicy>) -> bool {
        Self::resolve_target(anchor, path, policy).is_some()
    }

    /// The file a link target names, resolved against the directory the link is
    /// written relative to. That directory is the anchor for the spelling
    /// check: the components below it are the link author's, the ones above it
    /// belong to wherever the project happens to sit.
    fn resolve_target(
        anchor: &Path,
        path: &Path,
        policy: Option<&crate::lint_context::LinkTargetPolicy>,
    ) -> Option<PathBuf> {
        if let Some(supplied) = policy.and_then(|policy| policy.resolve_supplied(path)) {
            return Some(supplied);
        }
        if policy.is_some_and(|policy| !policy.allow_disk_fallback()) {
            return None;
        }
        resolve_existing_target(anchor, path)
    }

    fn missing_relative_message(url: &str, policy: Option<&crate::lint_context::LinkTargetPolicy>) -> String {
        if policy.is_some_and(|policy| !policy.allow_disk_fallback()) {
            format!("Relative link '{url}' target not in the supplied document set")
        } else {
            format!("Relative link '{url}' does not exist")
        }
    }

    /// Check if a relative link can be compacted and return the simplified form.
    ///
    /// Returns `None` if compact-paths is disabled, the link has no traversal,
    /// or the link is already the shortest form.
    /// Returns `Some(suggestion)` with the full compacted URL (including fragment/query suffix).
    fn compact_path_suggestion(&self, url: &str, base_path: &Path) -> Option<String> {
        if !self.config.compact_paths {
            return None;
        }

        // Split URL into path and suffix (fragment/query)
        let path_end = url
            .find('?')
            .unwrap_or(url.len())
            .min(url.find('#').unwrap_or(url.len()));
        let path_part = &url[..path_end];
        let suffix = &url[path_end..];

        // URL-decode the path portion for filesystem resolution
        let decoded_path = Self::url_decode(path_part);

        compute_compact_path(base_path, &decoded_path).map(|compact| format!("{compact}{suffix}"))
    }

    /// Classify a relative link that points back at the file it is written in.
    ///
    /// Returns `None` when the option is off, when the file under check is
    /// unknown, or when the link addresses anything else. Fragment-only links
    /// never reach here: they are already the form this reports towards.
    ///
    /// The link is resolved against the file's own directory first and then
    /// against each search path, matching how the existence check resolves it:
    /// a link that MD057 accepts through a search path is recognized here as
    /// well, and one that already resolves next to the document is judged
    /// against that target alone.
    fn self_referential_link(
        &self,
        url: &str,
        base_path: &Path,
        search_paths: &[PathBuf],
        source_file: Option<&Path>,
        policy: Option<&crate::lint_context::LinkTargetPolicy>,
    ) -> Option<SelfReferentialLink> {
        if !self.config.self_referential_links {
            return None;
        }
        let source_file = source_file?;

        let path_part = Self::strip_query_and_fragment(url);
        if path_part.is_empty() {
            return None;
        }
        let suffix = &url[path_part.len()..];

        let decoded_path = Self::url_decode(path_part);
        // First hit wins, as it does for the existence check: a target next to
        // the document is the one the link addresses, and a search path only
        // answers for a link that resolves nowhere else.
        let resolved = std::iter::once(base_path)
            .chain(search_paths.iter().map(PathBuf::as_path))
            .find_map(|dir| {
                Self::resolve_target(dir, &Self::resolve_link_path_with_base(&decoded_path, dir), policy)
            })?;
        if !Self::is_same_file(&resolved, source_file) {
            return None;
        }

        // A bare fragment reaches the same place. A query string does not
        // survive being detached from its path, and neither does an empty
        // fragment, so those are reported without a suggestion.
        match suffix.strip_prefix('#') {
            Some(fragment) if !fragment.is_empty() => Some(SelfReferentialLink::Fragment(suffix.to_string())),
            _ => Some(SelfReferentialLink::WholeFile),
        }
    }

    /// Byte range of a reference definition's destination in the document.
    ///
    /// Both the label and the title can repeat the destination text, so the
    /// search is bounded to what sits between the label's closing bracket and
    /// the title. Anchoring anywhere else risks a fix rewriting the label,
    /// which would leave every usage of the reference dangling.
    fn ref_def_url_range(content: &str, ref_def: &crate::lint_context::ReferenceDef) -> Option<std::ops::Range<usize>> {
        let def = content.get(ref_def.byte_offset..ref_def.byte_end)?;
        let label_end = Self::label_end(def)?;
        let search_end = ref_def.title_byte_start.map_or(def.len(), |title| {
            title.saturating_sub(ref_def.byte_offset).min(def.len())
        });
        let offset = def.get(label_end..search_end)?.find(ref_def.url.as_str())? + label_end;
        let start = ref_def.byte_offset + offset;
        Some(start..start + ref_def.url.len())
    }

    /// Offset just past the `]:` that closes a reference definition's label.
    ///
    /// A label may itself contain a bracket when the bracket is escaped, so
    /// escapes are skipped rather than matched.
    fn label_end(def: &str) -> Option<usize> {
        let bytes = def.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'\\' => i += 2,
                b']' if bytes.get(i + 1) == Some(&b':') => return Some(i + 2),
                _ => i += 1,
            }
        }
        None
    }

    /// Whether this document has frontmatter the rule is configured to check.
    /// Gates the body-link early exits, which would otherwise skip a document
    /// whose only destinations sit in its frontmatter.
    fn checks_front_matter_of(&self, ctx: &crate::lint_context::LintContext) -> bool {
        self.config.check_frontmatter && ctx.front_matter_end_line() > 0
    }

    /// The warning text for an absolute destination, or `None` when the
    /// configured handling accepts it.
    fn absolute_link_message(&self, url: &str, base_path: &Path, project_root: &Path) -> Option<String> {
        match self.config.absolute_links {
            AbsoluteLinksOption::Ignore => None,
            AbsoluteLinksOption::Warn => Some(format!("Absolute link '{url}' cannot be validated locally")),
            AbsoluteLinksOption::RelativeToDocs => Self::validate_absolute_link_via_docs_dir(url, base_path),
            AbsoluteLinksOption::RelativeToRoots => {
                Self::validate_absolute_link_via_roots(url, &self.config.roots, project_root)
            }
        }
    }

    /// Report frontmatter values that read as relative destinations but point
    /// at nothing.
    ///
    /// Only existence is checked. The compact-path and self-referential
    /// suggestions stay out of frontmatter: both rewrite a destination, and a
    /// frontmatter value is only ever a guess at being one.
    fn check_front_matter(
        &self,
        ctx: &crate::lint_context::LintContext,
        base_path: &Path,
        search_paths: &[PathBuf],
        project_root: &Path,
        warnings: &mut Vec<LintWarning>,
    ) {
        if !self.config.check_frontmatter {
            return;
        }

        let ignored: HashSet<String> = self
            .config
            .ignore_frontmatter_fields
            .iter()
            .map(|field| field.to_lowercase())
            .collect();

        for link in frontmatter_values::link_destinations(ctx) {
            if link.field_is_in(&ignored) {
                continue;
            }

            let line = ctx.lines[link.line - 1].content(ctx.content);
            let url = &line[link.range.clone()];

            // A fragment belongs to MD051, which validates it against the
            // document's own headings.
            if self.is_non_file_destination(url, ctx.flavor) || self.is_fragment_only_link(url) {
                continue;
            }

            let column = byte_to_char_count(line, link.range.start);
            let end_column = column + url.chars().count();

            if Self::is_absolute_path(url) {
                if let Some(message) = self.absolute_link_message(url, base_path, project_root) {
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: link.line,
                        column,
                        end_line: link.line,
                        end_column,
                        message,
                        severity: Severity::Warning,
                        fix: None,
                    });
                }
                continue;
            }

            if Self::relative_target_exists(url, base_path, search_paths, ctx.link_target_policy()) {
                continue;
            }

            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                line: link.line,
                column,
                end_line: link.line,
                end_column,
                message: Self::missing_relative_message(url, ctx.link_target_policy()),
                severity: Severity::Error,
                fix: None,
            });
        }
    }

    /// Whether a relative destination resolves to something on disk.
    ///
    /// The destination is stripped of its query and fragment, percent-decoded,
    /// then resolved against `base_path`, with two fallbacks: an `.html`/`.htm`
    /// target passes when the markdown source it is generated from exists, and
    /// any target passes when one of `search_paths` holds it.
    fn relative_target_exists(
        url: &str,
        base_path: &Path,
        search_paths: &[PathBuf],
        policy: Option<&crate::lint_context::LinkTargetPolicy>,
    ) -> bool {
        let decoded_path = Self::url_decode(Self::strip_query_and_fragment(url));
        let resolved_path = Self::resolve_link_path_with_base(&decoded_path, base_path);

        // An extensionless link is also tried with each markdown extension.
        if Self::target_exists(base_path, &resolved_path, policy) {
            return true;
        }

        if let Some(ext) = resolved_path.extension().and_then(|e| e.to_str())
            && (ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm"))
            && let (Some(stem), Some(parent)) = (
                resolved_path.file_stem().and_then(|s| s.to_str()),
                resolved_path.parent(),
            )
            && MARKDOWN_EXTENSIONS
                .iter()
                .any(|md_ext| Self::target_exists(base_path, &parent.join(format!("{stem}{md_ext}")), policy))
        {
            return true;
        }

        Self::exists_in_search_paths(&decoded_path, search_paths, policy)
    }

    /// Whether any enabled check can offer a fix. Broken links and absolute
    /// links are reported without one, so the answer rests on the two options
    /// that rewrite a destination.
    fn produces_fixes(&self) -> bool {
        self.config.compact_paths || self.config.self_referential_links
    }

    /// The warning text for a link that points at its own file.
    fn self_referential_message(url: &str, self_link: &SelfReferentialLink) -> String {
        match self_link {
            SelfReferentialLink::Fragment(fragment) => {
                format!("Relative link '{url}' points to the file it is in and can be simplified to '{fragment}'")
            }
            SelfReferentialLink::WholeFile => {
                format!("Relative link '{url}' points to the file it is in")
            }
        }
    }

    /// Whether two existing paths are the same file.
    ///
    /// Both sides are canonicalized, which settles symlinks and the platform's
    /// path representation; the lexical form is the fallback for a path the
    /// filesystem cannot answer for.
    fn is_same_file(resolved: &Path, source_file: &Path) -> bool {
        // Cheap reject before the syscall: a different name is a different file.
        if resolved.file_name() != source_file.file_name() {
            return false;
        }
        match (resolved.canonicalize(), source_file.canonicalize()) {
            (Ok(link), Ok(source)) => link == source,
            _ => normalize_relative_path(resolved) == normalize_relative_path(source_file),
        }
    }

    /// Validate an absolute link by resolving it relative to MkDocs docs_dir.
    ///
    /// Returns `Some(warning_message)` if the link is broken, `None` if valid.
    /// Falls back to a generic warning if no mkdocs.yml is found.
    /// Validate an absolute link against the MkDocs `docs_dir`.
    fn validate_absolute_link_via_docs_dir(url: &str, source_path: &Path) -> Option<String> {
        let Some(docs_dir) = resolve_docs_dir(source_path) else {
            return Some(format!(
                "Absolute link '{url}' cannot be validated locally (no mkdocs.yml found)"
            ));
        };

        let decoded = Self::prepare_absolute_url(url);

        // MkDocs mode: an extensionless directory link must have index.md.
        // `require_index_for_dirs = true` enforces this for all directory hits.
        match Self::resolve_under_root_with_opts(&docs_dir, &decoded, true) {
            Resolution::Found => None,
            Resolution::DirectoryWithoutIndex { resolved } => Some(format!(
                "Absolute link '{url}' resolves to directory '{}' which has no index.md",
                resolved.display()
            )),
            Resolution::NotFound { resolved } => Some(format!(
                "Absolute link '{url}' resolves to '{}' which does not exist",
                resolved.display()
            )),
        }
    }

    /// Validate an absolute link by resolving it against each configured root and the project root.
    ///
    /// Configured `roots` are tried first (first match wins), then the project
    /// root is tried as an implicit fallback. The fallback supports links
    /// written as literal absolute paths from the project root (e.g.
    /// `/content/en/foo.md`) alongside links written relative to a configured
    /// root (e.g. `/foo.md` with `roots = ["content/en"]`). A warning is
    /// emitted only when no root — configured or implicit — contains the target.
    fn validate_absolute_link_via_roots(url: &str, roots: &[String], project_root: &Path) -> Option<String> {
        let decoded = Self::prepare_absolute_url(url);

        for root in roots {
            let root_path = Self::resolve_against_project_root(root, project_root);
            // Filesystem mode: an existing directory is a valid target.
            // `require_index_for_dirs = false` aligns with relative-link behavior. (#632)
            if matches!(
                Self::resolve_under_root_with_opts(&root_path, &decoded, false),
                Resolution::Found
            ) {
                return None;
            }
        }

        if matches!(
            // Filesystem mode: see above.
            Self::resolve_under_root_with_opts(project_root, &decoded, false),
            Resolution::Found
        ) {
            return None;
        }

        let msg = if roots.is_empty() {
            format!("Absolute link '{url}' was not found under the project root")
        } else {
            format!("Absolute link '{url}' was not found under any configured root or the project root")
        };
        Some(msg)
    }

    /// Decode an absolute-link URL into a filesystem-relative path. Strips the
    /// leading `/`, query/fragment suffix, and percent-encoding.
    fn prepare_absolute_url(url: &str) -> String {
        let relative_url = url.trim_start_matches('/');
        let file_path = Self::strip_query_and_fragment(relative_url);
        Self::url_decode(file_path)
    }

    /// Try to resolve a decoded absolute-link path under a single root directory.
    ///
    /// `require_index_for_dirs` says what a link that lands on a directory means,
    /// and the two answers belong to two different worlds:
    ///
    /// - `true` (MkDocs / docs-dir mode): a URL is a route, and MkDocs serves
    ///   `/section` from `section/index.md`. A directory with no `index.md` is a
    ///   route that 404s, so it is reported.
    ///
    /// - `false` (roots / filesystem mode): a link names a path on disk, so an
    ///   existing directory is a valid target. That is what relative links already
    ///   do (they ask only whether the target is there), and the punctuation of
    ///   the link does not change it: `/adir`, `/adir/` and `/adir/#section` all
    ///   name the same directory, and no router is going to turn one of them into
    ///   `index.md`.
    ///
    /// Every path is resolved under `root_path`, which is therefore the anchor
    /// for the spelling check: a target is found only under the case the link
    /// writes it in.
    ///
    /// Applies resolution strategies in order:
    /// 1. A directory hit, answered by the mode as described above. Must be checked
    ///    before `file_exists_or_markdown_extension`, because a directory is one of
    ///    the things a target can be.
    /// 2. Direct existence (with markdown-extension fallback for extensionless links).
    /// 3. `.html`/`.htm` links: look for a markdown source with the same stem.
    fn resolve_under_root_with_opts(root_path: &Path, decoded: &str, require_index_for_dirs: bool) -> Resolution {
        let resolved = root_path.join(decoded);

        if resolved.is_dir() && exists_exact_case(root_path, &resolved) {
            if !require_index_for_dirs {
                return Resolution::Found;
            }
            return if exists_exact_case(root_path, &resolved.join("index.md")) {
                Resolution::Found
            } else {
                Resolution::DirectoryWithoutIndex { resolved }
            };
        }

        if file_exists_or_markdown_extension(root_path, &resolved) {
            return Resolution::Found;
        }

        // For .html/.htm links, accept a matching markdown source in the same
        // directory — supports doc sites that compile .md to .html.
        if let Some(ext) = resolved.extension().and_then(|e| e.to_str())
            && (ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm"))
            && let (Some(stem), Some(parent)) = (resolved.file_stem().and_then(|s| s.to_str()), resolved.parent())
        {
            let has_md_source = MARKDOWN_EXTENSIONS.iter().any(|md_ext| {
                let source_path = parent.join(format!("{stem}{md_ext}"));
                exists_exact_case(root_path, &source_path)
            });
            if has_md_source {
                return Resolution::Found;
            }
        }

        Resolution::NotFound { resolved }
    }
}

/// Cache invalidation for the on-disk lint cache, which only exists in builds
/// with a filesystem and the `blake3` hasher (native and WASI). The browser build
/// has neither, so nothing here can be reached from it.
#[cfg(feature = "blake3")]
impl MD057ExistingRelativeLinks {
    /// Fingerprint the filesystem facts that can change this file's MD057 verdict.
    ///
    /// The caller supplies path inputs from a content-matched workspace-index
    /// entry. Resolution stays here so cache validation follows the same config,
    /// project-root, search-path, and flavor rules as `check`.
    pub fn cache_dependency_fingerprint(
        &self,
        source_file: &Path,
        flavor: crate::config::MarkdownFlavor,
        file_index: &FileIndex,
    ) -> String {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"rumdl-md057-dependencies-v1");
        if file_index.md057_link_targets.is_empty() {
            return hasher.finalize().to_hex().to_string();
        }

        let explicit_base = self.base_path.lock().ok().and_then(|guard| guard.clone());
        let project_root = explicit_base.clone().unwrap_or_else(|| project_root().to_path_buf());
        let resolved_source = source_file.canonicalize().unwrap_or_else(|_| source_file.to_path_buf());
        let base_path = explicit_base.unwrap_or_else(|| {
            resolved_source
                .parent()
                .map_or_else(|| CURRENT_DIR.clone(), Path::to_path_buf)
        });
        let search_paths = self.compute_search_paths(flavor, Some(source_file), &base_path, &project_root);
        let ignored_frontmatter_fields: HashSet<String> = self
            .config
            .ignore_frontmatter_fields
            .iter()
            .map(|field| field.to_lowercase())
            .collect();

        for dependency in &file_index.md057_link_targets {
            if let LinkOrigin::FrontMatter { field } = &dependency.origin
                && (!self.config.check_frontmatter
                    || field
                        .as_ref()
                        .is_some_and(|field| ignored_frontmatter_fields.contains(field)))
            {
                continue;
            }

            let url = dependency.target.as_str();
            if self.is_non_file_destination(url, flavor) || self.is_fragment_only_link(url) {
                continue;
            }

            Self::hash_bytes(&mut hasher, url.as_bytes());
            if Self::is_absolute_path(url) {
                match self.config.absolute_links {
                    AbsoluteLinksOption::Ignore | AbsoluteLinksOption::Warn => {}
                    AbsoluteLinksOption::RelativeToDocs => {
                        hasher.update(b"docs");
                        if let Some(docs_dir) = resolve_docs_dir(source_file) {
                            Self::observe_absolute_resolution(&mut hasher, &docs_dir, url, true);
                        } else {
                            hasher.update(b"no-docs-dir");
                        }
                    }
                    AbsoluteLinksOption::RelativeToRoots => {
                        hasher.update(b"roots");
                        let decoded = Self::prepare_absolute_url(url);
                        let mut found = false;
                        for root in &self.config.roots {
                            let root_path = Self::resolve_against_project_root(root, &project_root);
                            if Self::observe_under_root(&mut hasher, &root_path, &decoded, false) {
                                found = true;
                                break;
                            }
                        }
                        if !found {
                            Self::observe_under_root(&mut hasher, &project_root, &decoded, false);
                        }
                    }
                }
            } else {
                hasher.update(b"relative");
                if self.config.self_referential_links
                    && Self::observe_self_referential_resolution(
                        &mut hasher,
                        url,
                        &base_path,
                        &search_paths,
                        &resolved_source,
                    )
                {
                    continue;
                }
                Self::observe_relative_resolution(&mut hasher, url, &base_path, &search_paths);
            }
        }

        hasher.finalize().to_hex().to_string()
    }

    fn hash_bytes(hasher: &mut blake3::Hasher, bytes: &[u8]) {
        hasher.update(&(bytes.len() as u64).to_le_bytes());
        hasher.update(bytes);
    }

    fn hash_path(hasher: &mut blake3::Hasher, path: &Path) {
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            Self::hash_bytes(hasher, path.as_os_str().as_bytes());
        }
        #[cfg(windows)]
        {
            use std::os::windows::ffi::OsStrExt;
            let encoded: Vec<u8> = path.as_os_str().encode_wide().flat_map(u16::to_le_bytes).collect();
            Self::hash_bytes(hasher, &encoded);
        }
        #[cfg(not(any(unix, windows)))]
        Self::hash_bytes(hasher, path.to_string_lossy().as_bytes());
    }

    /// Record one path and what is there, judged the way the check judges it: a
    /// target the filesystem answers for under a spelling it does not store
    /// counts as missing, so renaming a file to the case its links use changes
    /// the fingerprint and the cached verdict is thrown away.
    fn observe_path(hasher: &mut blake3::Hasher, anchor: &Path, path: &Path) -> DependencyPathState {
        Self::hash_path(hasher, path);
        let state = if exists_exact_case(anchor, path) {
            match std::fs::metadata(path) {
                Ok(metadata) if metadata.is_file() => DependencyPathState::File,
                Ok(metadata) if metadata.is_dir() => DependencyPathState::Directory,
                Ok(_) => DependencyPathState::Other,
                Err(_) => DependencyPathState::Missing,
            }
        } else {
            DependencyPathState::Missing
        };
        hasher.update(&[match state {
            DependencyPathState::Missing => 0,
            DependencyPathState::File => 1,
            DependencyPathState::Directory => 2,
            DependencyPathState::Other => 3,
        }]);
        state
    }

    fn observe_existing_target(hasher: &mut blake3::Hasher, anchor: &Path, path: &Path) -> Option<PathBuf> {
        if Self::observe_path(hasher, anchor, path) != DependencyPathState::Missing {
            return Some(path.to_path_buf());
        }
        if path.extension().is_none() {
            for extension in MARKDOWN_EXTENSIONS {
                let candidate = path.with_extension(&extension[1..]);
                if Self::observe_path(hasher, anchor, &candidate) != DependencyPathState::Missing {
                    return Some(candidate);
                }
            }
        }
        None
    }

    fn observe_self_referential_resolution(
        hasher: &mut blake3::Hasher,
        url: &str,
        base_path: &Path,
        search_paths: &[PathBuf],
        source_file: &Path,
    ) -> bool {
        let decoded = Self::url_decode(Self::strip_query_and_fragment(url));
        for directory in std::iter::once(base_path).chain(search_paths.iter().map(PathBuf::as_path)) {
            let candidate = Self::resolve_link_path_with_base(&decoded, directory);
            if let Some(resolved) = Self::observe_existing_target(hasher, directory, &candidate) {
                let canonical = resolved.canonicalize().unwrap_or(resolved);
                hasher.update(b"resolved-identity");
                Self::hash_path(hasher, &canonical);
                return Self::is_same_file(&canonical, source_file);
            }
        }
        false
    }

    fn observe_relative_resolution(hasher: &mut blake3::Hasher, url: &str, base_path: &Path, search_paths: &[PathBuf]) {
        let decoded = Self::url_decode(Self::strip_query_and_fragment(url));
        let resolved = Self::resolve_link_path_with_base(&decoded, base_path);
        if Self::observe_existing_target(hasher, base_path, &resolved).is_some() {
            return;
        }

        if let Some(extension) = resolved.extension().and_then(|extension| extension.to_str())
            && (extension.eq_ignore_ascii_case("html") || extension.eq_ignore_ascii_case("htm"))
            && let (Some(stem), Some(parent)) = (resolved.file_stem().and_then(|stem| stem.to_str()), resolved.parent())
            && MARKDOWN_EXTENSIONS.iter().any(|extension| {
                Self::observe_path(hasher, base_path, &parent.join(format!("{stem}{extension}")))
                    != DependencyPathState::Missing
            })
        {
            return;
        }

        for search_path in search_paths {
            if Self::observe_existing_target(hasher, search_path, &search_path.join(&decoded)).is_some() {
                return;
            }
        }
    }

    fn observe_absolute_resolution(
        hasher: &mut blake3::Hasher,
        root: &Path,
        url: &str,
        require_index_for_dirs: bool,
    ) -> bool {
        let decoded = Self::prepare_absolute_url(url);
        Self::observe_under_root(hasher, root, &decoded, require_index_for_dirs)
    }

    /// Mirror of `resolve_under_root_with_opts` that records the filesystem facts
    /// the verdict rests on. Any change to the resolution order there has to land
    /// here too, or a cached verdict outlives the state that produced it.
    fn observe_under_root(
        hasher: &mut blake3::Hasher,
        root: &Path,
        decoded: &str,
        require_index_for_dirs: bool,
    ) -> bool {
        let resolved = root.join(decoded);
        let resolved_state = Self::observe_path(hasher, root, &resolved);

        if resolved_state == DependencyPathState::Directory {
            if !require_index_for_dirs {
                return true;
            }
            return Self::observe_path(hasher, root, &resolved.join("index.md")) != DependencyPathState::Missing;
        }

        if resolved_state != DependencyPathState::Missing {
            return true;
        }
        if resolved.extension().is_none()
            && MARKDOWN_EXTENSIONS.iter().any(|extension| {
                Self::observe_path(hasher, root, &resolved.with_extension(&extension[1..]))
                    != DependencyPathState::Missing
            })
        {
            return true;
        }

        if let Some(extension) = resolved.extension().and_then(|extension| extension.to_str())
            && (extension.eq_ignore_ascii_case("html") || extension.eq_ignore_ascii_case("htm"))
            && let (Some(stem), Some(parent)) = (resolved.file_stem().and_then(|stem| stem.to_str()), resolved.parent())
        {
            return MARKDOWN_EXTENSIONS.iter().any(|extension| {
                Self::observe_path(hasher, root, &parent.join(format!("{stem}{extension}")))
                    != DependencyPathState::Missing
            });
        }

        false
    }
}

/// Outcome of trying to resolve an absolute link under a single root directory.
/// Carries the resolved path on the failure variants so callers can build
/// specific error messages without recomputing it.
enum Resolution {
    Found,
    DirectoryWithoutIndex { resolved: PathBuf },
    NotFound { resolved: PathBuf },
}

/// Search `re` in `line` starting at `expected_start`, accepting the match
/// only if it begins exactly there.
///
/// `Regex::captures_at` searches starting at the given offset but does not
/// require the match to *begin* there. A bracket's own destination that
/// fails to match at its own position (a fragment-only `(#bar)`, an empty
/// `()`) would otherwise silently slide forward and return a later,
/// unrelated match belonging to a different bracket on the same line.
/// Rejecting a non-anchored match treats that case as "no destination for
/// this bracket" instead of borrowing a sibling bracket's URL.
fn extract_url_at<'a>(re: &Regex, line: &'a str, expected_start: usize) -> Option<regex::Captures<'a>> {
    let caps = re.captures_at(line, expected_start)?;
    if caps.get(0)?.start() != expected_start {
        return None;
    }
    Some(caps)
}

/// The destination of one inline link, located in the document.
struct BodyLinkDestination<'a> {
    /// The destination without its fragment. This is the path the existence
    /// check resolves and the text a warning names.
    url: &'a str,
    /// The fragment that follows the destination, `#` included, or empty when
    /// the link carries none.
    fragment: &'a str,
    /// Byte range of `url` in the document, used for the warning position.
    url_range: std::ops::Range<usize>,
    /// Byte range covering the destination together with its fragment. A
    /// rewrite spans this range so the fragment survives the edit.
    fix_range: std::ops::Range<usize>,
}

impl<'a> BodyLinkDestination<'a> {
    /// The destination as the document spells it, fragment included. A
    /// destination carrying no fragment is borrowed rather than rebuilt.
    fn full_url(&self) -> Cow<'a, str> {
        if self.fragment.is_empty() {
            Cow::Borrowed(self.url)
        } else {
            Cow::Owned(format!("{}{}", self.url, self.fragment))
        }
    }
}

/// Every inline link destination in the document body, in document order.
///
/// The check pass and the cross-file index pass both read destinations through
/// this one iterator, so they always see the same set of links. Each
/// destination is located inside the link's own source span, which is what
/// lets a link whose text wraps onto another line be read at all.
///
/// Only `LinkType::Inline` qualifies, because that is the one shape whose
/// destination is a path written in the link itself. The gate excludes a
/// reference link, whose destination is written in the definition that both
/// passes read separately; a wiki link, whose target names a vault entry
/// rather than a path relative to this file; and an autolink or an email
/// address, which are spelled between angle brackets and carry no destination
/// to extract at all. Destinations in frontmatter, PyMdown blocks, code spans,
/// math spans and template shortcodes are skipped as well, as is a link
/// written inside an image's description, which renders as alt text rather
/// than as a hyperlink.
fn body_link_destinations<'ctx>(
    ctx: &'ctx crate::lint_context::LintContext<'_>,
) -> impl Iterator<Item = BodyLinkDestination<'ctx>> + 'ctx {
    // Links and images both leave the parser sorted by start offset, so one
    // sweep over the links finds the images around each of them. Images
    // either nest or are disjoint, never partially overlap, so the images
    // open at any offset form a chain with each inside the one below it. A
    // stack of them, popped once the sweep passes an image's end, holds
    // exactly the images around the current offset, and every image is pushed
    // and popped once, so the sweep is linear in images plus links.
    let mut pending_images = ctx.images().iter().peekable();
    let mut open_images: Vec<&crate::lint_context::ParsedImage<'_>> = Vec::new();
    let mut previous_link_offset = 0usize;
    ctx.links().iter().filter_map(move |link| {
        debug_assert!(
            link.byte_offset >= previous_link_offset,
            "the links arrive sorted by start offset, which is what lets one forward pass over the images find the ones around each link"
        );
        previous_link_offset = link.byte_offset;
        if !matches!(link.link_type, LinkType::Inline) {
            return None;
        }
        if ctx
            .line_info(link.line)
            .is_some_and(|info| info.in_front_matter || info.in_pymdown_block)
        {
            return None;
        }
        if ctx.is_in_code_span_byte(link.byte_offset)
            || ctx.is_in_math_span(link.byte_offset)
            || ctx.is_in_shortcode(link.byte_offset)
        {
            return None;
        }
        // Link syntax inside an image's description renders as the text of an
        // `alt` attribute and never as a hyperlink, so its destination names
        // nothing. The whole link has to lie inside the image: an image used
        // as a link's text starts after the link does, which leaves the link's
        // own destination readable.
        while let Some(image) = pending_images.next_if(|image| image.byte_offset <= link.byte_offset) {
            close_images_ending_by(&mut open_images, image.byte_offset);
            open_images.push(image);
        }
        close_images_ending_by(&mut open_images, link.byte_offset);
        if open_images
            .iter()
            .any(|image| link.byte_end <= image.byte_end && renders_as_image(ctx, image))
        {
            return None;
        }
        locate_destination(ctx.content, link)
    })
}

/// Pops every open image the sweep has passed the end of. The stack is a
/// chain of nested images, so the ends shrink from bottom to top and the
/// first image still open past `offset` stops the popping.
fn close_images_ending_by(open_images: &mut Vec<&crate::lint_context::ParsedImage<'_>>, offset: usize) {
    while open_images.last().is_some_and(|image| image.byte_end <= offset) {
        open_images.pop();
    }
}

/// Whether an image record is something the renderer turns into an image.
///
/// A reference image is only an image once its definition is found. Without
/// one, the renderer leaves every bracket as text and whatever is written
/// between them keeps its own meaning, so a link in there is a real link. An
/// inline image is always an image, an empty destination included, because the
/// parentheses are what make it one.
fn renders_as_image(ctx: &crate::lint_context::LintContext<'_>, image: &crate::lint_context::ParsedImage<'_>) -> bool {
    if !image.is_reference {
        return true;
    }
    image
        .reference_id
        .as_ref()
        .is_some_and(|id| ctx.reference_definition(id).is_some())
}

/// The destination written inside one link's source span.
///
/// The search is anchored at the `]` that closes the link text, so a link text
/// carrying a newline is read exactly like one written on a single line. That
/// bracket comes from the parse: the parsed text is the source between the
/// brackets, so the closing one sits just past it. Taking it from the parse
/// rather than walking the bytes again is what keeps a label holding a code
/// span, an escaped bracket or inline HTML with a bracket in an attribute
/// value from being read as ending somewhere else. A shape whose text is not
/// the source between brackets, an autolink above all, lands on something
/// other than `](` and carries no destination. The angle-bracketed spelling is
/// tried first, because a path holding parentheses is only read whole in that
/// form.
fn locate_destination<'a>(
    content: &'a str,
    link: &crate::lint_context::ParsedLink<'_>,
) -> Option<BodyLinkDestination<'a>> {
    let span = content.get(link.byte_offset..link.byte_end)?;
    let anchor = 1 + link.text.len();
    if !span.get(anchor..).is_some_and(|rest| rest.starts_with("](")) {
        return None;
    }
    let caps = extract_url_at(&URL_EXTRACT_ANGLE_BRACKET_REGEX, span, anchor)
        .or_else(|| extract_url_at(&URL_EXTRACT_REGEX, span, anchor))?;
    let url_group = caps.get(1)?;
    let fragment = caps.get(2);

    let span_start = link.byte_offset;
    let url_range = span_start + url_group.start()..span_start + url_group.end();
    let fix_end = fragment.map_or(url_range.end, |group| span_start + group.end());

    Some(BodyLinkDestination {
        url: url_group.as_str().trim(),
        fragment: fragment.map_or("", |group| group.as_str()),
        fix_range: url_range.start..fix_end,
        url_range,
    })
}

impl Rule for MD057ExistingRelativeLinks {
    fn name(&self) -> &'static str {
        "MD057"
    }

    fn description(&self) -> &'static str {
        "Relative links should point to existing files"
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Link
    }

    fn skippable_by_category(&self) -> bool {
        // A frontmatter path is a link this rule resolves, and the document
        // holding it needs no link syntax anywhere else.
        !self.config.check_frontmatter
    }

    fn should_skip(&self, ctx: &crate::lint_context::LintContext) -> bool {
        ctx.content.is_empty() || (!ctx.likely_has_links_or_images() && !self.checks_front_matter_of(ctx))
    }

    fn check(&self, ctx: &crate::lint_context::LintContext) -> LintResult {
        let content = ctx.content;

        if content.is_empty() {
            return Ok(Vec::new());
        }

        // Early returns for performance. A document whose only destinations
        // sit in its frontmatter has no link syntax to find, so the body-link
        // shortcuts only apply when frontmatter is not being checked.
        let has_body_links = content.contains('[') && (content.contains("](") || content.contains("]:"));
        if !has_body_links && !self.checks_front_matter_of(ctx) {
            return Ok(Vec::new());
        }

        // Reset the filesystem caches for a fresh run
        reset_file_existence_cache();

        let mut warnings = Vec::new();

        // Read the explicit base path (set via `with_path()` in tests) once; it
        // doubles as both the per-file base path and the project root override
        // for absolute-link resolution.
        let explicit_base = self.base_path.lock().ok().and_then(|g| g.clone());

        // Project root used for absolute-link resolution against configured
        // `roots` and as the implicit fallback root. The explicit base wins
        // when set; otherwise the discovered project root is used.
        let project_root: PathBuf = explicit_base.clone().unwrap_or_else(|| project_root().to_path_buf());

        // The file under check, as the filesystem sees it. Links are compared
        // against it to find the ones that point back at their own document.
        let self_path: Option<PathBuf> = ctx
            .source_file()
            .map(|source_file| source_file.canonicalize().unwrap_or_else(|_| source_file.to_path_buf()));

        // Determine base path for resolving relative links.
        // ALWAYS compute from ctx.source_file for each file - do not reuse cached base_path
        // This ensures each file resolves links relative to its own directory.
        let base_path: Option<PathBuf> = {
            if explicit_base.is_some() {
                explicit_base
            } else if let Some(ref resolved_file) = self_path {
                // Resolve symlinks to get the actual file location
                // This ensures relative links are resolved from the target's directory,
                // not the symlink's directory
                resolved_file
                    .parent()
                    .map(std::path::Path::to_path_buf)
                    .or_else(|| Some(CURRENT_DIR.clone()))
            } else {
                // No source file available - cannot validate relative links
                None
            }
        };

        // If we still don't have a base path, we can't validate relative links
        let Some(base_path) = base_path else {
            return Ok(warnings);
        };

        // Compute additional search paths for fallback link resolution
        let extra_search_paths = self.compute_search_paths(ctx.flavor, ctx.source_file(), &base_path, &project_root);

        // Destinations come from the parse, so a link whose text wraps onto
        // another line is read the same as one written on a single line. Every
        // report on a link points at its destination, which sits on the line
        // the link ends on rather than the line it starts on.
        for destination in body_link_destinations(ctx) {
            let url = destination.url;

            // Skip empty URLs
            if url.is_empty() {
                continue;
            }

            // Skip rustdoc intra-doc links (backtick-wrapped URLs)
            // These are Rust API references, not file paths
            // Example: [`f32::is_subnormal`], [`Vec::push`]
            if url.starts_with('`') && url.ends_with('`') {
                continue;
            }

            // Skip external URLs and fragment-only links
            if self.is_non_file_destination(url, ctx.flavor) || self.is_fragment_only_link(url) {
                continue;
            }

            // Handle absolute paths based on config
            if Self::is_absolute_path(url) {
                if let Some(message) = self.absolute_link_message(url, &base_path, &project_root) {
                    let (line, column) = ctx.offset_to_line_col(destination.url_range.start);
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line,
                        column,
                        end_line: line,
                        end_column: ctx.offset_to_line_col(destination.url_range.end).1,
                        message,
                        severity: Severity::Warning,
                        fix: None,
                    });
                }
                continue;
            }

            // The compaction and the self-link check both read the destination
            // together with its fragment, because both rewrite the whole of it.
            let full_url = destination.full_url();

            // A link back into the current file. Reported instead of
            // the compaction below, whose shorter path would still
            // be a link the reader should not follow, and instead
            // of the existence check, which this target passes.
            if let Some(self_link) = self.self_referential_link(
                &full_url,
                &base_path,
                &extra_search_paths,
                self_path.as_deref(),
                ctx.link_target_policy(),
            ) {
                let (line, column) = ctx.offset_to_line_col(destination.url_range.start);
                warnings.push(LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line,
                    column,
                    end_line: line,
                    end_column: ctx.offset_to_line_col(destination.fix_range.end).1,
                    message: Self::self_referential_message(&full_url, &self_link),
                    severity: Severity::Warning,
                    fix: match &self_link {
                        SelfReferentialLink::Fragment(fragment) => {
                            Some(Fix::new(destination.fix_range.clone(), fragment.clone()))
                        }
                        SelfReferentialLink::WholeFile => None,
                    },
                });
                continue;
            }

            if let Some(suggestion) = self.compact_path_suggestion(&full_url, &base_path) {
                let (line, column) = ctx.offset_to_line_col(destination.url_range.start);
                warnings.push(LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line,
                    column,
                    end_line: line,
                    end_column: ctx.offset_to_line_col(destination.fix_range.end).1,
                    message: format!("Relative link '{full_url}' can be simplified to '{suggestion}'"),
                    severity: Severity::Warning,
                    fix: Some(Fix::new(destination.fix_range.clone(), suggestion)),
                });
            }

            if Self::relative_target_exists(url, &base_path, &extra_search_paths, ctx.link_target_policy()) {
                continue;
            }

            // File doesn't exist and no source file found
            let (line, column) = ctx.offset_to_line_col(destination.url_range.start);
            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                line,
                column,
                end_line: line,
                end_column: ctx.offset_to_line_col(destination.url_range.end).1,
                message: Self::missing_relative_message(url, ctx.link_target_policy()),
                severity: Severity::Error,
                fix: None,
            });
        }

        // Also process images - they have URLs already parsed
        for image in ctx.images() {
            // Skip images inside PyMdown blocks (MkDocs flavor)
            if ctx
                .line_info(image.line)
                .is_some_and(|info| info.in_front_matter || info.in_pymdown_block)
            {
                continue;
            }

            // A wiki embed names a vault entry, not a path relative to this
            // file: `![[diagram.png]]` resolves wherever the attachment lives.
            // The links loop already leaves `[[diagram.png]]` alone.
            if matches!(image.link_type, LinkType::WikiLink { .. }) {
                continue;
            }

            // Image syntax inside a template shortcode tag is a parameter the
            // template resolves, not a path relative to this file.
            if ctx.is_in_shortcode(image.byte_offset) {
                continue;
            }

            let url = image.url.as_ref();

            // Skip empty URLs
            if url.is_empty() {
                continue;
            }

            // Skip external URLs and fragment-only links
            if self.is_non_file_destination(url, ctx.flavor) || self.is_fragment_only_link(url) {
                continue;
            }

            // Handle absolute paths based on config
            if Self::is_absolute_path(url) {
                if let Some(message) = self.absolute_link_message(url, &base_path, &project_root) {
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line: image.line,
                        column: image.start_col + 1,
                        end_line: image.line,
                        end_column: image.start_col + 1 + url.chars().count(),
                        message,
                        severity: Severity::Warning,
                        fix: None,
                    });
                }
                continue;
            }

            // Check for unnecessary path traversal (compact-paths)
            if let Some(suggestion) = self.compact_path_suggestion(url, &base_path) {
                // Find the URL position within the image syntax using document byte offsets.
                // Search from image.byte_offset (the `!` character) to locate the URL string.
                let fix = content[image.byte_offset..image.byte_end].find(url).map(|url_offset| {
                    let fix_byte_start = image.byte_offset + url_offset;
                    let fix_byte_end = fix_byte_start + url.len();
                    Fix::new(fix_byte_start..fix_byte_end, suggestion.clone())
                });

                let image_line = ctx.raw_lines().get(image.line - 1).copied().unwrap_or("");
                let img_line_start_byte = ctx.line_start_byte(image.line).unwrap_or(0);
                // The fix range is a document byte offset; the displayed column is
                // the corresponding character offset within the line.
                let url_col = fix.as_ref().map_or(image.start_col + 1, |f| {
                    byte_to_char_count(image_line, f.range.start - img_line_start_byte)
                });
                warnings.push(LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line: image.line,
                    column: url_col,
                    end_line: image.line,
                    end_column: url_col + url.chars().count(),
                    message: format!("Relative link '{url}' can be simplified to '{suggestion}'"),
                    severity: Severity::Warning,
                    fix,
                });
            }

            if Self::relative_target_exists(url, &base_path, &extra_search_paths, ctx.link_target_policy()) {
                continue;
            }

            // File doesn't exist and no source file found
            // Images already have correct position from parser
            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                line: image.line,
                column: image.start_col + 1,
                end_line: image.line,
                end_column: image.start_col + 1 + url.chars().count(),
                message: Self::missing_relative_message(url, ctx.link_target_policy()),
                severity: Severity::Error,
                fix: None,
            });
        }

        // Also process reference definitions: [ref]: ./path.md
        for ref_def in ctx.reference_definitions() {
            if ctx.line_info(ref_def.line).is_some_and(|info| info.in_front_matter) {
                continue;
            }
            let url = &ref_def.url;

            // Skip empty URLs
            if url.is_empty() {
                continue;
            }

            // Skip external URLs and fragment-only links
            if self.is_non_file_destination(url, ctx.flavor) || self.is_fragment_only_link(url) {
                continue;
            }

            // Where this definition's destination sits, shared by every report
            // on it. Without a located destination a warning falls back to the
            // start of the definition's line and offers no fix.
            let url_range = Self::ref_def_url_range(ctx.content, ref_def);
            let (line, col) = url_range
                .as_ref()
                .map_or((ref_def.line, 1), |range| ctx.offset_to_line_col(range.start));
            let end_col = col + url.chars().count();

            // Handle absolute paths based on config
            if Self::is_absolute_path(url) {
                if let Some(message) = self.absolute_link_message(url, &base_path, &project_root) {
                    warnings.push(LintWarning {
                        rule_name: Some(self.name().to_string()),
                        line,
                        column: col,
                        end_line: line,
                        end_column: end_col,
                        message,
                        severity: Severity::Warning,
                        fix: None,
                    });
                }
                continue;
            }

            // A definition whose destination is the file holding it.
            if let Some(self_link) = self.self_referential_link(
                url,
                &base_path,
                &extra_search_paths,
                self_path.as_deref(),
                ctx.link_target_policy(),
            ) {
                warnings.push(LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line,
                    column: col,
                    end_line: line,
                    end_column: end_col,
                    message: Self::self_referential_message(url, &self_link),
                    severity: Severity::Warning,
                    fix: match (&self_link, &url_range) {
                        (SelfReferentialLink::Fragment(fragment), Some(range)) => {
                            Some(Fix::new(range.clone(), fragment.clone()))
                        }
                        _ => None,
                    },
                });
                continue;
            }

            // Check for unnecessary path traversal (compact-paths)
            if let Some(suggestion) = self.compact_path_suggestion(url, &base_path) {
                warnings.push(LintWarning {
                    rule_name: Some(self.name().to_string()),
                    line,
                    column: col,
                    end_line: line,
                    end_column: end_col,
                    message: format!("Relative link '{url}' can be simplified to '{suggestion}'"),
                    severity: Severity::Warning,
                    fix: url_range.clone().map(|range| Fix::new(range, suggestion)),
                });
            }

            if Self::relative_target_exists(url, &base_path, &extra_search_paths, ctx.link_target_policy()) {
                continue;
            }

            // File doesn't exist and no source file found
            warnings.push(LintWarning {
                rule_name: Some(self.name().to_string()),
                line,
                column: col,
                end_line: line,
                end_column: end_col,
                message: Self::missing_relative_message(url, ctx.link_target_policy()),
                severity: Severity::Error,
                fix: None,
            });
        }

        self.check_front_matter(ctx, &base_path, &extra_search_paths, &project_root, &mut warnings);

        Ok(warnings)
    }

    fn fix_capability(&self) -> FixCapability {
        if self.produces_fixes() {
            FixCapability::ConditionallyFixable
        } else {
            FixCapability::Unfixable
        }
    }

    fn fix(&self, ctx: &crate::lint_context::LintContext) -> Result<String, LintError> {
        if !self.produces_fixes() {
            return Ok(ctx.content.to_string());
        }

        let warnings = self.check(ctx)?;
        let warnings =
            crate::utils::fix_utils::filter_warnings_by_inline_config(warnings, ctx.inline_config(), self.name());
        let mut content = ctx.content.to_string();

        // Collect fixable warnings (compact-paths) sorted by byte offset descending
        let mut fixes: Vec<_> = warnings.iter().filter_map(|w| w.fix.as_ref()).collect();
        fixes.sort_by_key(|f| std::cmp::Reverse(f.range.start));

        // Applying fixes right-to-left lets each range stay valid against the
        // still-unshifted content to its left. A duplicate or overlapping fix
        // would otherwise be applied a second time against content already
        // rewritten by an earlier fix, corrupting it; skip any fix whose range
        // overlaps the one most recently applied.
        let mut last_applied_start: Option<usize> = None;
        for fix in fixes {
            if let Some(prev_start) = last_applied_start
                && fix.range.end > prev_start
            {
                continue;
            }
            if fix.range.end <= content.len() {
                content.replace_range(fix.range.clone(), &fix.replacement);
                last_applied_start = Some(fix.range.start);
            }
        }

        Ok(content)
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    crate::impl_rule_config_sections!(MD057Config);

    fn from_config(config: &crate::config::Config) -> Box<dyn Rule>
    where
        Self: Sized,
    {
        let rule_config = crate::rule_config_serde::load_rule_config::<MD057Config>(config);
        // The flavor is deliberately not captured here: Obsidian attachment-folder
        // detection reads `ctx.flavor`, which resolves per file, so a rule built
        // once for a workspace still honors a per-file flavor override.
        Box::new(Self::from_config_struct(rule_config))
    }

    fn cross_file_scope(&self) -> CrossFileScope {
        CrossFileScope::Workspace
    }

    fn contribute_to_index(&self, ctx: &crate::lint_context::LintContext, index: &mut FileIndex) {
        self.contribute_dependency_targets(ctx, index);

        // Use the shared utility for cross-file link extraction
        // This ensures consistent position tracking between CLI and LSP
        let links = extract_cross_file_links(ctx);
        for link in links.relative {
            index.add_cross_file_link(link);
        }
        // Root-relative links are not linted, but indexing them keeps the cached
        // index complete so the LSP can resolve them for find-references.
        for link in links.root_relative {
            index.add_root_relative_link(link);
        }
    }

    fn cross_file_check(
        &self,
        _file_path: &Path,
        _file_index: &FileIndex,
        _workspace_index: &crate::workspace_index::WorkspaceIndex,
    ) -> LintResult {
        // All link targets are already validated by check() on each per-file pass.
        // check() resolves relative links against the file's own directory, handles
        // configured search paths, and applies the absolute_links config.
        // Validating them here too would produce identical duplicate warnings for
        // every broken link. (#631)
        //
        // The cross_file_scope / contribute_to_index / workspace-index infrastructure
        // remains in place to support future cross-file analyses (e.g. heading-anchor
        // validation across files).
        Ok(Vec::new())
    }
}

/// Compute the shortest relative path from `from_dir` to `to_path`.
///
/// Both paths must be normalized (no `.` or `..` components).
/// Returns a relative `PathBuf` that navigates from `from_dir` to `to_path`.
fn shortest_relative_path(from_dir: &Path, to_path: &Path) -> PathBuf {
    let from_components: Vec<_> = from_dir.components().collect();
    let to_components: Vec<_> = to_path.components().collect();

    // Find common prefix length
    let common_len = from_components
        .iter()
        .zip(to_components.iter())
        .take_while(|(a, b)| a == b)
        .count();

    let mut result = PathBuf::new();

    // Go up for each remaining component in from_dir
    for _ in common_len..from_components.len() {
        result.push("..");
    }

    // Append remaining components from to_path
    for component in &to_components[common_len..] {
        result.push(component);
    }

    result
}

/// Check if a relative link path can be shortened.
///
/// Given the source directory and the raw link path, computes whether there's
/// a shorter equivalent path. Returns `Some(compact_path)` if the link can
/// be simplified, `None` if it's already optimal.
fn compute_compact_path(source_dir: &Path, raw_link_path: &str) -> Option<String> {
    let link_path = Path::new(raw_link_path);

    // Only check paths that contain traversal (../ or ./)
    let has_traversal = link_path
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir | std::path::Component::CurDir));

    if !has_traversal {
        return None;
    }

    // Resolve: source_dir + raw_link_path, then normalize
    let combined = source_dir.join(link_path);
    let normalized_target = normalize_relative_path(&combined);

    // Compute shortest path from source_dir back to the normalized target
    let normalized_source = normalize_relative_path(source_dir);
    let shortest = shortest_relative_path(&normalized_source, &normalized_target);

    // Compare against the raw link path — if it differs, the path can be compacted
    if shortest != link_path {
        let compact = shortest.to_string_lossy().to_string();
        // Avoid suggesting empty path
        if compact.is_empty() {
            return None;
        }
        // Markdown links always use forward slashes regardless of platform
        Some(compact.replace('\\', "/"))
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::workspace_index::{CrossFileLinkIndex, LinkOrigin};
    use std::fs::File;
    use std::io::Write;
    use tempfile::tempdir;

    #[test]
    fn test_strip_query_and_fragment() {
        // Test query parameter stripping
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.png?raw=true"),
            "file.png"
        );
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.png?raw=true&version=1"),
            "file.png"
        );
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.png?"),
            "file.png"
        );

        // Test fragment stripping
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.md#section"),
            "file.md"
        );
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.md#"),
            "file.md"
        );

        // Test both query and fragment (query comes first, per RFC 3986)
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.md?raw=true#section"),
            "file.md"
        );

        // Test no query or fragment
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.png"),
            "file.png"
        );

        // Test with path
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("path/to/image.png?raw=true"),
            "path/to/image.png"
        );
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("path/to/image.png?raw=true#anchor"),
            "path/to/image.png"
        );

        // Edge case: fragment before query (non-standard but possible)
        assert_eq!(
            MD057ExistingRelativeLinks::strip_query_and_fragment("file.md#section?query"),
            "file.md"
        );
    }

    #[test]
    fn test_url_decode() {
        // Simple space encoding
        assert_eq!(
            MD057ExistingRelativeLinks::url_decode("penguin%20with%20space.jpg"),
            "penguin with space.jpg"
        );

        // Path with encoded spaces
        assert_eq!(
            MD057ExistingRelativeLinks::url_decode("assets/my%20file%20name.png"),
            "assets/my file name.png"
        );

        // Multiple encoded characters
        assert_eq!(
            MD057ExistingRelativeLinks::url_decode("hello%20world%21.md"),
            "hello world!.md"
        );

        // Lowercase hex
        assert_eq!(MD057ExistingRelativeLinks::url_decode("%2f%2e%2e"), "/..");

        // Uppercase hex
        assert_eq!(MD057ExistingRelativeLinks::url_decode("%2F%2E%2E"), "/..");

        // Mixed case hex
        assert_eq!(MD057ExistingRelativeLinks::url_decode("%2f%2E%2e"), "/..");

        // No encoding - return as-is
        assert_eq!(
            MD057ExistingRelativeLinks::url_decode("normal-file.md"),
            "normal-file.md"
        );

        // Incomplete percent encoding - leave as-is
        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%2.txt"), "file%2.txt");

        // Percent at end - leave as-is
        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%"), "file%");

        // Invalid hex digits - leave as-is
        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%GG.txt"), "file%GG.txt");

        // Plus sign (should NOT be decoded - that's form encoding, not URL encoding)
        assert_eq!(MD057ExistingRelativeLinks::url_decode("file+name.txt"), "file+name.txt");

        // Empty string
        assert_eq!(MD057ExistingRelativeLinks::url_decode(""), "");

        // UTF-8 multi-byte characters (é = C3 A9 in UTF-8)
        assert_eq!(MD057ExistingRelativeLinks::url_decode("caf%C3%A9.md"), "café.md");

        // Multiple consecutive encoded characters
        assert_eq!(MD057ExistingRelativeLinks::url_decode("%20%20%20"), "   ");

        // Encoded path separators
        assert_eq!(
            MD057ExistingRelativeLinks::url_decode("path%2Fto%2Ffile.md"),
            "path/to/file.md"
        );

        // Mixed encoded and non-encoded
        assert_eq!(
            MD057ExistingRelativeLinks::url_decode("hello%20world/foo%20bar.md"),
            "hello world/foo bar.md"
        );

        // Special characters that are commonly encoded
        assert_eq!(MD057ExistingRelativeLinks::url_decode("file%5B1%5D.md"), "file[1].md");

        // Percent at position that looks like encoding but isn't valid
        assert_eq!(MD057ExistingRelativeLinks::url_decode("100%pure.md"), "100%pure.md");
    }

    #[test]
    fn test_url_encoded_filenames() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create a file with spaces in the name
        let file_with_spaces = base_path.join("penguin with space.jpg");
        File::create(&file_with_spaces)
            .unwrap()
            .write_all(b"image data")
            .unwrap();

        // Create a subdirectory with spaces
        let subdir = base_path.join("my images");
        std::fs::create_dir(&subdir).unwrap();
        let nested_file = subdir.join("photo 1.png");
        File::create(&nested_file).unwrap().write_all(b"photo data").unwrap();

        // Test content with URL-encoded links
        let content = r#"
# Test Document with URL-Encoded Links

![Penguin](penguin%20with%20space.jpg)
![Photo](my%20images/photo%201.png)
![Missing](missing%20file.jpg)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only have one warning for the missing file
        assert_eq!(
            result.len(),
            1,
            "Should only warn about missing%20file.jpg. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("missing%20file.jpg"),
            "Warning should mention the URL-encoded filename"
        );
    }

    #[test]
    fn test_external_urls() {
        let rule = MD057ExistingRelativeLinks::new();

        // Common web protocols
        assert!(rule.is_external_url("https://example.com"));
        assert!(rule.is_external_url("http://example.com"));
        assert!(rule.is_external_url("ftp://example.com"));
        assert!(rule.is_external_url("www.example.com"));
        assert!(rule.is_external_url("example.com"));

        // Special URI schemes
        assert!(rule.is_external_url("file:///path/to/file"));
        assert!(rule.is_external_url("smb://server/share"));
        assert!(rule.is_external_url("macappstores://apps.apple.com/"));
        assert!(rule.is_external_url("mailto:user@example.com"));
        assert!(rule.is_external_url("tel:+1234567890"));
        assert!(rule.is_external_url("data:text/plain;base64,SGVsbG8="));
        assert!(rule.is_external_url("javascript:void(0)"));
        assert!(rule.is_external_url("ssh://git@github.com/repo"));
        assert!(rule.is_external_url("git://github.com/repo.git"));

        // Email addresses without mailto: protocol
        // These are clearly not file links and should be skipped
        assert!(rule.is_external_url("user@example.com"));
        assert!(rule.is_external_url("steering@kubernetes.io"));
        assert!(rule.is_external_url("john.doe+filter@company.co.uk"));
        assert!(rule.is_external_url("user_name@sub.domain.com"));
        assert!(rule.is_external_url("firstname.lastname+tag@really.long.domain.example.org"));

        // Template variables should be skipped (not checked as relative links)
        assert!(rule.is_external_url("{{URL}}")); // Handlebars/Mustache
        assert!(rule.is_external_url("{{#URL}}")); // Handlebars block helper
        assert!(rule.is_external_url("{{> partial}}")); // Handlebars partial
        assert!(rule.is_external_url("{{ variable }}")); // Mustache with spaces
        assert!(rule.is_external_url("{{% include %}}")); // Jinja2/Hugo shortcode
        assert!(rule.is_external_url("{{")); // Even partial matches (regex edge case)

        // Absolute paths are NOT external (handled separately via is_absolute_path)
        // By default they are ignored, but can be configured to warn
        assert!(!rule.is_external_url("/api/v1/users"));
        assert!(!rule.is_external_url("/blog/2024/release.html"));
        assert!(!rule.is_external_url("/react/hooks/use-state.html"));
        assert!(!rule.is_external_url("/pkg/runtime"));
        assert!(!rule.is_external_url("/doc/go1compat"));
        assert!(!rule.is_external_url("/index.html"));
        assert!(!rule.is_external_url("/assets/logo.png"));

        // But is_absolute_path should detect them
        assert!(MD057ExistingRelativeLinks::is_absolute_path("/api/v1/users"));
        assert!(MD057ExistingRelativeLinks::is_absolute_path("/blog/2024/release.html"));
        assert!(MD057ExistingRelativeLinks::is_absolute_path("/index.html"));
        assert!(!MD057ExistingRelativeLinks::is_absolute_path("./relative.md"));
        assert!(!MD057ExistingRelativeLinks::is_absolute_path("relative.md"));

        // Framework path aliases should be skipped (resolved by build tools)
        // Tilde prefix (common in Vite, Nuxt, Astro for project root)
        assert!(rule.is_external_url("~/assets/image.png"));
        assert!(rule.is_external_url("~/components/Button.vue"));
        assert!(rule.is_external_url("~assets/logo.svg")); // Nuxt style without /

        // @ prefix (common in Vue, webpack, Vite aliases)
        assert!(rule.is_external_url("@/components/Header.vue"));
        assert!(rule.is_external_url("@images/photo.jpg"));
        assert!(rule.is_external_url("@assets/styles.css"));

        // Relative paths should NOT be external (should be validated)
        assert!(!rule.is_external_url("./relative/path.md"));
        assert!(!rule.is_external_url("relative/path.md"));
        assert!(!rule.is_external_url("../parent/path.md"));
    }

    #[test]
    fn test_dot_com_only_skips_bare_domains() {
        let rule = MD057ExistingRelativeLinks::new();

        // Bare domains ending in .com are treated as external (skipped).
        assert!(rule.is_external_url("example.com"));
        assert!(rule.is_external_url("sub.example.com"));

        // A relative path that merely ends in ".com" must NOT be skipped:
        // it contains a path separator, so it is a relative file reference
        // that should be validated, not assumed external.
        assert!(!rule.is_external_url("../../vendor.com"));
        assert!(!rule.is_external_url("./vendor.com"));
        assert!(!rule.is_external_url("docs/vendor.com"));
    }

    #[test]
    fn test_framework_path_aliases() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Test content with framework path aliases (should all be skipped)
        let content = r#"
# Framework Path Aliases

![Image 1](~/assets/penguin.jpg)
![Image 2](~assets/logo.svg)
![Image 3](@images/photo.jpg)
![Image 4](@/components/icon.svg)
[Link](@/pages/about.md)

This is a [real missing link](missing.md) that should be flagged.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only have one warning for the real missing link
        assert_eq!(
            result.len(),
            1,
            "Should only warn about missing.md, not framework aliases. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("missing.md"),
            "Warning should be for missing.md"
        );
    }

    #[test]
    fn test_url_decode_security_path_traversal() {
        // Ensure URL decoding doesn't enable path traversal attacks
        // The decoded path is still validated against the base path
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create a file in the temp directory
        let file_in_base = base_path.join("safe.md");
        File::create(&file_in_base).unwrap().write_all(b"# Safe").unwrap();

        // Test with encoded path traversal attempt
        // Use a path that definitely won't exist on any platform (not /etc/passwd which exists on Linux)
        // %2F = /, so ..%2F..%2Fnonexistent%2Ffile = ../../nonexistent/file
        // %252F = %2F (double encoded), so ..%252F..%252F = ..%2F..%2F (literal, won't decode to ..)
        let content = r#"
[Traversal attempt](..%2F..%2Fnonexistent_dir_12345%2Fmissing.md)
[Double encoded](..%252F..%252Fnonexistent%252Ffile.md)
[Safe link](safe.md)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // The traversal attempts should still be flagged as missing
        // (they don't exist relative to base_path after decoding)
        assert_eq!(
            result.len(),
            2,
            "Should have warnings for traversal attempts. Got: {result:?}"
        );
    }

    #[test]
    fn test_url_encoded_utf8_filenames() {
        // Test with actual UTF-8 encoded filenames
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create files with unicode names
        let cafe_file = base_path.join("café.md");
        File::create(&cafe_file).unwrap().write_all(b"# Cafe").unwrap();

        let content = r#"
[Café link](caf%C3%A9.md)
[Missing unicode](r%C3%A9sum%C3%A9.md)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only warn about the missing file
        assert_eq!(
            result.len(),
            1,
            "Should only warn about missing résumé.md. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("r%C3%A9sum%C3%A9.md"),
            "Warning should mention the URL-encoded filename"
        );
    }

    #[test]
    fn test_url_encoded_emoji_filenames() {
        // URL-encoded emoji paths should be correctly resolved
        // 👤 = U+1F464 = F0 9F 91 A4 in UTF-8
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create directory with emoji in name: 👤 Personal
        let emoji_dir = base_path.join("👤 Personal");
        std::fs::create_dir(&emoji_dir).unwrap();

        // Create file in that directory: TV Shows.md
        let file_path = emoji_dir.join("TV Shows.md");
        File::create(&file_path)
            .unwrap()
            .write_all(b"# TV Shows\n\nContent here.")
            .unwrap();

        // Test content with URL-encoded emoji link
        // %F0%9F%91%A4 = 👤, %20 = space
        let content = r#"
# Test Document

[TV Shows](./%F0%9F%91%A4%20Personal/TV%20Shows.md)
[Missing](./%F0%9F%91%A4%20Personal/Missing.md)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only warn about the missing file, not the valid emoji path
        assert_eq!(result.len(), 1, "Should only warn about missing file. Got: {result:?}");
        assert!(
            result[0].message.contains("Missing.md"),
            "Warning should be for Missing.md, got: {}",
            result[0].message
        );
    }

    #[test]
    fn test_no_warnings_without_base_path() {
        let rule = MD057ExistingRelativeLinks::new();
        let content = "[Link](missing.md)";

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();
        assert!(result.is_empty(), "Should have no warnings without base path");
    }

    #[test]
    fn test_existing_and_missing_links() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create an existing file
        let exists_path = base_path.join("exists.md");
        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();

        // Verify the file exists
        assert!(exists_path.exists(), "exists.md should exist for this test");

        // Create test content with both existing and missing links
        let content = r#"
# Test Document

[Valid Link](exists.md)
[Invalid Link](missing.md)
[External Link](https://example.com)
[Media Link](image.jpg)
        "#;

        // Initialize rule with the base path (default: check all files including media)
        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        // Test the rule
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have two warnings: missing.md and image.jpg (both don't exist)
        assert_eq!(result.len(), 2);
        let messages: Vec<_> = result.iter().map(|w| w.message.as_str()).collect();
        assert!(messages.iter().any(|m| m.contains("missing.md")));
        assert!(messages.iter().any(|m| m.contains("image.jpg")));
    }

    #[test]
    fn test_angle_bracket_links() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create an existing file
        let exists_path = base_path.join("exists.md");
        File::create(&exists_path).unwrap().write_all(b"# Test File").unwrap();

        // Create test content with angle bracket links
        let content = r#"
# Test Document

[Valid Link](<exists.md>)
[Invalid Link](<missing.md>)
[External Link](<https://example.com>)
    "#;

        // Test with default settings
        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have one warning for missing.md
        assert_eq!(result.len(), 1, "Should have exactly one warning");
        assert!(
            result[0].message.contains("missing.md"),
            "Warning should mention missing.md"
        );
    }

    #[test]
    fn test_angle_bracket_links_with_parens() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create directory structure with parentheses in path
        let app_dir = base_path.join("app");
        std::fs::create_dir(&app_dir).unwrap();
        let upload_dir = app_dir.join("(upload)");
        std::fs::create_dir(&upload_dir).unwrap();
        let page_file = upload_dir.join("page.tsx");
        File::create(&page_file)
            .unwrap()
            .write_all(b"export default function Page() {}")
            .unwrap();

        // Create test content with angle bracket links containing parentheses
        let content = r#"
# Test Document with Paths Containing Parens

[Upload Page](<app/(upload)/page.tsx>)
[Unix pipe](<https://en.wikipedia.org/wiki/Pipeline_(Unix)>)
[Missing](<app/(missing)/file.md>)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only have one warning for the missing file
        assert_eq!(
            result.len(),
            1,
            "Should have exactly one warning for missing file. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("app/(missing)/file.md"),
            "Warning should mention app/(missing)/file.md"
        );
    }

    #[test]
    fn test_balanced_parentheses_in_link_paths() {
        // Reproduces https://github.com/rvben/rumdl/issues/830:
        // links whose file path contains balanced parentheses used to be
        // truncated at the first ')' and reported as missing even when the
        // target exists on disk.
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Existing file with parens in its name
        let paren_file = base_path.join("file(inner).md");
        File::create(&paren_file)
            .unwrap()
            .write_all(b"# file(inner).md\n")
            .unwrap();

        // Existing file inside a folder with parens in its name
        let folder = base_path.join("folder(inner)");
        std::fs::create_dir(&folder).unwrap();
        File::create(folder.join("file.md"))
            .unwrap()
            .write_all(b"# folder(inner)/file.md\n")
            .unwrap();

        let content = r#"
# Test cases

[File with parenthesis exists](file(inner).md)
[Folder with parenthesis exists](folder(inner)/file.md)
[Missing with parenthesis](missing(inner).md)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // The two existing targets must not warn, and the missing one must be
        // reported with its full, untruncated path.
        assert_eq!(
            result.len(),
            1,
            "Expected exactly one warning (the missing file). Got: {result:?}"
        );
        assert!(
            result[0].message.contains("missing(inner).md"),
            "Warning should name the full path `missing(inner).md`, got: {}",
            result[0].message
        );
    }

    #[test]
    fn test_all_file_types_checked() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create a test with various file types - all should be checked
        let content = r#"
[Image Link](image.jpg)
[Video Link](video.mp4)
[Markdown Link](document.md)
[PDF Link](file.pdf)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should warn about all missing files regardless of extension
        assert_eq!(result.len(), 4, "Should have warnings for all missing files");
    }

    #[test]
    fn test_code_span_detection() {
        let rule = MD057ExistingRelativeLinks::new();

        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let rule = rule.with_path(base_path);

        // Test with document structure
        let content = "This is a [link](nonexistent.md) and `[not a link](not-checked.md)` in code.";

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only find the real link, not the one in code
        assert_eq!(result.len(), 1, "Should only flag the real link");
        assert!(result[0].message.contains("nonexistent.md"));
    }

    #[test]
    fn test_inline_code_spans() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create test content with links in inline code spans
        let content = r#"
# Test Document

This is a normal link: [Link](missing.md)

This is a code span with a link: `[Link](another-missing.md)`

Some more text with `inline code [Link](yet-another-missing.md) embedded`.

    "#;

        // Initialize rule with the base path
        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        // Test the rule
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only have warning for the normal link, not for links in code spans
        assert_eq!(result.len(), 1, "Should have exactly one warning");
        assert!(
            result[0].message.contains("missing.md"),
            "Warning should be for missing.md"
        );
        assert!(
            !result.iter().any(|w| w.message.contains("another-missing.md")),
            "Should not warn about link in code span"
        );
        assert!(
            !result.iter().any(|w| w.message.contains("yet-another-missing.md")),
            "Should not warn about link in inline code"
        );
    }

    #[test]
    fn test_extensionless_link_resolution() {
        // Create a temporary directory for test files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create a markdown file WITHOUT specifying .md extension in the link
        let page_path = base_path.join("page.md");
        File::create(&page_path).unwrap().write_all(b"# Page").unwrap();

        // Test content with extensionless link that should resolve to page.md
        let content = r#"
# Test Document

[Link without extension](page)
[Link with extension](page.md)
[Missing link](nonexistent)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only have warning for nonexistent link
        // Both "page" and "page.md" should resolve to the same file
        assert_eq!(result.len(), 1, "Should only warn about nonexistent link");
        assert!(
            result[0].message.contains("nonexistent"),
            "Warning should be for 'nonexistent' not 'page'"
        );
    }

    // Cross-file validation tests
    #[test]
    fn test_cross_file_scope() {
        let rule = MD057ExistingRelativeLinks::new();
        assert_eq!(rule.cross_file_scope(), CrossFileScope::Workspace);
    }

    #[test]
    fn test_contribute_to_index_extracts_markdown_links() {
        let rule = MD057ExistingRelativeLinks::new();
        let content = r#"
# Document

[Link to docs](./docs/guide.md)
[Link with fragment](./other.md#section)
[External link](https://example.com)
[Image link](image.png)
[Media file](video.mp4)
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let mut index = FileIndex::new();
        rule.contribute_to_index(&ctx, &mut index);

        // Should only index markdown file links
        assert_eq!(index.cross_file_links.len(), 2);

        // Check first link
        assert_eq!(index.cross_file_links[0].target_path, "./docs/guide.md");
        assert_eq!(index.cross_file_links[0].fragment, "");

        // Check second link (with fragment)
        assert_eq!(index.cross_file_links[1].target_path, "./other.md");
        assert_eq!(index.cross_file_links[1].fragment, "section");
    }

    #[test]
    fn test_contribute_to_index_skips_external_and_anchors() {
        let rule = MD057ExistingRelativeLinks::new();
        let content = r#"
# Document

[External](https://example.com)
[Another external](http://example.org)
[Fragment only](#section)
[FTP link](ftp://files.example.com)
[Mail link](mailto:test@example.com)
[WWW link](www.example.com)
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let mut index = FileIndex::new();
        rule.contribute_to_index(&ctx, &mut index);

        // Should not index any of these
        assert_eq!(index.cross_file_links.len(), 0);
    }

    #[test]
    fn test_cross_file_check_valid_link() {
        use crate::workspace_index::WorkspaceIndex;

        let rule = MD057ExistingRelativeLinks::new();

        // Create a workspace index with the target file
        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());

        // Create file index with a link to an existing file
        let mut file_index = FileIndex::new();
        file_index.add_cross_file_link(CrossFileLinkIndex {
            target_path: "guide.md".to_string(),
            fragment: "".to_string(),
            line: 5,
            column: 1,
            origin: LinkOrigin::Body,
        });

        // Run cross-file check from docs/index.md
        let warnings = rule
            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
            .unwrap();

        // Should have no warnings - file exists
        assert!(warnings.is_empty());
    }

    #[test]
    fn test_cross_file_check_missing_link() {
        // cross_file_check delegates all validation to check() to avoid duplicates.
        // It always returns empty — the per-file check() path is authoritative.
        use crate::workspace_index::WorkspaceIndex;

        let rule = MD057ExistingRelativeLinks::new();
        let workspace_index = WorkspaceIndex::new();

        let mut file_index = FileIndex::new();
        file_index.add_cross_file_link(CrossFileLinkIndex {
            target_path: "missing.md".to_string(),
            fragment: "".to_string(),
            line: 5,
            column: 1,
            origin: LinkOrigin::Body,
        });

        let warnings = rule
            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
            .unwrap();

        // cross_file_check defers to check(); it produces no warnings of its own.
        assert!(
            warnings.is_empty(),
            "cross_file_check must not duplicate check()'s per-file warnings. Got: {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_check_parent_path() {
        use crate::workspace_index::WorkspaceIndex;

        let rule = MD057ExistingRelativeLinks::new();

        // Create a workspace index with the target file at the root
        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(PathBuf::from("readme.md"), FileIndex::new());

        // Create file index with a parent path link
        let mut file_index = FileIndex::new();
        file_index.add_cross_file_link(CrossFileLinkIndex {
            target_path: "../readme.md".to_string(),
            fragment: "".to_string(),
            line: 5,
            column: 1,
            origin: LinkOrigin::Body,
        });

        // Run cross-file check from docs/guide.md
        let warnings = rule
            .cross_file_check(Path::new("docs/guide.md"), &file_index, &workspace_index)
            .unwrap();

        // Should have no warnings - file exists at normalized path
        assert!(warnings.is_empty());
    }

    #[test]
    fn test_cross_file_check_html_link_with_md_source() {
        // Test that .html links are accepted when corresponding .md source exists
        // This supports mdBook and similar doc generators that compile .md to .html
        use crate::workspace_index::WorkspaceIndex;

        let rule = MD057ExistingRelativeLinks::new();

        // Create a workspace index with the .md source file
        let mut workspace_index = WorkspaceIndex::new();
        workspace_index.insert_file(PathBuf::from("docs/guide.md"), FileIndex::new());

        // Create file index with an .html link (from another rule like MD051)
        let mut file_index = FileIndex::new();
        file_index.add_cross_file_link(CrossFileLinkIndex {
            target_path: "guide.html".to_string(),
            fragment: "section".to_string(),
            line: 10,
            column: 5,
            origin: LinkOrigin::Body,
        });

        // Run cross-file check from docs/index.md
        let warnings = rule
            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
            .unwrap();

        // Should have no warnings - .md source exists for the .html link
        assert!(
            warnings.is_empty(),
            "Expected no warnings for .html link with .md source, got: {warnings:?}"
        );
    }

    #[test]
    fn test_cross_file_check_html_link_without_source() {
        // cross_file_check delegates all validation to check() to avoid duplicates.
        // Verifying that .html links without a matching .md source are caught is
        // already covered by test_html_link_with_md_source (check() path).
        use crate::workspace_index::WorkspaceIndex;

        let rule = MD057ExistingRelativeLinks::new();
        let workspace_index = WorkspaceIndex::new();

        let mut file_index = FileIndex::new();
        file_index.add_cross_file_link(CrossFileLinkIndex {
            target_path: "missing.html".to_string(),
            fragment: "".to_string(),
            line: 10,
            column: 5,
            origin: LinkOrigin::Body,
        });

        let warnings = rule
            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
            .unwrap();

        // cross_file_check defers to check(); it produces no warnings of its own.
        assert!(
            warnings.is_empty(),
            "cross_file_check must not duplicate check()'s per-file warnings. Got: {warnings:?}"
        );
    }

    #[test]
    fn test_normalize_path_function() {
        // Test simple cases
        assert_eq!(
            normalize_relative_path(Path::new("docs/guide.md")),
            PathBuf::from("docs/guide.md")
        );

        // Test current directory removal
        assert_eq!(
            normalize_relative_path(Path::new("./docs/guide.md")),
            PathBuf::from("docs/guide.md")
        );

        // Test parent directory resolution
        assert_eq!(
            normalize_relative_path(Path::new("docs/sub/../guide.md")),
            PathBuf::from("docs/guide.md")
        );

        // Test multiple parent directories
        assert_eq!(
            normalize_relative_path(Path::new("a/b/c/../../d.md")),
            PathBuf::from("a/d.md")
        );
    }

    #[test]
    fn test_html_link_with_md_source() {
        // Links to .html files should pass if corresponding .md source exists
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create guide.md (source file)
        let md_file = base_path.join("guide.md");
        File::create(&md_file).unwrap().write_all(b"# Guide").unwrap();

        let content = r#"
[Read the guide](guide.html)
[Also here](getting-started.html)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // guide.html passes (guide.md exists), getting-started.html fails
        assert_eq!(
            result.len(),
            1,
            "Should only warn about missing source. Got: {result:?}"
        );
        assert!(result[0].message.contains("getting-started.html"));
    }

    #[test]
    fn test_htm_link_with_md_source() {
        // .htm extension should also check for markdown source
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let md_file = base_path.join("page.md");
        File::create(&md_file).unwrap().write_all(b"# Page").unwrap();

        let content = "[Page](page.htm)";

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Should not warn when .md source exists for .htm link"
        );
    }

    #[test]
    fn test_html_link_finds_various_markdown_extensions() {
        // Should find .mdx, .markdown, etc. as source files
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        File::create(base_path.join("doc.md")).unwrap();
        File::create(base_path.join("tutorial.mdx")).unwrap();
        File::create(base_path.join("guide.markdown")).unwrap();

        let content = r#"
[Doc](doc.html)
[Tutorial](tutorial.html)
[Guide](guide.html)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Should find all markdown variants as source files. Got: {result:?}"
        );
    }

    #[test]
    fn test_html_link_in_subdirectory() {
        // Should find markdown source in subdirectories
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let docs_dir = base_path.join("docs");
        std::fs::create_dir(&docs_dir).unwrap();
        File::create(docs_dir.join("guide.md"))
            .unwrap()
            .write_all(b"# Guide")
            .unwrap();

        let content = "[Guide](docs/guide.html)";

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(result.is_empty(), "Should find markdown source in subdirectory");
    }

    #[test]
    fn test_absolute_path_skipped_in_check() {
        // Test that absolute paths are skipped during link validation
        // This fixes the bug where /pkg/runtime was being flagged
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"
# Test Document

[Go Runtime](/pkg/runtime)
[Go Runtime with Fragment](/pkg/runtime#section)
[API Docs](/api/v1/users)
[Blog Post](/blog/2024/release.html)
[React Hook](/react/hooks/use-state.html)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have NO warnings - all absolute paths should be skipped
        assert!(
            result.is_empty(),
            "Absolute paths should be skipped. Got warnings: {result:?}"
        );
    }

    #[test]
    fn test_absolute_path_skipped_in_cross_file_check() {
        // Test that absolute paths are skipped in cross_file_check()
        use crate::workspace_index::WorkspaceIndex;

        let rule = MD057ExistingRelativeLinks::new();

        // Create an empty workspace index (no files exist)
        let workspace_index = WorkspaceIndex::new();

        // Create file index with absolute path links (should be skipped)
        let mut file_index = FileIndex::new();
        file_index.add_cross_file_link(CrossFileLinkIndex {
            target_path: "/pkg/runtime.md".to_string(),
            fragment: "".to_string(),
            line: 5,
            column: 1,
            origin: LinkOrigin::Body,
        });
        file_index.add_cross_file_link(CrossFileLinkIndex {
            target_path: "/api/v1/users.md".to_string(),
            fragment: "section".to_string(),
            line: 10,
            column: 1,
            origin: LinkOrigin::Body,
        });

        // Run cross-file check
        let warnings = rule
            .cross_file_check(Path::new("docs/index.md"), &file_index, &workspace_index)
            .unwrap();

        // Should have NO warnings - absolute paths should be skipped
        assert!(
            warnings.is_empty(),
            "Absolute paths should be skipped in cross_file_check. Got warnings: {warnings:?}"
        );
    }

    #[test]
    fn test_protocol_relative_url_not_skipped() {
        // Test that protocol-relative URLs (//example.com) are NOT skipped as absolute paths
        // They should still be caught by is_external_url() though
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"
# Test Document

[External](//example.com/page)
[Another](//cdn.example.com/asset.js)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have NO warnings - protocol-relative URLs are external and should be skipped
        assert!(
            result.is_empty(),
            "Protocol-relative URLs should be skipped. Got warnings: {result:?}"
        );
    }

    #[test]
    fn test_email_addresses_skipped() {
        // Test that email addresses without mailto: are skipped
        // These are clearly not file links (the @ symbol is definitive)
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"
# Test Document

[Contact](user@example.com)
[Steering](steering@kubernetes.io)
[Support](john.doe+filter@company.co.uk)
[User](user_name@sub.domain.com)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have NO warnings - email addresses are clearly not file links and should be skipped
        assert!(
            result.is_empty(),
            "Email addresses should be skipped. Got warnings: {result:?}"
        );
    }

    #[test]
    fn test_email_addresses_vs_file_paths() {
        // Test that email addresses (anything with @) are skipped
        // Note: File paths with @ are extremely rare, so we treat anything with @ as an email
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"
# Test Document

[Email](user@example.com)  <!-- Should be skipped (email) -->
[Email2](steering@kubernetes.io)  <!-- Should be skipped (email) -->
[Email3](user@file.md)  <!-- Should be skipped (has @, treated as email) -->
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // All should be skipped - anything with @ is treated as an email
        assert!(
            result.is_empty(),
            "All email addresses should be skipped. Got: {result:?}"
        );
    }

    #[test]
    fn test_diagnostic_position_accuracy() {
        // Test that diagnostics point to the URL, not the link text
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Position markers:     0         1         2         3
        //                       0123456789012345678901234567890123456789
        let content = "prefix [text](missing.md) suffix";
        //             The URL "missing.md" starts at 0-indexed position 14
        //             which is 1-indexed column 15, and ends at 0-indexed 24 (1-indexed column 25)

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning");
        assert_eq!(result[0].line, 1, "Should be on line 1");
        assert_eq!(result[0].column, 15, "Should point to start of URL 'missing.md'");
        assert_eq!(result[0].end_column, 25, "Should point past end of URL 'missing.md'");
    }

    #[test]
    fn test_diagnostic_position_non_ascii_link() {
        // Issue #670: columns are character offsets, not byte offsets. The CJK
        // prefix is multi-byte in UTF-8, so a byte offset over-counts the column.
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Character columns: 1:你 2:好 3:你 4:好 5:[ 6:你 7:好 8:] 9:( 10:n ...
        // The URL "not-exist.md" (12 chars) starts at 1-indexed character column 10
        // and ends past character column 21, i.e. end_column 22.
        let content = "你好你好[你好](not-exist.md) bar";

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning");
        assert_eq!(result[0].line, 1, "Should be on line 1");
        assert_eq!(
            result[0].column, 10,
            "Column must be a character offset, not a byte offset"
        );
        assert_eq!(result[0].end_column, 22, "End column must be character-based");
    }

    #[test]
    fn test_diagnostic_position_angle_brackets() {
        // Test position accuracy with angle bracket links
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Position markers:     0         1         2
        //                       012345678901234567890
        let content = "[link](<missing.md>)";
        //             The URL "missing.md" starts at 0-indexed position 8 (1-indexed column 9)

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning");
        assert_eq!(result[0].line, 1, "Should be on line 1");
        assert_eq!(result[0].column, 9, "Should point to start of URL in angle brackets");
    }

    #[test]
    fn test_diagnostic_position_multiline() {
        // Test that line numbers are correct for links on different lines
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Title
Some text on line 2
[link on line 3](missing1.md)
More text
[link on line 5](missing2.md)"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 2, "Should have two warnings");

        // First warning should be on line 3
        assert_eq!(result[0].line, 3, "First warning should be on line 3");
        assert!(result[0].message.contains("missing1.md"));

        // Second warning should be on line 5
        assert_eq!(result[1].line, 5, "Second warning should be on line 5");
        assert!(result[1].message.contains("missing2.md"));
    }

    #[test]
    fn test_diagnostic_position_with_spaces() {
        // Test position with URLs that have spaces in parentheses
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = "[link]( missing.md )";
        //             0123456789012345678901
        //             0-indexed position 8 is 'm' in 'missing.md' (after space and paren)
        //             which is 1-indexed column 9

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning");
        // The regex captures the URL without leading/trailing spaces
        assert_eq!(result[0].column, 9, "Should point to URL after stripping spaces");
    }

    #[test]
    fn test_diagnostic_position_image() {
        // Test that image diagnostics also have correct positions
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = "![alt text](missing.jpg)";

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning for image");
        assert_eq!(result[0].line, 1);
        // Images use start_col from the parser, which should point to the URL
        assert!(result[0].column > 0, "Should have valid column position");
        assert!(result[0].message.contains("missing.jpg"));
    }

    #[test]
    fn test_diagnostic_position_non_ascii_image() {
        // Issue #670: image columns are character offsets, not byte offsets.
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Character columns: 1:你 2:好 3:你 4:好 5:! 6:[ 7:你 8:好 9:] 10:( 11:n ...
        // The image syntax starts at the '!' which is 1-indexed character column 5.
        let content = "你好你好![你好](not-exist.png)";

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning for image");
        assert_eq!(result[0].line, 1, "Should be on line 1");
        assert_eq!(
            result[0].column, 5,
            "Column must be a character offset, not a byte offset"
        );
        assert!(result[0].message.contains("not-exist.png"));
    }

    #[test]
    fn test_diagnostic_position_non_ascii_reference_def() {
        // Issue #670: reference-definition columns are character offsets. A
        // multi-byte label shifts the URL's byte offset away from its character
        // column.
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Character columns: 1:[ 2:你 3:好 4:] 5:: 6:space 7:n ...
        // The URL "not-exist.md" (12 chars) starts at 1-indexed character column 7.
        let content = "[你好]: not-exist.md";

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning for reference def");
        assert_eq!(result[0].line, 1, "Should be on line 1");
        assert_eq!(
            result[0].column, 7,
            "Column must be a character offset, not a byte offset"
        );
        assert_eq!(result[0].end_column, 19, "End column must be character-based");
    }

    #[test]
    fn test_wikilinks_skipped() {
        // Wikilinks should not trigger MD057 warnings
        // They use a different linking system (e.g., Obsidian, wiki software)
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Test Document

[[Microsoft#Windows OS]]
[[SomePage]]
[[Page With Spaces]]
[[path/to/page#section]]
[[page|Display Text]]

This is a [real missing link](missing.md) that should be flagged.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only warn about the regular markdown link, not wikilinks
        assert_eq!(
            result.len(),
            1,
            "Should only warn about missing.md, not wikilinks. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("missing.md"),
            "Warning should be for missing.md, not wikilinks"
        );
    }

    #[test]
    fn test_wiki_embeds_skipped() {
        // A wiki embed names a vault entry, not a path relative to this file,
        // so `![[diagram.png]]` is not a missing relative link even though no
        // such file sits next to the document.
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Test Document

![[diagram.png]]
![[subfolder/diagram.png]]
![[diagram.png|300]]
![[Some Note]]

This is a [real missing link](missing.md) that should be flagged.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        for flavor in [
            crate::config::MarkdownFlavor::Obsidian,
            crate::config::MarkdownFlavor::Standard,
        ] {
            let ctx = crate::lint_context::LintContext::new(content, flavor, None);
            let result = rule.check(&ctx).unwrap();

            assert_eq!(
                result.len(),
                1,
                "{flavor:?}: should only warn about missing.md, not embeds. Got: {result:?}"
            );
            assert!(result[0].message.contains("missing.md"));
        }
    }

    #[test]
    fn test_wikilinks_not_added_to_index() {
        // Wikilinks should not be added to the cross-file link index
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Test Document

[[Microsoft#Windows OS]]
[[SomePage#section]]
[Regular Link](other.md)
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        let mut file_index = FileIndex::new();
        rule.contribute_to_index(&ctx, &mut file_index);

        // Should only have the regular markdown link (if it's a markdown file)
        // Wikilinks should not be added
        let cross_file_links = &file_index.cross_file_links;
        assert_eq!(
            cross_file_links.len(),
            1,
            "Only regular markdown links should be indexed, not wikilinks. Got: {cross_file_links:?}"
        );
        assert_eq!(file_index.cross_file_links[0].target_path, "other.md");
    }

    #[test]
    fn test_reference_definition_missing_file() {
        // Reference definitions [ref]: ./path.md should be checked
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Test Document

[test]: ./missing.md
[example]: ./nonexistent.html

Use [test] and [example] here.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have warnings for both reference definitions
        assert_eq!(
            result.len(),
            2,
            "Should have warnings for missing reference definition targets. Got: {result:?}"
        );
        assert!(
            result.iter().any(|w| w.message.contains("missing.md")),
            "Should warn about missing.md"
        );
        assert!(
            result.iter().any(|w| w.message.contains("nonexistent.html")),
            "Should warn about nonexistent.html"
        );
    }

    #[test]
    fn test_reference_definition_existing_file() {
        // Reference definitions to existing files should NOT trigger warnings
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create an existing file
        let exists_path = base_path.join("exists.md");
        File::create(&exists_path)
            .unwrap()
            .write_all(b"# Existing file")
            .unwrap();

        let content = r#"# Test Document

[test]: ./exists.md

Use [test] here.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have NO warnings since the file exists
        assert!(
            result.is_empty(),
            "Should not warn about existing file. Got: {result:?}"
        );
    }

    #[test]
    fn test_reference_definition_external_url_skipped() {
        // Reference definitions with external URLs should be skipped
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Test Document

[google]: https://google.com
[example]: http://example.org
[mail]: mailto:test@example.com
[ftp]: ftp://files.example.com
[local]: ./missing.md

Use [google], [example], [mail], [ftp], [local] here.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only warn about the local missing file, not external URLs
        assert_eq!(
            result.len(),
            1,
            "Should only warn about local missing file. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("missing.md"),
            "Warning should be for missing.md"
        );
    }

    #[test]
    fn test_reference_definition_fragment_only_skipped() {
        // Reference definitions with fragment-only URLs should be skipped
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Test Document

[section]: #my-section

Use [section] here.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have NO warnings for fragment-only links
        assert!(
            result.is_empty(),
            "Should not warn about fragment-only reference. Got: {result:?}"
        );
    }

    #[test]
    fn test_reference_definition_column_position() {
        // Test that column position points to the URL in the reference definition
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Position markers:     0         1         2
        //                       0123456789012345678901
        let content = "[ref]: ./missing.md";
        //             The URL "./missing.md" starts at 0-indexed position 7
        //             which is 1-indexed column 8

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(result.len(), 1, "Should have exactly one warning");
        assert_eq!(result[0].line, 1, "Should be on line 1");
        assert_eq!(result[0].column, 8, "Should point to start of URL './missing.md'");
    }

    #[test]
    fn test_reference_definition_html_with_md_source() {
        // Reference definitions to .html files should pass if corresponding .md source exists
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create guide.md (source file)
        let md_file = base_path.join("guide.md");
        File::create(&md_file).unwrap().write_all(b"# Guide").unwrap();

        let content = r#"# Test Document

[guide]: ./guide.html
[missing]: ./missing.html

Use [guide] and [missing] here.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // guide.html passes (guide.md exists), missing.html fails
        assert_eq!(
            result.len(),
            1,
            "Should only warn about missing source. Got: {result:?}"
        );
        assert!(result[0].message.contains("missing.html"));
    }

    #[test]
    fn test_reference_definition_url_encoded() {
        // Reference definitions with URL-encoded paths should be decoded before checking
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create a file with spaces in the name
        let file_with_spaces = base_path.join("file with spaces.md");
        File::create(&file_with_spaces).unwrap().write_all(b"# Spaces").unwrap();

        let content = r#"# Test Document

[spaces]: ./file%20with%20spaces.md
[missing]: ./missing%20file.md

Use [spaces] and [missing] here.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only warn about the missing file
        assert_eq!(
            result.len(),
            1,
            "Should only warn about missing URL-encoded file. Got: {result:?}"
        );
        assert!(result[0].message.contains("missing%20file.md"));
    }

    #[test]
    fn test_inline_and_reference_both_checked() {
        // Both inline links and reference definitions should be checked
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let content = r#"# Test Document

[inline link](./inline-missing.md)
[ref]: ./ref-missing.md

Use [ref] here.
"#;

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should warn about both the inline link and the reference definition
        assert_eq!(
            result.len(),
            2,
            "Should warn about both inline and reference links. Got: {result:?}"
        );
        assert!(
            result.iter().any(|w| w.message.contains("inline-missing.md")),
            "Should warn about inline-missing.md"
        );
        assert!(
            result.iter().any(|w| w.message.contains("ref-missing.md")),
            "Should warn about ref-missing.md"
        );
    }

    #[test]
    fn test_footnote_definitions_not_flagged() {
        // Regression test for issue #286: footnote definitions should not be
        // treated as reference definitions and flagged as broken links
        let rule = MD057ExistingRelativeLinks::default();

        let content = r#"# Title

A footnote[^1].

[^1]: [link](https://www.google.com).
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Footnote definitions should not trigger MD057 warnings. Got: {result:?}"
        );
    }

    #[test]
    fn test_footnote_with_relative_link_inside() {
        // Footnotes containing relative links should not be checked
        // (the footnote content is not a URL, it's content that may contain links)
        let rule = MD057ExistingRelativeLinks::default();

        let content = r#"# Title

See the footnote[^1].

[^1]: Check out [this file](./existing.md) for more info.
[^2]: Also see [missing](./does-not-exist.md).
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // The inline links INSIDE footnotes should be checked (./existing.md, ./does-not-exist.md)
        // but the footnote definition itself should not be treated as a reference definition
        // Note: This test verifies that [^1]: and [^2]: are not parsed as ref defs with
        // URLs like "[this file](./existing.md)" or "[missing](./does-not-exist.md)"
        for warning in &result {
            assert!(
                !warning.message.contains("[this file]"),
                "Footnote content should not be treated as URL: {warning:?}"
            );
            assert!(
                !warning.message.contains("[missing]"),
                "Footnote content should not be treated as URL: {warning:?}"
            );
        }
    }

    #[test]
    fn test_mixed_footnotes_and_reference_definitions() {
        // Ensure regular reference definitions are still checked while footnotes are skipped
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let content = r#"# Title

A footnote[^1] and a [ref link][myref].

[^1]: This is a footnote with [link](https://example.com).

[myref]: ./missing-file.md "This should be checked"
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should only warn about the regular reference definition, not the footnote
        assert_eq!(
            result.len(),
            1,
            "Should only warn about the regular reference definition. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("missing-file.md"),
            "Should warn about missing-file.md in reference definition"
        );
    }

    #[test]
    fn test_absolute_links_ignore_by_default() {
        // By default, absolute links are ignored (not validated)
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let content = r#"# Links

[API docs](/api/v1/users)
[Blog post](/blog/2024/release.html)
![Logo](/assets/logo.png)

[ref]: /docs/reference.md
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // No warnings - absolute links are ignored by default
        assert!(
            result.is_empty(),
            "Absolute links should be ignored by default. Got: {result:?}"
        );
    }

    #[test]
    fn test_absolute_links_warn_config() {
        // When configured to warn, absolute links should generate warnings
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::Warn,
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = r#"# Links

[API docs](/api/v1/users)
[Blog post](/blog/2024/release.html)
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        // Should have 2 warnings for the 2 absolute links
        assert_eq!(
            result.len(),
            2,
            "Should warn about both absolute links. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("cannot be validated locally"),
            "Warning should explain why: {}",
            result[0].message
        );
        assert!(
            result[0].message.contains("/api/v1/users"),
            "Warning should include the link path"
        );
    }

    #[test]
    fn test_absolute_links_warn_images() {
        // Images with absolute paths should also warn when configured
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::Warn,
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = r#"# Images

![Logo](/assets/logo.png)
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(
            result.len(),
            1,
            "Should warn about absolute image path. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("/assets/logo.png"),
            "Warning should include the image path"
        );
    }

    #[test]
    fn test_absolute_links_warn_reference_definitions() {
        // Reference definitions with absolute paths should also warn when configured
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::Warn,
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = r#"# Reference

See the [docs][ref].

[ref]: /docs/reference.md
"#;

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(
            result.len(),
            1,
            "Should warn about absolute reference definition. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("/docs/reference.md"),
            "Warning should include the reference path"
        );
    }

    #[test]
    fn test_search_paths_inline_link() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // Create an "assets" directory with an image
        let assets_dir = base_path.join("assets");
        std::fs::create_dir_all(&assets_dir).unwrap();
        std::fs::write(assets_dir.join("photo.png"), "fake image").unwrap();

        let config = MD057Config {
            search_paths: vec![assets_dir.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = "# Test\n\n[Photo](photo.png)\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Should find photo.png via search-paths. Got: {result:?}"
        );
    }

    #[test]
    fn test_search_paths_image() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let assets_dir = base_path.join("attachments");
        std::fs::create_dir_all(&assets_dir).unwrap();
        std::fs::write(assets_dir.join("diagram.svg"), "<svg/>").unwrap();

        let config = MD057Config {
            search_paths: vec![assets_dir.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = "# Test\n\n![Diagram](diagram.svg)\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Should find diagram.svg via search-paths. Got: {result:?}"
        );
    }

    #[test]
    fn test_search_paths_reference_definition() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let assets_dir = base_path.join("images");
        std::fs::create_dir_all(&assets_dir).unwrap();
        std::fs::write(assets_dir.join("logo.png"), "fake").unwrap();

        let config = MD057Config {
            search_paths: vec![assets_dir.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = "# Test\n\nSee [logo][ref].\n\n[ref]: logo.png\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Should find logo.png via search-paths in reference definition. Got: {result:?}"
        );
    }

    #[test]
    fn test_search_paths_still_warns_when_truly_missing() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let assets_dir = base_path.join("assets");
        std::fs::create_dir_all(&assets_dir).unwrap();

        let config = MD057Config {
            search_paths: vec![assets_dir.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = "# Test\n\n![Missing](nonexistent.png)\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(
            result.len(),
            1,
            "Should still warn when file doesn't exist in any search path. Got: {result:?}"
        );
    }

    #[test]
    fn test_search_paths_nonexistent_directory() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let config = MD057Config {
            search_paths: vec!["/nonexistent/path/that/does/not/exist".to_string()],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = "# Test\n\n![Missing](photo.png)\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(
            result.len(),
            1,
            "Nonexistent search path should not cause errors, just not find the file. Got: {result:?}"
        );
    }

    #[test]
    fn test_obsidian_attachment_folder_named() {
        let temp_dir = tempdir().unwrap();
        let vault = temp_dir.path().join("vault");
        std::fs::create_dir_all(vault.join(".obsidian")).unwrap();
        std::fs::create_dir_all(vault.join("Attachments")).unwrap();
        std::fs::create_dir_all(vault.join("notes")).unwrap();

        std::fs::write(
            vault.join(".obsidian/app.json"),
            r#"{"attachmentFolderPath": "Attachments"}"#,
        )
        .unwrap();
        std::fs::write(vault.join("Attachments/photo.png"), "fake").unwrap();

        let notes_dir = vault.join("notes");
        let source_file = notes_dir.join("test.md");
        std::fs::write(&source_file, "# Test\n\n![Photo](photo.png)\n").unwrap();

        let rule = MD057ExistingRelativeLinks::from_config_struct(MD057Config::default()).with_path(&notes_dir);

        let content = "# Test\n\n![Photo](photo.png)\n";
        let ctx =
            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, Some(source_file));
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Obsidian attachment folder should resolve photo.png. Got: {result:?}"
        );
    }

    #[test]
    fn test_obsidian_attachment_same_folder_as_file() {
        let temp_dir = tempdir().unwrap();
        let vault = temp_dir.path().join("vault-rf");
        std::fs::create_dir_all(vault.join(".obsidian")).unwrap();
        std::fs::create_dir_all(vault.join("notes")).unwrap();

        std::fs::write(vault.join(".obsidian/app.json"), r#"{"attachmentFolderPath": "./"}"#).unwrap();

        // Image in the same directory as the file — default behavior, no extra search needed
        let notes_dir = vault.join("notes");
        let source_file = notes_dir.join("test.md");
        std::fs::write(&source_file, "placeholder").unwrap();
        std::fs::write(notes_dir.join("photo.png"), "fake").unwrap();

        let rule = MD057ExistingRelativeLinks::from_config_struct(MD057Config::default()).with_path(&notes_dir);

        let content = "# Test\n\n![Photo](photo.png)\n";
        let ctx =
            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, Some(source_file));
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "'./' attachment mode resolves to same folder — should work by default. Got: {result:?}"
        );
    }

    #[test]
    fn test_obsidian_not_triggered_without_obsidian_flavor() {
        let temp_dir = tempdir().unwrap();
        let vault = temp_dir.path().join("vault-nf");
        std::fs::create_dir_all(vault.join(".obsidian")).unwrap();
        std::fs::create_dir_all(vault.join("Attachments")).unwrap();
        std::fs::create_dir_all(vault.join("notes")).unwrap();

        std::fs::write(
            vault.join(".obsidian/app.json"),
            r#"{"attachmentFolderPath": "Attachments"}"#,
        )
        .unwrap();
        std::fs::write(vault.join("Attachments/photo.png"), "fake").unwrap();

        let notes_dir = vault.join("notes");
        let source_file = notes_dir.join("test.md");
        std::fs::write(&source_file, "placeholder").unwrap();

        let rule = MD057ExistingRelativeLinks::from_config_struct(MD057Config::default()).with_path(&notes_dir);

        let content = "# Test\n\n![Photo](photo.png)\n";
        // Standard flavor — NOT Obsidian
        let ctx =
            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, Some(source_file));
        let result = rule.check(&ctx).unwrap();

        assert_eq!(
            result.len(),
            1,
            "Without Obsidian flavor, attachment folder should not be auto-detected. Got: {result:?}"
        );
    }

    #[test]
    fn test_search_paths_combined_with_obsidian() {
        let temp_dir = tempdir().unwrap();
        let vault = temp_dir.path().join("vault-combo");
        std::fs::create_dir_all(vault.join(".obsidian")).unwrap();
        std::fs::create_dir_all(vault.join("Attachments")).unwrap();
        std::fs::create_dir_all(vault.join("extra-assets")).unwrap();
        std::fs::create_dir_all(vault.join("notes")).unwrap();

        std::fs::write(
            vault.join(".obsidian/app.json"),
            r#"{"attachmentFolderPath": "Attachments"}"#,
        )
        .unwrap();
        std::fs::write(vault.join("Attachments/photo.png"), "fake").unwrap();
        std::fs::write(vault.join("extra-assets/diagram.svg"), "fake").unwrap();

        let notes_dir = vault.join("notes");
        let source_file = notes_dir.join("test.md");
        std::fs::write(&source_file, "placeholder").unwrap();

        let extra_assets_dir = vault.join("extra-assets");
        let config = MD057Config {
            search_paths: vec![extra_assets_dir.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&notes_dir);

        // Both links should resolve: photo.png via Obsidian, diagram.svg via search-paths
        let content = "# Test\n\n![Photo](photo.png)\n\n![Diagram](diagram.svg)\n";
        let ctx =
            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, Some(source_file));
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Both Obsidian attachment and search-paths should resolve. Got: {result:?}"
        );
    }

    #[test]
    fn test_obsidian_attachment_subfolder_under_file() {
        let temp_dir = tempdir().unwrap();
        let vault = temp_dir.path().join("vault-sub");
        std::fs::create_dir_all(vault.join(".obsidian")).unwrap();
        std::fs::create_dir_all(vault.join("notes/assets")).unwrap();

        std::fs::write(
            vault.join(".obsidian/app.json"),
            r#"{"attachmentFolderPath": "./assets"}"#,
        )
        .unwrap();
        std::fs::write(vault.join("notes/assets/photo.png"), "fake").unwrap();

        let notes_dir = vault.join("notes");
        let source_file = notes_dir.join("test.md");
        std::fs::write(&source_file, "placeholder").unwrap();

        let rule = MD057ExistingRelativeLinks::from_config_struct(MD057Config::default()).with_path(&notes_dir);

        let content = "# Test\n\n![Photo](photo.png)\n";
        let ctx =
            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, Some(source_file));
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Obsidian './assets' mode should find photo.png in <file-dir>/assets/. Got: {result:?}"
        );
    }

    #[test]
    fn test_obsidian_attachment_vault_root() {
        let temp_dir = tempdir().unwrap();
        let vault = temp_dir.path().join("vault-root");
        std::fs::create_dir_all(vault.join(".obsidian")).unwrap();
        std::fs::create_dir_all(vault.join("notes")).unwrap();

        // Empty string = vault root
        std::fs::write(vault.join(".obsidian/app.json"), r#"{"attachmentFolderPath": ""}"#).unwrap();
        std::fs::write(vault.join("photo.png"), "fake").unwrap();

        let notes_dir = vault.join("notes");
        let source_file = notes_dir.join("test.md");
        std::fs::write(&source_file, "placeholder").unwrap();

        let rule = MD057ExistingRelativeLinks::from_config_struct(MD057Config::default()).with_path(&notes_dir);

        let content = "# Test\n\n![Photo](photo.png)\n";
        let ctx =
            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Obsidian, Some(source_file));
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Obsidian vault-root mode should find photo.png at vault root. Got: {result:?}"
        );
    }

    #[test]
    fn test_search_paths_multiple_directories() {
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let dir_a = base_path.join("dir-a");
        let dir_b = base_path.join("dir-b");
        std::fs::create_dir_all(&dir_a).unwrap();
        std::fs::create_dir_all(&dir_b).unwrap();
        std::fs::write(dir_a.join("alpha.png"), "fake").unwrap();
        std::fs::write(dir_b.join("beta.png"), "fake").unwrap();

        let config = MD057Config {
            search_paths: vec![
                dir_a.to_string_lossy().into_owned(),
                dir_b.to_string_lossy().into_owned(),
            ],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(base_path);

        let content = "# Test\n\n![A](alpha.png)\n\n![B](beta.png)\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Should find files across multiple search paths. Got: {result:?}"
        );
    }

    /// MD057 validates every link target in `check()`, so its `cross_file_check`
    /// deliberately reports nothing: emitting there too would double every broken
    /// link warning.
    ///
    /// The target here does not exist anywhere the rule would look, so a
    /// `cross_file_check` that started resolving paths would report it and fail
    /// this test. The paired `check()` call is the positive control proving the
    /// link really is broken, which is what keeps the empty result meaningful.
    #[test]
    fn test_cross_file_check_reports_nothing_even_for_a_broken_link() {
        use crate::workspace_index::{CrossFileLinkIndex, FileIndex, LinkOrigin, WorkspaceIndex};

        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let file_path = base_path.join("README.md");
        let content = "# Readme\n\n[Guide](missing-guide.md)\n";
        std::fs::write(&file_path, content).unwrap();

        let rule = MD057ExistingRelativeLinks::from_config_struct(MD057Config::default()).with_path(base_path);

        let ctx = crate::lint_context::LintContext::new(
            content,
            crate::config::MarkdownFlavor::Standard,
            Some(file_path.clone()),
        );
        let per_file = rule.check(&ctx).unwrap();
        assert_eq!(
            per_file.len(),
            1,
            "control: check() is the pass that reports the broken link. Got: {per_file:?}"
        );

        let mut file_index = FileIndex::default();
        file_index.cross_file_links.push(CrossFileLinkIndex {
            target_path: "missing-guide.md".to_string(),
            fragment: String::new(),
            line: 3,
            column: 1,
            origin: LinkOrigin::Body,
        });

        let result = rule
            .cross_file_check(&file_path, &file_index, &WorkspaceIndex::new())
            .unwrap();

        assert!(
            result.is_empty(),
            "cross_file_check must stay silent so the link is reported once, not twice. Got: {result:?}"
        );
    }

    #[test]
    fn test_check_clears_stale_cache() {
        // Verify that check() resets the file existence cache so stale entries from
        // a previous lint cycle do not suppress valid warnings.
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        // Seed the cache with a stale "exists" entry for a file that is NOT on disk.
        let phantom_path = base_path.join("phantom.md");
        {
            let mut cache = FILE_EXISTENCE_CACHE.lock().unwrap();
            cache.insert(phantom_path.clone(), true);
        }

        let content = "[phantom](phantom.md)\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let warnings = rule.check(&ctx).unwrap();

        // check() must reset the cache; stale "exists=true" must not suppress the warning.
        assert_eq!(
            warnings.len(),
            1,
            "check() should report missing file after clearing stale cache. Got: {warnings:?}"
        );
        assert!(warnings[0].message.contains("phantom.md"));
    }

    #[test]
    fn test_check_does_not_carry_over_cache_between_runs() {
        // Two consecutive check() calls should each start with a fresh cache.
        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        let content = "[missing](nonexistent.md)\n";
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);

        // First run: file doesn't exist — warning expected.
        let warnings_1 = rule.check(&ctx).unwrap();
        assert_eq!(warnings_1.len(), 1, "First run should detect missing file");

        // Inject a stale "exists = true" entry for the resolved path.
        let nonexistent_path = base_path.join("nonexistent.md");
        {
            let mut cache = FILE_EXISTENCE_CACHE.lock().unwrap();
            cache.insert(nonexistent_path.clone(), true);
        }

        // Second run: cache says file exists, but check() should reset it first.
        let warnings_2 = rule.check(&ctx).unwrap();
        assert_eq!(
            warnings_2.len(),
            1,
            "Second check() run should still detect missing file after cache reset. Got: {warnings_2:?}"
        );
    }

    // --- Bug #631: duplicate warnings for broken relative links ---

    /// Regression test: a single broken relative link must produce exactly one
    /// warning across both check() and cross_file_check(). Previously, each
    /// code path emitted an identical warning independently, causing duplicates.
    #[test]
    fn test_no_duplicate_warnings_for_broken_relative_link() {
        use crate::workspace_index::WorkspaceIndex;

        let temp_dir = tempdir().unwrap();
        let base_path = temp_dir.path();

        // The broken link target does NOT exist on disk.
        let source_file = base_path.join("index.md");
        std::fs::write(&source_file, "[broken](does/not/exist.md)\n").unwrap();

        let content = "[broken](does/not/exist.md)\n";

        let rule = MD057ExistingRelativeLinks::new().with_path(base_path);

        // Collect warnings from check() (per-file path)
        let ctx = crate::lint_context::LintContext::new(
            content,
            crate::config::MarkdownFlavor::Standard,
            Some(source_file.clone()),
        );
        let check_warnings = rule.check(&ctx).unwrap();

        // Collect warnings from cross_file_check() (workspace-index path)
        let mut file_index = FileIndex::new();
        rule.contribute_to_index(&ctx, &mut file_index);
        let workspace_index = WorkspaceIndex::new();
        let cross_warnings = rule
            .cross_file_check(&source_file, &file_index, &workspace_index)
            .unwrap();

        let total = check_warnings.len() + cross_warnings.len();
        assert_eq!(
            total, 1,
            "Expected exactly 1 warning total across check() and cross_file_check(), got {total}: \
             check={check_warnings:?}, cross={cross_warnings:?}"
        );
    }

    // --- Bug #632: absolute directory links incorrectly flagged ---

    /// With absolute-links = "relative_to_roots", links to existing targets must
    /// be accepted for all four cases: {relative, absolute} x {file, directory}.
    #[test]
    fn test_absolute_dir_link_accepted_relative_to_roots() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();

        // Create directory `d` with a file inside (but no index.md)
        let dir_d = root.join("d");
        std::fs::create_dir_all(&dir_d).unwrap();
        std::fs::write(dir_d.join("foo.md"), "# Foo\n").unwrap();

        // Content exercises all four matrix cells:
        //   relative file, relative dir, absolute file, absolute dir
        let content = "\
[absolute dir](/d)\n\
[relative dir](d)\n\
[absolute file](/d/foo.md)\n\
[relative file](d/foo.md)\n";

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::RelativeToRoots,
            roots: vec![],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(root);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "All four {{relative,absolute}} x {{file,dir}} links to existing targets must pass. Got: {result:?}"
        );
    }

    /// In filesystem mode every spelling of a link to an existing directory is
    /// accepted, and a link to a directory that does not exist is still reported.
    /// The trailing slash is punctuation here: nothing routes `/d/` to `d/index.md`
    /// outside a site generator, and the relative form `../d/` is already accepted
    /// by `path.exists()` with no such requirement. (#863)
    #[test]
    fn test_absolute_directory_link_is_accepted_however_it_is_spelled() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();

        // Create directory `d` WITHOUT index.md
        let dir_d = root.join("d");
        std::fs::create_dir_all(&dir_d).unwrap();
        std::fs::write(dir_d.join("foo.md"), "# Foo\n").unwrap();

        let content = "\
[no slash](/d)\n\
[trailing slash](/d/)\n\
[trailing slash and fragment](/d/#intro)\n\
[relative](d/)\n";

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::RelativeToRoots,
            roots: vec![],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(root);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert!(
            result.is_empty(),
            "Every spelling of a link to an existing directory must agree. Got: {result:?}"
        );
    }

    /// The control for the test above: dropping the index.md requirement must not
    /// have dropped the existence check with it.
    #[test]
    fn test_absolute_directory_link_to_a_missing_directory_is_still_reported() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();

        let content = "[gone](/nodir/)\n";

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::RelativeToRoots,
            roots: vec![],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(root);

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        assert_eq!(
            result.len(),
            1,
            "A directory link naming nothing on disk must still be reported. Got: {result:?}"
        );
    }

    /// The docs_dir (MkDocs) variant must still flag a directory link when index.md
    /// is absent. This is tested via the full check() path with RelativeToDocs config
    /// and a real mkdocs.yml pointing at a docs dir that contains the directory target.
    #[test]
    fn test_docs_dir_variant_still_enforces_index_md() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();

        // Create a minimal mkdocs.yml pointing at a "docs" directory
        std::fs::write(root.join("mkdocs.yml"), "site_name: Test\ndocs_dir: docs\n").unwrap();

        // Create docs/section/ WITHOUT index.md
        let docs_dir = root.join("docs");
        std::fs::create_dir_all(&docs_dir).unwrap();
        let section_dir = docs_dir.join("section");
        std::fs::create_dir_all(&section_dir).unwrap();
        std::fs::write(section_dir.join("page.md"), "# Page\n").unwrap();

        // Create the source markdown file inside docs/
        let source_file = docs_dir.join("index.md");
        std::fs::write(&source_file, "[sec](/section)\n").unwrap();

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::RelativeToDocs,
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);

        let content = "[sec](/section)\n";
        let ctx = crate::lint_context::LintContext::new(
            content,
            crate::config::MarkdownFlavor::Standard,
            Some(source_file.clone()),
        );
        let result = rule.check(&ctx).unwrap();

        // MkDocs enforces index.md for directory links, so this should be flagged.
        assert_eq!(
            result.len(),
            1,
            "MkDocs docs_dir variant must flag directory link without index.md. Got: {result:?}"
        );
        assert!(
            result[0].message.contains("index.md") || result[0].message.contains("section"),
            "Message should mention the directory or missing index.md: {}",
            result[0].message
        );
    }

    /// MkDocs mode is where the index.md requirement belongs, and every spelling
    /// of a directory link has to reach it — including one whose trailing slash is
    /// hidden behind a fragment (`/guide/#intro`). This is the control proving the
    /// roots-mode change did not disable the check everywhere.
    #[test]
    fn test_docs_mode_requires_index_for_every_spelling_of_a_directory_link() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        std::fs::write(root.join("mkdocs.yml"), "site_name: Test\ndocs_dir: docs\n").unwrap();

        // Create docs/guide WITHOUT index.md
        let docs_dir = root.join("docs");
        let guide_dir = docs_dir.join("guide");
        std::fs::create_dir_all(&guide_dir).unwrap();
        std::fs::write(guide_dir.join("page.md"), "# Page\n").unwrap();

        let source_file = docs_dir.join("t.md");
        let content = "\
[no slash](/guide)\n\
[trailing slash](/guide/)\n\
[trailing slash and fragment](/guide/#intro)\n";
        std::fs::write(&source_file, content).unwrap();

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::RelativeToDocs,
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(&docs_dir);
        let ctx = crate::lint_context::LintContext::new(
            content,
            crate::config::MarkdownFlavor::Standard,
            Some(source_file.clone()),
        );
        let result = rule.check(&ctx).unwrap();

        assert_eq!(
            result.len(),
            3,
            "Every directory link must be routed through the index.md check. Got: {result:?}"
        );
        for warning in &result {
            assert!(
                warning.message.contains("which has no index.md"),
                "The message must name the reason, not report the directory as missing: {}",
                warning.message
            );
        }
    }
}

#[cfg(test)]
mod self_referential_links_tests {
    use super::*;
    use tempfile::tempdir;

    /// A document written to `dir/<name>`, checked as itself.
    pub(super) fn check_as_file(dir: &Path, name: &str, content: &str, config: MD057Config) -> Vec<LintWarning> {
        let source_file = dir.join(name);
        std::fs::write(&source_file, content).unwrap();
        let rule = MD057ExistingRelativeLinks::from_config_struct(config);
        let ctx =
            crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, Some(source_file));
        rule.check(&ctx).unwrap()
    }

    fn enabled() -> MD057Config {
        MD057Config {
            self_referential_links: true,
            ..Default::default()
        }
    }

    #[test]
    fn test_a_link_with_a_fragment_is_reduced_to_the_fragment() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [the section](test.md#level-2-heading).\n\n## Level 2 heading\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(
            result[0].message,
            "Relative link 'test.md#level-2-heading' points to the file it is in and can be simplified to '#level-2-heading'"
        );
        let fix = result[0].fix.as_ref().expect("the fragment form is fixable");
        assert_eq!(fix.replacement, "#level-2-heading");
        assert_eq!(&content[fix.range.clone()], "test.md#level-2-heading");
    }

    #[test]
    fn test_a_link_to_the_whole_file_is_reported_without_a_fix() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [this file](test.md).\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'test.md' points to the file it is in");
        assert!(
            result[0].fix.is_none(),
            "Dropping the link would change the document, so there is no fix"
        );
    }

    #[test]
    fn test_the_check_is_off_by_default() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [this file](test.md) and [the section](test.md#title).\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert!(result.is_empty(), "Off by default. Got: {result:?}");
    }

    #[test]
    fn test_a_link_to_another_file_is_left_alone() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("other.md"), "# Other\n").unwrap();
        let content = "# Title\n\nSee [the other file](other.md#other) and [a heading here](#title).\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert!(result.is_empty(), "Neither link is self-referential. Got: {result:?}");
    }

    #[test]
    fn test_a_self_link_written_with_traversal_reports_once() {
        let temp_dir = tempdir().unwrap();
        let sub_dir = temp_dir.path().join("sub");
        std::fs::create_dir_all(&sub_dir).unwrap();

        let content = "# Title\n\nSee [the long way round](../sub/test.md).\n";
        let config = MD057Config {
            self_referential_links: true,
            compact_paths: true,
            ..Default::default()
        };
        let result = check_as_file(&sub_dir, "test.md", content, config);

        assert_eq!(
            result.len(),
            1,
            "A compacted path would still be a link back to this file. Got: {result:?}"
        );
        assert_eq!(
            result[0].message,
            "Relative link '../sub/test.md' points to the file it is in"
        );
    }

    #[test]
    fn test_compact_paths_still_reports_a_link_to_another_file() {
        let temp_dir = tempdir().unwrap();
        let sub_dir = temp_dir.path().join("sub");
        std::fs::create_dir_all(&sub_dir).unwrap();
        std::fs::write(sub_dir.join("other.md"), "# Other\n").unwrap();

        let content = "# Title\n\nSee [the long way round](../sub/other.md).\n";
        let config = MD057Config {
            self_referential_links: true,
            compact_paths: true,
            ..Default::default()
        };
        let result = check_as_file(&sub_dir, "test.md", content, config);

        assert_eq!(result.len(), 1, "Expected the compaction warning. Got: {result:?}");
        assert_eq!(
            result[0].message,
            "Relative link '../sub/other.md' can be simplified to 'other.md'"
        );
    }

    #[test]
    fn test_an_extensionless_self_link_resolves_the_same_way_the_existence_check_does() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [this file](test#title).\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(
            result[0].fix.as_ref().map(|f| f.replacement.as_str()),
            Some("#title"),
            "Got: {result:?}"
        );
    }

    #[test]
    fn test_a_reference_definition_pointing_at_its_own_file() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [the section][here].\n\n## Level 2 heading\n\n[here]: test.md#level-2-heading\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        let fix = result[0].fix.as_ref().expect("the fragment form is fixable");
        assert_eq!(fix.replacement, "#level-2-heading");
        assert_eq!(&content[fix.range.clone()], "test.md#level-2-heading");
    }

    #[test]
    fn test_a_reference_definition_whose_label_repeats_the_destination() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [the section][test.md#title].\n\n## Title\n\n[test.md#title]: test.md#title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        let fix = result[0].fix.as_ref().expect("the fragment form is fixable");
        // The label reads the same as the destination, so an unanchored search
        // would rewrite the label and orphan the usage above.
        assert_eq!(fix.range.start, content.rfind("test.md#title").unwrap());
        let fixed = MD057ExistingRelativeLinks::from_config_struct(enabled())
            .fix(&crate::lint_context::LintContext::new(
                content,
                crate::config::MarkdownFlavor::Standard,
                Some(temp_dir.path().join("test.md")),
            ))
            .unwrap();
        assert!(fixed.contains("[test.md#title]: #title"), "Got: {fixed}");
        assert!(fixed.contains("[the section][test.md#title]"), "Got: {fixed}");
    }

    #[test]
    fn test_a_self_link_resolved_through_a_search_path() {
        let temp_dir = tempdir().unwrap();
        let guide_dir = temp_dir.path().join("docs/guide");
        std::fs::create_dir_all(&guide_dir).unwrap();
        let config = MD057Config {
            search_paths: vec![temp_dir.path().join("docs").to_string_lossy().into_owned()],
            ..enabled()
        };
        let content = "# Title\n\nSee [this file](guide/test.md#title).\n";
        let result = check_as_file(&guide_dir, "test.md", content, config);

        assert_eq!(
            result.len(),
            1,
            "A link the existence check accepts through a search path resolves to this same file. Got: {result:?}"
        );
        assert_eq!(
            result[0].fix.as_ref().map(|f| f.replacement.as_str()),
            Some("#title"),
            "Got: {result:?}"
        );
    }

    #[test]
    fn test_a_target_next_to_the_document_outranks_a_search_path() {
        let temp_dir = tempdir().unwrap();
        let guide_dir = temp_dir.path().join("docs/guide");
        std::fs::create_dir_all(guide_dir.join("guide")).unwrap();
        std::fs::write(guide_dir.join("guide/test.md"), "# Other\n\n## Title\n").unwrap();
        let config = MD057Config {
            search_paths: vec![temp_dir.path().join("docs").to_string_lossy().into_owned()],
            ..enabled()
        };
        let content = "# Title\n\nSee [another file](guide/test.md#title).\n";
        let result = check_as_file(&guide_dir, "test.md", content, config);

        assert!(
            result.is_empty(),
            "The link resolves to guide/guide/test.md, so the search path never answers for it. Got: {result:?}"
        );
    }

    #[test]
    fn test_an_image_pointing_at_its_own_file_is_not_reported() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\n![not a navigation link](test.md)\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert!(
            result.is_empty(),
            "An image is not a link the reader follows. Got: {result:?}"
        );
    }

    #[test]
    fn test_a_query_string_is_reported_without_a_suggestion() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [this file](test.md?raw=true#title).\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, enabled());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert!(
            result[0].fix.is_none(),
            "A query does not survive losing its path. Got: {result:?}"
        );
    }

    #[test]
    fn test_fix_rewrites_the_document_and_settles() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [the section](test.md#level-2-heading).\n\n## Level 2 heading\n";
        let source_file = temp_dir.path().join("test.md");
        std::fs::write(&source_file, content).unwrap();

        let rule = MD057ExistingRelativeLinks::from_config_struct(enabled());
        let ctx = crate::lint_context::LintContext::new(
            content,
            crate::config::MarkdownFlavor::Standard,
            Some(source_file.clone()),
        );
        let fixed = rule.fix(&ctx).unwrap();
        assert_eq!(
            fixed,
            "# Title\n\nSee [the section](#level-2-heading).\n\n## Level 2 heading\n"
        );

        let refixed =
            crate::lint_context::LintContext::new(&fixed, crate::config::MarkdownFlavor::Standard, Some(source_file));
        assert_eq!(rule.fix(&refixed).unwrap(), fixed, "The fix converges in one pass");
    }

    #[test]
    fn test_the_rule_reports_no_fixes_when_neither_rewriting_option_is_on() {
        let unfixable = MD057ExistingRelativeLinks::default();
        assert_eq!(unfixable.fix_capability(), FixCapability::Unfixable);

        let fixable = MD057ExistingRelativeLinks::from_config_struct(enabled());
        assert_eq!(fixable.fix_capability(), FixCapability::ConditionallyFixable);
    }

    #[test]
    fn test_the_option_is_read_from_kebab_and_snake_case() {
        let kebab: MD057Config = toml::from_str("self-referential-links = true").unwrap();
        assert!(kebab.self_referential_links);

        let snake: MD057Config = toml::from_str("self_referential_links = true").unwrap();
        assert!(snake.self_referential_links);
    }

    fn front_matter_checked() -> MD057Config {
        MD057Config {
            check_frontmatter: true,
            ..Default::default()
        }
    }

    #[test]
    fn test_a_broken_frontmatter_path_is_reported_when_enabled() {
        let temp_dir = tempdir().unwrap();
        let content = "---\ntemplate: ./missing.md\n---\n\n# Title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, front_matter_checked());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link './missing.md' does not exist");
        assert_eq!(result[0].line, 2);
        assert_eq!(result[0].column, 11, "The warning points at the value, not the key");
        assert_eq!(result[0].end_column, 23);
    }

    #[test]
    fn test_frontmatter_paths_are_not_checked_by_default() {
        let temp_dir = tempdir().unwrap();
        let content = "---\ntemplate: ./missing.md\n---\n\n# Title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert!(
            result.is_empty(),
            "Frontmatter is only checked on request. Got: {result:?}"
        );
    }

    #[test]
    fn test_an_existing_frontmatter_path_is_not_reported() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("guide.md"), "# Guide\n").unwrap();
        let content = "---\ntemplate: ./guide.md\nfallback: ./gone.md\n---\n\n# Title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, front_matter_checked());

        assert_eq!(result.len(), 1, "Only the missing target is reported. Got: {result:?}");
        assert_eq!(result[0].line, 3);
    }

    #[test]
    fn test_an_ignored_frontmatter_field_is_not_checked() {
        let temp_dir = tempdir().unwrap();
        let content = "---\nimage: ./missing.png\ntemplate: ./missing.md\n---\n\n# Title\n";
        let config = MD057Config {
            check_frontmatter: true,
            ignore_frontmatter_fields: vec!["Image".to_string()],
            ..Default::default()
        };
        let result = check_as_file(temp_dir.path(), "test.md", content, config);

        assert_eq!(
            result.len(),
            1,
            "The ignored field is skipped and the other is not. Got: {result:?}"
        );
        assert_eq!(result[0].line, 3);
    }

    #[test]
    fn test_an_external_frontmatter_url_is_not_reported() {
        let temp_dir = tempdir().unwrap();
        let content = "---\ncanonical: https://example.com/docs/guide.md\n---\n\n# Title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, front_matter_checked());

        assert!(
            result.is_empty(),
            "An external URL has no local target. Got: {result:?}"
        );
    }

    #[test]
    fn test_a_frontmatter_fragment_is_left_to_md051() {
        let temp_dir = tempdir().unwrap();
        let content = "---\nanchor: '#missing'\n---\n\n# Title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, front_matter_checked());

        assert!(
            result.is_empty(),
            "A fragment names a heading, not a file. Got: {result:?}"
        );
    }

    #[test]
    fn test_an_absolute_frontmatter_path_follows_the_absolute_links_option() {
        let temp_dir = tempdir().unwrap();
        let content = "---\ntemplate: /docs/guide.md\n---\n\n# Title\n";

        let ignored = check_as_file(temp_dir.path(), "ignored.md", content, front_matter_checked());
        assert!(
            ignored.is_empty(),
            "Absolute paths are ignored by default. Got: {ignored:?}"
        );

        let warning_config = MD057Config {
            check_frontmatter: true,
            absolute_links: AbsoluteLinksOption::Warn,
            ..Default::default()
        };
        let warned = check_as_file(temp_dir.path(), "warned.md", content, warning_config);
        assert_eq!(warned.len(), 1, "Expected one warning. Got: {warned:?}");
        assert_eq!(
            warned[0].message,
            "Absolute link '/docs/guide.md' cannot be validated locally"
        );
    }

    #[test]
    fn test_a_frontmatter_path_carrying_a_query_is_checked() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("guide.md"), "# Guide\n").unwrap();
        let content = "---\ntemplate: docs/missing.md?raw=true\nfallback: guide.md?raw=true\n---\n\n# Title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, front_matter_checked());

        assert_eq!(
            result.len(),
            1,
            "A query names no file, so only the missing target is reported. Got: {result:?}"
        );
        assert_eq!(result[0].line, 2);
        assert_eq!(
            result[0].message,
            "Relative link 'docs/missing.md?raw=true' does not exist"
        );
    }

    #[test]
    fn test_prose_in_frontmatter_is_not_read_as_a_path() {
        let temp_dir = tempdir().unwrap();
        let content = "---\ntitle: Node.js\nversion: 1.2.3\ntags: ci/cd\ndate: 2026-07-31\n---\n\n# Title\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, front_matter_checked());

        assert!(
            result.is_empty(),
            "Only path-shaped values are destinations. Got: {result:?}"
        );
    }
}

/// An inline link whose text carries a newline is checked like any other.
///
/// The destination of such a link sits on the line the link ends on, so every
/// report on it names that line and the column the destination starts at.
#[cfg(test)]
mod wrapped_link_text_tests {
    use super::self_referential_links_tests::check_as_file;
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_a_wrapped_link_in_a_list_item_is_reported() {
        let temp_dir = tempdir().unwrap();
        let content = "- Items reimbursable by the various [one-off\n  expense](does-not-exist-anywhere)\n  budgets.\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(
            result[0].message,
            "Relative link 'does-not-exist-anywhere' does not exist"
        );
        assert_eq!(result[0].line, 2, "The destination sits on the second line");
        assert_eq!(result[0].end_line, 2);
        // Line 2 is `  expense](does-not-exist-anywhere)`, so the destination
        // starts at the twelfth character and runs 23 characters.
        assert_eq!(result[0].column, 12);
        assert_eq!(result[0].end_column, 35);
    }

    #[test]
    fn test_a_wrapped_link_in_a_paragraph_is_reported() {
        let temp_dir = tempdir().unwrap();
        let content = "Paragraph with [wrapped\ntext](also-missing) here.\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'also-missing' does not exist");
        assert_eq!(result[0].line, 2, "The destination sits on the second line");
        // Line 2 is `text](also-missing) here.`, so the destination starts at
        // the seventh character and runs 12 characters.
        assert_eq!(result[0].column, 7);
        assert_eq!(result[0].end_column, 19);
    }

    #[test]
    fn test_a_wrapped_link_carrying_a_title_is_reported() {
        let temp_dir = tempdir().unwrap();
        let content = "[wrapped\ntext](missing-titled.md \"t\")\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing-titled.md' does not exist");
        assert_eq!(result[0].line, 2);
        // The title is not part of the destination, so the warning ends with
        // the path at the twenty-fourth character.
        assert_eq!(result[0].column, 7);
        assert_eq!(result[0].end_column, 24);
    }

    #[test]
    fn test_a_wrapped_link_to_an_existing_file_is_left_alone() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("target.md"), "# Target\n").unwrap();
        let content = "Paragraph with [wrapped\ntext](target.md) here.\n";
        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert!(result.is_empty(), "The target exists. Got: {result:?}");
    }

    #[test]
    fn test_a_wrapped_link_target_reaches_the_dependency_index() {
        let rule = MD057ExistingRelativeLinks::new();
        let content = "Paragraph with [wrapped\ntext](./docs/guide.md) here.\n";

        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let mut index = FileIndex::new();
        rule.contribute_to_index(&ctx, &mut index);

        let targets: Vec<&str> = index
            .md057_link_targets
            .iter()
            .map(|target| target.target.as_str())
            .collect();
        assert_eq!(
            targets,
            vec!["./docs/guide.md"],
            "The index must record the target so a cached verdict is invalidated when the file appears"
        );
    }

    #[test]
    fn test_a_wrapped_link_is_compacted_over_the_right_bytes() {
        let temp_dir = tempdir().unwrap();
        let sub_dir = temp_dir.path().join("sub");
        std::fs::create_dir_all(&sub_dir).unwrap();
        std::fs::write(sub_dir.join("other.md"), "# Other\n").unwrap();

        let content = "See [the long way\nround](../sub/other.md#part) here.\n";
        let config = MD057Config {
            compact_paths: true,
            ..Default::default()
        };
        let result = check_as_file(&sub_dir, "test.md", content, config);

        assert_eq!(result.len(), 1, "Expected the compaction warning. Got: {result:?}");
        assert_eq!(
            result[0].message,
            "Relative link '../sub/other.md#part' can be simplified to 'other.md#part'"
        );
        assert_eq!(result[0].line, 2);
        let fix = result[0].fix.as_ref().expect("a compaction is fixable");
        assert_eq!(&content[fix.range.clone()], "../sub/other.md#part");
        assert_eq!(fix.replacement, "other.md#part");
    }

    #[test]
    fn test_a_wrapped_self_link_is_reduced_over_the_right_bytes() {
        let temp_dir = tempdir().unwrap();
        let content = "# Title\n\nSee [the section\nbelow](test.md#level-2-heading).\n\n## Level 2 heading\n";
        let config = MD057Config {
            self_referential_links: true,
            ..Default::default()
        };
        let result = check_as_file(temp_dir.path(), "test.md", content, config);

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(
            result[0].message,
            "Relative link 'test.md#level-2-heading' points to the file it is in and can be simplified to '#level-2-heading'"
        );
        assert_eq!(result[0].line, 4);
        let fix = result[0].fix.as_ref().expect("the fragment form is fixable");
        assert_eq!(&content[fix.range.clone()], "test.md#level-2-heading");
        assert_eq!(fix.replacement, "#level-2-heading");
    }
}

/// The destination is read from inside the link's label, never from past it.
///
/// A label can spell `](` in a code span, and a destination title can spell it
/// in plain text. Neither opens a destination, and a shape that carries no
/// destination at all yields nothing to report and nothing to rewrite.
#[cfg(test)]
mod destination_boundary_tests {
    use super::self_referential_links_tests::check_as_file;
    use super::*;
    use tempfile::tempdir;

    fn compacting() -> MD057Config {
        MD057Config {
            compact_paths: true,
            ..Default::default()
        }
    }

    /// A label holding an unmatched backtick still ends where the parse closes
    /// it. The destination is the one the label closes on, not the `](` the
    /// title happens to contain.
    #[test]
    fn test_a_title_spelling_a_bracket_paren_is_not_the_destination() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("existing.md"), "# Existing\n").unwrap();
        let content = "[literal `](missing.md \"See ](./existing.md)\")\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing.md' does not exist");
        assert_eq!(result[0].line, 1);
        // `missing.md` opens at the thirteenth character, just past `](`.
        assert_eq!(result[0].column, 13);
        assert_eq!(result[0].end_column, 23);
        assert!(result[0].fix.is_none(), "A missing target carries no fix");
    }

    /// The same document with compaction on. The path inside the title looks
    /// compactable, so a report naming it would rewrite the title.
    #[test]
    fn test_compaction_never_rewrites_a_title() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("existing.md"), "# Existing\n").unwrap();
        let content = "[literal `](missing.md \"See ](./existing.md)\")\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, compacting());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing.md' does not exist");
        assert_eq!(result[0].column, 13);
        assert!(
            result.iter().all(|warning| warning.fix.is_none()),
            "Nothing in this document is rewritable. Got: {result:?}"
        );
    }

    /// Brackets nest inside a label, so the first `]` is not the one that
    /// closes it.
    #[test]
    fn test_a_nested_bracket_does_not_close_the_label() {
        let temp_dir = tempdir().unwrap();
        let content = "[see [note]](./missing.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link './missing.md' does not exist");
        // `./missing.md` opens at the fourteenth character, past both brackets.
        assert_eq!(result[0].column, 14);
        assert_eq!(result[0].end_column, 26);
    }

    /// An autolink is a URL between angle brackets. Its text is the URL itself,
    /// so a `](` written in it opens no destination and nothing in it is a path
    /// this rule may rewrite.
    #[test]
    fn test_an_autolink_carries_no_destination() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("existing.md"), "# Existing\n").unwrap();
        let content = "<https://example.com/](./existing.md)> [ok](existing.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, compacting());

        assert!(result.is_empty(), "An autolink is not a relative link. Got: {result:?}");
    }

    /// Control for the autolink case: an email autolink is the same shape.
    #[test]
    fn test_an_email_autolink_carries_no_destination() {
        let temp_dir = tempdir().unwrap();
        let content = "<user@example.com>\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, compacting());

        assert!(
            result.is_empty(),
            "An email autolink is not a relative link. Got: {result:?}"
        );
    }

    /// A code span holds its own `](`, and the span runs past it to the second
    /// run of backticks. The link closes on the bracket after that run, so the
    /// path inside the code span is not a destination and nothing about it is
    /// reportable or rewritable.
    #[test]
    fn test_a_code_span_spelling_a_bracket_paren_is_not_the_destination() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.md"), "# Exists\n").unwrap();
        let content = "[``a\n](./exists.md)``](exists.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, compacting());

        assert!(
            result.is_empty(),
            "Both destinations exist, so nothing is reported. Got: {result:?}"
        );
        assert!(
            result.iter().all(|warning| warning.fix.is_none()),
            "Nothing here is rewritable, the code span least of all. Got: {result:?}"
        );
    }

    /// Inline HTML in a label can spell `[` inside an attribute value. The
    /// parse reads the attribute as text rather than as an opening bracket, so
    /// the label closes where it is written to.
    #[test]
    fn test_a_bracket_in_an_html_attribute_does_not_open_a_label() {
        let temp_dir = tempdir().unwrap();
        let content = "[<i title=\"[\">text</i>](missing.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing.md' does not exist");
        assert_eq!(result[0].line, 1);
        // `missing.md` opens at the twenty fifth character, just past `](`.
        assert_eq!(result[0].column, 25);
        assert_eq!(result[0].end_column, 35);
    }

    /// Link syntax inside an image's description is not a link. The renderer
    /// puts the description in an `alt` attribute, where a hyperlink cannot
    /// exist, so its destination names no target this document reaches.
    #[test]
    fn test_a_link_inside_an_image_description_is_not_a_link() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.png"), "x").unwrap();
        let content = "![an [example](missing.md)](exists.png)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert!(
            result.is_empty(),
            "The description of an image carries no link. Got: {result:?}"
        );
    }

    /// The control for the case above. A link cannot nest inside a link, so
    /// the outer brackets here are literal text and the inner link is the only
    /// one in the line. Nothing about it sits inside an image.
    #[test]
    fn test_a_link_inside_literal_brackets_is_still_a_link() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.png"), "x").unwrap();
        let content = "[outer [inner](missing2.md)](exists.png)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing2.md' does not exist");
        assert_eq!(result[0].line, 1);
        // `missing2.md` opens at the sixteenth character, just past `](`.
        assert_eq!(result[0].column, 16);
    }

    /// The second control. An image is still read by the image pass, which the
    /// link pass does not touch.
    #[test]
    fn test_an_image_of_its_own_is_still_reported() {
        let temp_dir = tempdir().unwrap();
        let content = "![plain](missing.png)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing.png' does not exist");
        assert_eq!(result[0].column, 1);
    }

    /// The third control. An image used as a link's text leaves the link
    /// itself outside the image, so the link's own destination is still read.
    #[test]
    fn test_an_image_used_as_link_text_leaves_the_link_readable() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.png"), "x").unwrap();
        let content = "[![alt](exists.png)](missing.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing.md' does not exist");
        // `missing.md` opens at the twenty second character.
        assert_eq!(result[0].column, 22);
    }

    /// The image used as link text is a collapsed reference. The label closes
    /// on the bracket after the image's `[]`, and the link's own destination
    /// is read from past that bracket.
    #[test]
    fn test_a_link_wrapping_a_collapsed_reference_image_is_still_read() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.png"), "x").unwrap();
        let content = "[![alt][]](missing.md)\n\n[alt]: exists.png\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing.md' does not exist");
        assert_eq!(result[0].line, 1);
        // `missing.md` opens at the twelfth character, just past `](`.
        assert_eq!(result[0].column, 12);
        assert_eq!(result[0].end_column, 22);
    }

    /// A reference image with no definition is not an image. The renderer
    /// leaves its brackets as text, so a link written between them is a real
    /// link and its destination is a real target. All three reference
    /// spellings behave the same way.
    #[test]
    fn test_a_link_inside_an_undefined_reference_image_is_a_link() {
        for content in [
            "![alt [x](missing.md)][nodef]\n",
            "![alt [x](missing.md)][]\n",
            "![alt [x](missing.md)]\n",
        ] {
            let temp_dir = tempdir().unwrap();

            let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

            assert_eq!(result.len(), 1, "Expected one warning for {content:?}. Got: {result:?}");
            assert_eq!(result[0].message, "Relative link 'missing.md' does not exist");
            // `missing.md` opens at the eleventh character, just past `](`.
            assert_eq!(result[0].column, 11, "Wrong column for {content:?}");
        }
    }

    /// An inline image with an empty destination is still an image, so what is
    /// written between its brackets is still alt text.
    #[test]
    fn test_an_image_with_an_empty_destination_is_still_an_image() {
        let temp_dir = tempdir().unwrap();
        let content = "![alt [x](missing.md)]()\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert!(
            result.is_empty(),
            "An image with no destination is still an image. Got: {result:?}"
        );
    }

    /// An image's description can hold another image before the link. The
    /// inner image ends before the link starts, so the image that contains
    /// the link is the outer one, and the link is alt text all the same.
    #[test]
    fn test_a_link_after_an_inner_image_is_still_inside_the_outer_image() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.png"), "x").unwrap();
        let content = "![outer ![inner](exists.png) [link](missing.md)](exists.png)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert!(
            result.is_empty(),
            "The link sits inside the outer image's description. Got: {result:?}"
        );
    }

    /// The control for the case above. Without the outer image, the link
    /// follows an image rather than sitting inside one.
    #[test]
    fn test_a_link_after_an_image_is_a_link() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.png"), "x").unwrap();
        let content = "![inner](exists.png) [link](missing.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'missing.md' does not exist");
        // `missing.md` opens at the twenty ninth character, just past `](`.
        assert_eq!(result[0].column, 29);
    }

    /// A reference image whose definition exists is an image like any other.
    #[test]
    fn test_a_link_inside_a_defined_reference_image_is_not_a_link() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("exists.png"), "x").unwrap();
        let content = "![alt [x](missing.md)][def]\n\n[def]: exists.png\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert!(
            result.is_empty(),
            "The description of a resolved reference image carries no link. Got: {result:?}"
        );
    }

    /// A destination may start on the line after the `](` that opens it. The
    /// report names the line the destination is written on.
    #[test]
    fn test_a_destination_on_the_next_line_is_reported_there() {
        let temp_dir = tempdir().unwrap();
        let content = "[a](\n  ./gone.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link './gone.md' does not exist");
        assert_eq!(result[0].line, 2, "The destination sits on the second line");
        assert_eq!(result[0].end_line, 2);
        // Line 2 is `  ./gone.md)`, so the destination opens at the third character.
        assert_eq!(result[0].column, 3);
        assert_eq!(result[0].end_column, 12);
    }
}

/// A link target has to be spelled the way the filesystem stores it.
///
/// macOS and Windows resolve a differently cased spelling to the same file, so
/// a link that 404s once the project is served, or once it is checked out on
/// Linux, passes on the machine it was written on. On Linux the metadata probe
/// alone reports every one of these rows, so the walk is only observable on a
/// case-insensitive volume.
#[cfg(test)]
mod exact_case_tests {
    use super::self_referential_links_tests::check_as_file;
    use super::*;
    use tempfile::tempdir;

    /// Whether the volume holding `dir` resolves a differently cased spelling
    /// to the same entry. Only such a volume can hide a case mismatch, so the
    /// rows that turn on one skip elsewhere, where the filesystem cannot
    /// produce the difference they assert.
    fn volume_folds_case(dir: &Path) -> bool {
        let probe = dir.join("case-fold-probe.tmp");
        std::fs::write(&probe, "").unwrap();
        let folded = dir.join("CASE-FOLD-PROBE.TMP").exists();
        std::fs::remove_file(&probe).unwrap();
        folded
    }

    /// `Foo.md` and `Docs/Guide.md` on disk, linked in every spelling from the
    /// report: the four case mismatches, the three exact spellings and a target
    /// that is not there at all.
    fn write_case_fixture(dir: &Path) {
        std::fs::write(dir.join("Foo.md"), "# Foo\n").unwrap();
        std::fs::create_dir_all(dir.join("Docs")).unwrap();
        std::fs::write(dir.join("Docs").join("Guide.md"), "# Guide\n").unwrap();
    }

    /// The control for every row below: on a volume that folds case the
    /// filesystem answers for a spelling it does not store, which is the whole
    /// reason the spelling has to be confirmed against the listing. On a volume
    /// that does not fold, the rows hold for the plainer reason that the path
    /// is simply not there.
    #[test]
    fn test_the_filesystem_answers_for_a_spelling_it_does_not_store() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        write_case_fixture(anchor);
        reset_file_existence_cache();

        assert_eq!(anchor.join("foo.md").exists(), volume_folds_case(anchor));
        assert!(!exists_exact_case(anchor, &anchor.join("foo.md")));
    }

    #[test]
    fn test_only_the_stored_spelling_of_a_target_exists() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        write_case_fixture(anchor);
        reset_file_existence_cache();

        for target in ["Foo.md", "Docs/Guide.md", "Docs"] {
            assert!(
                exists_exact_case(anchor, &anchor.join(target)),
                "{target} is on disk under this spelling"
            );
        }
        for target in ["foo.md", "docs/Guide.md", "Docs/guide.md", "docs", "Bar.md"] {
            assert!(
                !exists_exact_case(anchor, &anchor.join(target)),
                "{target} is not on disk under this spelling"
            );
        }
    }

    /// A target without an extension is looked for under each markdown
    /// extension, and every candidate answers for its own spelling.
    #[test]
    fn test_the_extension_fallback_keeps_the_case_of_the_target() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        write_case_fixture(anchor);
        reset_file_existence_cache();

        assert!(file_exists_or_markdown_extension(anchor, &anchor.join("Foo")));
        assert!(!file_exists_or_markdown_extension(anchor, &anchor.join("foo")));
    }

    /// A link out of a subdirectory names entries of the directory it climbs
    /// to, and those are checked like any other.
    #[test]
    fn test_a_target_reached_through_a_parent_step_is_checked() {
        let temp_dir = tempdir().unwrap();
        write_case_fixture(temp_dir.path());
        let anchor = temp_dir.path().join("Docs");
        reset_file_existence_cache();

        assert!(exists_exact_case(&anchor, &anchor.join("..").join("Foo.md")));
        assert!(!exists_exact_case(&anchor, &anchor.join("..").join("foo.md")));
    }

    /// The path to the project is not the link author's, so the anchor and
    /// everything above it are taken as given whatever their case.
    #[test]
    fn test_a_component_above_the_anchor_is_accepted() {
        let temp_dir = tempdir().unwrap();
        write_case_fixture(temp_dir.path());
        let anchor = temp_dir.path().join("docs");
        reset_file_existence_cache();

        assert!(has_exact_case_components(&anchor, &anchor.join("Guide.md")));
    }

    /// A symlinked directory is named by the link, and the name the symlink
    /// points at is the filesystem's business. Resolving the link to its
    /// target's path would compare that other name and report a link that works.
    #[cfg(unix)]
    #[test]
    fn test_a_link_through_a_symlinked_directory_exists() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::create_dir_all(anchor.join("shared").join("Docs")).unwrap();
        std::fs::write(anchor.join("shared").join("Docs").join("Guide.md"), "# Guide\n").unwrap();
        std::os::unix::fs::symlink("shared/Docs", anchor.join("docs")).unwrap();
        reset_file_existence_cache();

        assert!(exists_exact_case(anchor, &anchor.join("docs").join("Guide.md")));
    }

    /// macOS stores a name outside ASCII in whichever normalization it is
    /// created with and answers for either, so the two forms spell one name.
    #[cfg(target_os = "macos")]
    #[test]
    fn test_a_decomposed_name_matches_a_composed_link() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::write(anchor.join("cafe\u{301}.md"), "# Cafe\n").unwrap();
        reset_file_existence_cache();

        assert!(exists_exact_case(anchor, &anchor.join("caf\u{e9}.md")));
        assert!(!exists_exact_case(anchor, &anchor.join("CAF\u{c9}.md")));
    }

    #[test]
    fn test_a_link_reports_every_spelling_the_filesystem_does_not_store() {
        let temp_dir = tempdir().unwrap();
        write_case_fixture(temp_dir.path());
        let content = "\
[a](foo.md)\n\
[b](docs/Guide.md)\n\
[c](foo)\n\
[d](docs)\n\
[e](Foo.md)\n\
[f](Docs/Guide.md)\n\
[g](Docs)\n\
[h](Bar.md)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        let messages: Vec<&str> = result.iter().map(|warning| warning.message.as_str()).collect();
        assert_eq!(
            messages,
            vec![
                "Relative link 'foo.md' does not exist",
                "Relative link 'docs/Guide.md' does not exist",
                "Relative link 'foo' does not exist",
                "Relative link 'docs' does not exist",
                "Relative link 'Bar.md' does not exist",
            ],
            "Got: {result:?}"
        );
    }

    /// The reporter's own document: the file on disk is `changelog.md` and the
    /// link names `CHANGELOG.md`.
    #[test]
    fn test_the_reporters_link_is_reported() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("changelog.md"), "").unwrap();
        let content = "# Test\n\nSee the [changelog](CHANGELOG.md).\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'CHANGELOG.md' does not exist");
        assert_eq!(result[0].line, 3);
        assert_eq!(result[0].column, 21);
    }

    /// The markdown source behind an `.html` link is looked for under the stem
    /// the link spells, so a mis-cased stem finds nothing.
    #[test]
    fn test_the_html_fallback_keeps_the_case_of_the_stem() {
        let temp_dir = tempdir().unwrap();
        std::fs::write(temp_dir.path().join("Guide.md"), "# Guide\n").unwrap();
        let content = "[a](Guide.html)\n[b](guide.html)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, MD057Config::default());

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'guide.html' does not exist");
        assert_eq!(result[0].line, 2);
    }

    /// A search path answers for the spelling it stores, like the document's
    /// own directory does.
    #[test]
    fn test_a_search_path_answers_for_the_exact_spelling() {
        let temp_dir = tempdir().unwrap();
        let assets = temp_dir.path().join("assets");
        std::fs::create_dir_all(&assets).unwrap();
        std::fs::write(assets.join("Logo.png"), "").unwrap();
        let config = MD057Config {
            search_paths: vec![assets.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let content = "[a](Logo.png)\n[b](logo.png)\n";

        let result = check_as_file(temp_dir.path(), "test.md", content, config);

        assert_eq!(result.len(), 1, "Expected one warning. Got: {result:?}");
        assert_eq!(result[0].message, "Relative link 'logo.png' does not exist");
        assert_eq!(result[0].line, 2);
    }

    /// An absolute link resolves under a root, and the components below that
    /// root are the link author's spelling just as a relative link's are.
    #[test]
    fn test_an_absolute_link_under_a_root_keeps_its_case() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path();
        write_case_fixture(root);
        let content = "[a](/Docs/Guide.md)\n[b](/docs/Guide.md)\n[c](/Docs)\n[d](/docs)\n";

        let config = MD057Config {
            absolute_links: AbsoluteLinksOption::RelativeToRoots,
            roots: vec![],
            ..Default::default()
        };
        let rule = MD057ExistingRelativeLinks::from_config_struct(config).with_path(root);
        let ctx = crate::lint_context::LintContext::new(content, crate::config::MarkdownFlavor::Standard, None);
        let result = rule.check(&ctx).unwrap();

        let messages: Vec<&str> = result.iter().map(|warning| warning.message.as_str()).collect();
        assert_eq!(
            messages,
            vec![
                "Absolute link '/docs/Guide.md' was not found under the project root",
                "Absolute link '/docs' was not found under the project root",
            ],
            "Got: {result:?}"
        );
    }

    /// A `..` is resolved lexically, so `docs/../Foo.md` names `Foo.md` beside
    /// the document however `docs` is stored. Every renderer of the document
    /// resolves the link that way, and the reader gets whatever is at that
    /// path, so the rule reports what the reader sees.
    #[cfg(unix)]
    #[test]
    fn test_a_parent_step_is_resolved_lexically_through_a_symlink() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::create_dir_all(anchor.join("shared").join("Docs")).unwrap();
        std::fs::write(anchor.join("shared").join("Foo.md"), "# Foo\n").unwrap();
        std::fs::write(anchor.join("shared").join("Docs").join("Bar.md"), "# Bar\n").unwrap();
        std::os::unix::fs::symlink("shared/Docs", anchor.join("docs")).unwrap();
        let content = "[a](docs/../Foo.md)\n[b](docs/Bar.md)\n[c](docs/bar.md)\n";

        let result = check_as_file(anchor, "test.md", content, MD057Config::default());

        let messages: Vec<&str> = result.iter().map(|warning| warning.message.as_str()).collect();
        assert_eq!(
            messages,
            vec![
                "Relative link 'docs/../Foo.md' does not exist",
                "Relative link 'docs/bar.md' does not exist",
            ],
            "Got: {result:?}"
        );
    }

    /// Restores the mode a directory had when the guard was taken, so a test
    /// that takes read permission away gives it back even when an assertion
    /// between the two panics and the temporary directory still has to be
    /// removable.
    #[cfg(unix)]
    struct RestoreMode {
        directory: PathBuf,
        mode: u32,
    }

    #[cfg(unix)]
    impl RestoreMode {
        fn take(directory: &Path) -> Self {
            use std::os::unix::fs::PermissionsExt;
            Self {
                directory: directory.to_path_buf(),
                mode: std::fs::metadata(directory).unwrap().permissions().mode(),
            }
        }
    }

    #[cfg(unix)]
    impl Drop for RestoreMode {
        fn drop(&mut self) {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(&self.directory, std::fs::Permissions::from_mode(self.mode));
        }
    }

    /// A directory the process may enter but not read says nothing about how
    /// its entries are spelled, so every name under it is accepted. That is the
    /// branch making the walk unable to report a link that is really there.
    #[cfg(unix)]
    #[test]
    fn test_a_directory_that_cannot_be_listed_is_accepted() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        let locked = anchor.join("locked");
        std::fs::create_dir_all(&locked).unwrap();
        std::fs::write(locked.join("Target.md"), "# Target\n").unwrap();

        let _restore = RestoreMode::take(&locked);
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o111)).unwrap();
        if std::fs::read_dir(&locked).is_ok() {
            // A process with the privilege to read any directory cannot reach
            // the branch under test.
            return;
        }
        assert!(locked.join("Target.md").exists(), "the directory can still be entered");
        let content = "[a](locked/Target.md)\n";

        let result = check_as_file(anchor, "test.md", content, MD057Config::default());

        assert!(result.is_empty(), "Expected no warning. Got: {result:?}");
    }

    /// The other direction of the same name: a composed name on disk answers
    /// for a decomposed link, because the two spell one name. Case is a
    /// difference in the name itself and is still reported.
    #[cfg(target_os = "macos")]
    #[test]
    fn test_a_composed_name_matches_a_decomposed_link() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::write(anchor.join("caf\u{e9}.md"), "# Cafe\n").unwrap();
        reset_file_existence_cache();

        assert!(exists_exact_case(anchor, &anchor.join("cafe\u{301}.md")));
        assert!(!exists_exact_case(anchor, &anchor.join("CAFE\u{301}.md")));

        let content = "[a](cafe\u{301}.md)\n[b](CAFE\u{301}.md)\n";

        let result = check_as_file(anchor, "test.md", content, MD057Config::default());

        let messages: Vec<&str> = result.iter().map(|warning| warning.message.as_str()).collect();
        assert_eq!(
            messages,
            vec!["Relative link 'CAFE\u{301}.md' does not exist"],
            "Got: {result:?}"
        );
    }

    /// The Kelvin sign composes to the ASCII letter K, so a name written with
    /// it and the same name written with the letter spell one name, and the
    /// volume answers for both. A link in the ASCII spelling is accepted; a
    /// case difference is still reported.
    #[cfg(target_os = "macos")]
    #[test]
    fn test_a_name_composing_to_ascii_matches_an_ascii_link() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::write(anchor.join("\u{212a}elvin.md"), "# Kelvin\n").unwrap();
        reset_file_existence_cache();

        assert!(exists_exact_case(anchor, &anchor.join("Kelvin.md")));
        assert!(!exists_exact_case(anchor, &anchor.join("kelvin.md")));

        let content = "[a](Kelvin.md)\n[b](kelvin.md)\n";

        let result = check_as_file(anchor, "test.md", content, MD057Config::default());

        let messages: Vec<&str> = result.iter().map(|warning| warning.message.as_str()).collect();
        assert_eq!(
            messages,
            vec!["Relative link 'kelvin.md' does not exist"],
            "Got: {result:?}"
        );
    }

    /// The other direction: an ASCII name on disk answers for a link whose
    /// spelling composes to it, because the two spell one name. Case is a
    /// difference in the name itself and is still reported.
    #[cfg(target_os = "macos")]
    #[test]
    fn test_an_ascii_name_matches_a_link_composing_to_it() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::write(anchor.join("Kelvin.md"), "# Kelvin\n").unwrap();
        reset_file_existence_cache();

        assert!(exists_exact_case(anchor, &anchor.join("\u{212a}elvin.md")));
        assert!(!exists_exact_case(anchor, &anchor.join("\u{212a}ELVIN.md")));

        let content = "[a](\u{212a}elvin.md)\n[b](\u{212a}ELVIN.md)\n";

        let result = check_as_file(anchor, "test.md", content, MD057Config::default());

        let messages: Vec<&str> = result.iter().map(|warning| warning.message.as_str()).collect();
        assert_eq!(
            messages,
            vec!["Relative link '\u{212a}ELVIN.md' does not exist"],
            "Got: {result:?}"
        );
    }

    /// Puts a listing in the cache for `directory` naming only `Other.md`,
    /// recorded at `modified`. Any other name is absent from it, so a link to
    /// a file that is really on disk is reported for as long as this listing
    /// is the one a lookup accepts.
    ///
    /// The key is the directory's canonical path, which is what a check
    /// resolves a document's directory to and so what a lookup asks for.
    fn seed_listing(directory: &Path, modified: SystemTime) {
        let listing = DirectoryListing {
            modified: Some(modified),
            listed: true,
            names: HashSet::from([OsString::from("Other.md")]),
            composed: HashSet::new(),
        };
        let key = std::fs::canonicalize(directory).unwrap();
        DIRECTORY_LISTING_CACHE.lock().unwrap().insert(key, Arc::new(listing));
    }

    /// A listing answers for as long as the directory's modification time
    /// stands, so checking many documents in one directory reads it once; and
    /// it is read again as soon as that time moves, so a file appearing
    /// between two checks is seen.
    #[test]
    fn test_a_listing_answers_until_the_directory_changes() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::write(anchor.join("README.md"), "# Readme\n").unwrap();
        // The document is written before the time is taken, so the check's own
        // write of it does not move the directory on.
        std::fs::write(anchor.join("test.md"), "").unwrap();
        let read_at = std::fs::metadata(anchor).unwrap().modified().unwrap();
        seed_listing(anchor, read_at);

        let reported = check_as_file(anchor, "test.md", "[a](README.md)\n", MD057Config::default());

        let messages: Vec<&str> = reported.iter().map(|warning| warning.message.as_str()).collect();
        assert_eq!(
            messages,
            vec!["Relative link 'README.md' does not exist"],
            "the seeded listing answers while the directory's time stands. Got: {reported:?}"
        );

        std::fs::write(anchor.join("Another.md"), "# Another\n").unwrap();
        assert_ne!(
            std::fs::metadata(anchor).unwrap().modified().unwrap(),
            read_at,
            "creating an entry moves the directory's modification time"
        );

        let accepted = check_as_file(anchor, "test.md", "[a](README.md)\n", MD057Config::default());

        assert!(
            accepted.is_empty(),
            "the listing is read again once the directory has moved on. Got: {accepted:?}"
        );
    }

    /// A listing recorded at a moment that is not the directory's is
    /// discarded, so a directory that changed while nothing was checking it is
    /// read again rather than answered from.
    #[test]
    fn test_a_listing_from_another_moment_is_discarded() {
        let temp_dir = tempdir().unwrap();
        let anchor = temp_dir.path();
        std::fs::write(anchor.join("README.md"), "# Readme\n").unwrap();
        seed_listing(anchor, SystemTime::UNIX_EPOCH);

        let result = check_as_file(anchor, "test.md", "[a](README.md)\n", MD057Config::default());

        assert!(result.is_empty(), "Expected no warning. Got: {result:?}");
    }
}