miwa-cli 0.7.0

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

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ops::Range;

use pulldown_cmark::{Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd};

use crate::frontmatter::{FrontMatter, FrontMatterError};
use crate::markdown::parent_dir;
use crate::model::ReasonCode;

/// One list entry of an index: a list item that starts with a link.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexEntry {
    /// Source text of the link text (between `[` and the matching `]`).
    pub link_text: String,
    /// Link destination as interpreted by pulldown-cmark (without `<...>` and
    /// the title attribute). Used for comparison and resolution only; never
    /// written back.
    pub dest: String,
    /// Summary with the separator and surrounding whitespace removed.
    pub description: String,
    /// One of `-` `–` `—` `:`, if present.
    pub separator: Option<char>,
    /// From just after `[` to just before the matching `]`.
    pub text_span: Range<usize>,
    /// From the end of the link to the end of the inline content (separator +
    /// summary, may span lines).
    pub tail_span: Range<usize>,
    /// From the start of the line containing `text_span.start` through the line
    /// terminator (`\n` or `\r\n`) after `tail_span.end`.
    pub line_span: Range<usize>,
}

/// How an entry's link destination resolves.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
    /// External URL / URI scheme: ignored.
    External,
    /// Cannot be resolved (empty, absolute, escapes repo, outside root, self or
    /// ancestor directory); the reason is used as the finding detail.
    Unresolvable(&'static str),
    /// Repo-relative file path (may not exist).
    File(String),
    /// Repo-relative directory whose `index.md` is the target.
    Directory(String),
}

/// A typed document (has frontmatter `type`) under an index root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Document {
    pub path: String,
    pub title: String,
    pub description: Option<String>,
}

/// An `index.md` with the title and summary it contributes as a directory
/// (FR-071): frontmatter `title` (else the directory name) and `description`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexMeta {
    pub path: String,
    pub title: String,
    pub description: Option<String>,
    /// The frontmatter could not be parsed; the title and summary are then
    /// unknown and neither checked nor rewritten (reported as `invalid`).
    pub invalid: bool,
}

/// An index structure problem. `target` follows the canonical form: for
/// `BrokenEntry` and for `TitleMismatch` / `DescriptionMismatch` of a
/// directory entry it is `"<index path> -> <dest>"`, otherwise (including
/// `MissingDirectoryDescription`) the path.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct IndexIssue {
    pub reason: ReasonCode,
    pub target: String,
    pub detail: String,
}

/// File body and parsed frontmatter, read once by `build_graph`.
#[derive(Debug)]
pub struct ParsedText {
    pub text: String,
    pub front_matter: Result<Option<FrontMatter>, FrontMatterError>,
}

const BOM: char = '\u{feff}';

fn unescape_brackets(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\\' && matches!(chars.peek(), Some('\\' | '[' | ']')) {
            out.push(chars.next().unwrap_or(c));
        } else {
            out.push(c);
        }
    }
    out
}

fn escape_brackets(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(c, '\\' | '[' | ']') {
            out.push('\\');
        }
        out.push(c);
    }
    out
}

fn percent_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            ' ' | '(' | ')' | '<' | '>' | '%' | '#' | '\\' => {
                out.push_str(&format!("%{:02X}", c as u32));
            }
            _ => out.push(c),
        }
    }
    out
}

fn is_inline_event(ev: &Event) -> bool {
    match ev {
        Event::Text(_)
        | Event::Code(_)
        | Event::InlineMath(_)
        | Event::DisplayMath(_)
        | Event::InlineHtml(_)
        | Event::FootnoteReference(_)
        | Event::SoftBreak
        | Event::HardBreak => true,
        Event::Start(t) => matches!(
            t,
            Tag::Emphasis
                | Tag::Strong
                | Tag::Strikethrough
                | Tag::Superscript
                | Tag::Subscript
                | Tag::Link { .. }
                | Tag::Image { .. }
        ),
        Event::End(t) => matches!(
            t,
            TagEnd::Emphasis
                | TagEnd::Strong
                | TagEnd::Strikethrough
                | TagEnd::Superscript
                | TagEnd::Subscript
                | TagEnd::Link
                | TagEnd::Image
        ),
        _ => false,
    }
}

/// Extract index entries from `text`.
///
/// Parses with `Parser::new_ext(text, ENABLE_TASKLISTS).into_offset_iter()`. A
/// list item (any nesting, ordered or unordered) is an entry iff its first
/// inline event (skipping `Start(Paragraph)`) is `Start(Link)`. Task-list
/// markers, bold, plain text etc. are non-entries. A leading BOM is ignored for
/// parsing, and spans are offsets into `text` including the BOM. `text_span` covers all ranged events inside the
/// link (empty link: `start+1..start+1`); `tail_span` covers inline events after
/// `End(Link)` up to `End(Item)` / `End(Paragraph)` / `Start(List)` (excluding
/// soft/hard breaks). `description` is `tail_span` trimmed, minus one leading
/// separator char, trim_start; `\[` `\]` are unescaped for comparison.
pub fn parse_entries(text: &str) -> Vec<IndexEntry> {
    let (body, off) = match text.strip_prefix(BOM) {
        Some(b) => (b, BOM.len_utf8()),
        None => (text, 0),
    };
    let events: Vec<(Event, Range<usize>)> = Parser::new_ext(body, Options::ENABLE_TASKLISTS)
        .into_offset_iter()
        .collect();
    let mut entries = Vec::new();
    for i in 0..events.len() {
        if !matches!(events[i].0, Event::Start(Tag::Item)) {
            continue;
        }
        let mut k = i + 1;
        if matches!(events.get(k), Some((Event::Start(Tag::Paragraph), _))) {
            k += 1;
        }
        let (dest_url, link_type, link_range) = match events.get(k) {
            Some((
                Event::Start(Tag::Link {
                    dest_url,
                    link_type,
                    ..
                }),
                r,
            )) => (dest_url.to_string(), *link_type, r.clone()),
            _ => continue,
        };
        let mut j = k + 1;
        let mut t_max = link_range.start + 1;
        while j < events.len() && !matches!(events[j].0, Event::End(TagEnd::Link)) {
            t_max = t_max.max(events[j].1.end);
            j += 1;
        }
        // pulldown-cmark's Text ranges omit the backslash of an escape, so the
        // start is pinned to just after `[`, and the end is the first `]` at or
        // after the end of the last inner event.
        let close = body.as_bytes()[t_max.min(body.len())..]
            .iter()
            .position(|&b| b == b']')
            .map_or(t_max, |p| t_max + p);
        let text_span = link_range.start + 1 + off..close + off;
        // The End(Link) range of a collapsed reference `[T][]` stops before `[]`.
        let mut link_end = link_range.end;
        if link_type == LinkType::Collapsed && body[link_end..].starts_with("[]") {
            link_end += 2;
        }
        let mut m = j + 1;
        let mut a_max = None::<usize>;
        while m < events.len() && is_inline_event(&events[m].0) {
            if !matches!(events[m].0, Event::SoftBreak | Event::HardBreak) {
                a_max = Some(a_max.map_or(events[m].1.end, |x| x.max(events[m].1.end)));
            }
            m += 1;
        }
        let tail_end = a_max.map_or(link_end, |x| x.max(link_end));
        let tail_span = link_end + off..tail_end + off;
        let raw = &text[tail_span.clone()];
        let trimmed = raw.trim();
        let (separator, description) = match trimmed.chars().next() {
            Some(c) if matches!(c, '-' | '–' | '—' | ':') => {
                (Some(c), trimmed[c.len_utf8()..].trim_start().to_string())
            }
            _ => (None, trimmed.to_string()),
        };
        let line_start = text[..text_span.start]
            .rfind('\n')
            .map(|p| p + 1)
            .unwrap_or(0)
            .max(off);
        let line_end = match text[tail_span.end..].find('\n') {
            Some(p) => tail_span.end + p + 1,
            None => text.len(),
        };
        entries.push(IndexEntry {
            link_text: text[text_span.clone()].to_string(),
            dest: dest_url,
            description,
            separator,
            text_span,
            tail_span,
            line_span: line_start..line_end,
        });
    }
    entries
}

/// Resolve an entry destination relative to `index_path` within `root`.
///
/// Order: empty / `#...` -> `Unresolvable("empty target")`; `://` or URI scheme
/// -> `External`; leading `/` -> `Unresolvable("absolute path")`; strip
/// fragment, percent-decode, `markdown::normalize_relative` (escape ->
/// `Unresolvable("escapes repository")`); outside `root` ->
/// `Unresolvable("outside index root")`; trailing `/` or file name `index.md`
/// -> directory candidate (`index.md` -> its parent), and a candidate that is
/// the index's own directory or an ancestor -> `Unresolvable("self or ancestor
/// directory")`, else `Directory`; otherwise `File` if present in `file_set`,
/// or `Directory` if some file lies under `path/` (`repo.dirs`), else `File`
/// (missing).
pub fn resolve(index_path: &str, root: &str, dest: &str, repo: &RepoFiles) -> Resolution {
    if dest.is_empty() || dest.starts_with('#') {
        return Resolution::Unresolvable("empty target");
    }
    if dest.contains("://") || crate::markdown::has_uri_scheme(dest) {
        return Resolution::External;
    }
    if dest.starts_with('/') {
        return Resolution::Unresolvable("absolute path");
    }
    let no_frag = dest.split('#').next().unwrap_or("");
    let decoded = crate::markdown::percent_decode(no_frag);
    let path = match crate::markdown::normalize_relative(index_path, &decoded) {
        Some(p) => p,
        None => return Resolution::Unresolvable("escapes repository"),
    };
    if !crate::config::is_under(&path, root) {
        return Resolution::Unresolvable("outside index root");
    }
    let own_dir = parent_dir(index_path);
    let dir_candidate = |dir: String| {
        if own_dir == dir || own_dir.starts_with(&format!("{dir}/")) {
            Resolution::Unresolvable("self or ancestor directory")
        } else {
            Resolution::Directory(dir)
        }
    };
    let file_name = path.rsplit('/').next().unwrap_or("");
    if decoded.ends_with('/') {
        return dir_candidate(path);
    }
    if file_name == "index.md" {
        return dir_candidate(parent_dir(&path).to_string());
    }
    if repo.files.contains(path.as_str()) {
        return Resolution::File(path);
    }
    if repo.dirs.contains(path.as_str()) {
        return dir_candidate(path);
    }
    Resolution::File(path)
}

/// Repo files plus every ancestor directory of them, for O(1) lookups.
pub struct RepoFiles<'a> {
    pub files: HashSet<&'a str>,
    pub dirs: HashSet<String>,
}

impl<'a> RepoFiles<'a> {
    pub fn new(paths: impl IntoIterator<Item = &'a str>) -> Self {
        let files: HashSet<&str> = paths.into_iter().collect();
        let mut dirs = HashSet::new();
        for f in &files {
            let mut cur = parent_dir(f);
            while !cur.is_empty() && dirs.insert(cur.to_string()) {
                cur = parent_dir(cur);
            }
        }
        RepoFiles { files, dirs }
    }
}

/// Ownership and parent/child relations among the indexes of one root.
pub struct IndexTree {
    root: String,
    indexes: BTreeSet<String>,
}

impl IndexTree {
    pub fn new(root: &str, indexes: impl IntoIterator<Item = String>) -> Self {
        IndexTree {
            root: root.to_string(),
            indexes: indexes.into_iter().collect(),
        }
    }

    fn root_index(&self) -> String {
        format!("{}/index.md", self.root)
    }

    /// Nearest index at or above `dir`, never above the root (the root index
    /// even when it does not exist yet).
    fn nearest(&self, dir: &str) -> String {
        let mut cur = dir;
        loop {
            let cand = format!("{cur}/index.md");
            if self.indexes.contains(&cand) {
                return cand;
            }
            if cur == self.root || cur.is_empty() || !crate::config::is_under(cur, &self.root) {
                return self.root_index();
            }
            cur = parent_dir(cur);
        }
    }

    /// The index responsible for listing the document at `doc_path`.
    pub fn owner_of(&self, doc_path: &str) -> String {
        self.nearest(parent_dir(doc_path))
    }

    /// The index that should link to `index_path`; `None` for the root index.
    pub fn parent_of(&self, index_path: &str) -> Option<String> {
        let dir = parent_dir(index_path);
        if dir == self.root {
            None
        } else {
            Some(self.nearest(parent_dir(dir)))
        }
    }

    /// Indexes whose parent is `index_path`.
    pub fn children_of(&self, index_path: &str) -> Vec<String> {
        self.indexes
            .iter()
            .filter(|c| self.parent_of(c).as_deref() == Some(index_path))
            .cloned()
            .collect()
    }
}

/// Result of one index processed by [`run`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndexStatus {
    Created,
    Updated,
    Unchanged,
}

impl IndexStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            IndexStatus::Created => "created",
            IndexStatus::Updated => "updated",
            IndexStatus::Unchanged => "unchanged",
        }
    }
}

/// The `.md` files under an index root, classified.
#[derive(Debug, Default)]
pub struct RootFiles {
    pub documents: Vec<Document>,
    pub untyped: Vec<String>,
    pub indexes: Vec<IndexMeta>,
}

/// Classify the `.md` files under `root` into documents, untyped files and
/// indexes.
///
/// `index.md` -> indexes; `log.md` -> ignored; frontmatter error -> ignored
/// (already a ParseError); no frontmatter or no `type` -> untyped; otherwise a
/// `Document`.
pub fn collect_documents(root: &str, texts: &BTreeMap<String, ParsedText>) -> RootFiles {
    let mut out = RootFiles::default();
    for (path, parsed) in texts {
        if !path.ends_with(".md") || !crate::config::is_under(path, root) {
            continue;
        }
        match path.rsplit('/').next() {
            Some("index.md") => {
                let invalid = parsed.front_matter.is_err();
                let (fm_title, description) = match &parsed.front_matter {
                    Ok(Some(fm)) => (front_title(fm), normalize_description(fm)),
                    _ => (None, None),
                };
                let title = fm_title.unwrap_or_else(|| {
                    parent_dir(path)
                        .rsplit('/')
                        .next()
                        .unwrap_or_default()
                        .to_string()
                });
                out.indexes.push(IndexMeta {
                    path: path.clone(),
                    title,
                    description,
                    invalid,
                });
                continue;
            }
            Some("log.md") => continue,
            _ => {}
        }
        match &parsed.front_matter {
            Err(_) => {}
            Ok(Some(fm)) if fm.kind.is_some() => {
                let description = normalize_description(fm);
                out.documents.push(Document {
                    path: path.clone(),
                    title: document_title(path, fm),
                    description,
                });
            }
            Ok(_) => out.untyped.push(path.clone()),
        }
    }
    out
}

fn child_index_of(dir: &str) -> String {
    format!("{dir}/index.md")
}

/// Frontmatter `title`: trimmed, non-empty, single line.
fn front_title(fm: &FrontMatter) -> Option<String> {
    fm.title
        .as_deref()
        .map(str::trim)
        .filter(|t| !t.is_empty() && !t.contains('\n') && !t.contains('\r'))
        .map(str::to_string)
}

/// Frontmatter `description`: trimmed, non-empty, single line (no LF or CR).
pub fn normalize_description(fm: &FrontMatter) -> Option<String> {
    fm.description
        .as_deref()
        .map(str::trim)
        .filter(|d| !d.is_empty() && !d.contains('\n') && !d.contains('\r'))
        .map(str::to_string)
}

/// Title of a document: frontmatter `title` (trimmed, non-empty, single line)
/// -> first H1 of the body (source text of the inner events) -> file name
/// without `.md`.
pub fn document_title(path: &str, fm: &FrontMatter) -> String {
    if let Some(t) = front_title(fm) {
        return t;
    }
    let body = fm.body.as_str();
    let mut in_h1 = false;
    let (mut min, mut max) = (usize::MAX, 0usize);
    for (ev, range) in Parser::new(body).into_offset_iter() {
        match ev {
            Event::Start(Tag::Heading {
                level: HeadingLevel::H1,
                ..
            }) => {
                in_h1 = true;
                min = usize::MAX;
                max = 0;
            }
            Event::End(TagEnd::Heading(_)) if in_h1 => {
                // Only the first level-1 heading counts; an empty one falls
                // back to the file name.
                if min != usize::MAX {
                    return body[min..max].to_string();
                }
                break;
            }
            _ if in_h1 => {
                min = min.min(range.start);
                max = max.max(range.end);
            }
            _ => {}
        }
    }
    let name = path.rsplit('/').next().unwrap_or(path);
    name.strip_suffix(".md").unwrap_or(name).to_string()
}

fn is_excluded(path: &str, config: &crate::config::Config) -> bool {
    crate::source::is_under_dir_named(path, &config.exclude)
        || crate::source::is_under_dir_named(path, &crate::source::DEFAULT_EXCLUDED_DIRS)
}

/// `<index path> -> <dest>`, the finding target of an entry.
fn entry_target(index: &str, dest: &str) -> String {
    format!("{index} -> {dest}")
}

fn issue(reason: ReasonCode, target: impl Into<String>, detail: impl Into<String>) -> IndexIssue {
    IndexIssue {
        reason,
        target: target.into(),
        detail: detail.into(),
    }
}

/// Run all index checks for every root in `config.index`.
///
/// Per root: `UntypedFile` for untyped files and `MissingDescription` for
/// documents without a description; `MissingIndex` (target = root) if there is
/// no `root/index.md` and at least one document (then the index-side checks are
/// skipped); each document / non-root index is owned by the nearest ancestor
/// index; each entry is resolved: `External` ignored, `Unresolvable` ->
/// `BrokenEntry`, `File` not a document -> `BrokenEntry`, title mismatch ->
/// `TitleMismatch`, description mismatch -> `DescriptionMismatch`; `Directory`
/// without `index.md` -> `BrokenEntry`, otherwise compared with the child
/// index's title / description (`TitleMismatch` / `DescriptionMismatch`; no
/// description -> `MissingDirectoryDescription` targeting the child index); unlisted documents -> `NotListed`; child
/// indexes not reached from the parent -> `UnlinkedIndex`. Duplicates are
/// removed by the set.
pub fn collect_issues(
    config: &crate::config::Config,
    files: &[String],
    texts: &BTreeMap<String, ParsedText>,
) -> BTreeSet<IndexIssue> {
    let mut out = BTreeSet::new();
    let repo = RepoFiles::new(files.iter().map(String::as_str));
    for raw in &config.index {
        let root = crate::config::normalize_dir(raw);
        check_root(config, &root, &repo, texts, &mut out);
    }
    out
}

fn check_root(
    config: &crate::config::Config,
    root: &str,
    repo: &RepoFiles,
    texts: &BTreeMap<String, ParsedText>,
    out: &mut BTreeSet<IndexIssue>,
) {
    let RootFiles {
        documents,
        untyped,
        indexes,
    } = collect_documents(root, texts);
    for u in &untyped {
        out.insert(issue(
            ReasonCode::UntypedFile,
            u.clone(),
            "file has no `type` in its front matter",
        ));
    }
    for d in &documents {
        if d.description.is_none() {
            out.insert(issue(
                ReasonCode::MissingDescription,
                d.path.clone(),
                "document has no single-line `description`",
            ));
        }
    }
    let root_index = crate::config::join_under(root, "index.md");
    let index_set: HashSet<&str> = indexes.iter().map(|m| m.path.as_str()).collect();
    if !index_set.contains(root_index.as_str()) {
        if !documents.is_empty() {
            out.insert(issue(
                ReasonCode::MissingIndex,
                root.to_string(),
                format!("{root_index} does not exist"),
            ));
        }
        return;
    }
    let doc_map: HashMap<&str, &Document> =
        documents.iter().map(|d| (d.path.as_str(), d)).collect();
    let untyped_set: HashSet<&str> = untyped.iter().map(String::as_str).collect();
    let meta_map: HashMap<&str, &IndexMeta> =
        indexes.iter().map(|m| (m.path.as_str(), m)).collect();
    let tree = IndexTree::new(root, indexes.iter().map(|m| m.path.clone()));
    let mut listed: HashMap<&str, HashSet<String>> = HashMap::new();
    let mut linked: HashSet<String> = HashSet::new();
    for index in indexes.iter().map(|m| &m.path) {
        let text = &texts[index].text;
        for e in parse_entries(text) {
            match resolve(index, root, &e.dest, repo) {
                Resolution::External => {}
                Resolution::Unresolvable(why) => {
                    out.insert(issue(
                        ReasonCode::BrokenEntry,
                        entry_target(index, &e.dest),
                        why,
                    ));
                }
                Resolution::File(p) => match doc_map.get(p.as_str()) {
                    Some(doc) => {
                        listed.entry(index).or_default().insert(p.clone());
                        if unescape_brackets(&e.link_text) != doc.title {
                            out.insert(issue(
                                ReasonCode::TitleMismatch,
                                p.clone(),
                                format!(
                                    "link text differs from the document title `{}`",
                                    doc.title
                                ),
                            ));
                        }
                        if let Some(d) = &doc.description {
                            if unescape_brackets(&e.description) != *d {
                                out.insert(issue(
                                    ReasonCode::DescriptionMismatch,
                                    p.clone(),
                                    format!("summary differs from the document description `{d}`"),
                                ));
                            }
                        }
                    }
                    None => {
                        let why = if is_excluded(&p, config) {
                            "target is excluded from scan"
                        } else if !repo.files.contains(p.as_str()) {
                            "target does not exist"
                        } else if untyped_set.contains(p.as_str()) {
                            "target has no `type`"
                        } else {
                            "target is not a document"
                        };
                        out.insert(issue(
                            ReasonCode::BrokenEntry,
                            entry_target(index, &e.dest),
                            why,
                        ));
                    }
                },
                Resolution::Directory(d) => {
                    let child = child_index_of(&d);
                    if !index_set.contains(child.as_str()) {
                        out.insert(issue(
                            ReasonCode::BrokenEntry,
                            entry_target(index, &e.dest),
                            "directory has no index.md",
                        ));
                    } else {
                        if let Some(m) = meta_map.get(child.as_str()).filter(|m| !m.invalid) {
                            let target = entry_target(index, &e.dest);
                            if unescape_brackets(&e.link_text) != m.title {
                                out.insert(issue(
                                    ReasonCode::TitleMismatch,
                                    target.clone(),
                                    format!(
                                        "link text differs from the directory title `{}`",
                                        m.title
                                    ),
                                ));
                            }
                            match &m.description {
                                Some(d) => {
                                    if unescape_brackets(&e.description) != *d {
                                        out.insert(issue(
                                            ReasonCode::DescriptionMismatch,
                                            target,
                                            format!(
                                                "summary differs from the directory description `{d}`"
                                            ),
                                        ));
                                    }
                                }
                                None => {
                                    out.insert(issue(
                                        ReasonCode::MissingDirectoryDescription,
                                        child.clone(),
                                        "directory index has no single-line `description`",
                                    ));
                                }
                            }
                        }
                        if tree.parent_of(&child).as_deref() == Some(index.as_str()) {
                            linked.insert(child);
                        }
                    }
                }
            }
        }
    }
    for d in &documents {
        let owner = tree.owner_of(&d.path);
        let is_listed = listed
            .get(owner.as_str())
            .is_some_and(|s| s.contains(&d.path));
        if !is_listed {
            out.insert(issue(
                ReasonCode::NotListed,
                d.path.clone(),
                format!("not listed in {owner}"),
            ));
        }
    }
    for index in indexes.iter().map(|m| &m.path) {
        if *index != root_index && !linked.contains(index) {
            out.insert(issue(
                ReasonCode::UnlinkedIndex,
                index.clone(),
                "not linked from its parent index",
            ));
        }
    }
}

fn is_list_item_line(line: &str) -> bool {
    let l = line.trim_start();
    if l.starts_with("- ") || l.starts_with("* ") || l.starts_with("+ ") {
        return true;
    }
    let digits = l.chars().take_while(|c| c.is_ascii_digit()).count();
    digits > 0 && {
        let rest = &l[digits..];
        rest.starts_with(". ") || rest.starts_with(") ")
    }
}

/// Return the updated text of an index.
///
/// Only `text_span` and `tail_span` are rewritten; link destinations are never
/// touched. `documents` are all documents of the root; ownership is derived
/// from `tree`. For `File(p)` entries that are
/// documents: `text_span` becomes the escaped title (`[` `]` -> `\[` `\]`;
/// not for collapsed / shortcut references, whose link text doubles as the
/// reference label), `tail_span` becomes ` {sep} {desc}` (sep = existing or
/// `—`; empty if no description); directory entries (the link target is a
/// directory with a child `index.md` in `indexes`) are rewritten the same way
/// from the child's title / description. Entries whose `File(p)` does not exist
/// (`exists` false) and is not under a default-excluded directory have their
/// `line_span` removed. Then missing owned documents (path order) and unlinked
/// child indexes (path order, `- [<title>](<dir>/) — <summary>`, no separator
/// without a summary) are appended as list items, with percent-encoded
/// destinations, matching the text's line ending, and a blank line inserted
/// when the last non-empty line is not a list item.
#[allow(clippy::too_many_arguments)]
pub fn update_index(
    text: &str,
    index_path: &str,
    tree: &IndexTree,
    documents: &[Document],
    indexes: &[IndexMeta],
    repo: &RepoFiles,
    unlinked_child_indexes: &[String],
    excluded: &[String],
) -> String {
    let root = tree.root.as_str();
    let index_dir = parent_dir(index_path);
    let doc_map: HashMap<&str, &Document> =
        documents.iter().map(|d| (d.path.as_str(), d)).collect();
    let meta_map: HashMap<&str, &IndexMeta> =
        indexes.iter().map(|m| (m.path.as_str(), m)).collect();
    let mut edits: Vec<(Range<usize>, String)> = Vec::new();
    let mut listed: HashSet<String> = HashSet::new();
    for e in parse_entries(text) {
        let (doc_path, title, description): (Option<String>, &str, &Option<String>) =
            match resolve(index_path, root, &e.dest, repo) {
                Resolution::File(p) => match doc_map.get(p.as_str()) {
                    Some(doc) => (Some(p), doc.title.as_str(), &doc.description),
                    None => {
                        if !repo.files.contains(p.as_str())
                            && !crate::source::is_under_dir_named(&p, excluded)
                        {
                            edits.push((e.line_span.clone(), String::new()));
                        }
                        continue;
                    }
                },
                Resolution::Directory(d) => match meta_map.get(child_index_of(&d).as_str()) {
                    Some(m) if !m.invalid => (None, m.title.as_str(), &m.description),
                    _ => continue,
                },
                _ => continue,
            };
        if let Some(p) = doc_path {
            listed.insert(p);
        }
        let after = &text.as_bytes()[e.text_span.end..];
        // Collapsed `[T][]` and shortcut `[T]` references use the link text as
        // the reference label, so it must not change.
        let keep_label = after.first() == Some(&b']')
            && match after.get(1) {
                Some(b'(') => false,
                Some(b'[') => after.get(2) == Some(&b']'),
                _ => true,
            };
        if !keep_label {
            edits.push((e.text_span.clone(), escape_brackets(title)));
        }
        let tail = match description {
            Some(d) => format!(" {} {}", e.separator.unwrap_or('—'), escape_brackets(d)),
            None => String::new(),
        };
        edits.push((e.tail_span.clone(), tail));
    }
    edits.sort_by_key(|e| e.0.start);
    let mut out = String::with_capacity(text.len());
    let mut pos = 0;
    for (range, rep) in edits {
        out.push_str(&text[pos..range.start]);
        out.push_str(&rep);
        pos = range.end;
    }
    out.push_str(&text[pos..]);

    let rel = |path: &str| -> String {
        path.strip_prefix(&format!("{index_dir}/"))
            .unwrap_or(path)
            .to_string()
    };
    let mut missing: Vec<&Document> = documents
        .iter()
        .filter(|d| tree.owner_of(&d.path) == index_path && !listed.contains(&d.path))
        .collect();
    missing.sort_by(|a, b| a.path.cmp(&b.path));
    let mut children: Vec<&String> = unlinked_child_indexes.iter().collect();
    children.sort();
    let mut lines: Vec<String> = Vec::new();
    for d in missing {
        let mut l = format!(
            "- [{}]({})",
            escape_brackets(&d.title),
            percent_encode(&rel(&d.path))
        );
        if let Some(desc) = &d.description {
            l.push_str(&format!(" — {}", escape_brackets(desc)));
        }
        lines.push(l);
    }
    for c in children {
        if meta_map.get(c.as_str()).is_some_and(|m| m.invalid) {
            continue;
        }
        let dir = rel(parent_dir(c));
        let (title, description) = match meta_map.get(c.as_str()) {
            Some(m) => (m.title.clone(), m.description.clone()),
            None => (dir.rsplit('/').next().unwrap_or(&dir).to_string(), None),
        };
        let mut l = format!("- [{}]({}/)", escape_brackets(&title), percent_encode(&dir));
        if let Some(desc) = &description {
            l.push_str(&format!(" — {}", escape_brackets(desc)));
        }
        lines.push(l);
    }
    if lines.is_empty() {
        return out;
    }
    let nl = if text.contains("\r\n") { "\r\n" } else { "\n" };
    if !out.is_empty() {
        if !out.ends_with('\n') {
            out.push_str(nl);
        }
        if let Some(last) = out.lines().rev().find(|l| !l.trim().is_empty()) {
            if !is_list_item_line(last) {
                out.push_str(nl);
            }
        }
    }
    for l in lines {
        out.push_str(&l);
        out.push_str(nl);
    }
    out
}

fn write_atomic(path: &std::path::Path, content: &str) -> anyhow::Result<()> {
    use std::io::Write;
    use std::sync::atomic::{AtomicU64, Ordering};
    static SEQ: AtomicU64 = AtomicU64::new(0);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let name = format!(
        ".index.md.{}.{nanos}.{}.tmp",
        std::process::id(),
        SEQ.fetch_add(1, Ordering::Relaxed)
    );
    let tmp = path.with_file_name(name);
    let mut f = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&tmp)?;
    let tmp_ref = &tmp;
    let result = (move || -> std::io::Result<()> {
        f.write_all(content.as_bytes())?;
        f.sync_all()?;
        drop(f);
        std::fs::rename(tmp_ref, path)
    })();
    if let Err(e) = result {
        let _ = std::fs::remove_file(&tmp);
        return Err(e.into());
    }
    Ok(())
}

/// `miwa index`: create or update the indexes of every root in `config.index`.
///
/// Errors if `config.index` is empty ("index is not configured in
/// .miwa/config.yaml"). Creates a missing root index as a flat list, otherwise
/// updates the root index and its descendants. Each file is written to a
/// temporary file in the same directory and renamed into place. Returns the
/// status of every processed index, in processing order; nothing is printed.
pub fn run(
    repo_root: &std::path::Path,
    config: &crate::config::Config,
) -> anyhow::Result<Vec<(IndexStatus, String)>> {
    use crate::source::Source;
    if config.index.is_empty() {
        anyhow::bail!("index is not configured in .miwa/config.yaml");
    }
    let source = crate::source::FsSource::new(repo_root);
    let files: Vec<String> = source
        .list_files()?
        .into_iter()
        .filter(|p| !crate::source::is_under_dir_named(p, &config.exclude))
        .collect();
    let repo = RepoFiles::new(files.iter().map(String::as_str));
    let roots: Vec<String> = config
        .index
        .iter()
        .map(|r| crate::config::normalize_dir(r))
        .collect();
    let mut texts: BTreeMap<String, ParsedText> = BTreeMap::new();
    for path in &files {
        if path.ends_with(".md") && roots.iter().any(|r| crate::config::is_under(path, r)) {
            let bytes = source.read(path)?;
            let text = if path.rsplit('/').next() == Some("index.md") {
                String::from_utf8(bytes).map_err(|_| {
                    anyhow::anyhow!("{path} is not valid UTF-8; refusing to rewrite it")
                })?
            } else {
                String::from_utf8_lossy(&bytes).into_owned()
            };
            let front_matter = crate::frontmatter::parse(&text);
            texts.insert(path.clone(), ParsedText { text, front_matter });
        }
    }
    let excluded: Vec<String> = config
        .exclude
        .iter()
        .cloned()
        .chain(
            crate::source::DEFAULT_EXCLUDED_DIRS
                .iter()
                .map(|s| s.to_string()),
        )
        .collect();
    let mut results = Vec::new();
    for root in &roots {
        let RootFiles {
            documents, indexes, ..
        } = collect_documents(root, &texts);
        let index_paths: Vec<String> = indexes.iter().map(|m| m.path.clone()).collect();
        let tree = IndexTree::new(root, index_paths.iter().cloned());
        let root_index = crate::config::join_under(root, "index.md");
        let targets: Vec<String> = if index_paths.contains(&root_index) {
            index_paths.clone()
        } else if documents.is_empty() {
            continue;
        } else {
            let mut all = vec![root_index.clone()];
            all.extend(index_paths.iter().cloned());
            all
        };
        for index in targets {
            let existing = texts.get(&index).map(|t| t.text.as_str());
            let text = existing.unwrap_or("");
            let linked: HashSet<String> = parse_entries(text)
                .into_iter()
                .filter_map(|e| match resolve(&index, root, &e.dest, &repo) {
                    Resolution::Directory(d) => Some(child_index_of(&d)),
                    _ => None,
                })
                .collect();
            let unlinked: Vec<String> = tree
                .children_of(&index)
                .into_iter()
                .filter(|c| !linked.contains(c))
                .collect();
            let new_text = update_index(
                text, &index, &tree, &documents, &indexes, &repo, &unlinked, &excluded,
            );
            let status = if existing.is_none() {
                IndexStatus::Created
            } else if new_text == text {
                IndexStatus::Unchanged
            } else {
                IndexStatus::Updated
            };
            if status != IndexStatus::Unchanged {
                write_atomic(&repo_root.join(&index), &new_text)?;
            }
            results.push((status, index));
        }
    }
    Ok(results)
}

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

    // ---- helpers -------------------------------------------------------

    fn dests(text: &str) -> Vec<String> {
        parse_entries(text).into_iter().map(|e| e.dest).collect()
    }

    fn doc(path: &str, title: &str, description: Option<&str>) -> Document {
        Document {
            path: path.to_string(),
            title: title.to_string(),
            description: description.map(str::to_string),
        }
    }

    /// A typed document source with `title` / `description` front matter.
    fn typed(title: &str, description: Option<&str>) -> String {
        match description {
            Some(d) => format!("---\ntype: BusinessNeed\ntitle: {title}\ndescription: {d}\n---\n"),
            None => format!("---\ntype: BusinessNeed\ntitle: {title}\n---\n"),
        }
    }

    fn texts_of(files: &[(&str, &str)]) -> BTreeMap<String, ParsedText> {
        files
            .iter()
            .filter(|(p, _)| p.ends_with(".md"))
            .map(|(p, t)| {
                (
                    p.to_string(),
                    ParsedText {
                        text: t.to_string(),
                        front_matter: crate::frontmatter::parse(t),
                    },
                )
            })
            .collect()
    }

    fn issues_with(
        roots: &[&str],
        exclude: &[&str],
        files: &[(&str, &str)],
    ) -> BTreeSet<IndexIssue> {
        let mut config = Config::default_config();
        config.index = roots.iter().map(|s| s.to_string()).collect();
        config.exclude = exclude.iter().map(|s| s.to_string()).collect();
        let names: Vec<String> = files.iter().map(|(p, _)| p.to_string()).collect();
        collect_issues(&config, &names, &texts_of(files))
    }

    fn issues(files: &[(&str, &str)]) -> BTreeSet<IndexIssue> {
        issues_with(&["docs"], &[], files)
    }

    fn has(set: &BTreeSet<IndexIssue>, reason: ReasonCode, target: &str) -> bool {
        set.iter().any(|i| i.reason == reason && i.target == target)
    }

    fn count(set: &BTreeSet<IndexIssue>, reason: ReasonCode, target: &str) -> usize {
        set.iter()
            .filter(|i| i.reason == reason && i.target == target)
            .count()
    }

    fn detail_of(set: &BTreeSet<IndexIssue>, reason: ReasonCode, target: &str) -> String {
        set.iter()
            .find(|i| i.reason == reason && i.target == target)
            .unwrap_or_else(|| panic!("no {reason:?} for {target:?} in {set:?}"))
            .detail
            .clone()
    }

    fn fm(text: &str) -> FrontMatter {
        crate::frontmatter::parse(text).unwrap().unwrap()
    }

    /// `update_index` for `docs/index.md` (root `docs`); every file in `files`
    /// exists on disk.
    fn upd(text: &str, documents: &[Document], files: &[&str], unlinked: &[&str]) -> String {
        upd_meta(text, documents, &[], files, unlinked)
    }

    fn meta(path: &str, title: &str, description: Option<&str>) -> IndexMeta {
        IndexMeta {
            path: path.to_string(),
            title: title.to_string(),
            description: description.map(str::to_string),
            invalid: false,
        }
    }

    /// An `index.md` source with `title` / `description` front matter and one
    /// entry body line.
    fn index_with(title: Option<&str>, description: Option<&str>) -> String {
        let mut s = String::from("---\n");
        if let Some(t) = title {
            s.push_str(&format!("title: {t}\n"));
        }
        if let Some(d) = description {
            s.push_str(&format!("description: {d}\n"));
        }
        s.push_str("---\n- [B](b.md) — DB\n");
        s
    }

    /// Like `upd`, with the child index metadata supplied.
    fn upd_meta(
        text: &str,
        documents: &[Document],
        indexes: &[IndexMeta],
        files: &[&str],
        unlinked: &[&str],
    ) -> String {
        let unlinked: Vec<String> = unlinked.iter().map(|s| s.to_string()).collect();
        update_index(
            text,
            "docs/index.md",
            &tree_of(files),
            documents,
            indexes,
            &RepoFiles::new(files.iter().copied()),
            &unlinked,
            &test_excluded(),
        )
    }

    fn test_excluded() -> Vec<String> {
        crate::source::DEFAULT_EXCLUDED_DIRS
            .iter()
            .map(|s| s.to_string())
            .collect()
    }

    /// Index tree of root `docs` from the `index.md` files among `files`.
    fn tree_of(files: &[&str]) -> IndexTree {
        IndexTree::new(
            "docs",
            files
                .iter()
                .filter(|f| f.ends_with("/index.md"))
                .map(|f| f.to_string()),
        )
    }

    // ---- FR-068 parse_entries -----------------------------------------

    // [FR-068]
    #[test]
    fn 箇条書き記号とorderedの各形式がエントリとして検出される() {
        let text = "- [a](a.md)\n\n* [b](b.md)\n\n+ [c](c.md)\n\n1. [d](d.md)\n\n2) [e](e.md)\n";
        assert_eq!(dests(text), ["a.md", "b.md", "c.md", "d.md", "e.md"]);
    }

    // [FR-068]
    #[test]
    fn 入れ子の項目も任意の深さでエントリとして検出される() {
        let text = "- [a](a.md)\n  - [b](sub/b.md)\n    - [c](sub/c.md)\n";
        assert_eq!(dests(text), ["a.md", "sub/b.md", "sub/c.md"]);
    }

    // [FR-068]
    #[test]
    fn ルーズリストでも同じ結果になる() {
        let text = "- [a](a.md) — A\n\n- [b](b.md) — B\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 2);
        assert_eq!(es[0].description, "A");
        assert_eq!(es[1].description, "B");
        assert_eq!(&text[es[0].text_span.clone()], "a");
        assert_eq!(&text[es[1].text_span.clone()], "b");
    }

    // [FR-068]
    #[test]
    fn 太字で包まれたリンクで始まる項目はエントリではない() {
        assert!(parse_entries("- **[a](a.md)** — x\n").is_empty());
    }

    // [FR-068]
    #[test]
    fn タスクリストの項目はエントリではない() {
        assert!(parse_entries("- [ ] [a](a.md)\n- [x] [b](b.md)\n").is_empty());
    }

    // [FR-068]
    #[test]
    fn リンクで始まらない項目はエントリではない() {
        assert!(parse_entries("- see [a](a.md)\n- 説明のみ\n").is_empty());
    }

    // [FR-068]
    #[test]
    fn 段落中や見出し中のリンクはエントリではない() {
        let text = "intro [a](a.md)\n\n# [h](h.md)\n\n- [b](b.md)\n";
        assert_eq!(dests(text), ["b.md"]);
    }

    // [FR-068]
    #[test]
    fn 参照形式のリンクで始まる項目もエントリになる() {
        let text = "- [a][ref]\n- [b][]\n- [c]\n\n[ref]: a.md\n[b]: b.md\n[c]: c.md\n";
        let es = parse_entries(text);
        assert_eq!(
            es.iter().map(|e| e.dest.as_str()).collect::<Vec<_>>(),
            ["a.md", "b.md", "c.md"]
        );
        assert_eq!(&text[es[0].text_span.clone()], "a");
        assert_eq!(&text[es[1].text_span.clone()], "b");
        assert_eq!(&text[es[2].text_span.clone()], "c");
    }

    // [FR-068]
    #[test]
    fn リンクのtitle属性は無視される() {
        let text = "- [a](a.md \"tt\") — d\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 1);
        assert_eq!(es[0].dest, "a.md");
        assert_eq!(es[0].description, "d");
    }

    // [FR-068]
    #[test]
    fn 複数行にわたる項目も1つのエントリになる() {
        let text = "- [a](a.md) — one\n  two\n- [b](b.md)\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 2);
        assert_eq!(es[0].dest, "a.md");
    }

    // [FR-068]
    #[test]
    fn bomがあっても同じエントリが検出される() {
        let text = "\u{feff}- [a](a.md) — d\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 1);
        assert_eq!(&text[es[0].text_span.clone()], "a");
        assert_eq!(&text[es[0].tail_span.clone()], " — d");
    }

    // [FR-068]
    #[test]
    fn okf_version等のfrontmatter付き索引でも検出される() {
        let text = "---\nokf_version: 1\n---\n\n- [a](a.md)\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 1);
        assert_eq!(&text[es[0].text_span.clone()], "a");
    }

    // ---- FR-069 entry description -------------------------------------

    // [FR-069]
    #[test]
    fn 空のリンク文は空文字列でspanは開き括弧の直後になる() {
        let text = "- [](x.md)\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 1);
        assert_eq!(es[0].link_text, "");
        let pos = text.find('[').unwrap() + 1;
        assert_eq!(es[0].text_span, pos..pos);
    }

    // [FR-069]
    #[test]
    fn リンク文のコードスパンや入れ子の角括弧はソースのまま扱う() {
        let es = parse_entries("- [`a` b](x.md)\n- [T [x]](y.md)\n");
        assert_eq!(es[0].link_text, "`a` b");
        assert_eq!(es[1].link_text, "T [x]");
    }

    // [FR-069]
    #[test]
    fn 区切り4種を除いて要約を取り出す() {
        for sep in ['-', '–', '—', ':'] {
            let text = format!("- [a](a.md) {sep} desc\n");
            let es = parse_entries(&text);
            assert_eq!(es[0].separator, Some(sep), "{sep}");
            assert_eq!(es[0].description, "desc", "{sep}");
        }
    }

    // [FR-069]
    #[test]
    fn 区切りがなくても要約になり_区切りの二重指定は1文字だけ除く() {
        let es = parse_entries("- [a](a.md) desc\n- [b](b.md) — — x\n");
        assert_eq!(es[0].separator, None);
        assert_eq!(es[0].description, "desc");
        assert_eq!(es[1].separator, Some('—'));
        assert_eq!(es[1].description, "— x");
    }

    // [FR-069]
    #[test]
    fn 要約のないエントリは空の要約になる() {
        let es = parse_entries("- [a](a.md)\n");
        assert_eq!(es[0].description, "");
        assert_eq!(es[0].separator, None);
        assert!(es[0].tail_span.is_empty());
    }

    // [FR-069]
    #[test]
    fn 折り畳み参照の後ろから要約を取り出す() {
        let text = "- [a][] — desc\n\n[a]: a.md\n";
        let es = parse_entries(text);
        assert_eq!(es[0].description, "desc");
        assert_eq!(&text[es[0].tail_span.clone()], " — desc");
    }

    // [FR-069]
    #[test]
    fn 遅延継続行と複数行の要約を含む() {
        let lazy = parse_entries("- [a](a.md) — first\nsecond\n");
        assert_eq!(lazy[0].description, "first\nsecond");
        let indented = parse_entries("- [a](a.md) — first\n  second\n");
        assert_eq!(indented[0].description, "first\n  second");
    }

    // [FR-069]
    #[test]
    fn 要約に入れ子の子項目は含まれない() {
        let text = "- [a](a.md) — d\n  - [b](b.md) — e\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 2);
        assert_eq!(es[0].description, "d");
        assert_eq!(&text[es[0].tail_span.clone()], " — d");
        assert_eq!(es[1].description, "e");
    }

    // [FR-083]
    #[test]
    fn line_spanは先頭行から改行までを含む() {
        let text = "- [a](a.md) — d\r\n  - [b](b.md)\r\n- [c](c.md) — z";
        let es = parse_entries(text);
        assert_eq!(&text[es[0].line_span.clone()], "- [a](a.md) — d\r\n");
        assert_eq!(&text[es[1].line_span.clone()], "  - [b](b.md)\r\n");
        assert_eq!(&text[es[2].line_span.clone()], "- [c](c.md) — z");
    }

    // [FR-069]
    #[test]
    fn 角括弧のエスケープは比較時に戻される() {
        let files = [
            ("docs/index.md", "- [a\\[1\\]](a.md) — x \\] y\n"),
            (
                "docs/a.md",
                "---\ntype: BusinessNeed\ntitle: \"a[1]\"\ndescription: \"x ] y\"\n---\n",
            ),
        ];
        assert!(issues(&files).is_empty(), "{:?}", issues(&files));
    }

    // ---- FR-070 resolve -----------------------------------------------

    fn res(index_path: &str, dest: &str, files: &[&str]) -> Resolution {
        resolve(
            index_path,
            "docs",
            dest,
            &RepoFiles::new(files.iter().copied()),
        )
    }

    // [FR-070]
    #[test]
    fn 空とフラグメントのみは解決不能になる() {
        assert_eq!(
            res("docs/index.md", "", &[]),
            Resolution::Unresolvable("empty target")
        );
        assert_eq!(
            res("docs/index.md", "#x", &[]),
            Resolution::Unresolvable("empty target")
        );
    }

    // [FR-070]
    #[test]
    fn 外部リンクは無視される() {
        assert_eq!(
            res("docs/index.md", "https://example.com/a", &[]),
            Resolution::External
        );
        assert_eq!(
            res("docs/index.md", "mailto:a@example.com", &[]),
            Resolution::External
        );
    }

    // [FR-070]
    #[test]
    fn 絶対パスとリポジトリ外と根の外は解決不能になる() {
        assert_eq!(
            res("docs/index.md", "/abs.md", &[]),
            Resolution::Unresolvable("absolute path")
        );
        assert_eq!(
            res("docs/index.md", "../../out.md", &[]),
            Resolution::Unresolvable("escapes repository")
        );
        assert_eq!(
            res("docs/index.md", "../req/x.md", &["req/x.md"]),
            Resolution::Unresolvable("outside index root")
        );
    }

    // [FR-070]
    #[test]
    fn フラグメントを除いてファイルに解決される() {
        assert_eq!(
            res("docs/index.md", "a.md#sec", &["docs/a.md"]),
            Resolution::File("docs/a.md".to_string())
        );
        assert_eq!(
            res("docs/sub/index.md", "../a.md", &["docs/a.md"]),
            Resolution::File("docs/a.md".to_string())
        );
    }

    // [FR-070]
    #[test]
    fn パーセントデコードされ_デコード後のシャープは再分割されない() {
        assert_eq!(
            res("docs/index.md", "%E9%9B%86.md", &["docs/集.md"]),
            Resolution::File("docs/集.md".to_string())
        );
        assert_eq!(
            res("docs/index.md", "a%23b.md", &["docs/a#b.md"]),
            Resolution::File("docs/a#b.md".to_string())
        );
        assert_eq!(
            res("docs/index.md", "100%.md", &["docs/100%.md"]),
            Resolution::File("docs/100%.md".to_string())
        );
    }

    // [FR-070]
    #[test]
    fn ディレクトリを指す3形は同じディレクトリエントリになる() {
        let files = ["docs/sub/index.md", "docs/sub/x.md"];
        let want = Resolution::Directory("docs/sub".to_string());
        assert_eq!(res("docs/index.md", "sub/", &files), want);
        assert_eq!(res("docs/index.md", "sub", &files), want);
        assert_eq!(res("docs/index.md", "sub/index.md", &files), want);
    }

    // [FR-070]
    #[test]
    fn スラッシュなしでも配下にファイルがあればディレクトリになる() {
        assert_eq!(
            res("docs/index.md", "sub", &["docs/sub/x.md"]),
            Resolution::Directory("docs/sub".to_string())
        );
    }

    // [FR-070]
    #[test]
    fn 自身と祖先のディレクトリは解決不能になる() {
        let why = Resolution::Unresolvable("self or ancestor directory");
        assert_eq!(res("docs/index.md", "./", &[]), why);
        assert_eq!(res("docs/index.md", "index.md", &[]), why);
        assert_eq!(res("docs/a/index.md", "../", &[]), why);
        assert_eq!(res("docs/a/index.md", "../index.md", &[]), why);
        assert_eq!(res("docs/a/index.md", "./", &[]), why);
    }

    // [FR-070]
    #[test]
    fn 存在しないファイルは文書エントリとして扱う() {
        assert_eq!(
            res("docs/index.md", "missing.md", &[]),
            Resolution::File("docs/missing.md".to_string())
        );
    }

    // ---- FR-071 documents ----------------------------------------------

    // [FR-071]
    #[test]
    fn titleはフロントマターのtitleを優先し前後の空白を除く() {
        let t = fm("---\ntype: X\ntitle: \"  Front  \"\n---\n# Heading\n");
        assert_eq!(document_title("docs/a.md", &t), "Front");
    }

    // [FR-071]
    #[test]
    fn titleが空なら最初のh1にフォールバックする() {
        let t = fm("---\ntype: X\ntitle: \"  \"\n---\n# Heading\n");
        assert_eq!(document_title("docs/a.md", &t), "Heading");
    }

    // [FR-071]
    #[test]
    fn h1はatx閉じのシャープを含まない() {
        let t = fm("---\ntype: X\n---\n# Hello World #\n");
        assert_eq!(document_title("docs/a.md", &t), "Hello World");
    }

    // [FR-071]
    #[test]
    fn h1はsetext形式でも取れて下線を含まない() {
        let t = fm("---\ntype: X\n---\nHello World\n===\n");
        assert_eq!(document_title("docs/a.md", &t), "Hello World");
    }

    // [FR-071]
    #[test]
    fn h1のコードスパンはソースのまま含む() {
        let t = fm("---\ntype: X\n---\n# `code` and *em*\n");
        assert_eq!(document_title("docs/a.md", &t), "`code` and *em*");
    }

    // [FR-071]
    #[test]
    fn コードブロック内のシャープ行はh1として扱わない() {
        let t = fm("---\ntype: X\n---\n```\n# not heading\n```\n\n# Real\n");
        assert_eq!(document_title("docs/a.md", &t), "Real");
    }

    // [FR-071]
    #[test]
    fn h1以外の見出しは無視されファイル名にフォールバックする() {
        let t = fm("---\ntype: X\n---\n## second level\n");
        assert_eq!(document_title("docs/foo-bar.md", &t), "foo-bar");
    }

    fn collect(files: &[(&str, &str)]) -> RootFiles {
        collect_documents("docs", &texts_of(files))
    }

    // [FR-071]
    #[test]
    fn descriptionの有無と空と改行の扱い() {
        let files = [
            ("docs/none.md", "---\ntype: X\n---\n"),
            ("docs/empty.md", "---\ntype: X\ndescription: \"\"\n---\n"),
            (
                "docs/newline.md",
                "---\ntype: X\ndescription: \"a\\nb\"\n---\n",
            ),
            (
                "docs/folded.md",
                "---\ntype: X\ndescription: >\n  line1\n  line2\n---\n",
            ),
            (
                "docs/block.md",
                "---\ntype: X\ndescription: |\n  line1\n  line2\n---\n",
            ),
            (
                "docs/trim.md",
                "---\ntype: X\ndescription: \"  x  \"\n---\n",
            ),
        ];
        let RootFiles {
            documents: docs,
            untyped,
            ..
        } = collect(&files);
        assert!(untyped.is_empty());
        let d = |p: &str| {
            docs.iter()
                .find(|d| d.path == p)
                .unwrap_or_else(|| panic!("{p}"))
                .description
                .clone()
        };
        assert_eq!(d("docs/none.md"), None);
        assert_eq!(d("docs/empty.md"), None);
        assert_eq!(d("docs/newline.md"), None);
        assert_eq!(d("docs/folded.md"), Some("line1 line2".to_string()));
        assert_eq!(d("docs/block.md"), None);
        assert_eq!(d("docs/trim.md"), Some("x".to_string()));
    }

    // [FR-071]
    #[test]
    fn 索引のtitleとdescriptionはディレクトリのタイトルと要約になる() {
        let files = [
            (
                "docs/a/index.md",
                "---\ntitle: \"  Alpha  \"\ndescription: \"  DA  \"\n---\n",
            ),
            ("docs/b/index.md", "---\ndescription: DB\n---\n"),
            (
                "docs/c/index.md",
                "---\ntitle: \"\"\ndescription: \"\"\n---\n",
            ),
            (
                "docs/d/index.md",
                "---\ntitle: \"x\\ny\"\ndescription: \"a\\nb\"\n---\n",
            ),
            ("docs/e/f/index.md", "plain\n"),
            (
                "docs/g/index.md",
                "---\ntype: BusinessNeed\ntitle: G\ndescription: DG\n---\n",
            ),
        ];
        let RootFiles {
            documents, indexes, ..
        } = collect(&files);
        assert!(documents.is_empty(), "{documents:?}");
        let m = |p: &str| {
            indexes
                .iter()
                .find(|m| m.path == p)
                .unwrap_or_else(|| panic!("{p}"))
                .clone()
        };
        assert_eq!(
            m("docs/a/index.md"),
            meta("docs/a/index.md", "Alpha", Some("DA"))
        );
        assert_eq!(
            m("docs/b/index.md"),
            meta("docs/b/index.md", "b", Some("DB"))
        );
        assert_eq!(m("docs/c/index.md"), meta("docs/c/index.md", "c", None));
        assert_eq!(m("docs/d/index.md"), meta("docs/d/index.md", "d", None));
        assert_eq!(m("docs/e/f/index.md"), meta("docs/e/f/index.md", "f", None));
        assert_eq!(
            m("docs/g/index.md"),
            meta("docs/g/index.md", "G", Some("DG"))
        );
    }

    // [FR-067]
    #[test]
    fn indexとlogは予約名で文書にならず索引として分類される() {
        let files = [
            ("docs/index.md", "- [a](a.md)\n"),
            ("docs/sub/index.md", "- [b](b.md)\n"),
            ("docs/log.md", "---\ntype: BusinessNeed\n---\n"),
            ("docs/a.md", "---\ntype: Note\ntitle: A\n---\n"),
        ];
        let RootFiles {
            documents: docs,
            untyped,
            indexes,
        } = collect(&files);
        assert_eq!(docs.len(), 1, "{docs:?}");
        assert!(untyped.is_empty(), "{untyped:?}");
        let mut paths: Vec<String> = indexes.into_iter().map(|m| m.path).collect();
        paths.sort();
        assert_eq!(paths, ["docs/index.md", "docs/sub/index.md"]);
    }

    // [FR-075]
    #[test]
    fn typeなしとフロントマターなしはuntypedで壊れたフロントマターは無視される() {
        let files = [
            ("docs/plain.md", "# no frontmatter\n"),
            ("docs/notype.md", "---\ntitle: x\n---\n"),
            ("docs/broken.md", "---\ntype: [unclosed\n---\n"),
        ];
        let RootFiles {
            documents: docs,
            untyped,
            ..
        } = collect(&files);
        assert!(docs.is_empty(), "{docs:?}");
        let mut untyped = untyped;
        untyped.sort();
        assert_eq!(untyped, ["docs/notype.md", "docs/plain.md"]);
    }

    // [FR-071]
    #[test]
    fn typeは任意の値でも文書になる() {
        let files = [("docs/a.md", "---\ntype: Note\ntitle: A\n---\n")];
        let RootFiles {
            documents: docs, ..
        } = collect(&files);
        assert_eq!(docs.len(), 1, "{docs:?}");
        assert_eq!(docs[0].path, "docs/a.md");
        assert_eq!(docs[0].title, "A");
    }

    // ---- FR-072〜079 collect_issues ------------------------------------

    // [FR-072]
    #[test]
    fn 根のみの索引で整合していればfindingは出ない() {
        let a = typed("A", Some("D1"));
        let b = typed("B", Some("D2"));
        let files = [
            ("docs/index.md", "- [A](a.md) — D1\n- [B](b.md) - D2\n"),
            ("docs/a.md", a.as_str()),
            ("docs/b.md", b.as_str()),
        ];
        assert!(issues(&files).is_empty(), "{:?}", issues(&files));
    }

    // [FR-072]
    #[test]
    fn 入れ子の索引で子の文書は子の索引が担当する() {
        let sub = index_with(Some("sub"), Some("S"));
        let a = typed("A", Some("DA"));
        let b = typed("B", Some("DB"));
        let files = [
            ("docs/index.md", "- [A](a.md) — DA\n- [sub](sub/) — S\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/a.md", a.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        assert!(issues(&files).is_empty(), "{:?}", issues(&files));
    }

    // [FR-072]
    #[test]
    fn 親が子の担当文書を直接列挙しても_同じ文書の重複列挙もfindingにならない() {
        let sub = index_with(Some("sub"), Some("S"));
        let a = typed("A", Some("DA"));
        let b = typed("B", Some("DB"));
        let files = [
            (
                "docs/index.md",
                "- [A](a.md) — DA\n- [A](a.md) — DA\n- [sub](sub/index.md) — S\n- [B](sub/b.md) — DB\n",
            ),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/a.md", a.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        assert!(issues(&files).is_empty(), "{:?}", issues(&files));
    }

    // [FR-074]
    #[test]
    fn 担当索引が列挙していなければ他の索引が列挙していてもnot_listedになる() {
        let a = typed("A", Some("DA"));
        let b = typed("B", Some("DB"));
        let files = [
            (
                "docs/index.md",
                "- [A](a.md) — DA\n- [sub](sub/) — S\n- [B](sub/b.md) — DB\n",
            ),
            ("docs/sub/index.md", "intro only\n"),
            ("docs/a.md", a.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::NotListed, "docs/sub/b.md"), "{set:?}");
        assert!(!has(&set, ReasonCode::NotListed, "docs/a.md"));
    }

    // [FR-072]
    #[test]
    fn 中間ディレクトリに索引がなくても最も近い祖先の索引が親になる() {
        let c = typed("C", Some("DC"));
        let ab = "---\ntitle: a/b\ndescription: AB\n---\n- [C](c.md) — DC\n";
        let files = [
            ("docs/index.md", "- [a/b](a/b/) — AB\n"),
            ("docs/a/b/index.md", ab),
            ("docs/a/b/c.md", c.as_str()),
        ];
        assert!(issues(&files).is_empty(), "{:?}", issues(&files));
    }

    // [FR-072]
    #[test]
    fn 自前の索引を持たない中間ディレクトリへのエントリはbroken_entryになる() {
        let c = typed("C", Some("DC"));
        let files = [
            ("docs/index.md", "- [a](a/) — A\n"),
            ("docs/a/b/index.md", "- [C](c.md) — DC\n"),
            ("docs/a/b/c.md", c.as_str()),
        ];
        let set = issues(&files);
        assert_eq!(
            detail_of(&set, ReasonCode::BrokenEntry, "docs/index.md -> a/"),
            "directory has no index.md"
        );
        assert!(has(&set, ReasonCode::UnlinkedIndex, "docs/a/b/index.md"));
    }

    // [FR-072]
    #[test]
    fn 設定した根が配下のディレクトリでも担当範囲はその根の中だけになる() {
        let g = typed("G", Some("DG"));
        let files = [
            ("docs/guide/index.md", "- [G](g.md) — DG\n"),
            ("docs/guide/g.md", g.as_str()),
            ("docs/other.md", "---\ntype: X\n---\n"),
            ("docs/untyped.md", "plain\n"),
        ];
        let set = issues_with(&["docs/guide"], &[], &files);
        assert!(set.is_empty(), "{set:?}");
    }

    // [FR-073]
    #[test]
    fn 根の索引がなく文書があればmissing_indexで他の検査は省く() {
        let a = typed("A", Some("DA"));
        let files = [
            ("docs/a.md", a.as_str()),
            ("docs/nodesc.md", "---\ntype: X\ntitle: N\n---\n"),
            ("docs/sub/index.md", "- [gone](gone.md)\n"),
            ("docs/u.md", "plain\n"),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::MissingIndex, "docs"), "{set:?}");
        assert!(has(&set, ReasonCode::UntypedFile, "docs/u.md"));
        for r in [
            ReasonCode::NotListed,
            ReasonCode::BrokenEntry,
            ReasonCode::UnlinkedIndex,
            ReasonCode::TitleMismatch,
        ] {
            assert!(set.iter().all(|i| i.reason != r), "{r:?} in {set:?}");
        }
    }

    // [FR-073]
    #[test]
    fn 文書が0件の根ではmissing_indexを出さない() {
        assert!(issues(&[]).is_empty());
        assert!(issues(&[("docs/log.md", "---\ntype: X\n---\n")]).is_empty());
        let set = issues(&[("docs/u.md", "plain\n")]);
        assert!(!set.iter().any(|i| i.reason == ReasonCode::MissingIndex));
        assert!(has(&set, ReasonCode::UntypedFile, "docs/u.md"));
    }

    // [FR-074]
    #[test]
    fn 列挙されていない文書はnot_listedになりidの妥当性に依存しない() {
        let files = [
            ("docs/index.md", "intro\n"),
            (
                "docs/a.md",
                "---\ntype: X\nid: \"bad id!\"\ndescription: D\n---\n",
            ),
            ("docs/b.md", "---\ntype: X\ndescription: D\n---\n"),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::NotListed, "docs/a.md"), "{set:?}");
        assert!(has(&set, ReasonCode::NotListed, "docs/b.md"));
        assert_eq!(count(&set, ReasonCode::NotListed, "docs/a.md"), 1);
    }

    // [FR-075]
    #[test]
    fn typeのないmdはuntyped_fileでindexとlogと根の外は対象外() {
        let files = [
            ("docs/index.md", "- [x](x.md)\n"),
            ("docs/log.md", "plain\n"),
            ("docs/plain.md", "no frontmatter\n"),
            ("docs/notype.md", "---\ntitle: T\n---\n"),
            ("req/outside.md", "plain\n"),
        ];
        let set = issues(&files);
        assert!(
            has(&set, ReasonCode::UntypedFile, "docs/plain.md"),
            "{set:?}"
        );
        assert!(has(&set, ReasonCode::UntypedFile, "docs/notype.md"));
        assert!(!has(&set, ReasonCode::UntypedFile, "docs/index.md"));
        assert!(!has(&set, ReasonCode::UntypedFile, "docs/log.md"));
        assert!(!has(&set, ReasonCode::UntypedFile, "req/outside.md"));
    }

    // [FR-076]
    #[test]
    fn broken_entryのdetailとtargetの正準形() {
        let t = typed("T", Some("D"));
        let index = [
            "- [e]()\n",
            "- [a](#x)\n",
            "- [b](/abs.md)\n",
            "- [c](../../out.md)\n",
            "- [d](../req/x.md)\n",
            "- [s](./)\n",
            "- [f](missing.md)\n",
            "- [g](untyped.md)\n",
            "- [h](dirnoindex/)\n",
            "- [i](pic.png)\n",
            "- [j](vendor/x.md)\n",
            "- [k](node_modules/x.md)\n",
            "- [ext](https://example.com/x)\n",
            "- [mail](mailto:a@example.com)\n",
        ]
        .concat();
        let files = [
            ("docs/index.md", index.as_str()),
            ("docs/untyped.md", "plain\n"),
            ("docs/pic.png", ""),
            ("docs/dirnoindex/x.md", t.as_str()),
        ];
        let set = issues_with(&["docs"], &["vendor"], &files);
        let b = |dest: &str| {
            detail_of(
                &set,
                ReasonCode::BrokenEntry,
                &format!("docs/index.md -> {dest}"),
            )
        };
        assert_eq!(b(""), "empty target");
        assert_eq!(b("#x"), "empty target");
        assert_eq!(b("/abs.md"), "absolute path");
        assert_eq!(b("../../out.md"), "escapes repository");
        assert_eq!(b("../req/x.md"), "outside index root");
        assert_eq!(b("./"), "self or ancestor directory");
        assert_eq!(b("missing.md"), "target does not exist");
        assert_eq!(b("untyped.md"), "target has no `type`");
        assert_eq!(b("dirnoindex/"), "directory has no index.md");
        assert_eq!(b("pic.png"), "target is not a document");
        assert_eq!(b("vendor/x.md"), "target is excluded from scan");
        assert_eq!(b("node_modules/x.md"), "target is excluded from scan");
        assert!(!set.iter().any(|i| i.target.contains("example.com")));
    }

    // [FR-077]
    #[test]
    fn タイトルが一致しなければtitle_mismatchで対象は文書のパス() {
        let a = typed("Real", Some("D"));
        let files = [
            ("docs/index.md", "- [Wrong](a.md) — D\n"),
            ("docs/a.md", a.as_str()),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::TitleMismatch, "docs/a.md"), "{set:?}");
        assert!(set
            .iter()
            .all(|i| i.reason != ReasonCode::DescriptionMismatch));
    }

    // [FR-077]
    #[test]
    fn 要約が一致しなければdescription_mismatchで空白は正規化しない() {
        let a = typed("A", Some("x y"));
        let files = [
            ("docs/index.md", "- [A](a.md) — x  y\n"),
            ("docs/a.md", a.as_str()),
        ];
        let set = issues(&files);
        assert!(
            has(&set, ReasonCode::DescriptionMismatch, "docs/a.md"),
            "{set:?}"
        );
        assert!(set.iter().all(|i| i.reason != ReasonCode::TitleMismatch));
    }

    // [FR-077]
    #[test]
    fn 文書にdescriptionがなければdescription_mismatchを出さない() {
        let a = typed("A", None);
        let files = [
            ("docs/index.md", "- [A](a.md) — whatever\n"),
            ("docs/a.md", a.as_str()),
        ];
        let set = issues(&files);
        assert!(set
            .iter()
            .all(|i| i.reason != ReasonCode::DescriptionMismatch));
        assert!(has(&set, ReasonCode::MissingDescription, "docs/a.md"));
    }

    // [FR-077]
    #[test]
    fn 同じ文書を指す複数エントリはすべて比較され_findingは重複しない() {
        let a = typed("A", Some("D"));
        let files = [
            (
                "docs/index.md",
                "- [A](a.md) — D\n- [X](a.md) — D\n- [Y](a.md) — D\n",
            ),
            ("docs/a.md", a.as_str()),
        ];
        let set = issues(&files);
        assert_eq!(
            count(&set, ReasonCode::TitleMismatch, "docs/a.md"),
            1,
            "{set:?}"
        );
    }

    // [FR-078]
    #[test]
    fn descriptionがない_空_改行入りの文書はmissing_description() {
        let files = [
            ("docs/index.md", "- [A](a.md)\n- [B](b.md)\n- [C](c.md)\n"),
            ("docs/a.md", "---\ntype: X\ntitle: A\n---\n"),
            (
                "docs/b.md",
                "---\ntype: X\ntitle: B\ndescription: \"\"\n---\n",
            ),
            (
                "docs/c.md",
                "---\ntype: X\ntitle: C\ndescription: |\n  l1\n  l2\n---\n",
            ),
        ];
        let set = issues(&files);
        for p in ["docs/a.md", "docs/b.md", "docs/c.md"] {
            assert!(has(&set, ReasonCode::MissingDescription, p), "{p}: {set:?}");
        }
    }

    // [FR-078]
    #[test]
    fn missing_descriptionは未列挙の文書にも出る() {
        let files = [
            ("docs/index.md", "intro\n"),
            ("docs/a.md", "---\ntype: X\ntitle: A\n---\n"),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::MissingDescription, "docs/a.md"));
        assert!(has(&set, ReasonCode::NotListed, "docs/a.md"));
    }

    // [FR-079]
    #[test]
    fn 子の索引にdescriptionがなければmissing_directory_descriptionで対象は子の索引のパス() {
        let b = typed("B", Some("DB"));
        let sub = index_with(Some("S"), None);
        let files = [
            ("docs/index.md", "- [S](sub/) — 何か\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        assert!(
            has(
                &set,
                ReasonCode::MissingDirectoryDescription,
                "docs/sub/index.md"
            ),
            "{set:?}"
        );
        // The entry's own summary is not compared when the child has none.
        assert!(
            set.iter()
                .all(|i| i.reason != ReasonCode::DescriptionMismatch),
            "{set:?}"
        );
        assert!(set.iter().all(|i| i.reason != ReasonCode::UnlinkedIndex));
    }

    // [FR-079]
    #[test]
    fn 子のdescriptionが空や改行入りでもmissing_directory_description() {
        let b = typed("B", Some("DB"));
        for desc in ["\"\"", "\"a\\nb\""] {
            let sub = index_with(Some("S"), Some(desc));
            let files = [
                ("docs/index.md", "- [S](sub/) — x\n"),
                ("docs/sub/index.md", sub.as_str()),
                ("docs/sub/b.md", b.as_str()),
            ];
            let set = issues(&files);
            assert!(
                has(
                    &set,
                    ReasonCode::MissingDirectoryDescription,
                    "docs/sub/index.md"
                ),
                "{desc}: {set:?}"
            );
        }
    }

    // [FR-079]
    #[test]
    fn エントリの要約が空でも子にdescriptionがあればdescription_mismatchだけが出る() {
        let b = typed("B", Some("DB"));
        let sub = index_with(Some("S"), Some("DS"));
        let files = [
            ("docs/index.md", "- [S](sub/)\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        assert!(
            has(
                &set,
                ReasonCode::DescriptionMismatch,
                "docs/index.md -> sub/"
            ),
            "{set:?}"
        );
        assert!(
            set.iter()
                .all(|i| i.reason != ReasonCode::MissingDirectoryDescription),
            "{set:?}"
        );
    }

    // [FR-079]
    #[test]
    fn エントリの要約が空で子にもなければmissing_directory_descriptionだけが出る() {
        let b = typed("B", Some("DB"));
        let sub = index_with(Some("S"), None);
        let files = [
            ("docs/index.md", "- [S](sub/)\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        assert_eq!(set.len(), 1, "{set:?}");
        assert!(has(
            &set,
            ReasonCode::MissingDirectoryDescription,
            "docs/sub/index.md"
        ));
    }

    // [FR-079]
    #[test]
    fn 子の索引と一致するディレクトリエントリは問題にならない() {
        let b = typed("B", Some("DB"));
        let sub = index_with(Some("S"), Some("DS"));
        let files = [
            ("docs/index.md", "- [S](sub/) — DS\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        assert!(issues(&files).is_empty());
    }

    // [FR-077]
    #[test]
    fn ディレクトリエントリのリンク文が子のtitleと違えばtitle_mismatch() {
        let b = typed("B", Some("DB"));
        let sub = index_with(Some("S"), Some("DS"));
        let files = [
            ("docs/index.md", "- [sub](sub/) — DS\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        assert!(
            has(&set, ReasonCode::TitleMismatch, "docs/index.md -> sub/"),
            "{set:?}"
        );
        assert!(
            detail_of(&set, ReasonCode::TitleMismatch, "docs/index.md -> sub/").contains("`S`")
        );
        assert_eq!(set.len(), 1, "{set:?}");
    }

    // [FR-077]
    #[test]
    fn ディレクトリエントリの要約が子のdescriptionと違えばdescription_mismatch() {
        let b = typed("B", Some("DB"));
        let sub = index_with(Some("S"), Some("DS"));
        let files = [
            ("docs/index.md", "- [S](sub/) — 古い\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        assert!(
            has(
                &set,
                ReasonCode::DescriptionMismatch,
                "docs/index.md -> sub/"
            ),
            "{set:?}"
        );
        assert_eq!(set.len(), 1, "{set:?}");
    }

    // [FR-077]
    #[test]
    fn 子にtitleがなければディレクトリ名と照合される() {
        let b = typed("B", Some("DB"));
        let sub = index_with(None, Some("DS"));
        let ok = [
            ("docs/index.md", "- [sub](sub/) — DS\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        assert!(issues(&ok).is_empty());
        let ng = [
            ("docs/index.md", "- [other](sub/) — DS\n"),
            ("docs/sub/index.md", sub.as_str()),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&ng);
        assert!(
            has(&set, ReasonCode::TitleMismatch, "docs/index.md -> sub/"),
            "{set:?}"
        );
    }

    // [FR-079]
    #[test]
    fn 中間索引を飛ばしたディレクトリエントリも子の索引で判定する() {
        let c = typed("C", Some("DC"));
        let ab = index_with(Some("AB"), None);
        let files = [
            ("docs/index.md", "- [AB](a/b/) — x\n"),
            ("docs/a/b/index.md", ab.as_str()),
            ("docs/a/b/c.md", c.as_str()),
        ];
        let set = issues(&files);
        assert!(
            has(
                &set,
                ReasonCode::MissingDirectoryDescription,
                "docs/a/b/index.md"
            ),
            "{set:?}"
        );
        assert!(set.iter().all(|i| i.reason != ReasonCode::UnlinkedIndex));
    }

    // [FR-079]
    #[test]
    fn 親から辿れない子の索引はunlinked_index() {
        let b = typed("B", Some("DB"));
        let files = [
            ("docs/index.md", "intro\n"),
            ("docs/sub/index.md", "- [B](b.md) — DB\n"),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        assert!(
            has(&set, ReasonCode::UnlinkedIndex, "docs/sub/index.md"),
            "{set:?}"
        );
    }

    // ---- FR-081 update_index rewrite -----------------------------------

    // [FR-081]
    #[test]
    fn リンク文と要約を文書の値で置き換え区切りは既存を保つ() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let files = ["docs/a.md"];
        assert_eq!(
            upd("- [Old](a.md) - old\n", &docs, &files, &[]),
            "- [A](a.md) - D\n"
        );
        assert_eq!(
            upd("- [Old](a.md) : old\n", &docs, &files, &[]),
            "- [A](a.md) : D\n"
        );
        assert_eq!(
            upd("- [Old](a.md)\n", &docs, &files, &[]),
            "- [A](a.md) — D\n"
        );
    }

    // [FR-081]
    #[test]
    fn descriptionのない文書は区切りも要約も付けない() {
        let docs = [doc("docs/a.md", "A", None)];
        assert_eq!(
            upd("- [Old](a.md) — x\n", &docs, &["docs/a.md"], &[]),
            "- [A](a.md)\n"
        );
    }

    // [FR-081]
    #[test]
    fn リンク先のソースは変更しない() {
        let docs = [doc("docs/a b.md", "A", Some("D"))];
        let files = ["docs/a b.md"];
        assert_eq!(
            upd("- [Old](<a b.md> \"t\") — x\n", &docs, &files, &[]),
            "- [A](<a b.md> \"t\") — D\n"
        );
        assert_eq!(
            upd("- [Old](a%20b.md) — x\n", &docs, &files, &[]),
            "- [A](a%20b.md) — D\n"
        );
    }

    // [FR-081]
    #[test]
    fn 参照形式の定義とラベルは変更しない() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let files = ["docs/a.md"];
        assert_eq!(
            upd("- [Old][r] — x\n\n[r]: a.md\n", &docs, &files, &[]),
            "- [A][r] — D\n\n[r]: a.md\n"
        );
        // タイトルがラベルと同じなら折り畳み・短縮形も壊れない
        let docs = [doc("docs/a.md", "Old", Some("D"))];
        assert_eq!(
            upd("- [Old][] — x\n\n[Old]: a.md\n", &docs, &files, &[]),
            "- [Old][] — D\n\n[Old]: a.md\n"
        );
        assert_eq!(
            upd("- [Old] — x\n\n[Old]: a.md\n", &docs, &files, &[]),
            "- [Old] — D\n\n[Old]: a.md\n"
        );
    }

    // [FR-081]
    #[test]
    fn タイトルの角括弧はエスケープされる() {
        let docs = [doc("docs/a.md", "a[1]", Some("D"))];
        assert_eq!(
            upd("- [Old](a.md) — x\n", &docs, &["docs/a.md"], &[]),
            "- [a\\[1\\]](a.md) — D\n"
        );
    }

    // [FR-081]
    #[test]
    fn 複数行エントリは1行に畳まれる() {
        let docs = [doc("docs/a.md", "A", Some("first second"))];
        let text = "- [A](a.md) — first\n  second\n- [B](b.md) — DB\n";
        let docs = [docs[0].clone(), doc("docs/b.md", "B", Some("DB"))];
        assert_eq!(
            upd(text, &docs, &["docs/a.md", "docs/b.md"], &[]),
            "- [A](a.md) — first second\n- [B](b.md) — DB\n"
        );
    }

    // [FR-081]
    #[test]
    fn 同じ文書を指す重複エントリはすべて書き換える() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        assert_eq!(
            upd(
                "- [x](a.md) — 1\n- [y](./a.md) — 2\n",
                &docs,
                &["docs/a.md"],
                &[]
            ),
            "- [A](a.md) — D\n- [A](./a.md) — D\n"
        );
    }

    // [FR-081]
    #[test]
    fn すでに一致していればバイト列は変わらない() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let text = "- [A](a.md) — D\n";
        assert_eq!(upd(text, &docs, &["docs/a.md"], &[]), text);
    }

    // [FR-081]
    #[test]
    fn bomは書き換え後も保存される() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        assert_eq!(
            upd("\u{feff}- [Old](a.md) — x\n", &docs, &["docs/a.md"], &[]),
            "\u{feff}- [A](a.md) — D\n"
        );
    }

    // ---- FR-082 append --------------------------------------------------

    // [FR-082]
    #[test]
    fn 未列挙の文書がパス順に末尾へ追加される() {
        let docs = [
            doc("docs/c.md", "C", None),
            doc("docs/a.md", "A", Some("DA")),
            doc("docs/b.md", "B", Some("DB")),
        ];
        let text = "- [A](a.md) — DA\n";
        let files = ["docs/a.md", "docs/b.md", "docs/c.md"];
        assert_eq!(
            upd(text, &docs, &files, &[]),
            "- [A](a.md) — DA\n- [B](b.md) — DB\n- [C](c.md)\n"
        );
    }

    // [FR-082]
    #[test]
    fn 追加するパスは相対でエンコードされタイトルはエスケープされる() {
        let docs = [doc("docs/sub/a b(c)<d>%e#f\\g.md", "t[1]", Some("D"))];
        let files = ["docs/sub/a b(c)<d>%e#f\\g.md", "docs/x.md"];
        assert_eq!(
            upd("- [x](x.md)\n", &docs, &files, &[]),
            "- [x](x.md)\n- [t\\[1\\]](sub/a%20b%28c%29%3Cd%3E%25e%23f%5Cg.md) — D\n"
        );
    }

    // [FR-082]
    #[test]
    fn 末尾の改行と空行の規則() {
        let docs = [doc("docs/b.md", "B", Some("DB"))];
        let files = ["docs/b.md", "docs/x.md"];
        let item = "- [B](b.md) — DB\n";
        // 箇条書きで終わり改行なし -> 改行のみ足す
        assert_eq!(
            upd("- [x](x.md)", &docs, &files, &[]),
            format!("- [x](x.md)\n{item}")
        );
        // 段落で終わる -> 空行を 1 つ挟む
        assert_eq!(
            upd("# Index\n\nintro\n", &docs, &files, &[]),
            format!("# Index\n\nintro\n\n{item}")
        );
        assert_eq!(upd("intro", &docs, &files, &[]), format!("intro\n\n{item}"));
        // 順序付き・別記号の項目で終わる -> 空行なし
        assert_eq!(upd("1. x\n", &docs, &files, &[]), format!("1. x\n{item}"));
        assert_eq!(upd("* x\n", &docs, &files, &[]), format!("* x\n{item}"));
        // 本文が空 -> そのまま
        assert_eq!(upd("", &docs, &files, &[]), item);
    }

    // [FR-082]
    #[test]
    fn 改行コードは既存本文にcrlfがあればcrlfになる() {
        let docs = [doc("docs/b.md", "B", Some("DB"))];
        assert_eq!(
            upd("- [x](x.md)\r\n", &docs, &["docs/b.md", "docs/x.md"], &[]),
            "- [x](x.md)\r\n- [B](b.md) — DB\r\n"
        );
        assert_eq!(
            upd("# T\r\n\r\nintro\r\n", &docs, &["docs/b.md"], &[]),
            "# T\r\n\r\nintro\r\n\r\n- [B](b.md) — DB\r\n"
        );
    }

    // [FR-082]
    #[test]
    fn 辿れない子の索引はディレクトリエントリとして文書の後に追加される() {
        let docs = [doc("docs/a.md", "A", Some("DA"))];
        let metas = [
            meta("docs/zeta/index.md", "Zeta [z]", Some("DZ")),
            meta("docs/sub/index.md", "Sub", Some("DS")),
        ];
        let out = upd_meta(
            "- [x](x.md)\n",
            &docs,
            &metas,
            &["docs/a.md", "docs/x.md"],
            &["docs/zeta/index.md", "docs/sub/index.md"],
        );
        assert_eq!(
            out,
            "- [x](x.md)\n- [A](a.md) — DA\n- [Sub](sub/) — DS\n- [Zeta \\[z\\]](zeta/) — DZ\n"
        );
    }

    // [FR-082]
    #[test]
    fn 子に要約がなければ追加するディレクトリエントリは区切りを付けない() {
        let metas = [
            meta("docs/sub/index.md", "sub", None),
            meta("docs/two/index.md", "Two", None),
        ];
        let out = upd_meta(
            "- [x](x.md)\n",
            &[],
            &metas,
            &["docs/x.md"],
            &["docs/sub/index.md", "docs/two/index.md"],
        );
        assert_eq!(out, "- [x](x.md)\n- [sub](sub/)\n- [Two](two/)\n");
    }

    // [FR-081]
    #[test]
    fn ディレクトリエントリのリンク文と要約を子の索引の値で置き換える() {
        let metas = [meta("docs/sub/index.md", "Sub", Some("DS"))];
        let files = ["docs/sub/index.md"];
        let out = upd_meta("- [old](sub/) - 古い\n", &[], &metas, &files, &[]);
        assert_eq!(out, "- [Sub](sub/) - DS\n");
        // Destination source and reference forms stay as written.
        let out = upd_meta("- [old](<sub/> \"t\")\n", &[], &metas, &files, &[]);
        assert_eq!(out, "- [Sub](<sub/> \"t\") — DS\n");
        // Already matching: byte-identical.
        let same = "- [Sub](sub/) — DS\n";
        assert_eq!(upd_meta(same, &[], &metas, &files, &[]), same);
    }

    // [FR-081]
    #[test]
    fn 子に要約がなければディレクトリエントリの後ろは空になる() {
        let metas = [meta("docs/sub/index.md", "sub", None)];
        let out = upd_meta(
            "- [sub](sub/) — 古い\n",
            &[],
            &metas,
            &["docs/sub/index.md"],
            &[],
        );
        assert_eq!(out, "- [sub](sub/)\n");
    }

    // [FR-081]
    #[test]
    fn ディレクトリエントリの折り畳み参照はリンク文を保ち後ろだけ更新する() {
        let metas = [meta("docs/sub/index.md", "Sub", Some("DS"))];
        let out = upd_meta(
            "- [sub][] — x\n\n[sub]: sub/\n",
            &[],
            &metas,
            &["docs/sub/index.md"],
            &[],
        );
        assert_eq!(out, "- [sub][] — DS\n\n[sub]: sub/\n");
    }

    // [FR-085]
    #[test]
    fn ディレクトリエントリの書き換えは冪等() {
        let metas = [meta("docs/sub/index.md", "Sub", Some("DS"))];
        let files = ["docs/sub/index.md"];
        let once = upd_meta("- [x](sub/) — y\n", &[], &metas, &files, &[]);
        let twice = upd_meta(&once, &[], &metas, &files, &[]);
        assert_eq!(once, twice);
        assert_eq!(once, "- [Sub](sub/) — DS\n");
    }

    // ---- FR-083 removal --------------------------------------------------

    // [FR-083]
    #[test]
    fn 存在しない文書へのエントリ行は削除される() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let text = "- [A](a.md) — D\n- [G](gone.md) — g\n- [A](a.md) — D\n";
        assert_eq!(
            upd(text, &docs, &["docs/a.md"], &[]),
            "- [A](a.md) — D\n- [A](a.md) — D\n"
        );
    }

    // [FR-083]
    #[test]
    fn 削除した項目の子項目は残る() {
        let docs = [
            doc("docs/a.md", "A", Some("D")),
            doc("docs/b.md", "B", Some("DB")),
        ];
        let files = ["docs/a.md", "docs/b.md"];
        let text = "- [G](gone.md) — g\n  - [A](a.md) — D\n- [B](b.md) — DB\n";
        assert_eq!(
            upd(text, &docs, &files, &[]),
            "  - [A](a.md) — D\n- [B](b.md) — DB\n"
        );
    }

    // [FR-083]
    #[test]
    fn 削除時もbomは保存される() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        assert_eq!(
            upd(
                "\u{feff}- [G](gone.md)\n- [A](a.md) — D\n",
                &docs,
                &["docs/a.md"],
                &[]
            ),
            "\u{feff}- [A](a.md) — D\n"
        );
    }

    // [FR-083]
    #[test]
    fn 除外配下_typeなし_解決不能_ディレクトリは削除しない() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let text = "- [A](a.md) — D\n\
                    - [n](node_modules/x.md) — 1\n\
                    - [u](untyped.md) — 2\n\
                    - [o](../req/x.md) — 3\n\
                    - [d](sub/) — 4\n\
                    - [e](#x) — 5\n";
        let files = ["docs/a.md", "docs/untyped.md"];
        assert_eq!(upd(text, &docs, &files, &[]), text);
    }

    // ---- FR-084 create ---------------------------------------------------

    // [FR-084]
    #[test]
    fn 索引がなければ見出しなしの平坦なリストを作る() {
        let docs = [
            doc("docs/sub/b.md", "B", None),
            doc("docs/a.md", "A", Some("DA")),
        ];
        let out = upd("", &docs, &["docs/a.md", "docs/sub/b.md"], &[]);
        assert_eq!(out, "- [A](a.md) — DA\n- [B](sub/b.md)\n");
        assert!(!out.contains('#'));
    }

    // [FR-084]
    #[test]
    fn 新規作成でも子索引のディレクトリエントリは子のtitleと要約を使う() {
        let docs = [doc("docs/a.md", "A", Some("DA"))];
        let metas = [
            meta("docs/sub/index.md", "Sub", Some("DS")),
            meta("docs/two/index.md", "two", None),
        ];
        let out = upd_meta(
            "",
            &docs,
            &metas,
            &["docs/a.md", "docs/sub/index.md", "docs/two/index.md"],
            &["docs/sub/index.md", "docs/two/index.md"],
        );
        assert_eq!(out, "- [A](a.md) — DA\n- [Sub](sub/) — DS\n- [two](two/)\n");
    }

    // ---- FR-085 preserve / idempotent -----------------------------------

    // [FR-085]
    #[test]
    fn エントリ行以外のバイト列は変更されない() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let files = ["docs/a.md", "docs/sub/index.md"];
        let metas = [meta("docs/sub/index.md", "sub", Some("S"))];
        let text = "\u{feff}# Index\r\n\r\nintro  text\r\n\r\n## Sec\r\n\r\n- [Old](a.md) — x\r\n  - child [c](c.md)\r\n- **[b](b.md)** — bold\r\n- [sub](sub/) — S\r\n";
        let want = "\u{feff}# Index\r\n\r\nintro  text\r\n\r\n## Sec\r\n\r\n- [A](a.md) — D\r\n  - child [c](c.md)\r\n- **[b](b.md)** — bold\r\n- [sub](sub/) — S\r\n";
        assert_eq!(upd_meta(text, &docs, &metas, &files, &[]), want);
    }

    // [FR-085]
    #[test]
    fn 更新は冪等で2回目は同一文字列になる() {
        let docs = [
            doc("docs/a.md", "A", Some("D")),
            doc("docs/b.md", "B[1]", Some("DB")),
            doc("docs/c d.md", "C", None),
        ];
        let files = ["docs/a.md", "docs/b.md", "docs/c d.md"];
        let text = "# Index\n\n- [Old](a.md) - x\n  y\n- [G](gone.md)\n";
        let once = upd(text, &docs, &files, &[]);
        let twice = upd(&once, &docs, &files, &[]);
        assert_eq!(once, twice);
    }

    // ---- boundary tests added for review ---------------------------------

    // [FR-069]
    #[test]
    fn 参照形式とショートカットの後ろから要約を切り出す() {
        let text = "- [T][ref] — 要約1\n- [U] — 要約2\n\n[ref]: a.md\n[U]: b.md\n";
        let es = parse_entries(text);
        assert_eq!(es.len(), 2);
        assert_eq!(es[0].description, "要約1");
        assert_eq!(es[1].description, "要約2");
    }

    // [FR-070]
    #[test]
    fn パーセントエンコードされたドットドットはデコード後に正規化される() {
        assert_eq!(
            res("docs/sub/index.md", "%2E%2E/a.md", &["docs/a.md"]),
            Resolution::File("docs/a.md".to_string())
        );
        assert_eq!(
            res("docs/index.md", "%2E%2E/%2E%2E/x.md", &[]),
            Resolution::Unresolvable("escapes repository")
        );
    }

    // [FR-070]
    #[test]
    fn フラグメント付きの索引ファイル指定もディレクトリエントリになる() {
        assert_eq!(
            res("docs/index.md", "sub/index.md#frag", &["docs/sub/index.md"]),
            Resolution::Directory("docs/sub".to_string())
        );
    }

    // [FR-071]
    #[test]
    fn setextのレベル2下線はh1として扱わない() {
        let t = fm("---\ntype: X\n---\nIntro\n---\n");
        assert_eq!(document_title("docs/foo.md", &t), "foo");
    }

    // [FR-071]
    #[test]
    fn 改行を含むtitleは無いものとしてh1にフォールバックする() {
        let t = fm("---\ntype: X\ntitle: \"a\\nb\"\n---\n# Heading\n");
        assert_eq!(document_title("docs/foo.md", &t), "Heading");
        let t = fm("---\ntype: X\ntitle: \"a\\nb\"\n---\n");
        assert_eq!(document_title("docs/foo.md", &t), "foo");
    }

    // [FR-073]
    #[test]
    fn missing_index時は索引側の6種のfindingがすべて出ない() {
        let a = typed("A", Some("DA"));
        let b = typed("B", Some("DB"));
        let files = [
            ("docs/a.md", a.as_str()),
            (
                "docs/sub/index.md",
                "- [X](../a.md) — other\n- [gone](gone.md)\n- [d](dir/)\n- [e](dir2/)\n",
            ),
            ("docs/sub/dir/index.md", "intro\n"),
            ("docs/sub/dir/b.md", b.as_str()),
            ("docs/sub/dir2/index.md", "intro\n"),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::MissingIndex, "docs"), "{set:?}");
        for r in [
            ReasonCode::NotListed,
            ReasonCode::BrokenEntry,
            ReasonCode::TitleMismatch,
            ReasonCode::DescriptionMismatch,
            ReasonCode::MissingDirectoryDescription,
            ReasonCode::UnlinkedIndex,
        ] {
            assert!(set.iter().all(|i| i.reason != r), "{r:?} in {set:?}");
        }
    }

    // [FR-076]
    #[test]
    fn 索引自身を指すエントリは自己か祖先として壊れている() {
        let a = typed("A", Some("D"));
        let files = [
            (
                "docs/index.md",
                "- [A](a.md) — D\n- [me](index.md)\n- [s](sub/index.md)\n",
            ),
            ("docs/a.md", a.as_str()),
        ];
        let set = issues(&files);
        assert_eq!(
            detail_of(&set, ReasonCode::BrokenEntry, "docs/index.md -> index.md"),
            "self or ancestor directory"
        );
        assert_eq!(
            detail_of(
                &set,
                ReasonCode::BrokenEntry,
                "docs/index.md -> sub/index.md"
            ),
            "directory has no index.md"
        );
    }

    // [FR-077]
    #[test]
    fn 同じ文書を指す2本目だけ不一致でもfindingが出る() {
        let a = typed("A", Some("D"));
        let files = [
            ("docs/index.md", "- [A](a.md) — D\n- [X](a.md) — Y\n"),
            ("docs/a.md", a.as_str()),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::TitleMismatch, "docs/a.md"), "{set:?}");
        assert!(has(&set, ReasonCode::DescriptionMismatch, "docs/a.md"));
    }

    // [FR-081]
    #[test]
    fn 区切りのen_dashは書き戻しで保持される() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        assert_eq!(
            upd("- [Old](a.md) – old\n", &docs, &["docs/a.md"], &[]),
            "- [A](a.md) – D\n"
        );
    }

    // [FR-081]
    #[test]
    fn 折り畳み参照のラベルは変えず要約だけ更新されtitle_mismatchが残る() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let text = "- [旧][] — x\n\n[旧]: a.md\n";
        let out = upd(text, &docs, &["docs/a.md"], &[]);
        assert_eq!(out, "- [旧][] — D\n\n[旧]: a.md\n");
        let a = typed("A", Some("D"));
        let set = issues(&[("docs/index.md", out.as_str()), ("docs/a.md", a.as_str())]);
        assert!(has(&set, ReasonCode::TitleMismatch, "docs/a.md"), "{set:?}");
        assert!(set
            .iter()
            .all(|i| i.reason != ReasonCode::DescriptionMismatch));
    }

    // [FR-083]
    #[test]
    fn 直前に項目がある状態で削除すると子項目は直前の項目の下に残る() {
        let docs = [
            doc("docs/a.md", "A", Some("D")),
            doc("docs/b.md", "B", Some("DB")),
        ];
        let files = ["docs/a.md", "docs/b.md"];
        let text = "- [A](a.md) — D\n- [G](gone.md) — g\n  - [B](b.md) — DB\n";
        assert_eq!(
            upd(text, &docs, &files, &[]),
            "- [A](a.md) — D\n  - [B](b.md) — DB\n"
        );
    }

    // [FR-083]
    #[test]
    fn 複数行エントリの削除で末尾行まで消える() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let text = "- [G](gone.md) — first\n  second line\n- [A](a.md) — D\n";
        assert_eq!(upd(text, &docs, &["docs/a.md"], &[]), "- [A](a.md) — D\n");
    }

    // [FR-085]
    #[test]
    fn 書き込みはrename失敗時に同じディレクトリの一時ファイルを残さない() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("index.md");
        // rename 先がディレクトリなので失敗する。
        std::fs::create_dir(&target).unwrap();
        assert!(write_atomic(&target, "x").is_err());
        let names: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, ["index.md"]);

        let ok = dir.path().join("ok.md");
        write_atomic(&ok, "y").unwrap();
        assert_eq!(std::fs::read_to_string(&ok).unwrap(), "y");
        assert!(std::fs::read_dir(dir.path()).unwrap().all(|e| !e
            .unwrap()
            .file_name()
            .to_string_lossy()
            .ends_with(".tmp")));
    }

    // ---- review fixes ----------------------------------------------------

    // [FR-081]
    #[test]
    fn エスケープされた角括弧を含むリンク文は壊れずに冪等に書き換わる() {
        let docs = [doc("docs/a.md", "[x] y", Some("D"))];
        let files = ["docs/a.md"];
        let once = upd("- [\\[x\\]](a.md) — d\n", &docs, &files, &[]);
        assert_eq!(once, "- [\\[x\\] y](a.md) — D\n");
        assert_eq!(upd(&once, &docs, &files, &[]), once);
    }

    // [FR-081]
    #[test]
    fn 各リンク形式でリンク文の範囲は元のソースの閉じ括弧までになる() {
        let e = &parse_entries("- [a\\]b](a.md \"t\") — d\n")[0];
        assert_eq!(e.link_text, "a\\]b");
        let e = &parse_entries("- [a *b*][r] — d\n\n[r]: a.md\n")[0];
        assert_eq!(e.link_text, "a *b*");
        assert_eq!(e.description, "d");
        let e = &parse_entries("- [a\\]][] — d\n\n[a\\]]: a.md\n")[0];
        assert_eq!(e.link_text, "a\\]");
        assert_eq!(e.description, "d");
        let e = &parse_entries("- [a] — d\n\n[a]: a.md\n")[0];
        assert_eq!(e.link_text, "a");
        assert_eq!(e.description, "d");
        let e = &parse_entries("- [](a.md) — d\n")[0];
        assert_eq!(e.link_text, "");
    }

    // [FR-081]
    #[test]
    fn ハードブレークとソフトブレークの直後の要約は1行に畳まれる() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let files = ["docs/a.md"];
        assert_eq!(
            upd("- [a](a.md)  \n  hard\n", &docs, &files, &[]),
            "- [A](a.md) — D\n"
        );
        assert_eq!(
            upd("- [a](a.md)\n  soft\n", &docs, &files, &[]),
            "- [A](a.md) — D\n"
        );
    }

    // [FR-082]
    #[test]
    fn バックスラッシュはエスケープされ再パースで元のタイトルに戻る() {
        let docs = [doc("docs/a.md", "a\\", Some("D"))];
        let out = upd("", &docs, &["docs/a.md"], &[]);
        assert_eq!(out, "- [a\\\\](a.md) — D\n");
        let e = &parse_entries(&out)[0];
        assert_eq!(unescape_brackets(&e.link_text), "a\\");
        assert_eq!(upd(&out, &docs, &["docs/a.md"], &[]), out);
        assert_eq!(unescape_brackets("\\\\ \\[ \\] \\x"), "\\ [ ] \\x");
    }

    // [FR-081]
    #[test]
    fn 要約の角括弧とバックスラッシュもエスケープされ比較で不一致にならない() {
        let docs = [doc("docs/a.md", "T", Some("a [b] c\\d"))];
        let files = ["docs/a.md"];
        let once = upd("- [T](a.md) — old\n", &docs, &files, &[]);
        assert_eq!(once, "- [T](a.md) — a \\[b\\] c\\\\d\n");
        let e = &parse_entries(&once)[0];
        assert_eq!(unescape_brackets(&e.description), "a [b] c\\d");
        assert_eq!(upd(&once, &docs, &files, &[]), once);
    }

    // [FR-083]
    #[test]
    fn 除外名の配下を指す存在しないエントリ行は削除されない() {
        let docs = [doc("docs/a.md", "A", Some("D"))];
        let files = ["docs/a.md"];
        let text = "- [A](a.md) — D\n- [X](vendor/x.md) — x\n- [G](gone.md) — g\n";
        let excluded = vec!["vendor".to_string()];
        let out = update_index(
            text,
            "docs/index.md",
            &tree_of(&files),
            &docs,
            &[],
            &RepoFiles::new(files.iter().copied()),
            &[],
            &excluded,
        );
        assert_eq!(out, "- [A](a.md) — D\n- [X](vendor/x.md) — x\n");
    }

    // [FR-071]
    #[test]
    fn 改行crを含むdescriptionは要約なし() {
        let files = [("docs/cr.md", "---\ntype: X\ndescription: \"a\\rb\"\n---\n")];
        let docs = collect(&files).documents;
        assert_eq!(docs[0].description, None);
    }

    // [FR-071]
    #[test]
    fn 子の索引のフロントマターが壊れていればタイトルと要約の照合をしない() {
        let b = typed("B", Some("DB"));
        let files = [
            ("docs/index.md", "- [S](sub/) — 何か\n"),
            (
                "docs/sub/index.md",
                "---\ntitle: [\n---\n- [B](b.md) — DB\n",
            ),
            ("docs/sub/b.md", b.as_str()),
        ];
        let set = issues(&files);
        for r in [
            ReasonCode::TitleMismatch,
            ReasonCode::DescriptionMismatch,
            ReasonCode::MissingDirectoryDescription,
        ] {
            assert!(set.iter().all(|i| i.reason != r), "{set:?}");
        }
    }

    // [FR-071]
    #[test]
    fn 子の索引のフロントマターが壊れていれば親のエントリを書き換えない() {
        let files = ["docs/index.md", "docs/sub/index.md"];
        let mut m = meta("docs/sub/index.md", "sub", None);
        m.invalid = true;
        let text = "- [Old](sub/) — 古い\n";
        assert_eq!(upd_meta(text, &[], &[m.clone()], &files, &[]), text);
        // Not appended as an unlinked child either.
        assert_eq!(upd_meta("", &[], &[m], &files, &["docs/sub/index.md"]), "");
    }

    // [FR-071]
    #[test]
    fn 最初のh1が空なら次のh1を探さずファイル名にフォールバックする() {
        let t = fm("---\ntype: X\n---\n#\n\n# Second\n");
        assert_eq!(document_title("docs/foo.md", &t), "foo");
    }

    // [FR-069]
    #[test]
    fn 強調を含むリンク文はソース文字列のまま扱われる() {
        let e = &parse_entries("- [*a*](x.md)\n")[0];
        assert_eq!(e.link_text, "*a*");
    }

    // [FR-076]
    #[test]
    fn 山括弧とtitle付きの宛先のbroken_entryのtargetは解釈後のdestinationになる() {
        let files = [
            (
                "docs/index.md",
                "- [x](<gone file.md> \"t\")\n- [a](a.md)\n",
            ),
            ("docs/a.md", &typed("a", Some("d"))),
        ];
        let set = issues(&files);
        assert_eq!(
            detail_of(
                &set,
                ReasonCode::BrokenEntry,
                "docs/index.md -> gone file.md"
            ),
            "target does not exist"
        );
    }

    // [FR-079]
    #[test]
    fn 根が子孫を列挙していても直近の親が列挙していなければunlinked_indexになる() {
        let files = [
            ("docs/index.md", "- [a](a/) — A\n- [a/b](a/b/) — B\n"),
            ("docs/a/index.md", "- [x](x.md)\n"),
            ("docs/a/x.md", &typed("x", Some("d"))),
            ("docs/a/b/index.md", "- [y](y.md)\n"),
            ("docs/a/b/y.md", &typed("y", Some("d"))),
        ];
        let set = issues(&files);
        assert!(has(&set, ReasonCode::UnlinkedIndex, "docs/a/b/index.md"));
        assert!(!has(&set, ReasonCode::UnlinkedIndex, "docs/a/index.md"));
    }

    // [FR-082]
    #[test]
    fn 子索引の追加は直近の親の索引の末尾にだけ行われる() {
        let files = [
            "docs/index.md",
            "docs/a/index.md",
            "docs/a/b/index.md",
            "docs/a/x.md",
        ];
        let tree = tree_of(&files);
        let repo = RepoFiles::new(files.iter().copied());
        let child = vec!["docs/a/b/index.md".to_string()];
        let metas = [
            meta("docs/a/index.md", "A", Some("DA")),
            meta("docs/a/b/index.md", "B", Some("DB")),
        ];
        let out = update_index(
            "- [x](x.md)\n",
            "docs/a/index.md",
            &tree,
            &[],
            &metas,
            &repo,
            &child,
            &test_excluded(),
        );
        assert_eq!(out, "- [x](x.md)\n- [B](b/) — DB\n");
        let root = update_index(
            "- [A](a/) — DA\n",
            "docs/index.md",
            &tree,
            &[],
            &metas,
            &repo,
            &[],
            &test_excluded(),
        );
        assert_eq!(root, "- [A](a/) — DA\n");
    }
}