konoma 0.28.5

Terminal file browser built for AI pair-programming — full-screen previews (Markdown, images, PDF, CSV), a git suite (jj/Jujutsu in preview), and an agent-watch mode that follows your AI's edits (macOS and Linux)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
//! A structural block model of a preprocessed Markdown document, built by walking
//! `pulldown-cmark`'s own event stream **exactly once** — the first step of what was, when this
//! comment was originally written, a planned rendering refactor (`md-block-walk`). That refactor has
//! since completed (`479df2c`, `defd06e`): `crate::preview::markdown::render` — this module's own
//! sibling, built on `Doc` — is now the **sole** production Markdown renderer
//! (`render_markdown_with_images` calls `render::render_doc` directly and unconditionally, with no
//! fallback), and the legacy renderer this paragraph used to contrast it with (deriving block
//! structure from tui-markdown's *rendered output*) no longer exists — `tui-markdown` itself was
//! dropped entirely once nothing called into it any more. `Doc::parse` here still records the single
//! event stream that renderer reads every leaf block's inline content from (`Doc.events`), with no
//! second parse of any kind; see that module's own doc comment.
//!
//! (A handful of line-scanners in the parent module — `code_block_mask`/`structure_mask`/
//! `code_block_source_locs`/`task_source_locs` and others — still exist independently of `Doc`, for
//! write-back/copy purposes over the *rendered* lines rather than the model; whether they remain
//! necessary now that the `Doc`-based renderer is the only one was not re-audited as part of this
//! comment fix.)
//!
//! ## Why this exists
//!
//! Every one of the "renderer vs. scanner disagree" bugs this file's neighbors document at length
//! (`parser_code_blocks`'s doc comment alone lists this as the *seventh* recurrence of the same
//! shape) comes from the same root cause: konoma currently has no single source of truth for "what
//! block is this text inside of". The render path infers it from styled output; the copy/toggle
//! scanners infer it by re-implementing CommonMark's own block rules by hand. `Doc`/`Block` here is
//! meant to become *that* single source of truth — built once, by asking the real parser, with
//! byte ranges precise enough that a future `y c` or checkbox-toggle can slice the input directly
//! instead of re-deriving "which block is the Nth one on screen" via a count-guard.
//!
//! "Built once" is not just a byte-range promise: `Doc::parse` calls `pulldown_cmark::Parser::new_ext`
//! exactly one time, over the *whole* document, and never re-parses any substring of it for any
//! reason — not for a block's own inline content, not for a tight list item's stray inline run,
//! nowhere. An earlier version of `render.rs` re-parsed each `Heading`/`Paragraph`'s own byte range
//! in isolation instead, which meant a reference-style link (`[text][ref]`) whose `[ref]: url`
//! definition lived in a different top-level block could never resolve (the definition and the
//! reference never shared a re-parsed slice) — see `Doc.events`'s own doc comment for how a leaf
//! block gets at its inline content without that cost today.
//!
//! ## What text this model expects
//!
//! `Doc::parse` takes whatever string it is given and walks it directly — it does **not** strip
//! front matter, renumber footnotes, or convert inline HTML tags (`<kbd>`, `<br>`, ...) itself.
//! Those are konoma's own source pre-passes (`strip_front_matter`, `process_footnotes`,
//! `process_inline_html`, all in the parent module), run once, in that order, before the render
//! pipeline ever reaches tui-markdown — the result is `MdCache::pre_src` in `App`. A caller that
//! wants this model to agree with what the screen shows must hand it that same preprocessed text,
//! not the raw file. `md_model_snapshot_tests` (in `src/app/`) does exactly this, via
//! `md_snapshot_tests::pre_src_for` — the same helper the rendering golden-snapshot test uses, so
//! the two can never quietly drift onto different inputs.
//!
//! ## Scope
//!
//! Block-level structure only — this file never builds an inline-content *tree* (no `Emphasis`/
//! `Link`/`Code` node types here at all). Inline content nested *inside* a `TableCell` (emphasis,
//! links, code spans, images, ...) is walked *past* and recorded nowhere — see `skip_inline_to`. A
//! `Heading`'s or `Paragraph`'s own inline content is the one place this model *does* keep something:
//! not a tree, just *where* that content sits in the single, whole-document event stream every block
//! here was parsed from (`Doc.events`) — an index range (`BlockKind::Heading.inline` /
//! `BlockKind::Paragraph.inline`), the same way `BlockKind::CodeBlock.body_spans` names a code
//! block's own content by *byte* range into `src` instead. Either way, a caller wanting the actual
//! content still has to walk raw `pulldown_cmark::Event`s itself (`render.rs`'s own `walk_inline`
//! does exactly this) — this model draws the boundary, not the picture.
//!
//! `mermaid`-tagged fences are represented as an ordinary `CodeBlock { lang: Some("mermaid"), .. }`,
//! exactly like any other fenced block; the parent module's own choice to render some of those as
//! diagrams instead of code is a rendering decision, and this is a structural model of the document,
//! not of the screen.
//!
//! One exception, not a violation of the above: a **tight** list item's own inline text, which
//! pulldown-cmark reports with no enclosing `Paragraph` at all (unlike a loose item's), is still
//! coalesced into a synthetic one-off `Paragraph` node (`collect_stray_inline_run`), rather than
//! silently dropped — see `BlockKind::ListItem`'s own doc comment for why leaving it unrepresented
//! was a real gap, not a scope choice: without *some* leaf block covering that text, there would be
//! nothing for a future renderer built on `Doc` to read the item's own content from at all. That
//! synthetic `Paragraph` gets an `inline` range the same way a real one does — see
//! `collect_stray_inline_run`'s own doc comment for exactly which events it spans.
//!
//! `#![allow(dead_code)]`: this comment predates the `md-block-walk` migration completing. `Doc::parse`
//! itself is no longer dead code in a plain, non-test build — `render.rs`'s `render_doc` (called
//! unconditionally by the production `render_markdown_with_images`) reads from it directly. Whether
//! every other item in this module still needs the `allow` was not re-audited as part of this comment
//! fix; do not assume it still holds without checking.
#![allow(dead_code)]

use std::ops::Range;

use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd};

/// A parsed document: its top-level blocks, in source order, plus the single event stream
/// `Doc::parse` walked to build them.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Doc<'a> {
    /// The parser's own event stream, in source order, exactly as `Doc::parse`'s one walk consumed
    /// it (see `Walker::next`) — every `Event`/byte-range pair pulldown-cmark reported for the
    /// *whole* document, not merely the ones some `Block` below happens to reference. A leaf block
    /// whose own content is purely inline (`BlockKind::Heading`/`BlockKind::Paragraph`) names its
    /// own slice of this by *index* range (`inline`) rather than holding a copy of it, the same way
    /// `BlockKind::CodeBlock` names its content by *byte* range (`body_spans`) into `src` instead of
    /// copying it — `doc.events[block_inline_range]` is exactly the slice a renderer needs, with no
    /// second parse of any kind (see the module doc comment's "Why this exists" section for why that
    /// matters: a per-block re-parse cannot resolve a reference-style link whose definition lives in
    /// a different block, among other things a whole-document parse gets right "for free").
    pub events: Vec<(Event<'a>, Range<usize>)>,
    pub blocks: Vec<Block>,
}

/// One block-level construct and its extent in the source `Doc::parse` was given.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Block {
    pub kind: BlockKind,
    /// Byte range of the **entire** block in the input string — for a fenced code block this
    /// includes the fence lines and the info string; for a list item it includes the marker and
    /// every line the item owns, nested content included. Always a `pulldown-cmark`-reported
    /// range, so its endpoints are guaranteed to land on UTF-8 char boundaries.
    pub src: Range<usize>,
    /// Nested blocks (a list's items, an item's own content, a quote's body). Empty for every
    /// leaf kind (`Heading`, `Paragraph`, `CodeBlock`, `Table`, `Html`, `ThematicBreak`).
    pub children: Vec<Block>,
}

/// What kind of block-level construct a [`Block`] is, and the kind-specific data attached to it.
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum BlockKind {
    Heading {
        level: u8,
        /// Index range into `Doc.events` for this heading's own inline content: every event
        /// strictly *between* its `Start(Heading)` and matching `End(Heading)`, in source order,
        /// with **neither** endpoint included — there is nothing left in this slice for a reader to
        /// skip past; it is exactly what a fresh inline walk of this heading's own text would
        /// report (see `render.rs`'s `render_heading`, the one caller today). Always contained in
        /// `0..Doc.events.len()` and never decreasing; empty for a heading with no inline content at
        /// all. Computed by `parse_container`'s own `Tag::Heading` arm — see that call site for the
        /// exact bookkeeping (`Walker::pos`, read once before and once after the content is
        /// consumed).
        inline: Range<usize>,
        /// `{#id .class key=value}` heading-attribute syntax
        /// (`Options::ENABLE_HEADING_ATTRIBUTES`), read straight off `Tag::Heading`'s own fields and
        /// converted to owned `String`s so `BlockKind` itself never needs `Doc`'s own lifetime —
        /// `None`/empty exactly when the source used none, matching pulldown-cmark's own convention.
        id: Option<String>,
        classes: Vec<String>,
        /// The first item of each tuple is the attribute name, the second (if present) its value —
        /// matching `Tag::Heading.attrs`'s own shape exactly.
        attrs: Vec<(String, Option<String>)>,
    },
    /// A paragraph of inline content — real (pulldown-cmark reports one for a block quote's own
    /// text, a *loose* list item's, ...) or synthetic (`collect_stray_inline_run`'s one-off node for
    /// a *tight* list item's own inline text, which pulldown-cmark reports with no enclosing
    /// `Paragraph` at all — see that function's own doc comment, and `BlockKind::ListItem`'s).
    Paragraph {
        /// Same convention as `Heading.inline` above for a real paragraph — the events strictly
        /// between its `Start`/matching `End`, excluding both, and (for a loose list item's *first*
        /// paragraph specifically) excluding its own leading `Event::TaskListMarker` too, if it has
        /// one (see `parse_item_task_and_children`'s own doc comment for why that marker is
        /// recorded on `ListItem.task` instead, and never inside any paragraph's own `inline` range).
        /// For the synthetic case, exactly the events `collect_stray_inline_run` itself consumed —
        /// there is no wrapping `Start`/`End` pair to exclude in the first place, since
        /// pulldown-cmark never reported one.
        inline: Range<usize>,
    },
    /// A fenced (```` ``` ```` / `~~~`) or indented (4+ column) code block.
    CodeBlock {
        /// The fence's info string verbatim (e.g. `"rust"`, or `"rust {.line-numbers}"`), matching
        /// the render pipeline's own convention of using the *whole* trimmed info string as the
        /// language label rather than splitting it at whitespace (see `flush_code_run`'s `lang`).
        /// Always `None` for an indented block (CommonMark gives those no info string at all).
        lang: Option<String>,
        fenced: bool,
        /// Byte ranges of the block's **content only**, one per `Event::Text` pulldown-cmark
        /// reports between this block's `Start`/`End(CodeBlock)`, in source order — the fence
        /// lines, the info string, and any leading indentation the block's own container (a list
        /// item, a block quote) imposes on every line are never part of any of these ranges,
        /// because pulldown-cmark never reports them as text in the first place.
        ///
        /// ## Why a list of ranges, not one
        ///
        /// A single contiguous `Range<usize>` cannot represent a code block's content exactly
        /// whenever pulldown-cmark's own text excludes bytes that sit *between* two `Event::Text`
        /// spans — a continuation line's own share of a list item's or block quote's baseline
        /// indentation; a literal `\r` consumed by line-ending normalization. Those bytes still lie
        /// inside `first_text.start..last_text.end`, so a single range spanning that whole interval
        /// would include them even though pulldown-cmark's own reading of "the content" does not.
        /// This happens for: any indented block of 2+ lines; any fenced or indented block of 2+
        /// lines nested inside a list item or block quote; two indented chunks CommonMark glues
        /// across a blank line; and *any* code block at all in a CRLF-encoded file, even a single
        /// line. Recording each `Event::Text`'s own range instead of merging them skips exactly
        /// those gaps — there is no interval that both names only content bytes *and* has a hole in
        /// the middle of it, so representing this exactly needs a list.
        ///
        /// ## What concatenating them gives you
        ///
        /// `code_body_text(&body_spans, src)` — join every range's slice, in that order, then strip
        /// at most one trailing `\n` — reconstructs the block's content byte for byte, matching what
        /// `parser_code_blocks` computes by joining the same events' `Event::Text` *payloads*
        /// directly, for **every** code block in the corpus outside a block quote, not just the ones
        /// whose content happens to arrive as a single span; see
        /// `code_body_text_matches_parser_code_blocks_for_every_non_quote_code_block_in_the_corpus`.
        ///
        /// An empty code block (an opening fence immediately followed by a closing one — no content
        /// line at all) has no `Event::Text` to report, so its `body_spans` is simply empty;
        /// `code_body_text` on an empty slice returns `""`, matching that (empty) content.
        ///
        /// ## Code blocks inside a block quote
        ///
        /// This model does not special-case block-quote nesting at all: a code block whose nearest
        /// container is (or is nested inside) a `Quote` is represented exactly like any other one —
        /// present in `Block::children`, with a `body_spans` that reconstructs its content the same
        /// way. `parser_code_blocks`, the render pipeline's own scanner this field is cross-checked
        /// against, deliberately does **not** count these — its `quote_depth > 0` gate exists only
        /// because nothing downstream of it currently offers a "copy this code block" affordance for
        /// quoted text, not because a quoted code block fails to structurally exist. This model is
        /// therefore an intentional superset of what `parser_code_blocks` reports; a future renderer
        /// built on top of `Doc` gains the ability to handle quoted code blocks as a byproduct of
        /// switching to it, without this model itself needing to change.
        body_spans: Vec<Range<usize>>,
    },
    List {
        ordered: bool,
        /// The first item's number, for an ordered list (`Tag::List(Some(n))`). `None` for a
        /// bullet list, and also `None` for an ordered list that happens to start at a number
        /// pulldown-cmark did not report (never happens in practice — kept `Option` only because
        /// the tag itself is).
        start: Option<u64>,
    },
    /// A list item. Its checkbox marker, if it has one — GFM task-list syntax only recognizes a
    /// literal space, `x`, or `X` between the brackets (see `Task`'s doc comment) — is `task`; its
    /// own content is `Block::children`: a `Paragraph` (plus whatever follows) for a loose item, or
    /// nested lists/code/quotes for a tight one, if it has any of those. A tight item's own inline
    /// text — which pulldown-cmark emits with **no** enclosing `Paragraph` at all, unlike a loose
    /// item's — is still represented here, as a synthetic `Paragraph` `parse_blocks` builds on the
    /// fly (`collect_stray_inline_run`) spanning exactly that inline run, not simply absent the way
    /// an earlier version of this model left it; see that function's own doc comment.
    ListItem { task: Option<Task> },
    /// A block quote. `alert` is `Some` when the quote's first line matches GitHub's `> [!TYPE]`
    /// alert-header syntax, decided by calling the render pipeline's own `parse_alert_header` on
    /// that line — not a second classifier of this module's own (see `alert_kind_of`). `alert_title`
    /// is that same call's own second return value, the header's optional Obsidian-style trailing
    /// title (`> [!NOTE] My title` → `"My title"`) — kept as a sibling field rather than folded into
    /// `alert` itself (`Option<(AlertKind, String)>`) so every existing `alert`-only match arm needs
    /// only `..` added, not a payload-shape rewrite. Empty whenever `alert` is `None` (not an alert
    /// at all) or the header carried no title text — `alert_kind_of` never invents one.
    Quote {
        alert: Option<AlertKind>,
        alert_title: String,
    },
    /// A GFM table. `aligns` is the delimiter row's per-column alignment, straight from
    /// pulldown-cmark (`Alignment::None` for a column with no `:`, matching CommonMark — *not*
    /// the render pipeline's own `ColAlign`, which is a display-time choice with no "unspecified"
    /// state and defaults it to `Left`; see this variant's construction site for why the two are
    /// deliberately not the same type). `rows` is every row's cells, in source order, header row
    /// first (`rows[0]`) followed by the body rows (`rows[1..]`) — pulldown-cmark's own event
    /// stream keeps no other marker distinguishing them, since a GFM table has exactly one header
    /// row by construction. Each cell is its own byte range (the pipe-delimited span including its
    /// padding spaces); cell content is inline, so — like `Paragraph`/`Heading` — it is not
    /// represented as a nested `Block`.
    Table {
        aligns: Vec<Alignment>,
        rows: Vec<Vec<Range<usize>>>,
    },
    /// An HTML block (one of CommonMark's six HTML-block types — a `<div>`, a comment, a
    /// `<!DOCTYPE>`, ...). `tag` is a best-effort tag name read off the block's own opening line,
    /// `None` for a block that does not open with a plain `<name ...>`/`</name>` tag (a comment, a
    /// processing instruction, a declaration, a CDATA section). `<details>`/`</details>` are
    /// identified via the render pipeline's own `details_open_tag`/`is_details_close` predicates
    /// rather than the generic name scan, so this can never drift from what the renderer itself
    /// considers a details tag; everything else falls back to the generic scan (`html_tag_name`),
    /// which is not a competing *judgment* about anything the renderer decides — it is a plain
    /// "what's the first tag's name" read with no bearing on any other pass's behavior.
    ///
    /// Note pulldown-cmark does not merge a `<details>`/`<summary>` pair and the later `</details>`
    /// into one block the way `split_details` (the renderer's own peel) does — CommonMark only glues
    /// *consecutive, blank-line-free* HTML-tag lines into one `HtmlBlock`, so `<details>`,
    /// `<summary>...</summary>`, and (once the body paragraph in between closes it) the standalone
    /// `</details>` still parse here as three separate top-level blocks, exactly as this once-flat
    /// doc comment described. `fold_details` (run once, at every `parse_blocks` return point — see
    /// its own doc comment) folds a **well-formed** instance of that shape — a `<details ...>`
    /// opening tag whose closing `</details>` later shows up as its own, independent `Html` leaf
    /// (blank-line-separated on both sides, the shape every real-world `<details>` block in this
    /// codebase's own samples and every diff-harness case that now matches production uses) — into
    /// `BlockKind::Details`, matching `split_details`'s own "one folded block" view without a second
    /// parse. A `Details` block's own `Block::children` is exactly the sibling blocks `fold_details`
    /// found sitting between that open tag and its matching close, in source order — the same
    /// content a caller reading `split_details`'s own `body` string would get, structured instead of
    /// flat.
    ///
    /// A **pathological or malformed** shape a raw-line scanner (`split_details`) can decompose but
    /// this model's own, real-parser-driven segmentation cannot — most commonly, `<details>` and
    /// `<summary>...</summary>` (or a nested `<details>`) glued onto the very same `HtmlBlock` with
    /// **no** blank line anywhere inside the whole construct, so pulldown-cmark itself never reports
    /// a separate sibling block for `fold_details` to search for a close among at all — still parses
    /// as a plain, unfolded `Html` leaf here, exactly as before this variant existed. This is not a
    /// silent content loss: a caller (`render.rs`'s own `contains_unsupported`) that does not know
    /// how to draw a raw `Html` leaf already reports the *whole* enclosing construct as out of scope
    /// rather than rendering something incomplete — see that function's own doc comment.
    ///
    /// `body_spans` names this block's own content the identical way `CodeBlock.body_spans` does —
    /// one byte range per `Event::Html` pulldown-cmark reports, in source order, rather than a single
    /// range into `src` — and for the identical reason: `Block::src` (the whole `HtmlBlock`, fence-
    /// to-fence) is one un-split byte range, so inside a block quote its later lines still carry that
    /// quote's own `>` marker verbatim, while pulldown-cmark's own per-line `Event::Html` ranges do
    /// not (confirmed directly, the same way `CodeBlock.body_spans`'s own doc comment describes for
    /// `Event::Text`: parsing `"> <div>\n> body\n> </div>\n"` reports `Start(HtmlBlock)` at
    /// `2..len`, its slice still `>`-prefixed on every line but the first, while each `Event::Html`
    /// range — `2..23`, `25..43`, `45..52` for that exact input — already excludes the marker). Empty
    /// for a block pulldown-cmark reports as `HtmlBlock` with no `Event::Html` at all (not observed in
    /// practice — every CommonMark HTML-block type has at least one line of content by construction —
    /// but not assumed away either, the same defensive stance `collect_code_body_spans` takes).
    /// `html_body_text(&body_spans, src)` reconstructs the content; see its own doc comment for
    /// exactly what "reconstructs" means here (unlike `code_body_text`, no trailing-newline stripping
    /// — see that function's own doc comment for why the two conventions differ).
    Html {
        tag: Option<String>,
        body_spans: Vec<Range<usize>>,
    },
    /// An HTML block that is one complete `<table> … </table>` — the shape a great many READMEs use
    /// for a side-by-side screenshot grid, and the one shape of raw HTML this model gives real
    /// structure to rather than leaving as an opaque `Html` leaf for the renderer to tag-strip line
    /// by line. Built by [`parse_html_table`] from the *same* `Html` block this would otherwise have
    /// been (see `parse_container`'s own `Tag::HtmlBlock` arm: the table scan runs on the already-
    /// collected `body_spans`, so recognizing one costs no second parse of anything and a block that
    /// fails the scan is emitted as an ordinary `Html` leaf, byte for byte as before this variant
    /// existed). `render.rs`'s own `render_html_table_from_model` draws it through the identical
    /// `TableCells`/`render_table_cells` pair a GFM `BlockKind::Table` goes through.
    ///
    /// `body_spans` is this block's own `Html.body_spans`, kept verbatim and for the identical reason
    /// (see that field's own doc comment): inside a block quote, `Block::src`'s own continuation
    /// lines still carry the `>` marker while these ranges never do. Every `HtmlTableCell.inner`
    /// below is a range into `src` that is only ever read back *through* these spans
    /// ([`html_body_text_in`]), so a quote-nested table's cell text comes out marker-free even when
    /// the cell spans several physical lines.
    ///
    /// ## What this deliberately does not model
    ///
    /// * **`colspan`/`rowspan`** — read as an ordinary single cell, the attribute ignored. A row
    ///   written with a `colspan="2"` therefore reports fewer cells than its neighbours and comes out
    ///   as a ragged row, which `render_table_cells` pads with an empty cell on the right.
    /// * **A nested `<table>`** — only `<tr>`/`<td>`/`<th>` at the *outer* table's own depth are
    ///   structural; everything inside a nested table stays part of the enclosing cell's `inner`
    ///   range and is flattened to text by the cell renderer. The outer table's own grid survives.
    /// * **`<caption>`** — its text sits outside every `<td>`/`<th>`, and nothing here collects it.
    ///   Rather than fold and drop it, a `<table>` carrying *any* non-whitespace character outside
    ///   its cells (a caption included) is not folded at all — see [`parse_html_table`]'s condition
    ///   4 — so its text is still shown, in full, by the ordinary `Html` path.
    ///
    /// All three are recorded as open items in `docs/STATUS.md`; none of them makes this fold *lose*
    /// a character, and the first two are pinned by tests that fix the exact degraded output.
    HtmlTable {
        /// Exactly what `Html.body_spans` would have held for this same block — see above.
        body_spans: Vec<Range<usize>>,
        /// Every `<tr>`'s cells, in source order. Never empty, and no row is ever empty
        /// (`parse_html_table` refuses to fold a table with no cell at all).
        rows: Vec<Vec<HtmlTableCell>>,
    },
    /// A `<details>` … `</details>` block, folded from what `Doc::parse` itself would otherwise have
    /// reported for its opening and closing tags (see `Html`'s own doc comment on exactly which
    /// shapes qualify, and `fold_details` for the folding algorithm). Two different shapes fold into
    /// this one variant — see `glued_body`'s own doc comment for the second:
    ///
    /// * **Well-formed** (open tag, body, close tag each its own sibling `Html` leaf, blank-line
    ///   separated): `Block::src` spans from the opening tag's own first byte through the closing
    ///   tag's own last byte (or through the end of input, when unclosed — matching `split_details`'s
    ///   own `close.unwrap_or(lines.len())` fallback), and `Block::children` is the sibling blocks
    ///   that sat between them, in source order — the block's own rendered body, already structured,
    ///   with no second parse of any substring needed to read it. `glued_body` is `None`.
    Details {
        /// The `open` HTML attribute this block's own `<details ...>` tag carried
        /// (`details_open_tag`'s own return value) — the document's own *declared* default, not a
        /// runtime toggle state: whether a given `Details` block is actually expanded or collapsed
        /// on screen is a per-render decision the render pipeline makes elsewhere (see
        /// `crate::preview::markdown::next_details_open`'s own doc comment), which this model has no
        /// opinion about and does not track.
        open_attr: bool,
        /// The `<summary>...</summary>` label text, tags stripped, computed by handing the render
        /// pipeline's own `extract_summary_body` the exact same byte range `split_details` itself
        /// would hand it for identical source text (see `fold_details`'s own doc comment for exactly
        /// which range that is) — not a second, model-side reimplementation of that extraction.
        /// Empty when the block has no `<summary>` tag at all, matching `extract_summary_body`'s own
        /// "no summary" fallback.
        summary: String,
        /// Byte range, into `Doc::parse`'s own whole-document `src`, of this block's own **glued**
        /// body — set only for the second, pathological shape `fold_details` also recognizes (see
        /// `glued_details_fold`'s own doc comment for exactly which glued shapes qualify, and which
        /// stay an ordinary, unfolded `Html` leaf instead): the open tag, its own `<summary>`, and its
        /// own close all landed in the *same*, single, literal `Html` leaf (no blank line anywhere in
        /// the whole construct — see `Html`'s own doc comment), so pulldown-cmark's one whole-document
        /// walk never reported any block-level events for the body at all — an HTML block's own
        /// interior is copied *literally*, per spec, so there is no finer structure in `Doc.events`
        /// for `Block::children` to name a slice of, the way a well-formed `<details>`'s body always
        /// can. `Block::children` is always empty exactly when this is `Some` (and never empty when
        /// this is `None` for anything but a genuinely empty well-formed body) — `render.rs`'s own
        /// `render_details_from_model` is the one reader, and does its own fresh, isolated
        /// `Doc::parse` over `src[glued_body]` to render real Markdown structure for it (see that
        /// function's own doc comment for why this is the one place this file's whole "no second
        /// parse of any substring, ever" promise has a documented exception, and why it is safe: the
        /// isolated re-parse's own output is *rendered* immediately, into plain `Line`s, never spliced
        /// back into this `Doc`'s own `blocks`/`events` — nothing downstream of `Doc::parse` ever
        /// reads a `Block`/index built from that second parse).
        glued_body: Option<Range<usize>>,
    },
    /// A thematic break (`---` / `***` / `___`).
    ThematicBreak,
}

/// One `<td>`/`<th>` of a [`BlockKind::HtmlTable`].
///
/// Deliberately shaped like a `BlockKind::Table` cell — a byte range into the document `Doc::parse`
/// was given, never an owned string — so both table paths hand the renderer the same *kind* of thing
/// and neither one needs a cell-text representation of its own (see `BlockKind::Table.rows`'s own doc
/// comment for that convention, and `BlockKind::HtmlTable.body_spans` for the one way reading this
/// range differs: it is sliced *through* the block's own `body_spans`, via [`html_body_text_in`],
/// never straight off `src`).
/// `Eq` is deliberately absent (unlike `Task`'s own derive): `pulldown_cmark::Alignment` — the type
/// `align` reuses rather than duplicating — implements `PartialEq` only, so `Block`'s own
/// `PartialEq` is all this can (and all it needs to) participate in.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct HtmlTableCell {
    /// Byte range of the cell's own **content** — everything strictly between its `<td …>`/`<th …>`
    /// tag's own closing `>` and its matching `</td>`/`</th>`'s own opening `<`, with neither tag
    /// included. Empty (`n..n`) for an empty cell (`<td></td>`). An unclosed cell (`<td>a` with no
    /// `</td>` before the next `<td>`/`</tr>`/`</table>`) ends where the tag that implicitly closed
    /// it begins — the same "omitted end tag" rule browsers apply.
    pub inner: Range<usize>,
    /// `true` for a `<th>`, `false` for a `<td>`. `render.rs`'s own `render_html_table_from_model` is
    /// what turns a *leading run of all-`<th>` rows* into `TableCells::header_rows`, and a lone `<th>`
    /// anywhere else into that one cell's own header styling — deciding that here would bake a
    /// display choice into the model (see `BlockKind::Table.aligns`'s own doc comment for the same
    /// model-vs-display split drawn one field over).
    pub header: bool,
    /// The cell's own `align="left|center|right"` attribute, matched case-insensitively on both the
    /// name and the value, `None` when the attribute is absent or names anything else (`justify`,
    /// `char`, a typo). Reuses `pulldown_cmark::Alignment` — the exact type `BlockKind::Table.aligns`
    /// already uses — rather than a second three-valued enum, but note `Alignment::None` is *not* how
    /// "no `align` attribute" is spelled here: this is `Option<Alignment>` precisely so an explicit
    /// `align` and an absent one stay distinguishable, which is what lets the renderer fall back to
    /// the *column's* alignment for a cell that declares none.
    pub align: Option<Alignment>,
}

/// A task-list checkbox marker (`- [ ]` / `- [x]` / `- [X]`).
///
/// GFM task-list syntax (`pulldown_cmark::Options::ENABLE_TASKLISTS`, the only extension this
/// module uses to recognize one at all) accepts exactly one character between the brackets: a
/// space, `x`, or `X` — nothing else, including any of konoma's own custom task states (`/`, `-`,
/// ..., configured via `ui.md_task_states`), is emitted as `Event::TaskListMarker` by the parser at
/// all; a line like `- [/] in progress` parses as an ordinary list item whose text happens to start
/// with `[/]`. A future integration that wants custom states recognized here needs to read the
/// bracket contents itself rather than rely on this event — see the task report this module's
/// commit was reviewed against for the measurement backing this note.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Task {
    /// The character currently written between the brackets in the source (`' '`, `'x'`, or
    /// `'X'`) — read directly off the byte at `state_at`, not inferred from
    /// `Event::TaskListMarker`'s own `bool` payload, which collapses `x` and `X` into the same
    /// "checked" value and so cannot tell them apart.
    pub state: char,
    /// Byte offset of that character within the string `Doc::parse` was given. `src[state_at]` is
    /// always `[state]`'s own byte; `src.as_bytes()[state_at - 1] == b'['` and
    /// `src.as_bytes()[state_at + 1] == b']'` always hold — `check_invariants` checks exactly this,
    /// over the whole corpus (via `model_invariants_hold_across_the_full_parity_corpus` and
    /// `model_invariants_hold_across_the_sample_md_files`), not just the handful of cases
    /// `task_marker_state_and_position_are_exact` spells out by hand — so a future in-place toggle
    /// can overwrite this one byte with no further bookkeeping.
    ///
    /// Unlike `BlockKind::CodeBlock.body_spans`, this needs no analogous "list of ranges" fix:
    /// pulldown-cmark reports `Event::TaskListMarker` as a single event whose own range is always
    /// exactly the three bytes `[`, the state character, `]` — never wider (confirmed against the
    /// scanner's own source, `scan_task_list_marker`) — regardless of how much whitespace precedes
    /// the bracket, what container the item is nested in, or CRLF line endings elsewhere on the
    /// line, because none of those bytes are *inside* the marker the way a continuation line's
    /// indentation sits *inside* a code block's `first_text.start..last_text.end`. There is no gap
    /// for a single contiguous range to fail to skip.
    pub state_at: usize,
}

/// One of the five GitHub alert types a block quote's header can declare
/// (`> [!NOTE]`/`[!TIP]`/`[!IMPORTANT]`/`[!WARNING]`/`[!CAUTION]`, plus the render pipeline's own
/// Obsidian aliases — see `AlertKind::parse`). Re-exported here (rather than a second enum with the
/// same variants) so `BlockKind::Quote.alert` is always in lockstep with what the renderer draws as
/// a callout box: adding a sixth alert type only ever means editing one enum.
pub(crate) use super::AlertKind;

/// The single walk `Doc::parse` performs over `src` (see the module doc comment: exactly one
/// `Parser::new_ext` call for the whole document, never a second one for any substring of it).
/// Wraps pulldown-cmark's own `Peekable<OffsetIter>` — `peek`/`next` behave identically to that
/// type's own methods from every call site's point of view, which is why every block-parsing
/// function below barely changed shape when this replaced a plain `Peekable<OffsetIter>` alias —
/// and additionally records, in `events`, a clone of every event `next()` actually consumes (never
/// one merely `peek`ed at and left alone). `events` becomes `Doc.events` once parsing finishes.
/// `pos()`, read once before and once after a leaf block's own inline content is consumed, is how
/// `BlockKind::Heading`/`BlockKind::Paragraph` — and the tight-list-item stray-run case, see
/// `collect_stray_inline_run` — each compute which slice of it is theirs; see those construction
/// sites for the exact convention each one uses (which markers, if any, a block's own `inline`
/// range does or does not include).
struct Walker<'a> {
    iter: std::iter::Peekable<pulldown_cmark::OffsetIter<'a>>,
    events: Vec<(Event<'a>, Range<usize>)>,
}

impl<'a> Walker<'a> {
    fn peek(&mut self) -> Option<&(Event<'a>, Range<usize>)> {
        self.iter.peek()
    }

    /// Consumes and returns the next event — identical, from the caller's point of view, to
    /// `Peekable::next` — but first appends a clone of it to `self.events`. Cheap, not merely
    /// convenient: `Event`/`Range<usize>` are both `Clone`, and every event this walk ever sees
    /// borrows from `src` via `CowStr::Borrowed` (a fresh `Parser`, never a second one over a
    /// substring — see the module doc comment), so cloning one copies a couple of machine words,
    /// never allocates.
    fn next(&mut self) -> Option<(Event<'a>, Range<usize>)> {
        let item = self.iter.next()?;
        self.events.push(item.clone());
        Some(item)
    }

    /// The index the *next* `next()` call will record its event at — equivalently, how many events
    /// have been consumed (and recorded) so far. See the struct's own doc comment for how a leaf
    /// block uses two readings of this (one before, one after consuming its own inline content) to
    /// compute an `inline: Range<usize>` into `Doc.events`.
    fn pos(&self) -> usize {
        self.events.len()
    }
}

impl<'a> Doc<'a> {
    /// Parses `src` — which the caller is responsible for having already run through konoma's own
    /// source pre-passes if it wants the result to match what the screen shows; see the module doc
    /// comment — into a block tree, walking pulldown-cmark's own event stream for the whole document
    /// exactly once (`Walker`). Every leaf block whose own content is purely inline
    /// (`BlockKind::Heading`/`BlockKind::Paragraph`) records where its share of that single stream
    /// sits, by index range, rather than being handed a copy of it or (as an earlier version of the
    /// renderer built on this model did) needing to re-parse its own byte range separately later.
    pub(crate) fn parse(src: &'a str) -> Doc<'a> {
        let mut w = Walker {
            iter: Parser::new_ext(src, parse_options())
                .into_offset_iter()
                .peekable(),
            events: Vec::new(),
        };
        let blocks = parse_blocks(&mut w, src);
        Doc {
            events: w.events,
            blocks,
        }
    }
}

/// The `pulldown-cmark` options this model's walk uses. Built from the render pipeline's own
/// `markdown_parse_options` — by calling it, not by copying its six `insert` calls — so the two
/// option sets can never independently drift the way that function's own doc comment warns two
/// *different* option sets reading the same document eventually do; this model asks about
/// everything the renderer's own scanners already ask about, plus exactly one extension:
///
/// * `ENABLE_TABLES` — the render pipeline turns this **off** (see `markdown_parse_options`'s doc
///   comment: konoma's own hand-written table renderer, `split_tables`, intercepts table text
///   *before* it ever reaches this parser, so the render pipeline's own parser is never asked to
///   understand a table at all). This model has no such renderer standing between it and the
///   table — it is the thing a future renderer would *read* structure from — so it needs
///   pulldown-cmark's real `Table`/`TableHead`/`TableRow`/`TableCell` events to fill in
///   `BlockKind::Table`.
///
/// Two extensions that would add whole new *event kinds* stay off, on purpose, because konoma
/// already has a hand-written source pre-pass for each, run on `src` *before* it reaches any
/// parser — turning the parser's own equivalent on here would not add anything this model uses, it
/// would just be a second, silently-discarded reading of text those pre-passes already consumed:
///
/// * `ENABLE_MATH` — `$...$`/`$$...$$` are extracted by `split_math`, replaced with synthetic image
///   placements, before the text a Markdown parser ever sees is finalized.
/// * `ENABLE_FOOTNOTES` — `[^id]`/`[^id]: ...` are rewritten by `process_footnotes` into plain
///   numbered references (and a trailing rendered list) as one of the very pre-passes that produces
///   the `pre_src` this model expects (see the module doc comment) — by the time text reaches here,
///   a real footnote reference has already become plain text, not `Event::FootnoteReference`.
///
/// `ENABLE_GFM` (which, among other things, would make pulldown-cmark itself recognize `> [!NOTE]`
/// and report a `BlockQuoteKind`) is left off for a third, different reason: konoma already has a
/// hand-written alert-header parser, `parse_alert_header`, and `BlockKind::Quote.alert` is filled
/// in by *calling that function* on the quote's own first line (`alert_kind_of`) rather than by a
/// second, competing classifier reading pulldown-cmark's own opinion.
///
/// `pub(crate)`: `md_model_snapshot_tests` (in `src/app/`) drives its own independent,
/// tree-free reading of the same event stream — `scan_reference_events` — off *this exact*
/// function too, for the same reason `Doc::parse` itself calls `markdown_parse_options`
/// instead of copying it: a completeness check built on a second, hand-copied option set could
/// pass or fail for reasons that have nothing to do with whether `Doc::parse` actually covers
/// everything the real parser reports.
pub(crate) fn parse_options() -> Options {
    let mut o = super::markdown_parse_options();
    o.insert(Options::ENABLE_TABLES);
    o
}

/// Parses the children of the container whose `Start` event `events` has already consumed (or, at
/// the top level, the whole document) — every top-level block-shaped event, recursing one level for
/// each, until either the iterator is exhausted (top level) or an `Event::End` is reached, which
/// this function consumes and returns after (so the caller never needs to consume its own
/// terminator separately; see `parse_container`'s `List`/`Item`/`BlockQuote` arms).
///
/// Every construct pulldown-cmark can emit at this level either gets a specific `BlockKind` (see
/// `parse_container`), is silently skipped, balanced, via `skip_inline_to` (a construct this model
/// never represents at all — a footnote definition, a metadata block, ...; see the module doc
/// comment and `is_unmodeled_container_tag`), or — the one shape this loop does not simply hand off
/// to `parse_container` — is a **tight list item's own inline content, reaching this level with no
/// enclosing `Paragraph` at all**. Pulldown-cmark's tight/loose convention (`Task`'s doc comment
/// documents the identical shift for a task marker) omits the wrapping tag entirely for a tight
/// item, so the very next event here can legitimately be a plain `Text`/`Code`/... or even the
/// `Start` of an inline construct like `Strong`/`Link` (`is_inline_start_tag`) — either shape starts
/// a run `collect_stray_inline_run` coalesces into one synthetic `Paragraph`, rather than the
/// content being silently dropped the way an earlier version of this function left it (see the
/// completeness invariants in `md_model_snapshot_tests` that gap was caught by, and
/// `BlockKind::ListItem`'s own doc comment). Nothing here can desync the event stream either way:
/// every `Start` this loop sees — whether routed to `parse_container` or folded into a stray run —
/// is fully consumed (recursively, down to its own matching `End`) before the loop looks at the
/// next event.
///
/// A thin wrapper around [`parse_blocks_raw`], the actual event-walking loop: this level's own
/// sibling list is run through [`fold_details`] exactly once, right before it is handed back to
/// whichever caller asked for it — the top-level `Doc::parse`, or `parse_container`'s own
/// `List`/`Item`/`BlockQuote` arms, each of which calls `parse_blocks` (never `parse_blocks_raw`
/// directly), so a `<details>` block gets folded at *every* nesting depth this model builds a fresh
/// sibling list at, not merely the top of the document.
fn parse_blocks(events: &mut Walker, src: &str) -> Vec<Block> {
    fold_details(parse_blocks_raw(events, src), src)
}

/// The event-walking loop `parse_blocks` wraps — same signature, same contract (see that function's
/// own doc comment for what a "sibling list" here means and how a tight list item's own bare inline
/// content is handled) — split out purely so `parse_blocks` itself can run [`fold_details`] over the
/// result at a single, guaranteed exit point (this function still returns early, via `Event::End(_)
/// => return out`, for a `List`/`Item`/`BlockQuote`'s own children — `parse_blocks`'s own fold runs
/// *after* either exit, uniformly).
fn parse_blocks_raw(events: &mut Walker, src: &str) -> Vec<Block> {
    let mut out = Vec::new();
    while let Some((ev, range)) = events.next() {
        match ev {
            Event::End(_) => return out,
            Event::Start(tag) if is_inline_start_tag(&tag) => {
                // The `next()` call above already recorded this `Start(tag)` — it is the stray
                // run's own first event, so `events.pos() - 1` (its index) is where the run's
                // `inline` range starts; see `collect_stray_inline_run`'s own doc comment.
                let inline_start = events.pos() - 1;
                let run = collect_stray_inline_run((Event::Start(tag), range), events);
                let inline = inline_start..events.pos();
                out.push(leaf(BlockKind::Paragraph { inline }, run));
            }
            Event::Start(tag) => {
                if let Some(block) = parse_container(tag, range, events, src) {
                    out.push(block);
                }
            }
            Event::Rule => out.push(Block {
                kind: BlockKind::ThematicBreak,
                src: range,
                children: Vec::new(),
            }),
            other if is_stray_inline_leaf(&other) => {
                let inline_start = events.pos() - 1;
                let run = collect_stray_inline_run((other, range), events);
                let inline = inline_start..events.pos();
                out.push(leaf(BlockKind::Paragraph { inline }, run));
            }
            // `Event::TaskListMarker` reaching this loop at all (rather than being consumed by
            // `parse_item_task_and_children`, the only place that ever looks for one, at one of
            // the two positions it can legitimately appear) is not reachable for well-formed
            // input — a marker only ever exists as the first event of an item's own content.
            // Ignored rather than treated as an error: never crashing on any input pulldown-cmark
            // accepts is principle #3 (see `CLAUDE.md`), and there is no well-defined block to
            // build from three stray bytes that were supposed to be a list item's own marker.
            _ => {}
        }
    }
    out
}

/// Folds a `<details>` opening `Html` leaf and the sibling blocks that follow it, up to (and
/// swallowing) the first later sibling that is itself a `</details>`-closing `Html` leaf, into one
/// `BlockKind::Details` container — reshaping the *already-parsed* sibling list one `parse_blocks`
/// call just built (`blocks`), never re-parsing `src`: `Doc::parse` still performs exactly one
/// `Parser::new_ext` call for the whole document (see the module doc comment).
///
/// ## Why "first close wins", not depth-aware nesting
///
/// This deliberately reproduces `split_details`'s own greedy contract, not a properly nesting-aware
/// one: scanning forward from an open tag, the *first* sibling whose own first line reads
/// `</details>` is taken as *this* block's close, however many further `<details>` opens sit between
/// them. A `<details>` reached only by being swallowed into another one's body this way is not
/// folded a second time here — it stays an ordinary, unfolded `Html` leaf inside `children`, exactly
/// the shape `contains_unsupported` (`render.rs`) already knows how to react to for a `Table` or
/// plain `Html` block found anywhere inside a `List`/`Quote`'s own subtree: the *whole* enclosing
/// construct is out of this stage's scope, not silently rendered with a gap in it. Matching
/// `collect_details_open`'s own contract (its doc comment: "a `<details>` nested inside another …
/// is swallowed and not counted separately") is the whole reason for choosing this over a
/// depth-aware match — see that function's own doc comment, and `BlockKind::Details.open_attr`'s,
/// for why the two must never disagree about which blocks the document-wide Tab-toggle ordinal
/// sequence counts.
///
/// ## Why this only ever succeeds for the well-formed shape
///
/// A close is only ever found among *sibling* blocks — pulldown-cmark's own HTML-block grammar
/// glues any run of consecutive, blank-line-free HTML-tag lines into a single `HtmlBlock` (see
/// `BlockKind::Html`'s own doc comment), so a `<details>`/`<summary>`/`</details>` written with no
/// blank line anywhere inside the whole construct arrives here as *one* `Html` leaf already, with no
/// separate sibling for this function to have found a close among in the first place — it is left
/// exactly as before this function existed, an unfolded `Html` leaf. This is not a narrower
/// approximation of `split_details`'s own boundary-finding that risks disagreeing with it on content
/// that *does* fold: for the shape this function does fold (open tag, body, close tag, each
/// separated from the next by at least one blank line — the shape every real `<details>` block in
/// this codebase's own samples uses), pulldown-cmark's block segmentation and `split_details`'s own
/// raw-line scan land on the identical boundaries.
///
/// ## The summary text
///
/// `extract_summary_body` — the render pipeline's own — is handed the exact same slice
/// `split_details` itself would compute for identical source text: from the byte right after the
/// open tag's own **first source line** (`line_after`, matching `lines[start + 1]`'s own start
/// offset) through the close tag's own `src.start` (matching `lines[body_end]`'s own start offset)
/// — or, when unclosed, through the end of the last child this function actually collected (**not**
/// `src.len()` for the whole document: unlike `split_details`, which re-parses a *fresh substring*
/// per recursion level and so can safely use "the end of what I was handed" as its own fallback,
/// this model's `src` is always the one, whole-document text at every nesting depth — bounding the
/// unclosed case to the children actually gathered, rather than to the document's own end, is what
/// keeps this from scanning into unrelated, later document content it was never asked about).
fn fold_details(blocks: Vec<Block>, src: &str) -> Vec<Block> {
    let mut out = Vec::with_capacity(blocks.len());
    let mut rest: std::collections::VecDeque<Block> = blocks.into();
    while let Some(b) = rest.pop_front() {
        let open_attr = match &b.kind {
            BlockKind::Html { tag: Some(t), .. } if t == "details" => {
                super::details_open_tag(first_source_line(src, &b.src))
            }
            _ => None,
        };
        let Some(open_attr) = open_attr else {
            out.push(b);
            continue;
        };
        if rest.is_empty() || html_leaf_contains_its_own_close(src, &b) {
            // Either nothing follows this open tag at this sibling level at all, or this leaf's own
            // *raw text* already runs past a `</details>` line of its own — pulldown-cmark glued
            // everything (a `<summary>`, a nested `<details>`, its own close, ...) into this one
            // `Html` leaf, with no blank line anywhere inside the construct to have split any of it
            // into separate siblings for this function to have found (`b.src` can run well past its
            // own first line even though there is exactly one sibling here — confirmed directly:
            // `"<details>\n<summary>A</summary>\n<details>\n<summary>Nested</summary>\n</details>\n\
            // </details>\n"` parses as a *single* 89-byte `HtmlBlock`, not six). There is no
            // `children` this function could build here the normal, no-second-parse way — but
            // `glued_details_fold` (below) still recognizes the *unambiguous* instance of this shape
            // (see its own doc comment for exactly which one) and folds it anyway, storing the raw
            // body's own byte range for `render.rs`'s own isolated re-parse instead of a `children`
            // list (`BlockKind::Details.glued_body`). Anything more ambiguous — a nested `<details>`
            // glued into the same leaf, or unrelated content following the found close within it —
            // stays an ordinary, unfolded `Html` leaf, exactly as before either variant existed; see
            // `Html`'s own doc comment on exactly this shape.
            //
            // The second half of this check (`html_leaf_contains_its_own_close`) matters even when
            // `rest` is *not* empty: a glued block like the one above can still be followed by
            // further, wholly unrelated siblings (a trailing paragraph, a footnote section
            // `process_footnotes` appended, ...) — without this check, `close_pos` below would never
            // find this leaf's own (already-consumed) `</details>` among `rest` at all, and the
            // "unclosed" fallback would swallow every one of those unrelated siblings as if they were
            // this block's own body (confirmed directly: `code_span_corpus`'s own "details/summary
            // immediately followed by a fenced code block, no blank line" case, whose `src` appends a
            // footnote section after an already-self-closed, glued `<details>` block — and, since
            // 2026-08, one `glued_details_fold` *does* fold, its trailing blank line keeping that
            // footnote section correctly outside the found close's own line).
            if let Some((summary, glued_body)) = glued_details_fold(src, &b) {
                out.push(Block {
                    kind: BlockKind::Details {
                        open_attr,
                        summary,
                        glued_body: Some(glued_body),
                    },
                    src: b.src.clone(),
                    children: Vec::new(),
                });
                continue;
            }
            out.push(b);
            continue;
        }
        let close_pos = rest.iter().position(|c| is_details_close_block(c, src));
        let body_start = line_after(src, b.src.start);
        let (mut children, block_end, summary_end) = match close_pos {
            Some(pos) => {
                let mut children = Vec::with_capacity(pos);
                for _ in 0..pos {
                    children.push(rest.pop_front().expect("position() found this many ahead"));
                }
                let close = rest
                    .pop_front()
                    .expect("position() found a close at this offset");
                (children, close.src.end, close.src.start)
            }
            None => {
                // `rest` is non-empty here (checked above) and `close_pos` found nothing in it, so
                // every remaining sibling becomes a child — `children` is never empty in this arm.
                let children: Vec<Block> = rest.drain(..).collect();
                let end = children.last().map_or(b.src.end, |c| c.src.end);
                (children, end, end)
            }
        };
        // Defensive clamp (principle #3, `CLAUDE.md`): every real input keeps `body_start <=
        // summary_end` (a later sibling's own range never starts before this block's own first
        // line ends), but this guards against a slice panic outright if some future input this
        // function has not been tested against ever violated it.
        let inner_start = body_start.min(summary_end);
        let inner = &src[inner_start..summary_end];
        let (summary, _body) = super::extract_summary_body(inner);
        // A **no-blank-line-after-the-open-tag** rescue: `b.src` (the open tag's own leaf) can run
        // past its own first line even on this "normal" (not `glued_details_fold`) path — CommonMark's
        // HTML-block grammar keeps absorbing whatever *non-blank* lines follow `<details ...>`
        // (`alpha` in `<details open>\nalpha\n<br>\nbeta\n</details>\n`, confirmed directly: this
        // exact source's own `Html` leaf reports `src: 0..21`, covering the open tag's own line *and*
        // `alpha`'s) until the block genuinely ends at a blank line, and `alpha` here is no more a
        // `<summary>` than it is a `</details>` — it is ordinary body text that just happened to have
        // no blank line of its own separating it from the tag above. `super::split_details`'s own
        // raw-line body scan has no such gluing to begin with (it treats `body_start..summary_end` as
        // one flat span regardless of blank lines, then hands the whole thing to a fresh Markdown
        // parse), so production loses nothing here — this rescues the identical text on this file's
        // own path (found 2026-08, rendering every "no blank line under an unseparated `<details>`"
        // shape in the parity corpus: `alpha` above vanished outright, kept out of both `children`
        // — `fold_details` never sees it as a sibling `Block` at all, since it was never a `Doc.events`
        // block of its own — *and* the `extract_summary_body` call above, whose own `_body` return
        // value has always been discarded here (`inner` deliberately reaches past `b.src.end`, into
        // whatever real sibling children/close tag follow, purely so a *glued* `<summary>` — see
        // below — is still found; the well-formed "summary and body are separate siblings" shape
        // never had a leftover for `_body` to carry in the first place, which is why nothing here
        // needed it before now).
        //
        // The rescued range is only ever the slice `super::extract_summary_body` has *not* already
        // read as the summary tag (`super::summary_tag_end`, the identical boundary that function's
        // own second return value is sliced from) — clamped to `b.src.end`, this leaf's own extent, so
        // a `<summary>` glued onto the same line as the open tag (the everyday, blank-line-separated-
        // body idiom `<details>\n<summary>S</summary>\n\nbody\n</details>\n` glues *these two* lines
        // into one `Html` leaf too, confirmed directly) is never rescued a second time as raw body
        // text alongside its own already-extracted `summary` field: `real_body_start` lands at (or
        // past) `b.src.end` there, so the `if` below never fires, and this stays a pure no-op on
        // every shape that does not have this exact gap. Rendered via `render_html_block_from_model`
        // like any other `Html` block (`tag: None`, matching what `super::html_tag_name` would report
        // for a line that does not start with `<` at all) — reusing the one function this file already
        // trusts to turn arbitrary glued raw text into `Line`s, rather than a second, narrower
        // reimplementation of it here.
        //
        // Guarded on the leftover being more than whitespace: the everyday, blank-line-separated-body
        // idiom (`<details>\n<summary>S</summary>\n\nbody\n</details>\n`) glues the open tag and its
        // own `<summary>` into one `Html` leaf too (confirmed directly — no blank line separates
        // *those* two lines either), and, once rounded up to a line boundary (below), `real_body_start`
        // there lands *at* `b.src.end`: there is nothing left in the leaf past the summary line at all.
        // Rescuing an empty range as a `Block` on every well-formed `<details>` would still be a
        // *structural* regression `render.rs`'s own `contains_unsupported` can observe even though the
        // screen never changes: a quote-nested alert's own `<details>` reaches this exact shape
        // (`> <details open>\n> <summary>Nested</summary>\n`, `md_render_diff_tests`'s own
        // `details_nested_inside_an_alert_does_not_consume_the_top_level_ordinal` corpus case) with
        // `in_quote: true` already set, and a bare `BlockKind::Html` child there is reported
        // unsupported unconditionally (`contains_unsupported`'s own `Html { .. } if in_quote` arm) —
        // falling the *whole* alert back to the legacy renderer over one phantom, invisible child. The
        // `.trim()` check keeps this rescue narrowly targeted at the one shape it exists for (real body
        // text CommonMark genuinely glued to the open tag, confirmed non-whitespace) rather than firing
        // on every well-formed block regardless of whether there is anything left to rescue at all.
        //
        // Rounded up to the *next line* — via `line_after`, not used byte-exact — when a `<summary>`
        // was actually found and consumed: `super::summary_tag_end`'s own boundary lands mid-line,
        // right after `</summary>`'s own `>`, but pulldown-cmark's own `Event::Html` sub-events are
        // always whole, `'\n'`-inclusive physical lines (confirmed directly: `Doc::parse`'s own event
        // stream for a glued leaf reports one `Event::Html` per source line, trailing newline and all —
        // see the module doc comment's "How inline content is rendered" section). Splitting a leaf
        // mid-line here would leave neither the tag-line sliver `render.rs`'s own completeness check
        // (`app::md_model_snapshot_tests::model_covers_every_inline_event_across_the_full_corpus`)
        // computes from `b.src.start..first_child.src.start`, nor this rescued leaf itself, covering
        // that one summary line's own trailing `'\n'` in full — found the same way as the leaf-count
        // regression above, by running the full test suite after adding the byte-exact version first.
        // No such rounding when no `<summary>` was found at all (`summary_tag_end` returns `None`):
        // `inner_start` is already a clean line start there (`line_after(src, b.src.start)`, the
        // position right after the open tag's own first line) — rounding again would skip the very
        // first real body line (`alpha`, in the doc comment above) whole.
        let real_body_start = match super::summary_tag_end(inner) {
            Some(off) => line_after(src, inner_start + off),
            None => inner_start,
        }
        .min(b.src.end);
        if real_body_start < b.src.end && !src[real_body_start..b.src.end].trim().is_empty() {
            // `b` (the open tag's own leaf) is itself a `Html` block, and its own `body_spans`
            // already cover this whole leaf's content, one clean range per physical source line
            // (`real_body_start` is line-rounded, via `line_after` above, to exactly one of those
            // lines' own start) — this rescued child's own `body_spans` is just the tail of that
            // same list, not a fresh scan: correct inside a block quote too, the same way `b`'s own
            // were, with no separate `>`-marker handling needed here.
            let rescued_body_spans = match &b.kind {
                BlockKind::Html { body_spans, .. } => body_spans
                    .iter()
                    .filter(|r| r.start >= real_body_start)
                    .cloned()
                    .collect(),
                // Not reachable: `open_attr` above is only `Some` when `b.kind` already matched
                // `Html { tag: Some(t) } if t == "details"` — kept as a defensive fallback rather
                // than assumed away, per `CLAUDE.md` principle #3 (never crash).
                _ => Vec::new(),
            };
            children.insert(
                0,
                Block {
                    kind: BlockKind::Html {
                        tag: None,
                        body_spans: rescued_body_spans,
                    },
                    src: real_body_start..b.src.end,
                    children: Vec::new(),
                },
            );
        }
        out.push(Block {
            kind: BlockKind::Details {
                open_attr,
                summary,
                glued_body: None,
            },
            src: b.src.start..block_end,
            children,
        });
    }
    out
}

/// The first physical line of `src[r]`, trailing-whitespace-trimmed — mirrors `html_tag_of`'s own
/// identical read exactly (kept as a separate one-liner rather than shared with it, since that
/// function reads off a `body_spans` slice instead of a raw `Block::src` range — the two agree here
/// only because `r` is already a whole, already-parsed block's own range, not a fresh one this
/// function would need `events` to build). Used by `fold_details` to decide, for a `Html { tag:
/// Some("details") }` leaf, whether its own first line is an opening or a closing details tag.
fn first_source_line<'a>(src: &'a str, r: &Range<usize>) -> &'a str {
    src[r.clone()].lines().next().unwrap_or("").trim_end()
}

/// Whether `c` is a `Html { tag: Some("details") }` leaf whose own first source line is a
/// `</details>`-closing tag (as opposed to an opening `<details ...>` one — both share the same
/// `tag` value, see `html_tag_of`'s own doc comment on why: this is the one place that tells
/// them apart, by re-checking `is_details_close` on the block's own first line, the identical
/// predicate `split_details` itself uses).
fn is_details_close_block(c: &Block, src: &str) -> bool {
    matches!(&c.kind, BlockKind::Html { tag: Some(t), .. } if t == "details")
        && super::is_details_close(first_source_line(src, &c.src))
}

/// Whether an open-tag `Html { tag: Some("details") }` leaf's own **raw text** already runs past a
/// `</details>`-closing line of its own — i.e., whether pulldown-cmark glued this open tag and its
/// own matching close into the *same* `HtmlBlock` (no blank line anywhere between them) rather than
/// reporting the close as a separate sibling `fold_details` could find via `is_details_close_block`.
/// Scans every line of `b.src` *after* its own first (the `<details ...>` tag's own line, already
/// known not to be a close) for one matching `is_details_close` — used by `fold_details` to tell
/// "this open tag is genuinely unclosed, or closed only by a later sibling" apart from "this leaf
/// is already fully self-contained, whatever *else* happens to follow it at this sibling level" —
/// see that function's own call site for exactly why the distinction matters.
fn html_leaf_contains_its_own_close(src: &str, b: &Block) -> bool {
    let text = &src[b.src.clone()];
    text.lines()
        .skip(1)
        .any(|line| super::is_details_close(line.trim_end()))
}

/// Whether `b` — a glued `<details>` leaf `html_leaf_contains_its_own_close` has already confirmed
/// contains its own close — is the **unambiguous** instance of that shape: the summary and
/// `render.rs`'s own byte range for its isolated re-parse (`BlockKind::Details.glued_body`), when it
/// is. `None` when it is not, leaving `fold_details` on its previous, safe fallback (an ordinary,
/// unfolded `Html` leaf — see that function's own call site).
///
/// "Unambiguous" means both of the following hold, checked by scanning `b`'s own raw text one line at
/// a time, starting right after its own first line (the `<details ...>` open tag itself):
///
/// * The **first** line matching `is_details_close` is also `b`'s own **last** line (mod a single
///   trailing `'\n'`, or nothing at all — see the `after_close` check below) — no further, unrelated
///   content follows the found close within the same glued leaf. Without this, truncating
///   `Block::src` to end at that close (as this function's caller does) would silently orphan
///   whatever bytes come after it — there is no sibling slot left to carry them.
/// * No line strictly between the open tag and that close is **itself** a `<details ...>` open tag —
///   no nested `<details>` glued into the same leaf. Without this, "first close wins" would hand the
///   *inner* `<details>`'s own close to the *outer* tag (`</details>` on the line right after
///   `<summary>Nested</summary>` in `"<details>\n<summary>A</summary>\n<details>\n\
///   <summary>Nested</summary>\n</details>\n</details>\n"`, say — matching `split_details`'s own
///   line-scan contract exactly, since it does not track nesting either), which this function
///   deliberately does not attempt to resolve: see `glued_details_with_no_blank_line_anywhere_stays_\
///   an_unfolded_html_leaf`, still pinned exactly this way, for why an ambiguous glued shape like that
///   one stays an unfolded `Html` leaf rather than folding into something that would misrepresent
///   which `</details>` actually belongs to which `<details>`.
///
/// Both checks are read straight off a literal line-by-line scan of `b.src`'s own raw text, the
/// identical predicates (`super::is_details_close`/`super::details_open_tag`) `html_leaf_contains_\
/// its_own_close`/`fold_details`'s own well-formed branch already use — not a third, competing
/// classifier.
///
/// The returned range excludes the `<summary>...</summary>` tag itself (found the same way
/// `super::extract_summary_body` finds it, via `super::summary_tag_end` — the offset-returning
/// sibling of the same search, so the two can never disagree about where the summary ends and the
/// body begins) — a caller re-parsing `src[range]` in isolation must never see that tag a second
/// time, or the summary text would render twice (once as this block's own fold marker, again as the
/// re-parsed body's first line of literal text). Unlike `extract_summary_body`'s own `body` (its
/// second return value), this range is **not** blank-line-trimmed: a leading or trailing blank line
/// left inside it changes nothing about the block-level structure a fresh `Doc::parse` reads back —
/// CommonMark itself already treats leading/trailing blank lines as no content at all, the same way
/// `trim_blank_lines` removes them for `extract_summary_body`'s own, differently-purposed `body`
/// string — so there is no byte-offset equivalent of that trim to compute here.
fn glued_details_fold(src: &str, b: &Block) -> Option<(String, Range<usize>)> {
    let body_start = line_after(src, b.src.start);
    let scan = &src[body_start..b.src.end];
    let mut close: Option<(usize, usize)> = None; // (start, end) absolute into `src`; `end` excludes any trailing '\n'
    let mut nested = false;
    let mut pos = 0usize; // offset within `scan`
    loop {
        let rel_end = scan[pos..].find('\n').map_or(scan.len(), |i| pos + i);
        let line = &scan[pos..rel_end];
        if super::is_details_close(line) {
            close = Some((body_start + pos, body_start + rel_end));
            break;
        }
        if super::details_open_tag(line).is_some() {
            nested = true;
        }
        if rel_end >= scan.len() {
            break; // ran off the end of `b.src` with no close found
        }
        pos = rel_end + 1;
    }
    let (close_start, close_end) = close?;
    if nested {
        return None;
    }
    // Nothing but whitespace (a lone trailing '\n', most commonly, or nothing at all) may follow the
    // found close within this same leaf — anything else is unrelated trailing content this function
    // has no sibling slot to hand back to `fold_details`'s own caller.
    if !src[close_end..b.src.end].trim().is_empty() {
        return None;
    }
    let inner = &src[body_start..close_start];
    let (summary, _body) = super::extract_summary_body(inner);
    let body_off = super::summary_tag_end(inner).unwrap_or(0);
    Some((summary, (body_start + body_off)..close_start))
}

/// The byte position right after the next `'\n'` at or after `start` — `src.len()` if there is
/// none. Always a valid `char` boundary (`'\n'` is one ASCII byte, and `str::find` never returns a
/// non-boundary index), so a caller slicing `&src[line_after(src, x)..]` never risks a panic on that
/// account. Used by `fold_details` to compute "the start of the source line right after this
/// block's own first one" — the same position `lines[start + 1]` names in `split_details`'s own,
/// raw-line-indexed world (see that function's own doc comment) — without needing a `Vec<&str>` of
/// this model's own to index into.
fn line_after(src: &str, start: usize) -> usize {
    match src[start..].find('\n') {
        Some(off) => start + off + 1,
        None => src.len(),
    }
}

/// Builds the `Block` for one container whose `Start(tag)` (at `range`) `parse_blocks` has just
/// consumed, then consumes everything up to and including its matching `End` — so control returns
/// to `parse_blocks` exactly one event past this construct's own extent, every time. Returns `None`
/// for a construct this model does not represent (see the module doc comment on scope) after still
/// fully consuming and discarding its subtree, so the caller's stream position is unaffected either
/// way.
fn parse_container(tag: Tag, range: Range<usize>, events: &mut Walker, src: &str) -> Option<Block> {
    match tag {
        Tag::Paragraph => {
            let inline_start = events.pos();
            skip_inline_to(events, TagEnd::Paragraph);
            // `skip_inline_to` always returns having just consumed the matching `End` as the very
            // last event (see its own doc comment) — `events.pos() - 1` is that `End`'s own index,
            // so this excludes it from the paragraph's own `inline` range.
            let inline = inline_start..events.pos() - 1;
            Some(leaf(BlockKind::Paragraph { inline }, range))
        }
        Tag::Heading {
            level,
            id,
            classes,
            attrs,
        } => {
            let inline_start = events.pos();
            skip_inline_to(events, TagEnd::Heading(level));
            let inline = inline_start..events.pos() - 1;
            Some(leaf(
                BlockKind::Heading {
                    level: level as u8,
                    inline,
                    id: id.map(|c| c.into_string()),
                    classes: classes.into_iter().map(|c| c.into_string()).collect(),
                    attrs: attrs
                        .into_iter()
                        .map(|(k, v)| (k.into_string(), v.map(|v| v.into_string())))
                        .collect(),
                },
                range,
            ))
        }
        Tag::CodeBlock(kind) => {
            let (fenced, lang) = match kind {
                CodeBlockKind::Fenced(info) => (
                    true,
                    if info.trim().is_empty() {
                        None
                    } else {
                        Some(info.into_string())
                    },
                ),
                CodeBlockKind::Indented => (false, None),
            };
            let body_spans = collect_code_body_spans(events);
            Some(leaf(
                BlockKind::CodeBlock {
                    lang,
                    fenced,
                    body_spans,
                },
                range,
            ))
        }
        Tag::List(start) => {
            let children = parse_blocks(events, src); // also consumes End(List(_))
            Some(Block {
                kind: BlockKind::List {
                    ordered: start.is_some(),
                    start,
                },
                src: range,
                children,
            })
        }
        Tag::Item => {
            let (task, children) = parse_item_task_and_children(events, src);
            Some(Block {
                kind: BlockKind::ListItem { task },
                src: range,
                children,
            })
        }
        Tag::BlockQuote(_) => {
            let children = parse_blocks(events, src); // also consumes End(BlockQuote(_))
            let (alert, alert_title) = alert_kind_of(src, &range);
            Some(Block {
                kind: BlockKind::Quote { alert, alert_title },
                src: range,
                children,
            })
        }
        Tag::Table(aligns) => {
            let rows = collect_table_rows(events);
            Some(leaf(BlockKind::Table { aligns, rows }, range))
        }
        Tag::HtmlBlock => {
            let body_spans = collect_html_body_spans(events);
            let tag = html_tag_of(&body_spans, src);
            // One complete `<table> … </table>` gets real structure (`BlockKind::HtmlTable`) instead
            // of staying an opaque `Html` leaf; anything else — including a `<table>` this scan
            // cannot read as a whole table — falls through to the `Html` leaf it has always been.
            // See `parse_html_table`'s own doc comment for exactly which blocks qualify.
            if tag.as_deref() == Some("table") {
                if let Some(rows) = parse_html_table(&body_spans, src) {
                    return Some(leaf(BlockKind::HtmlTable { body_spans, rows }, range));
                }
            }
            Some(leaf(BlockKind::Html { tag, body_spans }, range))
        }
        // A YAML/`+++`-style metadata block (only reachable if the caller did not strip front
        // matter first — see the module doc comment), a footnote definition, or a definition list:
        // none has a `BlockKind`. Consumed and discarded rather than left half-read, so a caller
        // that *does* hand this a raw, un-preprocessed file still gets a well-formed (if partial)
        // tree instead of a desynced one.
        other => {
            debug_assert!(
                is_unmodeled_container_tag(&other),
                "parse_container's own exhaustive match and is_unmodeled_container_tag must \
                 agree on which Tag variants land here — the latter is a second, independent \
                 reading of the exact same set for md_model_snapshot_tests's completeness cross-\
                 check (see its own doc comment); a new Tag variant landing in *only one* of the \
                 two would let that check pass without actually exercising the gap it exists to \
                 catch."
            );
            skip_inline_to(events, other.to_end());
            None
        }
    }
}

fn leaf(kind: BlockKind, src: Range<usize>) -> Block {
    Block {
        kind,
        src,
        children: Vec::new(),
    }
}

/// Whether `tag` is one of the handful of constructs this model never represents at all —
/// `parse_container`'s own `other` arm, named as a predicate rather than left as an implicit "every
/// `Tag` variant not matched above" so it can be reused (and checked in lockstep with that match via
/// a `debug_assert!` right there) by `md_model_snapshot_tests`'s completeness cross-check, which
/// needs to know which parts of a raw event stream the model *deliberately* does not promise to
/// cover before it can flag anything else as a genuine gap. `FootnoteDefinition` and
/// `MetadataBlock` are reachable only when the caller hands `Doc::parse` un-preprocessed text
/// (konoma's own source pre-passes strip front matter and rewrite footnote definitions away before
/// any text reaches a parser at all — see the module doc comment); `Options::ENABLE_DEFINITION_LIST`
/// is never turned on by `parse_options` in the first place, so `Tag::DefinitionList*` can never
/// actually be emitted at all today, but is still named here for the same reason `parse_container`'s
/// own match still spells it out explicitly — an exhaustive match, not one relying on what today's
/// `parse_options` happens to enable.
///
/// `pub(crate)`: reused, unchanged, by `md_model_snapshot_tests`'s completeness cross-check
/// (`scan_reference_events`) — see `parse_options`'s own doc comment for why sharing a classifier
/// like this, rather than a second hand-copied list of the same `Tag` variants, is the whole point.
pub(crate) fn is_unmodeled_container_tag(tag: &Tag) -> bool {
    matches!(
        tag,
        Tag::FootnoteDefinition(_)
            | Tag::DefinitionList
            | Tag::DefinitionListTitle
            | Tag::DefinitionListDefinition
            | Tag::MetadataBlock(_)
    )
}

/// Whether `tag` opens one of pulldown-cmark's own *span-level* constructs — its own source groups
/// these under a `// span-level tags` comment, directly below the block-level ones — as opposed to
/// something block-shaped (`Paragraph`, `Heading`, `List`, ...). Needed because, for a tight list
/// item, either kind of `Start` can legitimately be the very next event `parse_blocks` sees (see its
/// own doc comment): this tells the two apart so the block-shaped ones still go to
/// `parse_container`, while the span-level ones start a stray inline run instead
/// (`collect_stray_inline_run`).
///
/// Not `pub(crate)` like its two siblings (`is_stray_inline_leaf`, `is_unmodeled_container_tag`):
/// `md_model_snapshot_tests`'s completeness cross-check has no runs of its own to group, only raw
/// event positions to record, so it never needs this particular distinction — see
/// `scan_reference_events`'s own doc comment there.
fn is_inline_start_tag(tag: &Tag) -> bool {
    matches!(
        tag,
        Tag::Emphasis
            | Tag::Strong
            | Tag::Strikethrough
            | Tag::Superscript
            | Tag::Subscript
            | Tag::Link { .. }
            | Tag::Image { .. }
    )
}

/// Whether `ev` is a leaf inline-content event this model can fold into a stray run's synthetic
/// `Paragraph` (see `parse_blocks`'s doc comment) — every `Event` variant that carries literal
/// document content and is neither a container (`Start`/`End`), `Rule` (its own leaf `BlockKind`),
/// nor `TaskListMarker`. `TaskListMarker` is deliberately excluded even though it is, in every other
/// sense, a leaf event this model's own `parse_options` can produce: it is recorded on
/// `ListItem.task` instead of folded into a `Paragraph`'s range, because its own three bytes (`[`,
/// the state character, `]`) sit in the item's own marker text — *outside* whatever `Paragraph`
/// (real or synthetic) the item's content becomes — not inside it; see `Task::state_at`'s doc
/// comment. Every genuine call site consumes a `TaskListMarker` before `parse_blocks` ever sees one
/// (`parse_item_task_and_children`); this function simply does not claim it as "content" in case
/// that assumption is ever wrong for some input this model has not been tested against, so it still
/// degrades to `parse_blocks`'s own final, silent catch-all rather than corrupting a `Paragraph`'s
/// range with marker bytes it never claimed to cover.
///
/// `pub(crate)`: reused, unchanged, by `md_model_snapshot_tests`'s completeness cross-check
/// (`scan_reference_events`) — see `parse_options`'s own doc comment for why sharing a classifier
/// like this, rather than a second hand-copied list of the same `Event` variants, is the whole
/// point.
pub(crate) fn is_stray_inline_leaf(ev: &Event) -> bool {
    matches!(
        ev,
        Event::Text(_)
            | Event::Code(_)
            | Event::InlineMath(_)
            | Event::DisplayMath(_)
            | Event::Html(_)
            | Event::InlineHtml(_)
            | Event::FootnoteReference(_)
            | Event::SoftBreak
            | Event::HardBreak
    )
}

/// Builds a "stray inline run"'s byte range — see `parse_blocks`'s own doc comment for when one
/// starts — given `first`, the run's own first event, **already consumed** by `parse_blocks`'s
/// loop (so this never re-peeks it; `first.1.start` is the run's own starting offset). The run's
/// `inline` *event-index* range (the synthetic `Paragraph`'s own share of `Doc.events`) is computed
/// by the caller instead, from `Walker::pos()` read before and after this call — not here, since
/// `first` was already consumed (and recorded) before this function was ever entered, so this
/// function alone cannot see where the run's own first index actually was. Balances
/// `first` exactly the way the loop below balances every further event it consumes itself: a leaf
/// (`is_stray_inline_leaf`) needs nothing further, but the `Start` of a further inline construct
/// (`is_inline_start_tag` — `**bold**`, a link, an image, ...) still has its own body sitting
/// unconsumed in `events`, so `skip_inline_to` drains it, down to and including its matching `End`,
/// before this can safely look at what comes next — an earlier version of this function forgot this
/// step for `first` specifically (handling it only for events the loop consumed on its own), which
/// left the very case this function exists for — a tight item beginning with `**bold**` rather than
/// plain text — desyncing the event stream one token in, corrupting every range downstream; see the
/// `emphasis in task` case in `task_corpus` and the parity corpus's own overlap invariant, which is
/// what actually caught it.
///
/// Drains every further event that belongs to the same run the identical way, advancing `end` to
/// each one's own range end — relying on the same pulldown-cmark behavior `parse_container` already
/// leans on throughout this file, that a `Start`'s reported range always equals its construct's
/// *whole* span, matching its `End`'s range exactly — so no separate bookkeeping is needed to find
/// where a nested `Start(Strong)`/`Start(Link)`/... really ends; its own `Start` event's range
/// already says. Stops, **without** consuming it, the moment the next event is not part of the run:
/// the `Event::End` that closes the *container* this content belongs to, or any block-level `Start`
/// (a nested list, a code block, a following loose paragraph, ...) — both are left for
/// `parse_blocks`'s own loop to see next, exactly like any other block boundary.
///
/// One real (not a bug) difference from a *real* `Paragraph`'s own range: pulldown-cmark reports a
/// `Tag::Paragraph`'s range as running through its trailing newline (`"a\n"` for a one-line
/// paragraph), while a synthetic one built here stops at the run's last inline event's own end
/// (`"a"`, no newline) — there is no wrapping tag here for pulldown-cmark to have assigned that
/// wider range to in the first place, only the leaf events themselves, whose own ranges never
/// include it; see `tight_list_item_gets_a_synthetic_paragraph_child_loose_item_gets_a_real_one`.
fn collect_stray_inline_run(first: (Event<'_>, Range<usize>), events: &mut Walker) -> Range<usize> {
    let (first_ev, first_range) = first;
    let start = first_range.start;
    let mut end = first_range.end;
    if let Event::Start(tag) = first_ev {
        skip_inline_to(events, tag.to_end());
    }
    loop {
        let continues = match events.peek() {
            Some((Event::Start(tag), _)) => is_inline_start_tag(tag),
            Some((ev, _)) => is_stray_inline_leaf(ev),
            None => false,
        };
        if !continues {
            return start..end;
        }
        let (ev, range) = events.next().expect("peeked Some above");
        end = range.end;
        if let Event::Start(tag) = ev {
            skip_inline_to(events, tag.to_end());
        }
    }
}

/// Consumes events up to and including the given `end`, for a tag whose `Start` the caller has
/// already consumed — recursing into any further `Start` it meets along the way so a *nested*
/// inline construct (a link containing emphasis, an image inside a link's title, ...) cannot be
/// mistaken for the enclosing one's own close. Used for every construct whose CommonMark content is
/// purely inline and this model does not represent as nested blocks: a heading's or paragraph's
/// text, and a table cell's.
fn skip_inline_to(events: &mut Walker, end: TagEnd) {
    while let Some((ev, _)) = events.next() {
        match ev {
            Event::Start(t) => skip_inline_to(events, t.to_end()),
            Event::End(e) if e == end => return,
            _ => {}
        }
    }
}

/// Parses one list item's task marker and its own children together — the two cannot be handled as
/// two independent steps (`take_task_marker` then `parse_blocks`) the way an earlier version of this
/// model did, because *where* the marker sits in the event stream depends on whether the item is
/// tight or loose (see `Task`'s own doc comment for the identical tight/loose distinction):
///
/// * **Tight item** (`- [ ] a`): `Event::TaskListMarker`, if present, is the very first event of the
///   item's own content — `take_task_marker` handles this directly, exactly as before.
/// * **Loose item** (`- [ ] a\n\n- b`): the marker instead sits *inside* the item's own first
///   `Paragraph` — pulldown-cmark still omits nothing, but wraps the item's text in a `Paragraph`
///   (as any loose item's is) and reports the marker as that paragraph's own first inline event,
///   ahead of its `Text`. Seeing it therefore means consuming `Start(Paragraph)` first — `Walker` is
///   only one-deep peekable, so there is no way to look two events ahead without consuming the
///   first — which means this function has to build that first `Paragraph` block itself (identically
///   to `parse_container`'s own `Tag::Paragraph` arm) rather than being able to hand `Start`
///   `(Paragraph)` back to `parse_blocks` the way it would for any *later* paragraph in the item.
///
/// Only the item's own *first* child is ever special-cased this way; every other one is reached
/// through the trailing `parse_blocks` call below, unchanged, and a nested item (inside a sublist
/// reached the same way) parses its own marker through its own, independent call to this same
/// function — so there is no path by which an outer item could mistake an inner one's marker, or an
/// inner one's first paragraph, for its own.
fn parse_item_task_and_children(events: &mut Walker, src: &str) -> (Option<Task>, Vec<Block>) {
    if matches!(events.peek(), Some((Event::Start(Tag::Paragraph), _))) {
        let (_, para_range) = events.next().expect("peeked Some above");
        let task = take_task_marker(events, src);
        // `pos()` is read *after* `take_task_marker` — a loose item's own leading marker, if any,
        // has already been consumed and excluded by this point, matching `Task::state_at`'s own
        // doc comment: those bytes sit in the item's marker text, not inside its paragraph's
        // content.
        let inline_start = events.pos();
        skip_inline_to(events, TagEnd::Paragraph);
        let inline = inline_start..events.pos() - 1;
        let mut children = vec![leaf(BlockKind::Paragraph { inline }, para_range)];
        children.extend(parse_blocks(events, src)); // also consumes End(Item)
        return (task, children);
    }
    let task = take_task_marker(events, src);
    let children = parse_blocks(events, src); // also consumes End(Item)
    (task, children)
}

/// If the very next event in `events` is `Event::TaskListMarker`, consumes it and returns the
/// `Task` it describes; otherwise leaves `events` untouched. Called from the two positions
/// `parse_item_task_and_children` documents — right after `Item`'s own `Start` (a tight item) and
/// right after the item's own first `Paragraph`'s `Start` (a loose item) — because a marker, when
/// present at all, is always the very next event at whichever of those two the item's own shape
/// calls for; see that function's own doc comment for why the two positions exist, and `Task`'s doc
/// comment for why a marker can only ever appear at one of them, never both, never neither.
fn take_task_marker(events: &mut Walker, src: &str) -> Option<Task> {
    if !matches!(events.peek(), Some((Event::TaskListMarker(_), _))) {
        return None;
    }
    let (_, range) = events.next().expect("peeked Some above");
    // `[` at `range.start`, the state char at `range.start + 1`, `]` at `range.start + 2` — see
    // `scan_task_list_marker` in pulldown-cmark's own scanner, which accepts nothing but a single
    // ASCII byte there, so this index always lands on (and this is always a one-byte) char.
    let state_at = range.start + 1;
    let state = src[state_at..]
        .chars()
        .next()
        .expect("a TaskListMarker range always has a state byte following '['");
    Some(Task { state, state_at })
}

/// Collects a code block's content as one byte range per `Event::Text` pulldown-cmark reports, in
/// order — see `BlockKind::CodeBlock.body_spans`'s doc comment for exactly what these ranges do and
/// do not guarantee and how to turn them back into content — by walking every such event up to the
/// block's own `End(CodeBlock)`, which this also consumes. If the stream is exhausted first (a
/// malformed/truncated caller input), this simply stops with whatever spans it collected so far. An
/// empty code block emits no `Event::Text` at all, so this returns an empty `Vec` for one — there is
/// no position to anchor a placeholder range on that would mean anything once the content is a list
/// rather than a single interval, so none is invented.
fn collect_code_body_spans(events: &mut Walker) -> Vec<Range<usize>> {
    let mut spans = Vec::new();
    while let Some((ev, range)) = events.next() {
        match ev {
            Event::Text(_) => spans.push(range),
            Event::End(TagEnd::CodeBlock) => break,
            // Not reachable for well-formed input (a code block's content is never itself a
            // container), balanced defensively rather than assumed away — see `parse_blocks`'s
            // doc comment on never desyncing the stream.
            Event::Start(t) => skip_inline_to(events, t.to_end()),
            _ => {}
        }
    }
    spans
}

/// Reconstructs a code block's content, byte for byte, from its `body_spans` — concatenating each
/// range's slice of `src`, in order, then stripping at most one trailing `\n` — matching
/// `parser_code_blocks`'s own "join every `Event::Text`, strip one trailing newline" convention
/// exactly. See `BlockKind::CodeBlock.body_spans`'s doc comment for what bytes the spans themselves
/// necessarily skip (a continuation line's own share of container indentation; a `\r` consumed by
/// line-ending normalization) and why concatenating them still gets the content right regardless.
pub(crate) fn code_body_text(body_spans: &[Range<usize>], src: &str) -> String {
    let mut s = String::new();
    for r in body_spans {
        s.push_str(&src[r.clone()]);
    }
    match s.strip_suffix('\n') {
        Some(t) => t.to_string(),
        None => s,
    }
}

/// Consumes a `Table`'s `TableHead`/`TableRow` children up to and including its own `End(Table)`,
/// collecting each row's cells. `rows[0]` is always the header row — GFM defines a table as
/// exactly one header row followed by zero or more body rows, and pulldown-cmark's own event
/// stream (one `TableHead`, then any number of `TableRow`s, all inside one `Table`) mirrors that
/// directly, so no extra bookkeeping is needed to tell them apart.
fn collect_table_rows(events: &mut Walker) -> Vec<Vec<Range<usize>>> {
    let mut rows = Vec::new();
    while let Some((ev, _)) = events.next() {
        match ev {
            Event::Start(Tag::TableHead) => rows.push(collect_row_cells(events, TagEnd::TableHead)),
            Event::Start(Tag::TableRow) => rows.push(collect_row_cells(events, TagEnd::TableRow)),
            Event::End(TagEnd::Table) => break,
            Event::Start(t) => skip_inline_to(events, t.to_end()), // defensive; not reachable
            _ => {}
        }
    }
    rows
}

/// Consumes one table row's `TableCell`s up to and including its own `end` (`TableHead` or
/// `TableRow`), collecting each cell's byte range. Cell content is inline (see `BlockKind::Table`'s
/// doc comment), so — like a paragraph or heading — it is walked past via `skip_inline_to`, not
/// turned into a nested `Block`.
fn collect_row_cells(events: &mut Walker, end: TagEnd) -> Vec<Range<usize>> {
    let mut cells = Vec::new();
    while let Some((ev, range)) = events.next() {
        match ev {
            Event::Start(Tag::TableCell) => {
                skip_inline_to(events, TagEnd::TableCell);
                cells.push(range);
            }
            Event::End(e) if e == end => break,
            Event::Start(t) => skip_inline_to(events, t.to_end()), // defensive; not reachable
            _ => {}
        }
    }
    cells
}

/// Collects an `HtmlBlock`'s content as one byte range per `Event::Html` pulldown-cmark reports, in
/// order — mirrors `collect_code_body_spans` exactly (see that function's own doc comment for the
/// walk itself), for the identical reason: see `BlockKind::Html.body_spans`'s own doc comment for why
/// a list of ranges, not one, is needed here and what each range does and does not include. Consumes
/// up to and including the block's own `End(HtmlBlock)`.
fn collect_html_body_spans(events: &mut Walker) -> Vec<Range<usize>> {
    let mut spans = Vec::new();
    while let Some((ev, range)) = events.next() {
        match ev {
            Event::Html(_) => spans.push(range),
            Event::End(TagEnd::HtmlBlock) => break,
            // Not reachable for well-formed input (an HTML block's content is never itself a
            // container), balanced defensively rather than assumed away — see `parse_blocks`'s doc
            // comment on never desyncing the stream.
            Event::Start(t) => skip_inline_to(events, t.to_end()),
            _ => {}
        }
    }
    spans
}

/// Reconstructs an HTML block's content from its `body_spans` — concatenating each range's slice of
/// `src`, in order — with **no** trailing-newline stripping, unlike `code_body_text`: every
/// `Event::Html` range already includes its own physical line's trailing `\n` verbatim (confirmed by
/// the same dump `BlockKind::Html.body_spans`'s own doc comment quotes), and `render_html_block_from_model`
/// (`render.rs`) walks the result back apart one physical line at a time (`split_inclusive('\n')`) —
/// the identical way it walked `&src[block_src]` before this field existed — so stripping a trailing
/// newline here would silently glue the block's last two lines into one for that walk. A block whose
/// very last line in the source carries no trailing `\n` at all (end of file) is reproduced exactly
/// that way too, since nothing here invents one.
pub(crate) fn html_body_text(body_spans: &[Range<usize>], src: &str) -> String {
    let mut s = String::new();
    for r in body_spans {
        s.push_str(&src[r.clone()]);
    }
    s
}

/// The part of [`html_body_text`] that falls inside `want` — every `body_spans` range clipped to
/// `want`, in order, concatenated.
///
/// This, not `&src[want]`, is how an `HtmlTableCell.inner` range is read back. The two agree byte for
/// byte whenever `body_spans` is contiguous (every HTML block outside a block quote — confirmed by
/// dump: `"<table>\n<tr>\n<td>a</td>\n"` reports `0..8`, `8..13`, `13..24`, with no gap), and differ
/// exactly where it is not: inside a block quote each continuation line's own `> ` marker sits in the
/// *gap between* two spans, so a naive `&src[want]` for a cell spanning two physical lines would
/// splice that marker into the middle of the cell's text while this skips it — the same asymmetry
/// `BlockKind::Html.body_spans`'s own doc comment describes, applied one level down.
pub(crate) fn html_body_text_in(
    body_spans: &[Range<usize>],
    src: &str,
    want: &Range<usize>,
) -> String {
    // `body_spans` is ordered and non-overlapping (`collect_html_body_spans` pushes them in event
    // order; `check_invariants` pins exactly that property for the identically-built
    // `CodeBlock.body_spans`), so the spans that can overlap `want` are one contiguous run and the
    // first of them can be found by binary search instead of a scan. That is what keeps reading N
    // cells out of an N-line table linear rather than quadratic — measured on a generated
    // 3,000-row table, where the scanning form was already a visible share of the render budget.
    let first = body_spans.partition_point(|r| r.end <= want.start);
    let mut s = String::new();
    for r in &body_spans[first..] {
        if r.start >= want.end {
            break;
        }
        let start = r.start.max(want.start);
        let end = r.end.min(want.end);
        if start < end {
            s.push_str(&src[start..end]);
        }
    }
    s
}

/// Every `<tr>`'s cells of an HTML block that is one complete `<table> … </table>`, or `None` for a
/// block that is not one — the whole of [`BlockKind::HtmlTable`]'s recognition, run once per `Html`
/// block whose tag name is `table` (`parse_container`'s own `Tag::HtmlBlock` arm).
///
/// ## What it scans
///
/// [`html_body_text`] — the block's content with every enclosing block quote's `>` markers already
/// gone — walked once, tag by tag, with each offset mapped straight back to a `src` byte offset
/// through the same `body_spans` (`span_offset` below). No second `Parser` and no re-slicing of the
/// document: this reads the bytes the one whole-document walk already named, exactly like every other
/// function in this file (see the module doc comment).
///
/// ## What makes a block a table
///
/// All four of:
///
/// 1. the first tag is `<table …>` (the caller has already checked the *name*, via `html_tag_of`;
///    this rejects a block that merely *mentions* `<table>` after some other opening tag),
/// 2. a matching `</table>` is found — nesting-aware, so an inner table's own close cannot end the
///    outer one — i.e. the block holds a **complete** table,
/// 3. at least one `<td>`/`<th>` was collected, and
/// 4. every non-whitespace character in the block sits inside some `<td>`/`<th>` — nothing outside
///    the cells, and nothing after `</table>`.
///
/// A block failing any of them stays an ordinary `Html` leaf, rendered exactly as it was before this
/// function existed. Conditions 3 and 4 are the same rule at two strengths, and the rule is: **this
/// variant can carry cell text and nothing else, so it must never be given a block holding text it
/// cannot carry.** Condition 3 keeps out a caption-only or entirely empty `<table>` (no cell at all);
/// condition 4 keeps out a table whose cells are real but which *also* holds a `<caption>`, a stray
/// line inside the `<table>` or a `<tr>`, or prose between two cells — folding either would delete
/// those characters from the screen, whereas leaving the block alone keeps the current, lossless
/// rendering. `fold_details` takes the identical decision for the identical situation ("unrelated
/// content following the found close within it — stays an ordinary, unfolded `Html` leaf"). Condition
/// 2 is what makes a `<table>` interrupted by a blank line safe: CommonMark ends an HTML block at a
/// blank line, so such a `<table>`'s own opening half arrives here with no `</table>` in it at all
/// and is left alone (its trailing half is a *separate* block whose own first tag is not `<table>`,
/// so it never reaches here).
///
/// ## Structural tags, and everything else
///
/// `<tr>` opens a row, `</tr>` closes it; `<td>`/`<th>` open a cell, `</td>`/`</th>` close it. End
/// tags may be omitted the way HTML allows: a new `<tr>`/`<td>`/`<th>`, a `</tr>`, or the table's own
/// `</table>` all implicitly close whatever cell is open, and a `<tr>`/`</table>` likewise closes an
/// open row. A `<td>`/`<th>` outside any `<tr>` opens an implicit row of its own rather than being
/// dropped. Every other tag — `<thead>`/`<tbody>`/`<tfoot>`, `<colgroup>`/`<col>`, `<caption>`, and
/// all inline markup — is *not* structural: it is simply part of whatever cell is currently open (or,
/// outside every cell, ignored), which is what makes `<thead>`/`<tbody>` wrappers and arbitrary inline
/// HTML inside a cell both work with no case of their own. Tag names are matched case-insensitively,
/// so `<TABLE>`/`<TD>` read the same as the lowercase spellings. "Ignored" there means the *tag* —
/// markup carries no characters of its own — but any **text** such a tag wraps outside a cell (a
/// `<caption>`'s words, most of all) is not ignored: it trips condition 4 and the block declines to
/// fold, so the words survive.
///
/// An `<!-- … -->` comment is **not** scanned for tags at all: it is text the author removed, so a
/// `<tr>`/`<td>`/`<table>`/`</table>` inside one is skipped whole rather than read as this table's
/// structure (`super::html_comment_end`, the same rule `render_html_block` applies when it drops a
/// comment from an un-folded HTML block). Without it a commented-out `<tr>` folded into a real row
/// whose own byte range no longer held the `<!--` that hid it, and the row was drawn — the author's
/// deleted text, disclosed. A comment lying *inside* a cell simply stays part of that cell's content,
/// where the cell renderer drops it, exactly as it does for an ordinary HTML block.
fn parse_html_table(body_spans: &[Range<usize>], src: &str) -> Option<Vec<Vec<HtmlTableCell>>> {
    let text = html_body_text(body_spans, src);
    // Offset in `text` -> offset in `src`. `text` is the spans concatenated in order, so
    // `starts[i]` — the cumulative length before span `i` — is where span `i`'s own bytes begin in
    // `text`, and `partition_point` finds which span an offset landed in with a binary search
    // rather than a scan (this is called twice per cell, so scanning would make a table's parse
    // cost quadratic in its own line count).
    let mut starts: Vec<usize> = Vec::with_capacity(body_spans.len());
    let mut seen = 0usize;
    for r in body_spans {
        starts.push(seen);
        seen += r.end - r.start;
    }
    let span_offset = |at: usize| -> usize {
        // `partition_point` never exceeds `starts.len()`, so `i` always indexes both vectors (they
        // are built with the same length); `get` all the same, per principle #3. `checked_sub`
        // fails only for an empty `body_spans`, whose `text` is empty too.
        let i = starts.partition_point(|&s| s <= at).checked_sub(1);
        match i.and_then(|i| Some((body_spans.get(i)?, *starts.get(i)?))) {
            // `at` past the last span's own content (`at == text.len()`, or defensively beyond it)
            // clamps to that span's end rather than running off it.
            Some((r, s)) => (r.start + (at - s)).min(r.end),
            None => body_spans.first().map(|r| r.start).unwrap_or(0),
        }
    };
    // Set to the offset just past the outer `</table>` once it is found, so the trailing-content
    // check below can look at what (if anything) the block still holds after it.
    let mut after_close = 0usize;

    let mut rows: Vec<Vec<HtmlTableCell>> = Vec::new();
    let mut row: Vec<HtmlTableCell> = Vec::new();
    let mut open_cell: Option<(usize, bool, Option<Alignment>)> = None;
    let mut in_row = false;
    // How many `<table>` opens are currently unclosed. The outer table's own structural tags are the
    // ones seen at depth 1; anything at depth 2+ belongs to a nested table and is left inside the
    // enclosing cell's own range as ordinary content (see `BlockKind::HtmlTable`'s doc comment).
    let mut depth = 0usize;
    let mut closed = false;
    let mut first_tag = true;

    let mut i = 0usize;
    while let Some(rel) = text[i..].find('<') {
        let lt = i + rel;
        // Characters sitting between the previous tag (or comment) and this one, with no `<td>`/
        // `<th>` open around them, belong to no cell — a `<caption>`'s text, a stray line inside the
        // `<table>` or a `<tr>`, prose between two cells. `HtmlTable` carries cell ranges and
        // nothing else, so folding would delete them from the screen, which is exactly the silent
        // loss the trailing-content check below already refuses (and `fold_details` before it).
        // Same judgment, same answer: decline to fold, and let the ordinary `Html` path draw the
        // block tag-stripped, with every character still in it. Whitespace does not count (it is
        // the layout of every real table's markup), and neither does a comment — the branch right
        // below moves `i` past a whole comment, so its removed text is never part of a run examined
        // here, the same way it is never read as structure.
        if open_cell.is_none() && !text[i..lt].trim().is_empty() {
            return None;
        }
        // A comment is text the author removed, not markup: skip all of it, so a `<tr>`, a `<td>`, a
        // `<table>` or a `</table>` written inside one is never read as this table's own structure.
        // Through `super::html_comment_end` — the pipeline's one comment rule, shared with
        // `render_html_block`, which is what actually decides whether a run of bytes is visible (see
        // that function's own doc comment for why agreeing with it, rather than with the CommonMark
        // letter, is the safe direction here). Always moves `i` past `lt`, so this cannot loop.
        if let Some(end) = super::html_comment_end(&text, lt) {
            i = end;
            continue;
        }
        let Some(rel_gt) = text[lt..].find('>') else {
            break;
        };
        let gt = lt + rel_gt;
        // The tag verbatim, `<`/`>` excluded, plus its name and open/close sense.
        let tag = &text[lt + 1..gt];
        i = gt + 1;
        let close = tag.starts_with('/');
        let name: String = tag
            .trim_start_matches('/')
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
            .collect();
        let name = name.to_ascii_lowercase();
        if first_tag {
            first_tag = false;
            if close || name != "table" {
                return None;
            }
        }
        let close_cell_at = |end: usize,
                             open_cell: &mut Option<(usize, bool, Option<Alignment>)>,
                             row: &mut Vec<HtmlTableCell>| {
            if let Some((start, header, align)) = open_cell.take() {
                row.push(HtmlTableCell {
                    inner: span_offset(start)..span_offset(end.max(start)),
                    header,
                    align,
                });
            }
        };
        match name.as_str() {
            "table" if !close => depth += 1,
            "table" if close => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    close_cell_at(lt, &mut open_cell, &mut row);
                    if in_row || !row.is_empty() {
                        rows.push(std::mem::take(&mut row));
                    }
                    closed = true;
                    after_close = i;
                    break;
                }
            }
            "tr" | "td" | "th" if depth == 1 => {
                close_cell_at(lt, &mut open_cell, &mut row);
                if name == "tr" {
                    if in_row || !row.is_empty() {
                        rows.push(std::mem::take(&mut row));
                    }
                    in_row = !close;
                } else if !close {
                    // A `<td>`/`<th>` with no enclosing `<tr>` opens a row of its own.
                    in_row = true;
                    open_cell = Some((i, name == "th", html_align_attr(tag)));
                }
            }
            _ => {}
        }
    }
    if !closed || rows.iter().all(|r| r.is_empty()) {
        return None;
    }
    // Anything but whitespace still sitting in this block *after* the table's own `</table>` is not
    // the table's — CommonMark only ends an HTML block at a blank line, so a `</table>` immediately
    // followed by a paragraph, a `<br>`, or a wrapper's closing tag arrives here glued onto the very
    // same block. Nothing in this variant can carry that text, and folding anyway would silently
    // drop it, so the whole block declines to fold and renders exactly as it always has. This is
    // `fold_details`'s own choice for the identical situation ("unrelated content following the
    // found close within it — stays an ordinary, unfolded `Html` leaf") and the second half of
    // condition 4 — the loop above already refused, on identical grounds, every non-whitespace
    // character outside a cell *before* the close. The shape is vanishingly
    // rare in practice: of 8,532 real `.md` files swept while this was written (`~/.cargo/registry`,
    // `~/work`, `~/.claude`), 18 contained a `<table>` and **none** had content on the line right
    // after its `</table>`.
    if !text[after_close..].trim().is_empty() {
        return None;
    }
    rows.retain(|r| !r.is_empty());
    Some(rows)
}

/// A cell's own `align="left|center|right"` attribute, read off the tag's own text with the same
/// attribute reader every other HTML attribute in this pipeline goes through
/// (`super::html_attr` — the one `extract_html_img` uses for `src`/`alt`, so quoting styles and
/// name matching can never drift between the two). `None` for an absent attribute, and for any value
/// this pipeline has no rendering for (`justify`, `char`, …) — see `HtmlTableCell.align`.
fn html_align_attr(tag: &str) -> Option<Alignment> {
    match super::html_attr(tag, "align")?
        .trim()
        .to_ascii_lowercase()
        .as_str()
    {
        "left" => Some(Alignment::Left),
        "center" => Some(Alignment::Center),
        "right" => Some(Alignment::Right),
        _ => None,
    }
}

/// Reads a best-effort tag name off an `HtmlBlock`'s own opening line — see `BlockKind::Html`'s doc
/// comment for exactly what this does and does not distinguish. `body_spans` must be this same
/// block's own `collect_html_body_spans` result: its first entry is exactly the block's first
/// physical line, `>`-marker-free even inside a block quote (see that function's own doc comment),
/// which is what makes reading the tag name off it — rather than off `src[block_range]` directly —
/// correct inside a block quote too, not merely for the top-level case where the two happen to
/// already agree (a block's *first* line is never `>`-marked even inside a quote; only its
/// *continuation* lines are — see `BlockKind::Html.body_spans`'s own doc comment).
fn html_tag_of(body_spans: &[Range<usize>], src: &str) -> Option<String> {
    let first_line = body_spans
        .first()
        .map(|r| src[r.clone()].lines().next().unwrap_or(""))
        .unwrap_or("")
        .trim_end();
    if super::details_open_tag(first_line).is_some() || super::is_details_close(first_line) {
        return Some("details".to_string());
    }
    html_tag_name(first_line)
}

/// A permissive, best-effort HTML tag name off the start of `line`: `<name`/`</name`, taking every
/// following ASCII alphanumeric-or-hyphen character as part of the name (so `<detailsx>` reads as
/// `"detailsx"`, not a truncated match on `"details"` — the full run is compared, not a prefix).
/// `None` for anything that is not a plain opening/closing tag at all — a comment (`<!--`), a
/// declaration (`<!DOCTYPE`), or a processing instruction (`<?php`) — since none of those has a
/// "tag name" in the sense this field means.
fn html_tag_name(line: &str) -> Option<String> {
    let rest = line.trim_start().strip_prefix('<')?;
    let rest = rest.strip_prefix('/').unwrap_or(rest);
    if rest.starts_with(['!', '?']) {
        return None;
    }
    let name: String = rest
        .chars()
        .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
        .collect();
    if name.is_empty() {
        None
    } else {
        Some(name.to_ascii_lowercase())
    }
}

/// Whether the block quote at `range` opens with a GitHub alert header (`> [!NOTE]`, optionally
/// followed by an Obsidian-style title) — decided by handing the quote's own first line to the
/// render pipeline's real `parse_alert_header`, not a second parser of this module's own. Returns
/// that same call's own title text too (`String::new()` when there is no alert, or the header
/// carried none) — see `BlockKind::Quote.alert_title`'s own doc comment for why it travels
/// alongside `alert` as a sibling field rather than folded into it.
fn alert_kind_of(src: &str, range: &Range<usize>) -> (Option<AlertKind>, String) {
    let first_line = src[range.clone()].lines().next().unwrap_or("");
    match super::parse_alert_header(first_line) {
        Some((kind, title)) => (Some(kind), title),
        None => (None, String::new()),
    }
}

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

    /// Pins the exact, asymmetric byte range `render.rs`'s own `render_paragraph_math` doc comment
    /// cites as the reason a quoted paragraph's text is never scanned for math directly from
    /// `Block.src`: a quoted `Paragraph`'s own range excludes the `>` marker on its *first* line
    /// (`Paragraph`'s own `src.start` lands right after it) but *includes* it on every continuation
    /// line (the range simply runs to the end of whatever pulldown-cmark last consumed, markers and
    /// all) — so a naive line-based `>`-prefix check over that one range would misjudge the first
    /// line every time.
    #[test]
    fn quoted_paragraph_src_range_excludes_the_first_lines_marker_but_not_a_continuation_lines() {
        let src = "> hello $x$ world\n> line2\n";
        let doc = Doc::parse(src);
        let BlockKind::Quote { .. } = &doc.blocks[0].kind else {
            panic!("expected a top-level quote: {:?}", doc.blocks[0].kind);
        };
        assert_eq!(doc.blocks[0].children.len(), 1);
        let child = &doc.blocks[0].children[0];
        assert!(matches!(&child.kind, BlockKind::Paragraph { .. }));
        assert_eq!(&src[child.src.clone()], "hello $x$ world\n> line2\n");
    }

    /// Pins the tight list item counterpart: unlike a quote, a list marker is never repeated on a
    /// continuation line, so a **synthetic** first paragraph's own range (`collect_stray_inline_run`)
    /// never includes any container marker at all — no asymmetry to guard against there, which is
    /// exactly why `render.rs`'s own `walk_inline_math` is safe to scan a list item's first child
    /// directly (see that module's own doc comment on `render_doc`'s `math_here` for the contrast).
    #[test]
    fn tight_list_items_synthetic_first_paragraph_never_includes_the_bullet_marker() {
        let src = "- item $x$ here\n- second\n";
        let doc = Doc::parse(src);
        let BlockKind::List { .. } = &doc.blocks[0].kind else {
            panic!("expected a top-level list: {:?}", doc.blocks[0].kind);
        };
        assert_eq!(doc.blocks[0].children.len(), 2);
        let BlockKind::ListItem { .. } = &doc.blocks[0].children[0].kind else {
            panic!("expected the first list item");
        };
        let first_child = &doc.blocks[0].children[0].children[0];
        assert!(matches!(&first_child.kind, BlockKind::Paragraph { .. }));
        assert_eq!(&src[first_child.src.clone()], "item $x$ here");
    }

    /// Concatenates every `Event::Text`/`Event::Code`/`Event::SoftBreak`(→ `" "`)/
    /// `Event::HardBreak`(→ `"\n"`) payload in `doc.events[inline]`, in order — a minimal,
    /// style-blind reconstruction, good enough for a unit test to confirm a leaf's own `inline`
    /// range names the right slice of `Doc.events` (and, implicitly, that it excludes whatever it
    /// is supposed to — a task marker, the block's own wrapping `Start`/`End` — since any of those
    /// leaking in would show up here as extra text). `render.rs`'s own diff harness is the
    /// exhaustive, style-aware check on top of this; this helper only needs to catch "wrong slice
    /// entirely" at the unit-test level.
    fn inline_plain_text(doc: &Doc<'_>, inline: &Range<usize>) -> String {
        let mut s = String::new();
        for (ev, _) in &doc.events[inline.clone()] {
            match ev {
                Event::Text(t) => s.push_str(t),
                Event::Code(c) => s.push_str(c),
                Event::SoftBreak => s.push(' '),
                Event::HardBreak => s.push('\n'),
                _ => {}
            }
        }
        s
    }

    // ---- construction sanity: one focused case per construct -------------------------------

    #[test]
    fn heading_and_paragraph_are_leaves_with_no_children() {
        let doc = Doc::parse("# Title\n\nbody\n");
        assert_eq!(doc.blocks.len(), 2);
        let BlockKind::Heading {
            level: 1, inline, ..
        } = &doc.blocks[0].kind
        else {
            panic!("expected a level-1 heading")
        };
        assert_eq!(inline_plain_text(&doc, inline), "Title");
        assert!(doc.blocks[0].children.is_empty());
        assert_eq!(doc.blocks[0].src, 0..8);
        let BlockKind::Paragraph { inline } = &doc.blocks[1].kind else {
            panic!("expected a paragraph")
        };
        assert_eq!(inline_plain_text(&doc, inline), "body");
        assert_eq!(doc.blocks[1].src, 9..14);
    }

    #[test]
    fn heading_level_matches_the_number_of_hashes() {
        for (n, marker) in [
            (1, "#"),
            (2, "##"),
            (3, "###"),
            (4, "####"),
            (5, "#####"),
            (6, "######"),
        ] {
            let src = format!("{marker} h\n");
            let doc = Doc::parse(&src);
            let BlockKind::Heading { level, inline, .. } = &doc.blocks[0].kind else {
                panic!("expected a heading for {marker:?}")
            };
            assert_eq!(*level, n, "marker {marker:?}");
            assert_eq!(inline_plain_text(&doc, inline), "h");
        }
    }

    #[test]
    fn heading_attributes_are_captured_as_owned_data() {
        // `{#id .class key=value}` heading-attribute syntax used to only ever reach `render.rs` by
        // re-parsing the heading's own byte range a second time (`Tag::Heading`'s `id`/`classes`/
        // `attrs` fields) — `Doc::parse` now captures the exact same data itself, converted to owned
        // `String`s, so a caller never needs a second parse to read it.
        let doc = Doc::parse("## Custom Heading {#custom-id .note lang=en}\n");
        let BlockKind::Heading {
            id,
            classes,
            attrs,
            inline,
            ..
        } = &doc.blocks[0].kind
        else {
            panic!("expected a heading")
        };
        assert_eq!(id.as_deref(), Some("custom-id"));
        assert_eq!(classes, &["note".to_string()]);
        assert_eq!(attrs, &[("lang".to_string(), Some("en".to_string()))]);
        // The attribute block itself is not part of the heading's own inline *content* — it is a
        // separate field pulldown-cmark reports on `Tag::Heading` itself, not an inline event.
        assert_eq!(inline_plain_text(&doc, inline), "Custom Heading");
    }

    #[test]
    fn heading_with_no_attribute_syntax_has_none_and_empty() {
        let doc = Doc::parse("## Plain\n");
        let BlockKind::Heading {
            id, classes, attrs, ..
        } = &doc.blocks[0].kind
        else {
            panic!("expected a heading")
        };
        assert_eq!(*id, None);
        assert!(classes.is_empty());
        assert!(attrs.is_empty());
    }

    #[test]
    fn reference_link_with_definition_in_a_different_block_resolves_across_the_whole_document() {
        // The whole point of `Doc::parse` walking the document once instead of block-by-block: a
        // resolved reference link's label becomes an `Event::Text` inside a real `Tag::Link`, not
        // literal bracket text, only if the parser has already seen the `[ref]: url` definition
        // (here, in the *next* top-level block) by the time it reaches this paragraph — something a
        // per-block re-parse (an earlier version of `render.rs`) could never see, because a link
        // reference definition contributes no events of its own to any block's range at all (see
        // `md_render_diff_tests`'s own module doc comment).
        let doc = Doc::parse("See [the docs][ref] here.\n\n[ref]: https://example.com/docs\n");
        let BlockKind::Paragraph { inline } = &doc.blocks[0].kind else {
            panic!("expected a paragraph")
        };
        assert_eq!(inline_plain_text(&doc, inline), "See the docs here.");

        // Control: a dangling reference (no definition anywhere) reports the literal bracket text
        // instead of a `Link`'s label — this reconstruction shows exactly that difference, rather
        // than merely asserting the two cases differ.
        let dangling = Doc::parse("See [the docs][missing] here.\n");
        let BlockKind::Paragraph { inline } = &dangling.blocks[0].kind else {
            panic!("expected a paragraph")
        };
        assert_eq!(
            inline_plain_text(&dangling, inline),
            "See [the docs][missing] here."
        );
    }

    #[test]
    fn fenced_code_block_body_excludes_fence_and_info_string() {
        let src = "```rust\nfn a() {}\nfn b() {}\n```\n";
        let doc = Doc::parse(src);
        let BlockKind::CodeBlock {
            lang,
            fenced,
            body_spans,
        } = &doc.blocks[0].kind
        else {
            panic!("expected a code block")
        };
        assert_eq!(lang.as_deref(), Some("rust"));
        assert!(fenced);
        assert_eq!(
            code_body_text(body_spans, src),
            "fn a() {}\nfn b() {}",
            "content, with the one trailing newline stripped"
        );
    }

    #[test]
    fn fenced_code_block_with_no_info_string_has_no_lang() {
        let doc = Doc::parse("```\nplain\n```\n");
        let BlockKind::CodeBlock { lang, fenced, .. } = &doc.blocks[0].kind else {
            panic!("expected a code block")
        };
        assert_eq!(*lang, None);
        assert!(fenced);
    }

    #[test]
    fn indented_code_block_is_not_fenced_and_has_no_lang() {
        let doc = Doc::parse("para\n\n    line one\n    line two\n");
        let BlockKind::CodeBlock { lang, fenced, .. } = &doc.blocks[1].kind else {
            panic!("expected a code block")
        };
        assert_eq!(*lang, None);
        assert!(!fenced);
    }

    #[test]
    fn empty_fenced_code_block_has_no_body_spans() {
        let src = "```\n```\n";
        let doc = Doc::parse(src);
        let BlockKind::CodeBlock { body_spans, .. } = &doc.blocks[0].kind else {
            panic!("expected a code block")
        };
        assert_eq!(
            body_spans,
            &Vec::<Range<usize>>::new(),
            "an empty code block reports no Event::Text spans at all"
        );
        assert_eq!(code_body_text(body_spans, src), "");
    }

    #[test]
    fn list_children_are_items_and_ordered_lists_report_their_start() {
        let doc = Doc::parse("5. a\n6. b\n");
        assert_eq!(doc.blocks.len(), 1);
        let BlockKind::List { ordered, start } = doc.blocks[0].kind else {
            panic!("expected a list")
        };
        assert!(ordered);
        assert_eq!(start, Some(5));
        assert_eq!(doc.blocks[0].children.len(), 2);
        for item in &doc.blocks[0].children {
            assert!(matches!(item.kind, BlockKind::ListItem { task: None }));
        }
    }

    #[test]
    fn bullet_list_is_unordered_with_no_start() {
        let doc = Doc::parse("- a\n- b\n");
        let BlockKind::List { ordered, start } = doc.blocks[0].kind else {
            panic!("expected a list")
        };
        assert!(!ordered);
        assert_eq!(start, None);
    }

    #[test]
    fn tight_list_item_gets_a_synthetic_paragraph_child_loose_item_gets_a_real_one() {
        // Tight item: pulldown-cmark emits the item's own text with no enclosing `Paragraph` at
        // all — `parse_blocks` still gives the model somewhere to represent it, coalescing the
        // stray inline run into a synthetic `Paragraph` (`collect_stray_inline_run`) rather than
        // leaving the item with no children at all (an earlier version of this model did exactly
        // that; see `BlockKind::ListItem`'s doc comment).
        let src = "- a\n- b\n";
        let tight = Doc::parse(src);
        assert_eq!(tight.blocks[0].children[0].children.len(), 1);
        let synthetic = &tight.blocks[0].children[0].children[0];
        let BlockKind::Paragraph { inline } = &synthetic.kind else {
            panic!("expected a synthetic paragraph")
        };
        assert_eq!(inline_plain_text(&tight, inline), "a");
        assert_eq!(&src[synthetic.src.clone()], "a");

        // Loose item: pulldown-cmark itself wraps the text in a real `Paragraph`, so there is no
        // coalescing to do — the model just represents what the parser already reported. Note the
        // real `Paragraph`'s own range includes the trailing newline ("a\n") the way pulldown-cmark
        // always reports a `Paragraph`'s range, while the synthetic one above does not (it is built
        // purely from `Event::Text`'s own, narrower range) — a real difference in convention between
        // the two, not a bug; see `collect_stray_inline_run`'s doc comment.
        let loose_src = "- a\n\n- b\n";
        let loose = Doc::parse(loose_src);
        assert_eq!(loose.blocks[0].children[0].children.len(), 1);
        let real = &loose.blocks[0].children[0].children[0];
        let BlockKind::Paragraph { inline } = &real.kind else {
            panic!("expected a real paragraph")
        };
        assert_eq!(inline_plain_text(&loose, inline), "a");
        assert_eq!(&loose_src[real.src.clone()], "a\n");
    }

    #[test]
    fn task_marker_state_and_position_are_exact() {
        let src = "- [ ] a\n- [x] b\n- [X] c\n";
        let doc = Doc::parse(src);
        let states: Vec<(char, usize)> = doc.blocks[0]
            .children
            .iter()
            .map(|item| {
                let BlockKind::ListItem { task } = &item.kind else {
                    panic!("expected a list item")
                };
                let t = task.expect("expected a task marker");
                (t.state, t.state_at)
            })
            .collect();
        assert_eq!(states, vec![(' ', 3), ('x', 11), ('X', 19)]);
        for (_, at) in &states {
            assert_eq!(src.as_bytes()[at - 1], b'[');
            assert_eq!(src.as_bytes()[at + 1], b']');
        }
    }

    #[test]
    fn loose_task_item_task_marker_is_still_captured() {
        // Gap A: a *loose* item's `Event::TaskListMarker` sits inside the item's own first
        // `Paragraph`, not directly after `Start(Item)` the way a tight item's does — see
        // `parse_item_task_and_children`'s doc comment. An earlier version of this model only ever
        // peeked right after `Start(Item)`, so a loose task item's marker was silently dropped
        // (`task: None`) even though pulldown-cmark reported it.
        let src = "- [ ] outer\n\n  - [ ] nested at matching indent\n";
        let doc = Doc::parse(src);
        let outer = &doc.blocks[0].children[0];
        let BlockKind::ListItem { task } = &outer.kind else {
            panic!("expected a list item")
        };
        let t = task.expect("expected the outer (loose) item's task marker to be captured");
        assert_eq!((t.state, t.state_at), (' ', 3));
        // The item's own first child is still its real `Paragraph` (loose items get one) — the
        // marker being captured on the side does not change that, and the marker's own three bytes
        // (`[`, the state char, `]`) must not leak into the paragraph's own `inline` range either.
        let BlockKind::Paragraph { inline } = &outer.children[0].kind else {
            panic!("expected the loose item's own paragraph")
        };
        assert_eq!(inline_plain_text(&doc, inline), "outer");

        // The nested item's own marker (necessarily a *tight* one — a lone item can't itself be
        // loose) is captured too, with no leakage between the outer item's own marker lookup and
        // the inner one's independent call to the same function.
        let nested_list = &outer.children[1];
        let nested_item = &nested_list.children[0];
        let BlockKind::ListItem {
            task: nested_task, ..
        } = &nested_item.kind
        else {
            panic!("expected the nested list item")
        };
        let nested = nested_task.expect("expected the nested item's own marker to be captured");
        assert_eq!(nested.state, ' ');
    }

    #[test]
    fn tight_list_item_starting_with_inline_formatting_is_still_captured() {
        // Gap B, the harder case: a tight item whose content does not start with plain text at all
        // — pulldown-cmark can hand `parse_blocks` the `Start` of an inline construct
        // (`Start(Strong)`/`Start(Link)`/...) directly, with no leading `Text` event to notice
        // first. `collect_stray_inline_run` has to balance that construct's own subtree
        // (`skip_inline_to`) for real, not just record its range — an earlier version of this
        // function forgot to do that for the *first* event specifically, desyncing the event
        // stream on exactly this shape (see its own doc comment): every block appearing anywhere
        // after this item in that earlier version came out with corrupted, overlapping ranges.
        let src = "- **bold** and *em* and `code` end\n";
        let doc = Doc::parse(src);
        let item = &doc.blocks[0].children[0];
        assert_eq!(item.children.len(), 1);
        let synthetic = &item.children[0];
        let BlockKind::Paragraph { inline } = &synthetic.kind else {
            panic!("expected a synthetic paragraph")
        };
        assert_eq!(
            &src[synthetic.src.clone()],
            "**bold** and *em* and `code` end"
        );
        // `collect_stray_inline_run`'s own event-desync bug (see above) would have corrupted this
        // range too — the plain-text reconstruction from `doc.events[inline]` is a second, coarser
        // proof the run's own events line up correctly, on top of the byte-range check above.
        assert_eq!(inline_plain_text(&doc, inline), "bold and em and code end");
    }

    #[test]
    fn non_task_list_item_has_no_task() {
        let doc = Doc::parse("- plain\n");
        let BlockKind::ListItem { task } = doc.blocks[0].children[0].kind else {
            panic!("expected a list item")
        };
        assert_eq!(task, None);
    }

    #[test]
    fn custom_task_state_char_is_not_recognized_as_a_task_by_pulldown_cmark() {
        // Documents the limitation `Task`'s doc comment describes: `[/]` is not GFM task syntax,
        // so no `Event::TaskListMarker` fires and this model reports no task at all for it.
        let doc = Doc::parse("- [/] in progress\n");
        let BlockKind::ListItem { task } = doc.blocks[0].children[0].kind else {
            panic!("expected a list item")
        };
        assert_eq!(
            task, None,
            "pulldown-cmark does not emit TaskListMarker for a custom state"
        );
    }

    #[test]
    fn block_quote_alert_kind_uses_the_real_alert_header_parser() {
        let doc = Doc::parse("> [!WARNING] Heads up\n> body\n");
        let BlockKind::Quote { alert, alert_title } = doc.blocks[0].kind.clone() else {
            panic!("expected a quote")
        };
        assert_eq!(alert, Some(AlertKind::Warning));
        assert_eq!(
            alert_title, "Heads up",
            "the header's own Obsidian-style trailing title travels alongside alert"
        );
    }

    #[test]
    fn plain_block_quote_has_no_alert_kind() {
        let doc = Doc::parse("> just a quote\n");
        let BlockKind::Quote { alert, alert_title } = doc.blocks[0].kind.clone() else {
            panic!("expected a quote")
        };
        assert_eq!(alert, None);
        assert_eq!(alert_title, "", "no alert header means no title either");
    }

    #[test]
    fn table_rows_have_header_first_then_body_with_correct_alignment() {
        let src = "| a | b |\n|:--|--:|\n| 1 | 2 |\n| 3 | 4 |\n";
        let doc = Doc::parse(src);
        let BlockKind::Table { aligns, rows } = &doc.blocks[0].kind else {
            panic!("expected a table")
        };
        assert_eq!(aligns, &[Alignment::Left, Alignment::Right]);
        assert_eq!(rows.len(), 3, "1 header row + 2 body rows");
        assert_eq!(&src[rows[0][0].clone()], " a ");
        assert_eq!(&src[rows[0][1].clone()], " b ");
        assert_eq!(&src[rows[1][0].clone()], " 1 ");
        assert_eq!(&src[rows[2][1].clone()], " 4 ");
    }

    #[test]
    fn table_with_no_alignment_colons_reports_none_not_left() {
        // Distinguishes this from the render pipeline's own `ColAlign`, which has no "unspecified"
        // state and would default this to `Left` for display — the model keeps CommonMark's real
        // answer (see `BlockKind::Table`'s doc comment).
        let doc = Doc::parse("| a |\n|---|\n| 1 |\n");
        let BlockKind::Table { aligns, .. } = &doc.blocks[0].kind else {
            panic!("expected a table")
        };
        assert_eq!(aligns, &[Alignment::None]);
    }

    #[test]
    fn html_block_tag_name_is_read_from_the_opening_line() {
        let doc = Doc::parse("<div class=\"x\">\nhello\n</div>\n");
        let BlockKind::Html { tag, .. } = &doc.blocks[0].kind else {
            panic!("expected an html block")
        };
        assert_eq!(tag.as_deref(), Some("div"));
    }

    #[test]
    fn html_comment_block_has_no_tag_name() {
        let doc = Doc::parse("<!-- a comment -->\n");
        let BlockKind::Html { tag, .. } = &doc.blocks[0].kind else {
            panic!("expected an html block")
        };
        assert_eq!(*tag, None);
    }

    // ---- `<table>` folding (`BlockKind::HtmlTable`) ----

    /// The one shape this whole feature exists for: a `<table>` split across physical lines, one
    /// `<td>` per line, comes back as a real 2x2 grid rather than an opaque `Html` leaf.
    #[test]
    fn a_complete_html_table_folds_into_rows_of_cells() {
        let src = "<table>\n<tr>\n<td>a</td>\n<td>b</td>\n</tr>\n<tr>\n<td>c</td>\n<td>d</td>\n</tr>\n</table>\n";
        let doc = Doc::parse(src);
        assert_eq!(doc.blocks.len(), 1);
        let BlockKind::HtmlTable { body_spans, rows } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable: {:?}", doc.blocks[0].kind)
        };
        let text: Vec<Vec<String>> = rows
            .iter()
            .map(|r| {
                r.iter()
                    .map(|c| html_body_text_in(body_spans, src, &c.inner))
                    .collect()
            })
            .collect();
        assert_eq!(text, vec![vec!["a", "b"], vec!["c", "d"]]);
        assert!(
            doc.blocks[0].children.is_empty(),
            "an HtmlTable is a leaf, like the Html block it replaces"
        );
    }

    /// `inner` names the cell's own content and nothing else — not its tags, not its padding.
    #[test]
    fn html_table_cell_inner_excludes_both_of_its_own_tags() {
        let src = "<table><tr><td>abc</td></tr></table>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { rows, .. } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable")
        };
        let inner = rows[0][0].inner.clone();
        assert_eq!(&src[inner.clone()], "abc");
        assert_eq!(&src[inner.start - 4..inner.start], "<td>");
        assert_eq!(&src[inner.end..inner.end + 5], "</td>");
    }

    /// A paragraph glued onto the same HTML block right after `</table>` must never go missing: the
    /// block declines to fold, so its text is still drawn by the ordinary `Html` path. Checked as
    /// *content preservation*, not merely as "no HtmlTable" — losing a line silently is the failure
    /// this guard exists to prevent.
    #[test]
    fn text_glued_after_the_close_is_never_dropped() {
        let src = "<table>\n<tr><td>a</td></tr>\n</table>\nafter\n";
        let doc = Doc::parse(src);
        let BlockKind::Html { body_spans, .. } = &doc.blocks[0].kind else {
            panic!("expected a plain Html leaf: {:?}", doc.blocks[0].kind)
        };
        assert!(
            html_body_text(body_spans, src).contains("after"),
            "the trailing paragraph is still part of what the renderer draws"
        );
    }

    /// `<th>` and `align=` travel on the cell, not the column — HTML has no delimiter row, so there
    /// is nowhere else for either to live (see `HtmlTableCell`'s own doc comment).
    #[test]
    fn html_table_reads_th_and_the_align_attribute_per_cell() {
        let src = "<table>\n<tr><th align=\"center\">H</th><th>P</th></tr>\n<tr><td align='right'>a</td><td align=\"justify\">b</td></tr>\n</table>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { rows, .. } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable")
        };
        assert!(rows[0].iter().all(|c| c.header), "first row is all <th>");
        assert!(!rows[1].iter().any(|c| c.header), "second row is all <td>");
        assert_eq!(rows[0][0].align, Some(Alignment::Center));
        assert_eq!(rows[0][1].align, None, "no align attribute at all");
        assert_eq!(
            rows[1][0].align,
            Some(Alignment::Right),
            "single-quoted value"
        );
        assert_eq!(
            rows[1][1].align, None,
            "`justify` has no rendering here, so it reads as unspecified"
        );
    }

    /// Tag names are matched case-insensitively, the same way `html_tag_name` already lowercases the
    /// block's own opening tag.
    #[test]
    fn html_table_recognizes_uppercase_tags() {
        let src = "<TABLE>\n<TR><TH>H</TH></TR>\n<TR><TD>b</TD></TR>\n</TABLE>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { rows, .. } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable: {:?}", doc.blocks[0].kind)
        };
        assert_eq!(rows.len(), 2);
        assert!(rows[0][0].header);
        assert!(!rows[1][0].header);
    }

    /// `<thead>`/`<tbody>`/`<tfoot>`/`<colgroup>` are not structural here — they are simply not
    /// `<tr>`/`<td>`/`<th>`, so they need no case of their own and change nothing.
    #[test]
    fn html_table_ignores_section_wrappers() {
        let src = "<table>\n<colgroup><col><col></colgroup>\n<thead><tr><th>H</th><th>I</th></tr></thead>\n<tbody><tr><td>a</td><td>b</td></tr></tbody>\n</table>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { rows, .. } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable")
        };
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].len(), 2);
        assert_eq!(rows[1].len(), 2);
    }

    /// HTML lets `</td>`/`</tr>` be omitted; the next opener closes whatever is open.
    #[test]
    fn html_table_handles_omitted_end_tags() {
        let src = "<table>\n<tr><td>a<td>b\n<tr><td>c<td>d\n</table>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { body_spans, rows } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable")
        };
        let text: Vec<Vec<String>> = rows
            .iter()
            .map(|r| {
                r.iter()
                    .map(|c| html_body_text_in(body_spans, src, &c.inner))
                    .collect()
            })
            .collect();
        assert_eq!(text, vec![vec!["a", "b\n"], vec!["c", "d\n"]]);
    }

    /// A `<td>` with no enclosing `<tr>` still gets a row rather than being dropped.
    #[test]
    fn html_table_cells_outside_any_row_get_an_implicit_one() {
        let src = "<table>\n<td>a</td><td>b</td>\n</table>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { rows, .. } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable")
        };
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].len(), 2);
    }

    /// A documented non-goal: an inner `<table>`'s own `</table>` must not end the outer one, and its
    /// markup stays inside the enclosing cell rather than producing rows of its own.
    #[test]
    fn html_table_leaves_a_nested_table_inside_its_enclosing_cell() {
        let src = "<table>\n<tr><td><table><tr><td>inner</td></tr></table></td><td>outer</td></tr>\n</table>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { body_spans, rows } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable")
        };
        assert_eq!(rows.len(), 1, "only the outer table produces rows");
        assert_eq!(rows[0].len(), 2);
        assert_eq!(
            html_body_text_in(body_spans, src, &rows[0][0].inner),
            "<table><tr><td>inner</td></tr></table>",
            "the nested table's markup is the outer cell's own content"
        );
    }

    /// A documented non-goal: `colspan` is one ordinary cell, so the row simply comes out short.
    #[test]
    fn html_table_reads_a_colspan_cell_as_one_plain_cell() {
        let src = "<table>\n<tr><td colspan=\"2\">wide</td></tr>\n<tr><td>a</td><td>b</td></tr>\n</table>\n";
        let doc = Doc::parse(src);
        let BlockKind::HtmlTable { rows, .. } = &doc.blocks[0].kind else {
            panic!("expected an HtmlTable")
        };
        assert_eq!(rows[0].len(), 1);
        assert_eq!(rows[1].len(), 2);
    }

    /// Inside a block quote, `Block::src` still carries every continuation line's `>` marker while
    /// `body_spans` does not — so a cell spanning several lines has to be read back through the
    /// spans (`html_body_text_in`), never as `&src[inner]`. This pins both halves of that: the
    /// marker-free reading *and* the fact that the naive slice really would have been wrong.
    #[test]
    fn html_table_in_a_quote_reads_a_multi_line_cell_without_the_quote_marker() {
        let src = "> <table>\n> <tr>\n> <td>\n> first\n> second\n> </td>\n> </tr>\n> </table>\n";
        let doc = Doc::parse(src);
        let quote = &doc.blocks[0];
        assert!(matches!(quote.kind, BlockKind::Quote { .. }));
        let BlockKind::HtmlTable { body_spans, rows } = &quote.children[0].kind else {
            panic!("expected an HtmlTable inside the quote")
        };
        let inner = rows[0][0].inner.clone();
        assert_eq!(
            html_body_text_in(body_spans, src, &inner),
            "\nfirst\nsecond\n"
        );
        assert!(
            src[inner].contains(">"),
            "the naive `&src[inner]` slice really does still carry the quote markers"
        );
    }

    /// Every cell's `inner` range really is bounded by its **own tags in `src`** — the property
    /// `HtmlTableCell.inner`'s doc comment states ("everything strictly between its `<td …>`/`<th
    /// …>` tag's own closing `>` and its matching `</td>`/`</th>`'s own opening `<`") — checked on
    /// the one family of inputs where `parse_html_table`'s `span_offset` map can get it wrong.
    ///
    /// **Why a quote.** Outside a block quote an HTML block's `body_spans` are contiguous
    /// (`"<table>\n"` = `0..8`, `"<tr>\n"` = `8..13`, …), so an offset sitting exactly on a span
    /// boundary maps to the same `src` byte whichever of the two adjacent spans it is attributed
    /// to, and an off-by-one-span map is unobservable. Inside a quote each continuation line's own
    /// `> ` marker sits in the **gap between** two spans, and the two attributions then differ by
    /// exactly that marker. A cell whose content ends at a line boundary — its closing tag is the
    /// first thing on the next line — is what separates them.
    ///
    /// **Why the range and not the text.** `html_body_text_in` clips every `body_spans` range to
    /// the wanted range, and the marker bytes belong to no span at all, so *both* attributions
    /// reconstruct byte-identical cell text. The test right above, and every other cell assertion
    /// in this tree, reads that text — so a mis-mapped range is invisible to all of them, and only
    /// the range itself (here, and `check_invariants`'s own corpus-wide version of this same
    /// property) can see it. It matters because `inner` is a `src` range: anything that later
    /// resolves it against the source rather than through `html_body_text_in` — an `<img src=…>`
    /// offset, an editor jump — would land on the `> ` marker instead of on the tag.
    #[test]
    fn a_quote_nested_cells_inner_range_is_bounded_by_its_own_tags_in_src() {
        // `(why, source)`. Every one of these closes a cell at the *start of a line*, which is the
        // only position at which the two attributions differ — one per way a cell can be closed
        // (explicit `</td>`, an implicit close by the next `<tr>`, by `</table>`), plus a `<th>`
        // carrying attributes, an empty cell, and a doubly-nested quote (whose gap is 4 bytes, not
        // 2, so a map that merely happened to be off by a fixed 2 would still fail here).
        for (why, src) in [
            (
                "a multi-line cell whose `</td>` opens the next line",
                "> <table>\n> <tr>\n> <td>\n> first line\n> second line\n> </td>\n> </tr>\n> </table>\n",
            ),
            (
                "a cell closed implicitly by the `<tr>` that opens the next line",
                "> <table>\n> <tr><td>a\n> <tr><td>b\n> </table>\n",
            ),
            (
                "a cell closed by the table's own `</table>` on the next line",
                "> <table>\n> <tr><td>only\n> </table>\n",
            ),
            (
                "a `<th align=…>` closed at the start of the next line",
                "> <table>\n> <tr><th align=\"right\">h\n> </th></tr>\n> </table>\n",
            ),
            (
                "an empty cell whose `</td>` opens the next line",
                "> <table>\n> <tr><td>\n> </td></tr>\n> </table>\n",
            ),
            (
                "two quote levels deep, so the gap between two spans is 4 bytes",
                "> > <table>\n> > <tr><td>x\n> > </table>\n",
            ),
        ] {
            let doc = Doc::parse(src);
            let mut seen = 0usize;
            for table in html_table_cells(&doc.blocks) {
                for row in table {
                    for cell in row {
                        seen += 1;
                        let r = &cell.inner;
                        assert!(
                            src[..r.start].ends_with('>'),
                            "{why}: セルの開始が自分の開きタグの `>` の直後でない \
                             ({r:?} の直前: {:?})",
                            src.get(r.start.saturating_sub(8)..r.start)
                        );
                        assert!(
                            src[r.end..].starts_with('<'),
                            "{why}: セルの終了が、それを閉じたタグの `<` の直前でない \
                             ({r:?} の直後: {:?})",
                            src.get(r.end..(r.end + 8).min(src.len()))
                        );
                    }
                }
            }
            assert!(seen > 0, "{why}: セルが 1 つも折り畳まれていない — 前提が崩れている");
        }
    }

    /// Every folded HTML table's rows, in source order, however deeply nested the table is —
    /// the cells themselves rather than `html_table_cell_text`'s reconstructed strings, for the
    /// assertions that are about the `inner` **ranges**.
    fn html_table_cells(blocks: &[Block]) -> Vec<&Vec<Vec<HtmlTableCell>>> {
        fn walk<'a>(blocks: &'a [Block], out: &mut Vec<&'a Vec<Vec<HtmlTableCell>>>) {
            for b in blocks {
                if let BlockKind::HtmlTable { rows, .. } = &b.kind {
                    out.push(rows);
                }
                walk(&b.children, out);
            }
        }
        let mut out = Vec::new();
        walk(blocks, &mut out);
        out
    }

    /// Every shape that is *not* one complete table stays an ordinary `Html` leaf, rendered exactly
    /// as it was before this variant existed. Grouped into one test on purpose: each of these is the
    /// same assertion about a different reason to decline, and splitting them would only repeat the
    /// same three lines six times.
    #[test]
    fn a_block_that_is_not_one_complete_table_stays_a_plain_html_leaf() {
        for (why, src) in [
            ("no closing tag at all", "<table>\n<tr><td>a</td></tr>\n"),
            (
                // Would otherwise silently drop `after` — see `parse_html_table`'s own doc comment.
                "content glued onto the block after the close",
                "<table>\n<tr><td>a</td></tr>\n</table>\nafter\n",
            ),
            ("no cell at all", "<table>\n</table>\n"),
            (
                "only a caption, no cell",
                "<table>\n<caption>C</caption>\n</table>\n",
            ),
            (
                "the table is not the block's own first tag",
                "<div>\n<table>\n<tr><td>a</td></tr>\n</table>\n</div>\n",
            ),
            (
                // CommonMark ends an HTML block at a blank line, so this never arrives as one block.
                "a blank line splits the table into two blocks",
                "<table>\n<tr>\n\n<td>a</td>\n</tr>\n</table>\n",
            ),
        ] {
            let doc = Doc::parse(src);
            assert!(
                !doc.blocks
                    .iter()
                    .any(|b| matches!(b.kind, BlockKind::HtmlTable { .. })),
                "{why}: expected no HtmlTable, got {:?}",
                doc.blocks.iter().map(|b| &b.kind).collect::<Vec<_>>()
            );
        }
    }

    /// Every `HtmlTable` in `doc`, as the text each of its cells actually holds — read back through
    /// `html_body_text_in`, which is exactly how `render.rs`'s `render_html_table_from_model` reads
    /// a cell (so a quoted table's `>` markers are gone here too, and a table nested inside another
    /// block is still found). One entry per table, in source order.
    fn html_table_cell_text(doc: &Doc, src: &str) -> Vec<Vec<Vec<String>>> {
        fn walk(blocks: &[Block], src: &str, out: &mut Vec<Vec<Vec<String>>>) {
            for b in blocks {
                if let BlockKind::HtmlTable { body_spans, rows } = &b.kind {
                    out.push(
                        rows.iter()
                            .map(|r| {
                                r.iter()
                                    .map(|c| html_body_text_in(body_spans, src, &c.inner))
                                    .collect()
                            })
                            .collect(),
                    );
                }
                walk(&b.children, src, out);
            }
        }
        let mut out = Vec::new();
        walk(&doc.blocks, src, &mut out);
        out
    }

    /// An empty `<tr></tr>` is markup with nothing in it, so it must never reach the renderer as a
    /// row: a table folded with one would draw a blank, full-width band between its real rows (and,
    /// right after a header, push the divider rule down past a row that holds nothing).
    ///
    /// Why this needed its own test: **no** corpus case, and no `samples/*.md` file, contained a
    /// `<tr>` with no cell in it, so `parse_html_table`'s `rows.retain(|r| !r.is_empty())` could be
    /// deleted outright and every table test in the tree still passed. The shape is ordinary in real
    /// documents — a row whose cells were commented out or cut leaves the `<tr></tr>` behind.
    ///
    /// A note on the guard's other half, recorded here rather than left for the next reader to
    /// rediscover: `in_row = !close` (the `tr` arm) and this `retain` are **not** independent. The
    /// only thing `in_row` ever decides is whether an *empty* row gets pushed, and `retain` then
    /// drops every empty row unconditionally — so replacing `in_row = !close` with a constant `true`
    /// is output-equivalent for every input while the `retain` stands, and no test can distinguish
    /// them. Only the `retain` is observable; it is the half this test pins.
    #[test]
    fn an_empty_tr_never_becomes_a_row() {
        // `(why, src, every table's cell text)`. An empty `want` means the block declines to fold.
        let cases = vec![
            (
                "an empty row before a real one",
                "<table><tr></tr><tr><td>a</td></tr></table>\n",
                vec![vec![vec!["a"]]],
            ),
            (
                "an empty row before a real one, one tag per line",
                "<table>\n<tr></tr>\n<tr><td>a</td><td>b</td></tr>\n</table>\n",
                vec![vec![vec!["a", "b"]]],
            ),
            (
                "an empty row after the last real one",
                "<table>\n<tr><td>a</td></tr>\n<tr></tr>\n</table>\n",
                vec![vec![vec!["a"]]],
            ),
            (
                "two empty rows in a row",
                "<table>\n<tr></tr>\n<tr></tr>\n<tr><td>a</td></tr>\n</table>\n",
                vec![vec![vec!["a"]]],
            ),
            (
                // The shape that also moves the header divider if the empty row survives.
                "an empty row between the header row and the body",
                "<table>\n<tr><th>H</th></tr>\n<tr></tr>\n<tr><td>a</td></tr>\n</table>\n",
                vec![vec![vec!["H"], vec!["a"]]],
            ),
            (
                "a row holding nothing but whitespace",
                "<table>\n<tr>  </tr>\n<tr><td>a</td></tr>\n</table>\n",
                vec![vec![vec!["a"]]],
            ),
            (
                // Nothing but empty rows: `rows.iter().all(|r| r.is_empty())` refuses the fold before
                // `retain` is ever reached, so this stays an ordinary `Html` leaf.
                "a table of nothing but empty rows",
                "<table>\n<tr></tr><tr></tr>\n</table>\n",
                vec![],
            ),
        ];
        let mut bad: Vec<String> = Vec::new();
        for (why, src, want) in cases {
            let want: Vec<Vec<Vec<String>>> = want
                .iter()
                .map(|t| {
                    t.iter()
                        .map(|r| r.iter().map(|c| (*c).to_string()).collect())
                        .collect()
                })
                .collect();
            let doc = Doc::parse(src);
            let got = html_table_cell_text(&doc, src);
            if got != want {
                bad.push(format!("{why}\n     got: {got:?}\n    want: {want:?}"));
            }
        }
        assert!(
            bad.is_empty(),
            "空の <tr> が行として残っている:\n  - {}",
            bad.join("\n  - ")
        );
    }

    /// An HTML comment is text the author **removed**, so nothing inside one may become structure.
    ///
    /// This is an information-disclosure guard, not a cosmetic one. Commenting a whole `<tr>` out is
    /// the ordinary way to disable a row, and a `<tr>`/`<td>` *inside* `<!-- … -->` used to open a
    /// real row here: the folded cell then names a byte range that no longer contains the `<!--`
    /// that would have hidden it, so `render_html_table_from_model` drew the author's commented-out
    /// text as an ordinary cell. (The un-folded `Html` path never had this bug — `render_html_block`
    /// has skipped comments since long before tables folded — which is why the same source is hidden
    /// when anything is glued after `</table>` and disclosed when it is not.)
    ///
    /// Both halves are pinned per case: the commented-out text never reaches a cell **and** the live
    /// rows still do — a fix that simply stopped folding these tables would hide the marker too, and
    /// silently lose the real content instead.
    ///
    /// A cell whose *own* content contains a comment keeps holding it verbatim (the `-->` crossing
    /// case below): the comment is inside that cell's range, and the one pass that decides visible
    /// text — `render_html_block`, reached through `html_cell_to_markdown` — strips it there, as the
    /// `html_table_corpus` goldens show. Stripping it here as well would be a second, competing
    /// implementation of the same rule.
    #[test]
    fn a_comment_is_content_never_table_structure() {
        // `(why, src, every table's cell text)`. An empty `want` means the block declines to fold at
        // all and stays an ordinary `Html` leaf, whose own renderer drops the comment.
        let cases = vec![
            (
                "a whole row commented out on one line",
                "<table>\n<tr><td>keep</td></tr>\n<!-- <tr><td>SECRET-row</td></tr> -->\n</table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                "a whole row commented out across several lines",
                "<table>\n<tr><td>keep</td></tr>\n<!--\n<tr><td>SECRET-multiline</td></tr>\n-->\n</table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                "a whole thead commented out",
                "<table>\n<!--\n<thead><tr><th>SECRET-head</th></tr></thead>\n-->\n<tbody><tr><td>keep</td></tr></tbody>\n</table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                "one td commented out inside a live row",
                "<table>\n<tr><td>keep</td><!-- <td>SECRET-cell</td> --></tr>\n</table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                // Already correct before the fix (the comment's own `>` ended a nameless pseudo-tag
                // that happened to swallow the `<td>` inside it) — pinned so it stays correct.
                "a comment inline before a cell on the same line",
                "<table>\n<tr><!-- <td>SECRET-inline</td> --><td>keep</td></tr>\n</table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                // The comment opens inside the cell and closes past the cell's own `</td>`, so the
                // whole run belongs to that one cell — including the `-->` — and the renderer, not
                // this parser, is what hides it. Before the fix the `</td></tr><tr><td>` inside the
                // comment really did open a second row holding the marker.
                "a comment that opens in a cell and closes past its end tag",
                "<table>\n<tr><td>keep <!-- </td></tr><tr><td>SECRET-crossing --> tail</td></tr>\n</table>\n",
                vec![vec![vec![
                    "keep <!-- </td></tr><tr><td>SECRET-crossing --> tail",
                ]]],
            ),
            (
                "a comment containing the table's own closing tag",
                "<table>\n<tr><td>keep</td></tr>\n<!-- </table> -->\n<tr><td>second</td></tr>\n</table>\n",
                vec![vec![vec!["keep"], vec!["second"]]],
            ),
            (
                // Comments do not nest: the first `-->` closes the one opened by the first `<!--`.
                "a comment containing a second comment opener",
                "<table>\n<tr><td>keep</td></tr>\n<!-- <tr><td>SECRET-outer</td></tr> <!-- <tr><td>SECRET-inner</td></tr> -->\n<tr><td>after the comment</td></tr>\n</table>\n",
                vec![vec![vec!["keep"], vec!["after the comment"]]],
            ),
            (
                // No `-->` at all: the comment swallows the `</table>` too, so the table is never
                // closed and the block declines to fold — and the `Html` renderer drops everything
                // from `<!--` on, which is what an unterminated comment means everywhere else.
                "a comment that is never closed",
                "<table>\n<tr><td>keep</td></tr>\n<!-- <tr><td>SECRET-unclosed</td></tr>\n</table>\n",
                vec![],
            ),
            (
                "a table whose only row is commented out",
                "<table>\n<!-- <tr><td>SECRET-only</td></tr> -->\n</table>\n",
                vec![],
            ),
            (
                "an attribute value that looks like a comment opener",
                "<table>\n<tr><td title=\"<!--\">keep</td></tr>\n</table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                // A degradation that predates this fix and is unchanged by it: the tag scan ends a
                // tag at the first `>`, which here is the one inside the attribute's own `-->`, so
                // the rest of the attribute leaks into the cell. Pinned, not fixed: the `<` this
                // starts at is `<td`, never `<!--`, so no comment rule of any kind applies to it.
                "an attribute value that looks like a whole comment",
                "<table>\n<tr><td title=\"<!-- x -->\">keep</td></tr>\n</table>\n",
                vec![vec![vec!["\">keep"]]],
            ),
            (
                "a comment indented, with blank space around it",
                "<table>\n  <!--\n    <tr><td>SECRET-spaced</td></tr>\n  -->  \n  <tr><td>keep</td></tr>\n</table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                // Inside a quote the comment's own bytes are `>`-marked in `src` but not in
                // `body_spans`, so the skip has to run over the marker-free text like every other
                // tag here does.
                "a commented-out row inside a quoted table",
                "> <table>\n> <tr><td>keep</td></tr>\n> <!-- <tr><td>SECRET-quoted</td></tr> -->\n> </table>\n",
                vec![vec![vec!["keep"]]],
            ),
            (
                // Declines to fold, like any other content glued on after `</table>` — see the
                // trailing-content check in `parse_html_table`.
                "a comment glued onto the block after the close",
                "<table>\n<tr><td>keep</td></tr>\n</table>\n<!-- trailing -->\n",
                vec![],
            ),
            (
                // The `<table>` inside the comment used to raise the nesting depth, so the real
                // `</table>` only brought it back to 1 and the table never closed.
                "a comment containing a nested table",
                "<table>\n<tr><td>keep</td></tr>\n<!-- <table><tr><td>SECRET-nested</td></tr></table> -->\n<tr><td>second</td></tr>\n</table>\n",
                vec![vec![vec!["keep"], vec!["second"]]],
            ),
        ];
        // Collected, not asserted case by case: a regression here usually hits several shapes at
        // once, and seeing all of them is what tells a reader which rule broke.
        let mut bad: Vec<String> = Vec::new();
        for (why, src, want) in cases {
            let want: Vec<Vec<Vec<String>>> = want
                .iter()
                .map(|t| {
                    t.iter()
                        .map(|r| r.iter().map(|c| (*c).to_string()).collect())
                        .collect()
                })
                .collect();
            let doc = Doc::parse(src);
            let got = html_table_cell_text(&doc, src);
            if got != want {
                bad.push(format!("{why}\n     got: {got:?}\n    want: {want:?}"));
            }
        }
        assert!(
            bad.is_empty(),
            "an HTML comment was read as table structure in {} case(s):\n  - {}",
            bad.len(),
            bad.join("\n  - ")
        );
    }

    /// Text sitting **outside** every `<td>`/`<th>` — a `<caption>`, a stray line inside the
    /// `<table>` or a `<tr>`, prose between two cells — has nowhere to live in a folded table:
    /// `HtmlTable` carries cell ranges and nothing else, so folding one silently deletes that text
    /// from the screen. That is the identical loss `parse_html_table` already refuses for content
    /// glued on *after* `</table>` (and `fold_details` for content after `</details>`), so it takes
    /// the identical decision: decline to fold, and let the ordinary `Html` path draw the block —
    /// tag-stripped, but with every character still there.
    ///
    /// Why this needed its own test: before it, `<caption>Fruit</caption>` next to real rows was
    /// pinned by a corpus case whose own name said the caption "is dropped" — a real disclosure-
    /// shaped loss recorded as if it were the specification.
    #[test]
    fn text_outside_every_cell_keeps_the_table_unfolded() {
        // `(why, src, every table's cell text)`. An empty `want` means the block declines to fold
        // and stays an ordinary `Html` leaf, which still draws every character it holds.
        let cases = vec![
            (
                "a line straight inside <table>",
                "<table>\nLOOSE\n<tr><td>a</td></tr>\n</table>\n",
                vec![],
            ),
            (
                "a line straight inside <tr>",
                "<table>\n<tr>\nLOOSE\n<td>a</td></tr>\n</table>\n",
                vec![],
            ),
            (
                "a line straight inside <thead>",
                "<table>\n<thead>\nLOOSE\n<tr><th>H</th></tr></thead>\n<tr><td>a</td></tr>\n</table>\n",
                vec![],
            ),
            (
                "a line straight inside <tfoot>",
                "<table>\n<tr><td>a</td></tr>\n<tfoot>\nLOOSE\n<tr><td>f</td></tr></tfoot>\n</table>\n",
                vec![],
            ),
            (
                "a caption alongside real rows",
                "<table>\n<caption>Fruit</caption>\n<tr><td>apple</td></tr>\n</table>\n",
                vec![],
            ),
            (
                "prose between one cell's end tag and the next cell's start tag",
                "<table>\n<tr><td>a</td>LOOSE<td>b</td></tr>\n</table>\n",
                vec![],
            ),
            (
                "prose after the last cell of a row",
                "<table>\n<tr><td>a</td>LOOSE</tr>\n</table>\n",
                vec![],
            ),
            (
                "prose between two rows",
                "<table>\n<tr><td>a</td></tr>\nLOOSE\n<tr><td>b</td></tr>\n</table>\n",
                vec![],
            ),
            (
                "prose between the last row and </table>",
                "<table>\n<tr><td>a</td></tr>\nLOOSE\n</table>\n",
                vec![],
            ),
            (
                // The control: exactly the same shape with nothing but whitespace outside the
                // cells still folds, which is what every real table looks like.
                "whitespace and newlines only outside the cells",
                "<table>\n  <tr>\n    <td>a</td>\n    <td>b</td>\n  </tr>\n</table>\n",
                vec![vec![vec!["a", "b"]]],
            ),
            (
                // Structural and non-structural tags alike are markup, not characters.
                "nothing but tags outside the cells",
                "<table>\n<colgroup><col><col></colgroup>\n<thead><tr><th>H</th></tr></thead>\n<tbody><tr><td>a</td></tr></tbody>\n</table>\n",
                vec![vec![vec!["H"], vec!["a"]]],
            ),
            (
                // A comment is text the author removed — it is never drawn, so folding cannot lose
                // it. Skipped whole by `html_comment_end`, exactly as the tag scan skips it.
                "a comment outside the cells is not text",
                "<table>\n<!-- SECRET-outside -->\n<tr><td>a</td></tr>\n</table>\n",
                vec![vec![vec!["a"]]],
            ),
            (
                "a multi-line comment outside the cells is not text",
                "<table>\n<!--\nSECRET-outside-multiline\n-->\n<tr><td>a</td></tr>\n</table>\n",
                vec![vec![vec!["a"]]],
            ),
            (
                // Text *before* the comment, on the other hand, is real.
                "text next to a comment outside the cells",
                "<table>\nLOOSE <!-- SECRET -->\n<tr><td>a</td></tr>\n</table>\n",
                vec![],
            ),
            (
                // Inside a quote the loose text's own bytes are `>`-marked in `src` but not in
                // `body_spans`, so the check has to run over the marker-free text (a `>` marker
                // read as content would make every quoted table look like it had loose text).
                "loose text inside a quoted table",
                "> <table>\n> LOOSE\n> <tr><td>a</td></tr>\n> </table>\n",
                vec![],
            ),
            (
                "a quoted table with nothing loose in it still folds",
                "> <table>\n> <tr><td>a</td></tr>\n> </table>\n",
                vec![vec![vec!["a"]]],
            ),
            (
                // Everything inside a cell is the cell's, including a nested table's own text —
                // that is content, not loose text (see `BlockKind::HtmlTable`'s doc comment).
                "a nested table inside a cell is not loose text",
                "<table>\n<tr><td><table><tr><td>inner</td></tr></table></td><td>outer</td></tr>\n</table>\n",
                vec![vec![vec!["<table><tr><td>inner</td></tr></table>", "outer"]]],
            ),
        ];
        // Collected, not asserted case by case: a regression here usually hits several shapes at
        // once, and seeing all of them is what tells a reader which rule broke.
        let mut bad: Vec<String> = Vec::new();
        for (why, src, want) in cases {
            let want: Vec<Vec<Vec<String>>> = want
                .iter()
                .map(|t| {
                    t.iter()
                        .map(|r| r.iter().map(|c| (*c).to_string()).collect())
                        .collect()
                })
                .collect();
            let doc = Doc::parse(src);
            let got = html_table_cell_text(&doc, src);
            if got != want {
                bad.push(format!("{why}\n     got: {got:?}\n    want: {want:?}"));
            }
        }
        assert!(
            bad.is_empty(),
            "text outside every cell was folded away (or a clean table stopped folding) in {} \
             case(s):\n  - {}",
            bad.len(),
            bad.join("\n  - ")
        );
    }

    #[test]
    fn well_formed_details_folds_into_one_container_with_summary_and_children() {
        let src = "<details>\n<summary>S</summary>\n\nbody\n\n</details>\n";
        let doc = Doc::parse(src);
        // pulldown-cmark still groups `<details>`/`<summary>...</summary>` into one HtmlBlock (no
        // blank line between them) and reports the paragraph and the standalone `</details>` as two
        // further siblings — three raw blocks total, same as before `fold_details` existed (see
        // `BlockKind::Html`'s own doc comment) — but `parse_blocks` now folds all three into one
        // `Details` container before handing the sibling list back to any caller.
        assert_eq!(doc.blocks.len(), 1, "folded into a single Details block");
        let BlockKind::Details {
            open_attr, summary, ..
        } = &doc.blocks[0].kind
        else {
            panic!("expected a Details block: {:?}", doc.blocks[0].kind)
        };
        assert!(!open_attr, "no `open` attribute on the tag");
        assert_eq!(summary, "S");
        assert_eq!(
            &src[doc.blocks[0].src.clone()],
            src,
            "spans the whole construct"
        );
        assert_eq!(doc.blocks[0].children.len(), 1, "just the body paragraph");
        let BlockKind::Paragraph { inline } = &doc.blocks[0].children[0].kind else {
            panic!("expected the body paragraph")
        };
        assert_eq!(inline_plain_text(&doc, inline), "body");
    }

    #[test]
    fn details_open_attribute_is_captured() {
        let doc = Doc::parse("<details open>\n<summary>S</summary>\n\nbody\n\n</details>\n");
        let BlockKind::Details { open_attr, .. } = &doc.blocks[0].kind else {
            panic!("expected a Details block")
        };
        assert!(open_attr);
    }

    #[test]
    fn details_with_no_summary_tag_reports_an_empty_summary() {
        let doc = Doc::parse("<details>\n\nbody\n\n</details>\n");
        let BlockKind::Details { summary, .. } = &doc.blocks[0].kind else {
            panic!("expected a Details block")
        };
        assert_eq!(summary, "");
    }

    #[test]
    fn unclosed_details_folds_every_remaining_sibling_as_its_body() {
        let src = "<details>\n<summary>S</summary>\n\nbody one\n\nbody two\n";
        let doc = Doc::parse(src);
        assert_eq!(doc.blocks.len(), 1);
        let BlockKind::Details {
            open_attr, summary, ..
        } = &doc.blocks[0].kind
        else {
            panic!("expected a Details block")
        };
        assert!(!open_attr);
        assert_eq!(summary, "S");
        assert_eq!(
            doc.blocks[0].children.len(),
            2,
            "both trailing paragraphs, with no closing tag to stop at"
        );
        assert_eq!(
            doc.blocks[0].src.end,
            src.len(),
            "an unclosed block runs to the end of input"
        );
    }

    #[test]
    fn nested_details_swallows_the_inner_close_first_matching_split_details() {
        // Mirrors `markdown.rs`'s own `nested_details_do_not_drift_later_block_open_state`
        // (`split_details`'s own greedy, non-nesting-aware contract), but with the outer/inner tags
        // separated by blank lines so pulldown-cmark itself reports each one as its own sibling
        // block (rather than gluing everything into one opaque `Html` leaf) — exercising
        // `fold_details`'s own "first close wins" search, not merely `split_details`'s line scan.
        let src = "<details>\n<summary>Outer</summary>\n\n\
                   <details open>\n<summary>Inner</summary>\n\n\
                   inner body\n\n\
                   </details>\n\n\
                   outer body after inner\n\n\
                   </details>\n";
        let doc = Doc::parse(src);
        // The outer's own search finds the *inner's* close first, swallowing it — its own trailing
        // `</details>` (and the paragraph right before it) are left as top-level siblings, not
        // children of anything.
        assert_eq!(
            doc.blocks.len(),
            3,
            "outer Details, the leftover paragraph, and the leftover close tag: {:?}",
            doc.blocks
        );
        let BlockKind::Details {
            open_attr, summary, ..
        } = &doc.blocks[0].kind
        else {
            panic!("expected the outer Details block")
        };
        assert!(!open_attr);
        assert_eq!(summary, "Outer");
        // The inner `<details>` is swallowed into the outer's own body as a raw, unfolded `Html`
        // leaf — not itself recognized as a nested `Details` container (see `fold_details`'s own
        // doc comment on why this is not recursive).
        assert_eq!(doc.blocks[0].children.len(), 2);
        assert!(matches!(
            doc.blocks[0].children[0].kind,
            BlockKind::Html { tag: Some(ref t), .. } if t == "details"
        ));
        let BlockKind::Paragraph { inline } = &doc.blocks[0].children[1].kind else {
            panic!("expected the inner body paragraph")
        };
        assert_eq!(inline_plain_text(&doc, inline), "inner body");
        // Leftover siblings after the outer's own (stolen) close.
        assert!(matches!(doc.blocks[1].kind, BlockKind::Paragraph { .. }));
        assert!(matches!(
            doc.blocks[2].kind,
            BlockKind::Html { tag: Some(ref t), .. } if t == "details"
        ));
    }

    #[test]
    fn glued_details_with_no_blank_line_anywhere_stays_an_unfolded_html_leaf() {
        // No blank line separates the open tag, the nested block, or either close — pulldown-cmark
        // merges the whole thing into a single `HtmlBlock`, so there is no separate sibling for
        // `fold_details` to have found a close among at all (see `BlockKind::Html`'s own doc
        // comment on exactly this shape) — unchanged from before `Details` existed.
        let src = "<details>\n<summary>A</summary>\n<details>\n<summary>Nested</summary>\n</details>\n</details>\n";
        let doc = Doc::parse(src);
        assert_eq!(doc.blocks.len(), 1);
        assert!(matches!(
            doc.blocks[0].kind,
            BlockKind::Html { tag: Some(ref t), .. } if t == "details"
        ));
    }

    #[test]
    fn details_nested_inside_a_list_item_folds_at_that_level_too() {
        let src = "- item\n\n  <details>\n  <summary>S</summary>\n\n  body\n\n  </details>\n";
        let doc = Doc::parse(src);
        let item = &doc.blocks[0].children[0];
        let details = item
            .children
            .iter()
            .find(|b| matches!(b.kind, BlockKind::Details { .. }))
            .expect("expected a folded Details block inside the list item");
        let BlockKind::Details { summary, .. } = &details.kind else {
            unreachable!()
        };
        assert_eq!(summary, "S");
    }

    #[test]
    fn details_nested_inside_a_quote_folds_at_that_level_too() {
        let src = "> <details>\n> <summary>S</summary>\n>\n> body\n>\n> </details>\n";
        let doc = Doc::parse(src);
        let quote = &doc.blocks[0];
        assert!(matches!(quote.kind, BlockKind::Quote { .. }));
        let details = quote
            .children
            .iter()
            .find(|b| matches!(b.kind, BlockKind::Details { .. }))
            .expect("expected a folded Details block inside the quote");
        let BlockKind::Details { summary, .. } = &details.kind else {
            unreachable!()
        };
        assert_eq!(summary, "S");
    }

    #[test]
    fn a_tag_name_prefix_is_not_confused_with_details_itself() {
        let doc = Doc::parse("<detailsx>\nhi\n</detailsx>\n");
        let BlockKind::Html { tag, .. } = &doc.blocks[0].kind else {
            panic!("expected an html block")
        };
        assert_eq!(
            tag.as_deref(),
            Some("detailsx"),
            "not truncated down to \"details\""
        );
    }

    #[test]
    fn thematic_break_is_reported_with_its_own_source_range() {
        let src = "a\n\n---\n\nb\n";
        let doc = Doc::parse(src);
        assert!(matches!(doc.blocks[1].kind, BlockKind::ThematicBreak));
        assert_eq!(&src[doc.blocks[1].src.clone()], "---\n");
    }

    #[test]
    fn nested_list_inside_a_list_item_is_a_child_block_not_flattened() {
        let doc = Doc::parse("- a\n  - b\n");
        let outer_item = &doc.blocks[0].children[0];
        // The outer item's own tight inline text ("a") is a synthetic `Paragraph` ahead of the
        // nested list — see
        // `tight_list_item_gets_a_synthetic_paragraph_child_loose_item_gets_a_real_one` — not
        // flattened into, or dropped in favor of, the nested list either way.
        assert_eq!(outer_item.children.len(), 2);
        assert!(matches!(
            outer_item.children[0].kind,
            BlockKind::Paragraph { .. }
        ));
        assert!(matches!(
            outer_item.children[1].kind,
            BlockKind::List { .. }
        ));
    }

    #[test]
    fn code_block_nested_inside_a_list_item_is_a_real_child_block() {
        // The render pipeline's `parser_code_blocks` deliberately does *not* count this one (its
        // `quote_depth` gate only excludes block-quote nesting, list nesting is fine for it) — this
        // just pins that the model represents it as a genuine nested CodeBlock either way.
        let doc = Doc::parse("- item\n\n  ```rust\n  code\n  ```\n");
        let item = &doc.blocks[0].children[0];
        let code = item
            .children
            .iter()
            .find(|b| matches!(b.kind, BlockKind::CodeBlock { .. }))
            .expect("expected a nested code block");
        assert!(matches!(
            code.kind,
            BlockKind::CodeBlock { fenced: true, .. }
        ));
    }

    #[test]
    fn cjk_ranges_land_on_char_boundaries_and_slice_correctly() {
        let src = "# 見出し\n\n```rust\nfn 関数() {}\n```\n";
        let doc = Doc::parse(src);
        assert_eq!(&src[doc.blocks[0].src.clone()], "# 見出し\n");
        let BlockKind::Heading { inline, .. } = &doc.blocks[0].kind else {
            panic!("expected a heading")
        };
        assert_eq!(inline_plain_text(&doc, inline), "見出し");
        let BlockKind::CodeBlock { body_spans, .. } = &doc.blocks[1].kind else {
            panic!("expected a code block")
        };
        for r in body_spans {
            assert!(src.is_char_boundary(r.start) && src.is_char_boundary(r.end));
        }
        assert_eq!(code_body_text(body_spans, src), "fn 関数() {}");
    }

    #[test]
    fn empty_document_has_no_blocks() {
        assert_eq!(Doc::parse("").blocks, Vec::new());
    }

    // ---- invariants, checked over the full parity corpus ------------------------------------

    /// Recursively checks, for every block in `blocks` (whose own extent, if any, is `parent`):
    /// every range lands on char boundaries and inside the input; siblings are in non-decreasing,
    /// non-overlapping source order; every child's range is contained in its parent's; a
    /// `CodeBlock`'s `body_spans` are each contained in its own `src`, land on char boundaries, and
    /// are themselves in non-decreasing, non-overlapping order; a `Heading`/`Paragraph`'s own
    /// `inline` index range is well-formed and inside `[0, events_len]` (`events_len` is
    /// `Doc.events.len()` for the whole document this block came from — every `inline` range, at any
    /// nesting depth, indexes into that same single `Vec`, not a per-block one); and a `ListItem`'s
    /// `Task`, if any, has its bracket invariant (`state_at`'s doc comment) hold. Returns every
    /// violation found (empty on success) rather than asserting inline, so one test run reports
    /// everything wrong at once instead of stopping at the first failure.
    fn check_invariants(
        blocks: &[Block],
        src: &str,
        events_len: usize,
        parent: Option<&Range<usize>>,
        path: &str,
        out: &mut Vec<String>,
    ) {
        let mut prev_end: Option<usize> = None;
        for (i, b) in blocks.iter().enumerate() {
            let here = format!("{path}[{i}]");
            if b.src.start > b.src.end {
                out.push(format!("{here}: src.start > src.end ({:?})", b.src));
            }
            if b.src.end > src.len() {
                out.push(format!(
                    "{here}: src.end past the input's length ({:?})",
                    b.src
                ));
            } else if !src.is_char_boundary(b.src.start) || !src.is_char_boundary(b.src.end) {
                out.push(format!("{here}: src {:?} is not on a char boundary", b.src));
            }
            if let Some(pe) = prev_end {
                if b.src.start < pe {
                    out.push(format!(
                        "{here}: overlaps the previous sibling (starts at {} before it ends at {pe})",
                        b.src.start
                    ));
                }
            }
            if let Some(p) = parent {
                if b.src.start < p.start || b.src.end > p.end {
                    out.push(format!("{here}: src {:?} escapes its parent {p:?}", b.src));
                }
            }
            if let BlockKind::CodeBlock { body_spans, .. } = &b.kind {
                let mut prev_span_end: Option<usize> = None;
                for (si, span) in body_spans.iter().enumerate() {
                    let here = format!("{here}.body_spans[{si}]");
                    if span.start > span.end {
                        out.push(format!("{here}: start > end ({span:?})"));
                    } else if span.end > src.len() {
                        out.push(format!("{here}: end past the input's length ({span:?})"));
                    } else if !src.is_char_boundary(span.start) || !src.is_char_boundary(span.end) {
                        out.push(format!("{here}: {span:?} is not on a char boundary"));
                    } else if span.start < b.src.start || span.end > b.src.end {
                        out.push(format!(
                            "{here}: {span:?} escapes its own block's src {:?}",
                            b.src
                        ));
                    }
                    if let Some(pe) = prev_span_end {
                        if span.start < pe {
                            out.push(format!(
                                "{here}: overlaps the previous span (starts at {} before it ends at {pe})",
                                span.start
                            ));
                        }
                    }
                    prev_span_end = Some(span.end);
                }
            }
            // Every folded HTML table cell's `inner` is a `src` range produced by
            // `parse_html_table`'s own `span_offset` (a `body_spans` offset mapped back to a `src`
            // offset). The contract `HtmlTableCell.inner` states is a *tag* boundary, not merely a
            // byte one: the range begins right after its own `<td …>`/`<th …>`'s closing `>` and
            // ends right before the `<` of whatever tag closed it. It is checked here, over the
            // whole parity corpus, because the one input shape that can break that map — a
            // quote-nested table, where each continuation line's own `> ` marker sits in the *gap*
            // between two spans — reconstructs the identical cell *text* either way
            // (`html_body_text_in` clips to the spans, and the marker belongs to none of them), so
            // no text-level assertion anywhere in the tree can see an off-by-one-span range. See
            // `a_quote_nested_cells_inner_range_is_bounded_by_its_own_tags_in_src` for the shapes
            // spelled out one at a time.
            if let BlockKind::HtmlTable { rows, .. } = &b.kind {
                for (ri, row) in rows.iter().enumerate() {
                    for (ci, cell) in row.iter().enumerate() {
                        let here = format!("{here}.rows[{ri}][{ci}].inner");
                        let r = &cell.inner;
                        if r.start > r.end {
                            out.push(format!("{here}: start > end ({r:?})"));
                        } else if r.end > src.len() {
                            out.push(format!("{here}: end past the input's length ({r:?})"));
                        } else if !src.is_char_boundary(r.start) || !src.is_char_boundary(r.end) {
                            out.push(format!("{here}: {r:?} is not on a char boundary"));
                        } else if r.start < b.src.start || r.end > b.src.end {
                            out.push(format!(
                                "{here}: {r:?} escapes its own block's src {:?}",
                                b.src
                            ));
                        } else {
                            if !src[..r.start].ends_with('>') {
                                out.push(format!(
                                    "{here}: {r:?} does not begin right after its own tag's `>` \
                                     (the bytes before it: {:?})",
                                    src.get(r.start.saturating_sub(8)..r.start)
                                ));
                            }
                            if !src[r.end..].starts_with('<') {
                                out.push(format!(
                                    "{here}: {r:?} does not end right before the `<` of the tag \
                                     that closed it (the bytes after it: {:?})",
                                    src.get(r.end..(r.end + 8).min(src.len()))
                                ));
                            }
                        }
                    }
                }
            }
            if let BlockKind::ListItem { task: Some(t) } = &b.kind {
                if !src.is_char_boundary(t.state_at) {
                    out.push(format!(
                        "{here}: task.state_at {} is not on a char boundary",
                        t.state_at
                    ));
                } else if !src[t.state_at..].starts_with(t.state) {
                    out.push(format!(
                        "{here}: task.state_at {} does not point at task.state {:?}",
                        t.state_at, t.state
                    ));
                } else if src.as_bytes().get(t.state_at.wrapping_sub(1)) != Some(&b'[')
                    || src.as_bytes().get(t.state_at + 1) != Some(&b']')
                {
                    out.push(format!(
                        "{here}: task.state_at {} is not bracketed by '[' and ']'",
                        t.state_at
                    ));
                }
            }
            let inline = match &b.kind {
                BlockKind::Heading { inline, .. } => Some(inline),
                BlockKind::Paragraph { inline } => Some(inline),
                _ => None,
            };
            if let Some(inline) = inline {
                if inline.start > inline.end {
                    out.push(format!("{here}: inline.start > inline.end ({inline:?})"));
                } else if inline.end > events_len {
                    out.push(format!(
                        "{here}: inline.end {} past events_len {events_len}",
                        inline.end
                    ));
                }
            }
            check_invariants(&b.children, src, events_len, Some(&b.src), &here, out);
            prev_end = Some(b.src.end);
        }
    }

    /// Every raw and preprocessed case in the same parity corpus `md_snapshot_tests` covers
    /// (`task_corpus`/`code_corpus`/`code_span_corpus`/`preprocess_corpus`), both as written and
    /// after the same front-matter/footnote/inline-HTML pre-passes the render pipeline itself
    /// applies before any of this text reaches a parser. Checking both is deliberate: the raw form
    /// exercises constructs the pre-passes remove entirely (front matter, footnote definitions)
    /// that would otherwise never be modeled at all, and the preprocessed form is what this
    /// module's own contract (see the module doc comment) actually promises to handle correctly.
    fn all_corpus_texts() -> Vec<(String, String)> {
        let mut v: Vec<(String, String)> = Vec::new();
        for (name, src) in super::super::task_corpus::cases() {
            v.push((format!("task_corpus: {name}"), src.to_string()));
        }
        for (name, src) in super::super::code_corpus::cases() {
            v.push((format!("code_corpus: {name}"), src.to_string()));
        }
        for case in super::super::code_span_corpus::cases() {
            v.push((format!("code_span_corpus: {}", case.name), case.src));
        }
        for (name, src) in super::super::preprocess_corpus::cases() {
            v.push((format!("preprocess_corpus: {name}"), src.to_string()));
        }
        for (name, src) in super::super::html_table_corpus::cases() {
            v.push((format!("html_table_corpus: {name}"), src.to_string()));
        }
        let mut with_preprocessing: Vec<(String, String)> = Vec::new();
        for (name, raw) in &v {
            with_preprocessing.push((format!("{name} [preprocessed]"), preprocess_default(raw)));
        }
        v.extend(with_preprocessing);
        v
    }

    /// The default-config equivalent of `md_snapshot_tests::pre_src_for` — front matter stripped,
    /// then footnotes, then inline HTML, unconditionally (matching `Config::default()`, under which
    /// all three are on) — reimplemented here, rather than depending on `crate::app`/`Config` from
    /// this module's own test suite, so this file's tests stay self-contained within
    /// `preview::markdown`. `md_model_snapshot_tests` (in `src/app/`) uses the real
    /// `pre_src_for` directly instead, and the two are required to agree — see that module's doc
    /// comment.
    fn preprocess_default(src: &str) -> String {
        let (_front_matter, body) = super::super::strip_front_matter(src);
        let origin = super::super::identity_origin(&body);
        let (s, origin) = super::super::process_footnotes_traced(&body, &origin);
        let (pre_src, _origin) = super::super::process_inline_html_traced(&s, &origin);
        pre_src
    }

    #[test]
    fn model_invariants_hold_across_the_full_parity_corpus() {
        let mut violations = Vec::new();
        for (name, src) in all_corpus_texts() {
            let doc = Doc::parse(&src);
            check_invariants(
                &doc.blocks,
                &src,
                doc.events.len(),
                None,
                &name,
                &mut violations,
            );
        }
        assert!(
            violations.is_empty(),
            "{} invariant violation(s):\n{}",
            violations.len(),
            violations.join("\n")
        );
    }

    #[test]
    fn model_invariants_hold_across_the_sample_md_files() {
        // `samples/` is excluded from the published crate (see `Cargo.toml`) — degrade to "skip"
        // rather than fail a build from an extracted tarball, mirroring
        // `md_snapshot_tests::sample_src`'s own contract.
        let mut violations = Vec::new();
        let mut checked = 0usize;
        for name in [
            "images.md",
            "links.md",
            "links.ja.md",
            "markdown.md",
            "markdown.ja.md",
            "README.md",
            "tutorial.md",
            "tutorial.ja.md",
        ] {
            let p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("samples")
                .join(name);
            let Ok(raw) = std::fs::read_to_string(&p) else {
                continue;
            };
            checked += 1;
            let pre = preprocess_default(&raw);
            let doc = Doc::parse(&pre);
            check_invariants(
                &doc.blocks,
                &pre,
                doc.events.len(),
                None,
                name,
                &mut violations,
            );
        }
        if checked == 0 {
            eprintln!("model_invariants_hold_across_the_sample_md_files: no samples/*.md found (published-crate build?) — skipping");
            return;
        }
        assert!(
            violations.is_empty(),
            "{} invariant violation(s) across {checked} sample file(s):\n{}",
            violations.len(),
            violations.join("\n")
        );
    }

    // ---- cross-check against `parser_code_blocks` --------------------------------------------

    /// Recursively collects `(is_inside_a_quote, body_spans)` for every `CodeBlock` in `blocks`, in
    /// source order — `inside_quote` true for any block whose nearest ancestor is (or is nested
    /// inside) a `BlockKind::Quote`, matching `parser_code_blocks`'s own `quote_depth > 0` gate
    /// exactly (both increment/decrement, respectively track, at precisely the same `BlockQuote`
    /// `Start`/`End` events — this model via nesting, `parser_code_blocks` via a counter). See
    /// `BlockKind::CodeBlock.body_spans`'s doc comment for why this model deliberately does **not**
    /// filter these out itself the way `parser_code_blocks` does — `inside_quote` is reported here
    /// precisely so the tests below can apply that same filter before comparing.
    fn code_block_bodies(
        blocks: &[Block],
        inside_quote: bool,
        out: &mut Vec<(bool, Vec<Range<usize>>)>,
    ) {
        for b in blocks {
            match &b.kind {
                BlockKind::CodeBlock { body_spans, .. } => {
                    out.push((inside_quote, body_spans.clone()))
                }
                BlockKind::Quote { .. } => code_block_bodies(&b.children, true, out),
                _ => code_block_bodies(&b.children, inside_quote, out),
            }
        }
    }

    /// An independent walk of the same event stream `Doc::parse` reads, joining each code block's
    /// `Event::Text` *contents* (rather than deriving a `Range` from their positions) and tagging
    /// block-quote nesting exactly like `code_block_bodies` above — the same shape as
    /// `parser_code_blocks` itself (same options, same `Start`/`End(CodeBlock)` bracketing, same
    /// join, same trailing-`\n` strip), except it reports quote nesting instead of filtering by it.
    /// Existing on purpose as *test* code, not production: its whole job is to be a second,
    /// differently-shaped computation of the same thing, used two ways below —
    /// `code_blocks_match_parser_code_blocks_outside_block_quotes_across_the_corpus` filters its own
    /// results by `!inside_quote` and checks that reproduces `parser_code_blocks`'s real output
    /// exactly (confirming `parser_code_blocks` itself behaves as documented, independent of
    /// `Doc::parse` entirely), and `model_body_ranges_are_internally_consistent_with_parser_code_blocks_quote_filtering`
    /// cross-checks `Doc::parse`'s tree against it on block *count* and quote nesting, not content.
    /// The exhaustive content check
    /// (`code_body_text_matches_parser_code_blocks_for_every_non_quote_code_block_in_the_corpus`)
    /// compares `Doc::parse`'s reconstructed `body_spans` directly against `parser_code_blocks`
    /// instead, without going through this function at all.
    fn joined_code_block_texts(src: &str) -> Vec<(bool, String)> {
        let mut out = Vec::new();
        let mut quote_depth = 0usize;
        let mut in_quote_at_open = false;
        let mut body: Option<String> = None;
        for (ev, _) in Parser::new_ext(src, parse_options()).into_offset_iter() {
            match ev {
                Event::Start(Tag::BlockQuote(_)) => quote_depth += 1,
                Event::End(TagEnd::BlockQuote(_)) => quote_depth = quote_depth.saturating_sub(1),
                Event::Start(Tag::CodeBlock(_)) => {
                    in_quote_at_open = quote_depth > 0;
                    body = Some(String::new());
                }
                Event::End(TagEnd::CodeBlock) => {
                    if let Some(b) = body.take() {
                        let trimmed = b.strip_suffix('\n').unwrap_or(&b).to_string();
                        out.push((in_quote_at_open, trimmed));
                    }
                }
                Event::Text(t) => {
                    if let Some(b) = body.as_mut() {
                        b.push_str(&t);
                    }
                }
                _ => {}
            }
        }
        out
    }

    /// A parity check on `parser_code_blocks` itself, independent of `Doc::parse`: over the whole
    /// corpus, joining `Event::Text` straight off a fresh event walk (`joined_code_block_texts`,
    /// filtered to non-quote-nested blocks) reproduces exactly what `parser_code_blocks` computes —
    /// confirming the render pipeline's own scanner behaves as documented, before the tests below
    /// ask whether `Doc::parse`'s tree agrees with it too.
    #[test]
    fn code_blocks_match_parser_code_blocks_outside_block_quotes_across_the_corpus() {
        let mut total_checked = 0usize;
        for (name, src) in all_corpus_texts() {
            let mut expected = Vec::new();
            super::super::parser_code_blocks(&src, &mut expected);
            let actual: Vec<String> = joined_code_block_texts(&src)
                .into_iter()
                .filter(|(in_quote, _)| !in_quote)
                .map(|(_, text)| text)
                .collect();
            assert_eq!(actual, expected, "case {name:?}");
            total_checked += expected.len();
        }
        assert!(
            total_checked > 20,
            "the corpus's non-quote-nested code block count looks suspiciously small \
             ({total_checked}) — a corpus-gathering call probably broke"
        );
    }

    /// `Doc::parse`'s own tree — walked via `code_block_bodies` above — finds the same *number* of
    /// code blocks as a fresh, independent event walk (`joined_code_block_texts`), and agrees with
    /// it on which ones are block-quote-nested, for every case in the corpus, regardless of how many
    /// `Event::Text` spans any individual block took to build. A count/nesting check, not a content
    /// one — see the next test for the exhaustive content comparison against `parser_code_blocks`
    /// itself.
    #[test]
    fn model_body_ranges_are_internally_consistent_with_parser_code_blocks_quote_filtering() {
        for (name, src) in all_corpus_texts() {
            let doc = Doc::parse(&src);
            let mut model = Vec::new();
            code_block_bodies(&doc.blocks, false, &mut model);
            let joined = joined_code_block_texts(&src);
            assert_eq!(
                model.len(),
                joined.len(),
                "case {name:?}: model found {} code blocks, the independent walk found {}",
                model.len(),
                joined.len()
            );
            for (i, ((model_in_quote, _), (joined_in_quote, _))) in
                model.iter().zip(joined.iter()).enumerate()
            {
                assert_eq!(
                    model_in_quote, joined_in_quote,
                    "case {name:?} block #{i}: model and the independent walk disagree about quote nesting"
                );
            }
        }
    }

    /// The primary parity check this module exists for: over the whole corpus, reconstructing every
    /// **non-quote-nested** code block's content from `Doc::parse`'s own `body_spans` (via
    /// `code_body_text`) matches `parser_code_blocks` — the render pipeline's real write-back
    /// scanner — byte for byte. No exceptions: unlike an earlier version of this test, this does not
    /// carve out a "single `Event::Text` span" case and merely tally the rest; every code block in
    /// the corpus, however many spans its content took to build (an indented block, a block nested
    /// inside a list item or block quote, a block in a CRLF file, ...), is checked the same way. See
    /// `BlockKind::CodeBlock.body_spans`'s doc comment for why quote-nested blocks are excluded here
    /// specifically (`parser_code_blocks` itself never counts them — this model still models them,
    /// deliberately, as a superset) rather than a limitation of the reconstruction being tested.
    #[test]
    fn code_body_text_matches_parser_code_blocks_for_every_non_quote_code_block_in_the_corpus() {
        let mut total_checked = 0usize;
        for (name, src) in all_corpus_texts() {
            let mut expected = Vec::new();
            super::super::parser_code_blocks(&src, &mut expected);

            let doc = Doc::parse(&src);
            let mut model = Vec::new();
            code_block_bodies(&doc.blocks, false, &mut model);
            let actual: Vec<String> = model
                .into_iter()
                .filter(|(in_quote, _)| !in_quote)
                .map(|(_, spans)| code_body_text(&spans, &src))
                .collect();

            assert_eq!(actual, expected, "case {name:?}");
            total_checked += expected.len();
        }
        assert!(
            total_checked > 20,
            "the corpus's non-quote-nested code block count looks suspiciously small \
             ({total_checked}) — a corpus-gathering call probably broke"
        );
    }

    // ---- determinism --------------------------------------------------------------------------

    #[test]
    fn parsing_the_same_text_twice_gives_the_same_tree() {
        for (_, src) in all_corpus_texts() {
            assert_eq!(Doc::parse(&src), Doc::parse(&src));
        }
    }

    // =============================================================================================
    // Test-hardening pass (pre-release audit): everything from here down was added to close two
    // kinds of gap found by measuring line coverage on this file (`cargo llvm-cov`):
    //
    //   1. `check_invariants` itself (above) had 100% *function* coverage but was missing ~85 *line*
    //      lines — every one of its "report a violation" branches, the whole reason the function
    //      exists, had never actually fired in any test run. A checker nobody has ever seen catch
    //      anything is not yet proven to catch anything — see `invariant_violations` below, which
    //      builds a deliberately-broken `Block`/`Task` for each violation kind `check_invariants`
    //      claims to detect and asserts it is actually reported.
    //   2. A handful of defensive branches (a handful of `Event::Start` arms marked "not reachable
    //      for well-formed input", `parse_blocks_raw`'s own stray-`TaskListMarker` catch-all,
    //      `collect_stray_inline_run`'s exhausted-stream arm, `glued_details_fold`'s "ran off the
    //      end with no close" and "found a close but something unrelated follows it" arms,
    //      `html_tag_name`'s empty-name arm) are real code, but only reachable either through a
    //      *malformed* — not merely unusual — event stream, or through document shapes this model's
    //      own doc comments already anticipated (`<details>` with no close anywhere, glued to
    //      trailing content, ending mid-line with no trailing newline). Reached below either by a
    //      genuinely adversarial `Doc::parse` input, or — where no real document reaches a purely
    //      defensive branch at all — by calling the private helper directly with a hand-built
    //      `Walker`/`Task`/`Block`, exactly as this module's own contract (private items are visible
    //      to this same file's own `#[cfg(test)] mod tests`) allows.
    //
    // Three "completeness proxy" tests round this out for the one class of gap line coverage cannot
    // measure at all: the render pipeline's own completeness cross-check
    // (`app::md_model_snapshot_tests::model_covers_every_inline_event_across_the_full_corpus`, in
    // `src/app/`) is out of scope for this file to touch or duplicate — instead, three small,
    // self-contained scans (over this same `Doc`) are built here, purely to *prove* — by corrupting a
    // real, correctly-parsed `Doc` one way at a time and showing the scan notices — that "an inline
    // event belongs to no leaf" / "a `TaskListMarker` was dropped" / "a `CodeBlock` was dropped" are
    // all things *some* check can catch, without claiming these three toy scans are a substitute for
    // the real one.

    // ---- adversarial coverage of `check_invariants` itself: prove each violation kind is caught ---
    //
    // Every test below builds a `Block`/`Task` value that breaks exactly one invariant
    // `check_invariants` is documented to catch, then asserts the violation is actually reported.
    // `check_invariants` is called directly (never through `Doc::parse`) — nothing here needs a
    // document real parsing could ever produce, only a `Block` tree shaped the way the checker is
    // supposed to reject. `src`/`events_len` are likewise whatever this test needs them to be, not
    // values a real `Doc::parse` call produced — `check_invariants` takes them as plain parameters
    // and has no way to tell the difference.

    /// Runs `check_invariants` over `blocks` at the top level (`parent: None`) and returns whatever
    /// it reports — a thin wrapper purely to avoid repeating the same four parameters at every call
    /// site below.
    fn violations_of(blocks: &[Block], src: &str, events_len: usize) -> Vec<String> {
        let mut out = Vec::new();
        check_invariants(blocks, src, events_len, None, "root", &mut out);
        out
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges)] // deliberately backwards: this is the violation under test
    fn check_invariants_catches_src_start_after_end() {
        let bad = leaf(BlockKind::ThematicBreak, 5..2);
        let out = violations_of(std::slice::from_ref(&bad), "0123456789", 0);
        assert!(
            out.iter().any(|m| m.contains("src.start > src.end")),
            "expected a start>end violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_src_end_past_input_length() {
        let src = "abc";
        let bad = leaf(BlockKind::ThematicBreak, 0..99);
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter().any(|m| m.contains("past the input's length")),
            "expected an end-past-length violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_a_range_that_splits_a_multibyte_char() {
        let src = ""; // one 3-byte character: valid boundaries are only 0 and 3
        let bad = leaf(BlockKind::ThematicBreak, 0..1); // ends mid-character
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter().any(|m| m.contains("is not on a char boundary")),
            "expected a char-boundary violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_a_child_escaping_its_parent() {
        let src = "0123456789";
        let child = leaf(BlockKind::ThematicBreak, 6..8); // outside the parent's own 0..5
        let parent = Block {
            kind: BlockKind::List {
                ordered: false,
                start: None,
            },
            src: 0..5,
            children: vec![child],
        };
        let out = violations_of(std::slice::from_ref(&parent), src, 0);
        assert!(
            out.iter().any(|m| m.contains("escapes its parent")),
            "expected a parent-escape violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_overlapping_siblings() {
        let src = "0123456789";
        let a = leaf(BlockKind::ThematicBreak, 0..5);
        let b = leaf(BlockKind::ThematicBreak, 3..8); // starts before `a` ends
        let out = violations_of(&[a, b], src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("overlaps the previous sibling")),
            "expected an overlap violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_siblings_out_of_source_order() {
        let src = "0123456789";
        // Not overlapping in the visual sense either sibling's own text occupies, but the second
        // one's own start (0) sits *before* the first one's own end (9) — `check_invariants` only
        // has one guard for "siblings must be in non-decreasing source order" (the same `start < pe`
        // check `check_invariants_catches_overlapping_siblings` exercises above), so a genuinely
        // reversed pair trips the identical branch — see this module's own report on why "siblings
        // overlap" and "siblings are out of order" are, in this checker, the same check.
        let a = leaf(BlockKind::ThematicBreak, 5..9);
        let b = leaf(BlockKind::ThematicBreak, 0..2);
        let out = violations_of(&[a, b], src, 0);
        assert!(
            !out.is_empty(),
            "expected a violation for an out-of-source-order sibling pair, got none"
        );
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges, clippy::single_range_in_vec_init)] // deliberately backwards single-span body_spans: this is the violation under test
    fn check_invariants_catches_a_code_block_span_start_after_end() {
        let src = "0123456789";
        let bad = leaf(
            BlockKind::CodeBlock {
                lang: None,
                fenced: true,
                body_spans: vec![5..2],
            },
            0..10,
        );
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("body_spans") && m.contains("start > end")),
            "expected a body_spans start>end violation, got {out:?}"
        );
    }

    #[test]
    #[allow(clippy::single_range_in_vec_init)] // a real body_spans is a Vec<Range<usize>>; one span is the normal case
    fn check_invariants_catches_a_code_block_span_past_input_length() {
        let src = "0123456789";
        let bad = leaf(
            BlockKind::CodeBlock {
                lang: None,
                fenced: true,
                body_spans: vec![0..99],
            },
            0..10,
        );
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("body_spans") && m.contains("past the input's length")),
            "expected a body_spans length violation, got {out:?}"
        );
    }

    #[test]
    #[allow(clippy::single_range_in_vec_init)] // a real body_spans is a Vec<Range<usize>>; one span is the normal case
    fn check_invariants_catches_a_code_block_span_splitting_a_multibyte_char() {
        let src = "0あ23456789"; // "あ" occupies bytes 1..4
        let bad = leaf(
            BlockKind::CodeBlock {
                lang: None,
                fenced: true,
                body_spans: vec![0..2], // ends mid-character
            },
            0..src.len(),
        );
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("body_spans") && m.contains("is not on a char boundary")),
            "expected a body_spans char-boundary violation, got {out:?}"
        );
    }

    #[test]
    #[allow(clippy::single_range_in_vec_init)] // a real body_spans is a Vec<Range<usize>>; one span is the normal case
    fn check_invariants_catches_a_code_block_span_escaping_its_own_block() {
        let src = "0123456789";
        let bad = leaf(
            BlockKind::CodeBlock {
                lang: None,
                fenced: true,
                body_spans: vec![6..8], // the block's own src (below) ends at 5
            },
            0..5,
        );
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("body_spans") && m.contains("escapes its own block's src")),
            "expected a body_spans own-block-escape violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_overlapping_code_block_spans() {
        let src = "0123456789";
        let bad = leaf(
            BlockKind::CodeBlock {
                lang: None,
                fenced: true,
                body_spans: vec![0..5, 3..8], // second starts before the first ends
            },
            0..10,
        );
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("body_spans") && m.contains("overlaps the previous span")),
            "expected an overlapping-spans violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_a_task_state_at_splitting_a_multibyte_char() {
        let src = "[あ]"; // '[' at byte 0, "あ" at bytes 1..4, ']' at byte 4
        let bad = Block {
            kind: BlockKind::ListItem {
                task: Some(Task {
                    state: 'x',
                    state_at: 2, // mid-character
                }),
            },
            src: 0..src.len(),
            children: Vec::new(),
        };
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("task.state_at") && m.contains("is not on a char boundary")),
            "expected a task char-boundary violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_a_task_state_that_does_not_match_the_byte_at_state_at() {
        let src = "[y]";
        let bad = Block {
            kind: BlockKind::ListItem {
                task: Some(Task {
                    state: 'x', // the byte at state_at is actually 'y'
                    state_at: 1,
                }),
            },
            src: 0..src.len(),
            children: Vec::new(),
        };
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter()
                .any(|m| m.contains("does not point at task.state")),
            "expected a task state-mismatch violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_a_task_state_at_not_bracketed() {
        let src = "(x)"; // parens, not square brackets
        let bad = Block {
            kind: BlockKind::ListItem {
                task: Some(Task {
                    state: 'x',
                    state_at: 1,
                }),
            },
            src: 0..src.len(),
            children: Vec::new(),
        };
        let out = violations_of(std::slice::from_ref(&bad), src, 0);
        assert!(
            out.iter().any(|m| m.contains("is not bracketed by")),
            "expected a task bracket violation, got {out:?}"
        );
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges)] // deliberately backwards: this is the violation under test
    fn check_invariants_catches_a_headings_inline_start_after_end() {
        let src = "# hi\n";
        let bad = leaf(
            BlockKind::Heading {
                level: 1,
                inline: 5..2,
                id: None,
                classes: Vec::new(),
                attrs: Vec::new(),
            },
            0..src.len(),
        );
        let out = violations_of(std::slice::from_ref(&bad), src, 10);
        assert!(
            out.iter().any(|m| m.contains("inline.start > inline.end")),
            "expected an inline start>end violation, got {out:?}"
        );
    }

    #[test]
    fn check_invariants_catches_a_paragraphs_inline_end_past_events_len() {
        let src = "hi\n";
        let bad = leaf(BlockKind::Paragraph { inline: 0..99 }, 0..src.len());
        let out = violations_of(std::slice::from_ref(&bad), src, 3); // only 3 real events exist
        assert!(
            out.iter()
                .any(|m| m.contains("inline.end") && m.contains("past events_len")),
            "expected an inline-past-events_len violation, got {out:?}"
        );
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges)] // deliberately backwards: this is one of the two violations under test
    fn check_invariants_reports_every_violation_at_once_not_just_the_first() {
        // `check_invariants`'s own doc comment promises this ("Returns every violation found ...
        // rather than asserting inline, so one test run reports everything wrong at once") — pin it
        // directly: two independently-broken top-level siblings should both show up in `out`, not
        // just whichever is encountered first.
        let src = "0123456789";
        let a = leaf(BlockKind::ThematicBreak, 5..2); // start > end
        let b = leaf(BlockKind::ThematicBreak, 0..99); // past input length
        let out = violations_of(&[a, b], src, 0);
        assert!(
            out.iter().any(|m| m.contains("src.start > src.end")),
            "{out:?}"
        );
        assert!(
            out.iter().any(|m| m.contains("past the input's length")),
            "{out:?}"
        );
    }

    // ---- completeness proxies: prove "a piece of the raw stream went unrepresented" is catchable -
    //
    // The render pipeline's own completeness cross-check (`app::md_model_snapshot_tests`, in
    // `src/app/`) is out of scope here — these three tests instead build small, local, self-contained
    // scans over a `Doc` this file already trusts (real output of `Doc::parse`), then *corrupt a
    // clone* of that same `Doc` one way at a time and show the scan's own count changes. This proves
    // each described gap is detectable by *some* check, without claiming these scans are a substitute
    // for the real one.

    /// Marks every event index claimed by some `Heading`/`Paragraph` leaf's own `inline` range,
    /// recursively. A narrow proxy for "every inline-content event belongs to some leaf" — real
    /// completeness also has to account for `CodeBlock`/`Table` content (byte ranges, not event
    /// indices) and container `Start`/`End` events, none of which this toy scan attempts; see the
    /// section doc comment above.
    fn events_claimed_by_a_leaf(blocks: &[Block], claimed: &mut [bool]) {
        for b in blocks {
            let inline = match &b.kind {
                BlockKind::Heading { inline, .. } => Some(inline),
                BlockKind::Paragraph { inline } => Some(inline),
                _ => None,
            };
            if let Some(inline) = inline {
                for i in inline.clone() {
                    if let Some(slot) = claimed.get_mut(i) {
                        *slot = true;
                    }
                }
            }
            events_claimed_by_a_leaf(&b.children, claimed);
        }
    }

    #[test]
    fn completeness_proxy_detects_an_inline_event_dropped_from_every_leaf() {
        // A heading, a paragraph, *and* a thematic break — so `events_claimed_by_a_leaf`'s own match
        // exercises all three of its arms (`Heading`, `Paragraph`, and the `_ => None` fallback for
        // every other `BlockKind`, `ThematicBreak` here), not just the one this proxy happens to
        // corrupt below.
        let src = "# Title\n\nhello world\n\n---\n";
        let doc = Doc::parse(src);
        assert_eq!(
            doc.blocks.len(),
            3,
            "heading, paragraph, thematic break: {:?}",
            doc.blocks
        );
        let mut claimed = vec![false; doc.events.len()];
        events_claimed_by_a_leaf(&doc.blocks, &mut claimed);
        assert!(
            claimed.iter().any(|&c| c),
            "sanity: the real model should claim at least one event"
        );

        // Corrupt a copy: truncate the paragraph's own `inline` range so it drops its own trailing
        // content — exactly what "an inline event belongs to no leaf" looks like.
        let mut corrupted = doc.blocks.clone();
        let BlockKind::Paragraph { inline } = &mut corrupted[1].kind else {
            panic!("expected the paragraph at index 1: {:?}", corrupted[1].kind)
        };
        inline.end = inline.start;
        let mut claimed_after = vec![false; doc.events.len()];
        events_claimed_by_a_leaf(&corrupted, &mut claimed_after);
        assert!(
            claimed
                .iter()
                .zip(claimed_after.iter())
                .any(|(&before, &after)| before && !after),
            "corrupting the paragraph's own inline range should un-claim at least one event the \
             real model claims"
        );
    }

    fn count_task_list_markers_in_events(doc: &Doc<'_>) -> usize {
        doc.events
            .iter()
            .filter(|(ev, _)| matches!(ev, Event::TaskListMarker(_)))
            .count()
    }

    fn count_tasks_recorded_in_tree(blocks: &[Block]) -> usize {
        let mut n = 0;
        for b in blocks {
            if let BlockKind::ListItem { task: Some(_) } = &b.kind {
                n += 1;
            }
            n += count_tasks_recorded_in_tree(&b.children);
        }
        n
    }

    #[test]
    fn completeness_proxy_detects_a_task_list_marker_dropped_from_the_tree() {
        let src = "- [ ] a\n- [x] b\n";
        let doc = Doc::parse(src);
        assert_eq!(
            count_task_list_markers_in_events(&doc),
            2,
            "sanity: two markers in the raw event stream"
        );
        assert_eq!(
            count_tasks_recorded_in_tree(&doc.blocks),
            2,
            "sanity: the real model records both"
        );

        // Corrupt a copy: drop one item's own recorded task, as if `take_task_marker` had missed it.
        let mut corrupted = doc.blocks.clone();
        let BlockKind::ListItem { task } = &mut corrupted[0].children[0].kind else {
            panic!("expected the first list item")
        };
        *task = None;
        assert_eq!(
            count_tasks_recorded_in_tree(&corrupted),
            1,
            "the corrupted copy under-counts relative to the raw stream's own marker count"
        );
        assert_ne!(
            count_task_list_markers_in_events(&doc),
            count_tasks_recorded_in_tree(&corrupted),
            "a TaskListMarker present in the raw stream but absent from every ListItem.task is \
             exactly the completeness gap this proxy exists to catch"
        );
    }

    fn count_code_block_starts_in_raw_events(src: &str) -> usize {
        Parser::new_ext(src, parse_options())
            .into_offset_iter()
            .filter(|(ev, _)| matches!(ev, Event::Start(Tag::CodeBlock(_))))
            .count()
    }

    fn count_code_blocks_recorded_in_tree(blocks: &[Block]) -> usize {
        let mut n = 0;
        for b in blocks {
            if matches!(b.kind, BlockKind::CodeBlock { .. }) {
                n += 1;
            }
            n += count_code_blocks_recorded_in_tree(&b.children);
        }
        n
    }

    #[test]
    fn completeness_proxy_detects_a_code_block_dropped_from_the_tree() {
        let src = "```rust\nfn a() {}\n```\n\npara\n\n```\nplain\n```\n";
        let doc = Doc::parse(src);
        let raw = count_code_block_starts_in_raw_events(src);
        assert_eq!(
            raw, 2,
            "sanity: two Start(CodeBlock) events in the raw stream"
        );
        assert_eq!(
            count_code_blocks_recorded_in_tree(&doc.blocks),
            2,
            "sanity: the real model records both"
        );

        // Corrupt a copy: replace one CodeBlock with an unrelated leaf kind, as if
        // `parse_container`'s own `Tag::CodeBlock` arm had been skipped instead of building a
        // `Block` for it.
        let mut corrupted = doc.blocks.clone();
        corrupted[0].kind = BlockKind::ThematicBreak;
        assert_eq!(
            count_code_blocks_recorded_in_tree(&corrupted),
            1,
            "the corrupted copy under-counts relative to the raw stream's own CodeBlock count"
        );
        assert_ne!(
            raw,
            count_code_blocks_recorded_in_tree(&corrupted),
            "a Start(CodeBlock) present in the raw stream but represented by no \
             BlockKind::CodeBlock anywhere in the tree is exactly the completeness gap this proxy \
             exists to catch"
        );
    }

    // ---- defensive branches reachable only through a malformed event stream, poked directly ------
    //
    // Every function below is documented, at its own definition, as having a branch "not reachable
    // for well-formed input" — a real `Doc::parse` call can never desync its own event stream enough
    // to trip these, because pulldown-cmark's own event stream is always well-formed (every opened
    // tag is eventually closed). They exist purely as principle-#3 ("never crash on any input
    // pulldown-cmark accepts") insurance. Reaching them at all means calling the private helper
    // directly, with a hand-built `Walker` deliberately positioned somewhere the function does not
    // expect — legitimate here because `Walker`/every helper below is private to this file, and
    // `#[cfg(test)] mod tests` is a descendant module of it (same privacy rule the rest of this file
    // already relies on to construct `Block`/`Task` values by hand above).

    fn walker_for(src: &str) -> Walker<'_> {
        Walker {
            iter: Parser::new_ext(src, parse_options())
                .into_offset_iter()
                .peekable(),
            events: Vec::new(),
        }
    }

    #[test]
    fn parse_blocks_raw_silently_ignores_a_top_level_task_list_marker() {
        // `parse_item_task_and_children`/`take_task_marker` are the *only* real callers that ever
        // look for a `TaskListMarker` — every genuine one is consumed by one of them before
        // `parse_blocks_raw`'s own loop ever sees it. Advancing a walker past `Start(List)` and
        // `Start(Item)` by hand, then handing it straight to `parse_blocks_raw` (bypassing
        // `parse_item_task_and_children` entirely), puts the marker exactly where its own doc
        // comment says it can never legitimately be: the very next event that loop's own `match`
        // sees. No panic, no desync — the marker is dropped (its own three bytes never claimed by
        // anything, matching `is_stray_inline_leaf`'s own doc comment on why `TaskListMarker` is
        // excluded from a stray run), and parsing continues normally past it.
        let src = "- [ ] a\n";
        let mut w = walker_for(src);
        let _ = w.next(); // Start(List)
        let _ = w.next(); // Start(Item)
        let out = parse_blocks_raw(&mut w, src);
        assert_eq!(
            out.len(),
            1,
            "the item's own text still becomes a block: {out:?}"
        );
        let BlockKind::Paragraph { inline } = &out[0].kind else {
            panic!("expected a synthetic paragraph: {:?}", out[0].kind)
        };
        assert_eq!(
            inline_plain_text(
                &Doc {
                    events: w.events.clone(),
                    blocks: Vec::new()
                },
                inline
            ),
            "a"
        );
    }

    #[test]
    fn collect_stray_inline_run_handles_an_exhausted_event_stream() {
        // Reachable only through a manufactured stream: a genuine tight-list-item stray run is
        // always followed by at least an `End(Item)` (pulldown-cmark closes every tag it opens), so
        // `events.peek()` never actually returns `None` mid-run for real input. Feeding this
        // function a walker over an *already-exhausted* parser (an empty document has zero events)
        // exercises the `None => false` arm directly — the run still ends cleanly, at the one event
        // handed in as `first`, with no panic.
        let mut w = walker_for("");
        let range = collect_stray_inline_run((Event::Text("x".into()), 3..4), &mut w);
        assert_eq!(
            range,
            3..4,
            "an exhausted stream ends the run at just its own first event"
        );
    }

    #[test]
    fn collect_code_body_spans_defensively_skips_an_unexpected_start_event() {
        // Called on a walker that never consumed the `Start(Paragraph)` opening this text — its own
        // first `next()` sees that `Start` directly, not a `Start(CodeBlock)`'s own content.
        let src = "**bold** x\n";
        let mut w = walker_for(src);
        let spans = collect_code_body_spans(&mut w);
        assert!(
            spans.is_empty(),
            "no Event::Text was ever seen at code-block level: {spans:?}"
        );
    }

    #[test]
    fn collect_code_body_spans_defensively_skips_an_event_that_is_neither_text_nor_end() {
        // Same idea as the sibling test above, but positioned to reach the function's own final
        // `_ => {}` catch-all specifically (unlike a `Start`, a bare `SoftBreak`/`End(Paragraph)` —
        // neither `Event::Text` nor `Event::End(TagEnd::CodeBlock)` nor a `Start` — has no arm of its
        // own at all): consume the opening `Start(Paragraph)` by hand first, so the walker handed to
        // `collect_code_body_spans` starts mid-paragraph, at `Text("a")`/`SoftBreak`/`Text("b")`/
        // `End(Paragraph)` directly. Two of those are genuine `Event::Text` (collected, however
        // meaningless the resulting "spans" are outside any real code block — this function has no
        // way to know it was handed the wrong context), and the other two both land on `_ => {}`.
        let src = "a\nb\n"; // a single-newline soft break inside one paragraph
        let mut w = walker_for(src);
        let _ = w.next(); // Start(Paragraph)
        let spans = collect_code_body_spans(&mut w);
        assert_eq!(
            spans.len(),
            2,
            "both Text(\"a\") and Text(\"b\") still get collected: {spans:?}"
        );
    }

    #[test]
    fn collect_table_rows_defensively_skips_an_unexpected_start_event() {
        let src = "**bold** x\n";
        let mut w = walker_for(src);
        let rows = collect_table_rows(&mut w);
        assert!(
            rows.is_empty(),
            "no TableHead/TableRow was ever seen: {rows:?}"
        );
    }

    #[test]
    fn collect_table_rows_defensively_skips_an_event_that_is_neither_a_row_kind_nor_end() {
        // Reaches `collect_table_rows`'s own final `_ => {}` the same way as
        // `collect_code_body_spans_defensively_skips_an_event_that_is_neither_text_nor_end` above.
        let src = "a\nb\n";
        let mut w = walker_for(src);
        let _ = w.next(); // Start(Paragraph)
        let rows = collect_table_rows(&mut w);
        assert!(
            rows.is_empty(),
            "no TableHead/TableRow/End(Table) event ever appears in this stream: {rows:?}"
        );
    }

    #[test]
    fn collect_row_cells_defensively_skips_an_unexpected_start_event() {
        let src = "**bold** x\n";
        let mut w = walker_for(src);
        let cells = collect_row_cells(&mut w, TagEnd::TableRow);
        assert!(cells.is_empty(), "no TableCell was ever seen: {cells:?}");
    }

    #[test]
    fn collect_row_cells_defensively_skips_an_event_that_is_neither_a_cell_nor_its_own_end() {
        // Reaches `collect_row_cells`'s own final `_ => {}` the same way as the two tests above —
        // `end` is `TagEnd::TableRow`, which the stray `End(Paragraph)` here does not match either.
        let src = "a\nb\n";
        let mut w = walker_for(src);
        let _ = w.next(); // Start(Paragraph)
        let cells = collect_row_cells(&mut w, TagEnd::TableRow);
        assert!(cells.is_empty(), "no TableCell was ever seen: {cells:?}");
    }

    #[test]
    fn collect_html_body_spans_defensively_skips_an_unexpected_start_event() {
        // Mirrors `collect_code_body_spans_defensively_skips_an_unexpected_start_event` exactly —
        // this stream is not an `HtmlBlock`'s at all (`walker_for` hands back raw events starting at
        // `Start(Paragraph)`), so the first event hits `collect_html_body_spans`'s own defensive
        // `Event::Start(t) => skip_inline_to` branch, and no `End(HtmlBlock)` ever follows to break
        // on — this pins that the walk simply stops with whatever it collected (nothing) instead of
        // panicking or looping.
        let src = "**bold** x\n";
        let mut w = walker_for(src);
        let spans = collect_html_body_spans(&mut w);
        assert!(spans.is_empty(), "no Event::Html was ever seen: {spans:?}");
    }

    #[test]
    #[allow(clippy::single_range_in_vec_init)] // a real body_spans is a Vec<Range<usize>>; one span is the normal case
    fn html_tag_of_reports_none_for_a_body_that_does_not_start_with_a_tag() {
        // `html_tag_of` reads no events at all (unlike the old, since-split `collect_html_tag`) — it
        // is a pure read off `body_spans`/`src` — so this pins its own scope directly: a first line
        // starting with `*`, not `<`, reports `None` via `html_tag_name`'s own early `?` (a different
        // branch than the one this test targets — see
        // `html_tag_name_reports_none_when_no_name_characters_follow_the_opening_bracket` below for
        // that one directly).
        let src = "**bold** x\n";
        let tag = html_tag_of(&[0..src.len()], src);
        assert_eq!(tag, None);
    }

    #[test]
    fn html_tag_name_reports_none_when_no_name_characters_follow_the_opening_bracket() {
        // `html_tag_name` is a pure function of a line, callable directly with no `Doc`/`Walker` at
        // all — real CommonMark HTML-block recognition never hands it a line shaped like these (a
        // "complete" open/close tag requires a valid name right after `<`/`</`), so its own
        // `if name.is_empty()` branch is otherwise unreachable through any document that actually
        // parses as an `HtmlBlock` in the first place.
        assert_eq!(
            html_tag_name("< foo>"),
            None,
            "space right after '<' leaves no name chars"
        );
        assert_eq!(html_tag_name("<"), None, "nothing at all after '<'");
        assert_eq!(
            html_tag_name("</"),
            None,
            "nothing after the closing-tag slash either"
        );
        // Controls: the ordinary, well-formed cases this function exists to handle still work.
        assert_eq!(html_tag_name("<div>"), Some("div".to_string()));
        assert_eq!(html_tag_name("</div>"), Some("div".to_string()));
        assert_eq!(html_tag_name(""), None, "doesn't even start with '<'");
        assert_eq!(
            html_tag_name("<!doctype>"),
            None,
            "excluded by the '!' guard, not this branch"
        );
    }

    // ---- `glued_details_fold`'s own two "give up" arms, reached through real `Doc::parse` input ---
    //
    // Unlike the previous section, every case below *is* reachable through ordinary `Doc::parse` —
    // no hand-built `Walker` needed — because pulldown-cmark really does glue an unclosed or
    // trailing-content `<details>` block into one literal `HtmlBlock`; `fold_details` really does
    // call `glued_details_fold` on it (whenever it is the last sibling at its own level, whether or
    // not it happens to also contain its own close — see `fold_details`'s own doc comment on why
    // `rest.is_empty()` alone is enough to try).

    #[test]
    fn unclosed_glued_details_with_no_close_anywhere_in_the_document_stays_unfolded() {
        // No `</details>` anywhere in the whole (single-block) document — `glued_details_fold`'s own
        // scan runs off the end of `b.src` having found nothing, returns `None`, and `fold_details`
        // falls back to leaving the raw `Html` leaf exactly as it was.
        let src = "<details>\n<summary>S</summary>\nno close anywhere\n";
        let doc = Doc::parse(src);
        assert_eq!(doc.blocks.len(), 1);
        assert!(matches!(
            doc.blocks[0].kind,
            BlockKind::Html { tag: Some(ref t), .. } if t == "details"
        ));
    }

    #[test]
    fn glued_details_with_unrelated_content_after_the_close_stays_unfolded() {
        // A close *is* found this time (`</details>` on line 3), but the same glued `HtmlBlock`
        // keeps running past it (no blank line separates "extra content here" from the close
        // either) — `glued_details_fold` refuses to silently drop that trailing text, and
        // `fold_details` leaves the whole thing as one unfolded `Html` leaf rather than truncating
        // `Block::src` and orphaning bytes with no sibling slot to carry them.
        let src = "<details>\n<summary>A</summary>\n</details>\nextra content here\n";
        let doc = Doc::parse(src);
        assert_eq!(doc.blocks.len(), 1);
        assert!(matches!(
            doc.blocks[0].kind,
            BlockKind::Html { tag: Some(ref t), .. } if t == "details"
        ));
        assert_eq!(
            &src[doc.blocks[0].src.clone()],
            src,
            "the whole glued leaf is kept intact"
        );
    }

    #[test]
    fn unclosed_details_with_no_trailing_newline_stays_unfolded() {
        // The open tag is *also* the entire input, with no trailing `'\n'` at all — `line_after`'s
        // own "no '\n' found" fallback (`src.len()`) and `glued_details_fold`'s own "ran off the
        // end" arm both fire from this one case.
        let src = "<details>";
        let doc = Doc::parse(src);
        assert_eq!(doc.blocks.len(), 1);
        assert!(matches!(
            doc.blocks[0].kind,
            BlockKind::Html { tag: Some(ref t), .. } if t == "details"
        ));
        assert_eq!(doc.blocks[0].src, 0..src.len());
    }

    // ---- Details ordinal contract vs. `collect_details_open` (markdown.rs) ------------------------

    /// Depth-first, source-order collection of every `BlockKind::Details`'s own `open_attr` — the
    /// model's own analogue of `collect_details_open`'s return value, used only by the two tests
    /// below to compare the two.
    fn collect_model_details_open(blocks: &[Block], out: &mut Vec<bool>) {
        for b in blocks {
            if let BlockKind::Details { open_attr, .. } = &b.kind {
                out.push(*open_attr);
            }
            collect_model_details_open(&b.children, out);
        }
    }

    #[test]
    fn model_details_ordinal_matches_collect_details_open_for_well_formed_non_quote_nesting() {
        // `collect_details_open` (`markdown.rs`) is the render pipeline's own scanner for seeding a
        // `<details>` block's default open/closed toggle state — see its own doc comment. This
        // model's `BlockKind::Details` sequence (walked depth-first, in source order) must agree
        // with it for every shape the two are documented, or empirically confirmed, to fold
        // identically: well-formed and blank-line-separated (at the top level, nested inside a list
        // item, several deep), unclosed, and "first close wins" swallowing of an inner `<details>`
        // glued into an *outer* one's own well-formed body.
        //
        // Two shapes are deliberately **excluded** here — not because they are hard to write, but
        // because the two sides are already known to disagree about them (found empirically while
        // writing this test, not merely inferred from a doc comment):
        //
        //   * a `<details>` nested inside a **block quote** — see
        //     `model_details_ordinal_diverges_from_collect_details_open_for_a_quote_nested_details`
        //     below, which pins the divergence directly and explains it.
        //   * a `<details>` glued (no blank line anywhere) to a *further nested* `<details>`, itself
        //     also glued with no blank line: this model deliberately leaves the whole construct as
        //     one unfolded `Html` leaf (see
        //     `glued_details_with_no_blank_line_anywhere_stays_an_unfolded_html_leaf`, above) — there
        //     is no separate sibling boundary for `fold_details`'s "first close wins" search to have
        //     found in the first place — while `split_details`'s own, differently-shaped raw-line
        //     scan folds it anyway. A pre-existing, intentional divergence for this one pathological
        //     shape (confirmed directly: `model` reports `[]`, `collect_details_open` reports
        //     `[false]`, for `"<details>\n<summary>A</summary>\n<details>\n<summary>Nested\
        //     </summary>\n</details>\n</details>\n"`), not something this test asserts parity on.
        let cases = [
            "<details>\n<summary>S</summary>\n\nbody\n\n</details>\n",
            "<details>\n<summary>A</summary>\n\na\n\n</details>\n\n\
             <details open>\n<summary>B</summary>\n\nb\n\n</details>\n",
            "- item\n\n  <details>\n  <summary>S</summary>\n\n  body\n\n  </details>\n",
            "<details>\n<summary>S</summary>\n\nbody one\n\nbody two\n",
            "<details>\n<summary>Outer</summary>\n\n\
             <details open>\n<summary>Inner</summary>\n\ninner body\n\n</details>\n\n\
             outer body after inner\n\n</details>\n",
            "- item\n\n  <details>\n  <summary>Outer</summary>\n\n  body\n\n  </details>\n\n\
             - item2\n\n  <details open>\n  <summary>Second</summary>\n\n  body2\n\n  </details>\n",
            "<details open>\n<summary>A</summary>\n\na\n\n</details>\n\n\
             <details>\n<summary>B</summary>\n\nb\n\n</details>\n\n\
             <details open>\n<summary>C</summary>\n\nc\n\n</details>\n",
        ];
        for src in cases {
            let doc = Doc::parse(src);
            let mut model_open: Vec<bool> = Vec::new();
            collect_model_details_open(&doc.blocks, &mut model_open);
            let split_open = super::super::collect_details_open(src);
            assert_eq!(model_open, split_open, "case {src:?}");
        }
    }

    #[test]
    fn model_details_ordinal_diverges_from_collect_details_open_for_a_quote_nested_details() {
        // Documents, rather than papers over, a real gap: `collect_details_open`'s own doc comment
        // explains that a `<details>` reachable only through a GitHub *alert*'s body is invisible to
        // it, "because `split_details` sees the raw, not-yet-alert-stripped source, where such a
        // block's opening tag is still `>`-prefixed and so does not match `details_open_tag`". The
        // identical mechanism — the raw line still carries a `>` prefix — applies just as much to a
        // *plain*, non-alert block quote, which that doc comment does not separately call out. This
        // model still folds it correctly (pulldown-cmark's own event stream has already stripped the
        // `>` by the time this model ever sees the text), so the two genuinely disagree here — worth
        // flagging as a discovered gap in `collect_details_open`'s own documented contract, not
        // something this file can fix (it lives in `markdown.rs`).
        let src = "> <details>\n> <summary>S</summary>\n>\n> body\n>\n> </details>\n";
        let doc = Doc::parse(src);
        let mut model_open: Vec<bool> = Vec::new();
        collect_model_details_open(&doc.blocks, &mut model_open);
        assert_eq!(
            model_open,
            vec![false],
            "the model itself still folds a quote-nested details"
        );
        assert_eq!(
            super::super::collect_details_open(src),
            Vec::<bool>::new(),
            "collect_details_open misses it — the same '>'-prefix mechanism its own doc comment \
             documents for alerts specifically also applies to a plain quote"
        );
    }

    // ---- extreme / adversarial input: `Doc::parse` must never panic, and invariants must hold ----
    //
    // Every case below is real Markdown source text handed straight to `Doc::parse` — not a
    // hand-built `Block` tree — covering shapes principle #3 (`CLAUDE.md`: "never crash on any input
    // pulldown-cmark accepts") says this model must survive: unclosed constructs, deep nesting, huge
    // single lines, huge sibling counts, CJK/emoji/combining/zero-width/RTL text, CRLF/no-trailing-
    // newline/BOM/NUL/control-byte encodings, tab/full-width-space/mixed indentation, empty/
    // whitespace-only input, and every backslash-escape form this model's own module doc comment
    // discusses (`\*` `\_` `\[` `\]` `\(` `\)` `\$` `\\`), including immediately before a multi-byte
    // character — the exact shape that has caused byte-boundary panics elsewhere in this codebase's
    // own history (see this file's own CJK/multibyte tests above, and `markdown.rs`'s own
    // `scan_inline_math`/`find_inline_dollar` fixes for the same class of bug). `Doc::parse` is run
    // through `super::super::catch_silent` (the project's own shared panic-catching helper, already
    // `pub(crate)`) so one panicking case does not stop the rest of the corpus from being checked —
    // every failure (a panic, or an invariant violation) is collected and reported together, in the
    // same "report everything wrong, not just the first" style `check_invariants` itself follows.

    /// Every extreme/adversarial `(name, source)` pair this section checks. Kept as a single,
    /// reusable list so both `doc_parse_never_panics_and_invariants_hold_across_extreme_inputs`
    /// (below) and any future addition to this corpus benefit from the same collection.
    fn extreme_input_corpus() -> Vec<(String, String)> {
        let mut v: Vec<(String, String)> = Vec::new();
        let mut push = |name: &str, src: String| v.push((name.to_string(), src));

        // -- unclosed constructs --
        push("unclosed fence", "```rust\nfn a() {}\n".to_string());
        push("unclosed fence, no lang", "```\nplain\n".to_string());
        push(
            "unclosed fence nested in a list item",
            "- item\n\n  ```rust\n  fn a() {}\n".to_string(),
        );
        push(
            "unclosed details, well-formed open/summary",
            "<details>\n<summary>S</summary>\n\nbody\n".to_string(),
        );
        push(
            "unclosed details, no summary tag",
            "<details>\nbody only\n".to_string(),
        );
        push(
            "unclosed html comment",
            "<!-- never closes\nmore text\nstill in the comment\n".to_string(),
        );
        push(
            "unclosed emphasis (asterisk)",
            "*never closes\nmore text\n".to_string(),
        );
        push(
            "unclosed emphasis (underscore)",
            "_never closes\nmore text\n".to_string(),
        );
        push("unclosed strong", "**never closes\nmore text\n".to_string());
        push(
            "unclosed link, no matching bracket",
            "[never closes (no matching bracket\n".to_string(),
        );
        push(
            "unclosed link, no matching paren",
            "[text](never closes\n".to_string(),
        );
        push(
            "unclosed inline code",
            "`never closes\nmore text\n".to_string(),
        );
        push(
            "unclosed strikethrough",
            "~~never closes\nmore text\n".to_string(),
        );
        push(
            "table header with no body rows",
            "| a | b |\n|---|---|\n".to_string(),
        );
        push(
            "table header row with no delimiter row at all",
            "| a | b |\nnot a delimiter row\n".to_string(),
        );

        // -- deep nesting --
        push("deeply nested bullet list (10 levels)", {
            let mut s = String::new();
            for i in 0..10 {
                s.push_str(&"  ".repeat(i));
                s.push_str("- level\n");
            }
            s
        });
        push("deeply nested block quote (10 levels)", {
            let mut s = "> ".repeat(10);
            s.push_str("deep quote\n");
            s
        });
        push(
            "list inside quote inside list",
            "- outer\n\n  > quoted\n  >\n  > - inner list\n  >   - inner inner\n".to_string(),
        );
        push("alternating quote/list nesting (8 levels)", {
            let mut s = String::new();
            for i in 0..8 {
                if i % 2 == 0 {
                    s.push_str(&"> ".repeat(i / 2 + 1));
                } else {
                    s.push_str(&"  ".repeat(i));
                    s.push_str("- ");
                }
            }
            s.push_str("bottom\n");
            s
        });

        // -- huge single line / many blank lines / many siblings --
        push("huge single line, no newline (~1MB)", "x".repeat(1_000_000));
        push("huge single line, unclosed emphasis (~1MB)", {
            let mut s = String::from("*");
            s.push_str(&"a".repeat(1_000_000));
            s
        });
        push("many blank lines (5000)", "\n".repeat(5000));
        push("many sibling paragraphs (2000)", {
            let mut s = String::new();
            for i in 0..2000 {
                s.push_str(&format!("para {i}\n\n"));
            }
            s
        });
        push("many sibling list items (3000)", {
            let mut s = String::new();
            for i in 0..3000 {
                s.push_str(&format!("- item {i}\n"));
            }
            s
        });

        // -- CJK / emoji / combining / zero-width / RTL --
        push(
            "cjk heavy",
            "# 見出しタイトル\n\n本文は日本語です。**強調**も*斜体*も入ります。\n\n\
             - 項目一\n- 項目二\n\n> 引用も日本語\n"
                .to_string(),
        );
        push(
            "emoji throughout",
            "# 🎉 Title 🚀\n\nHello 👋 world 🌍! `code 💻` and **bold 🔥**.\n\n- [ ] 🧪 test\n"
                .to_string(),
        );
        push(
            "combining marks stacked",
            "e\u{0301}\u{0301}\u{0301}\u{0301}\u{0301} five combining acutes on one base\n"
                .to_string(),
        );
        push(
            "zero width characters",
            "zero\u{200B}width\u{200C}space\u{200D}joiner\u{FEFF}mixed\n".to_string(),
        );
        push(
            "rtl text mixed with ltr",
            "\u{202B}שלום עולם\u{202C} mixed with English text\n".to_string(),
        );
        push(
            "rtl heading",
            "# \u{0645}\u{0631}\u{062D}\u{0628}\u{0627} Arabic heading\n".to_string(),
        );
        push(
            "cjk task list and code fence",
            "- [ ] 日本語のタスク\n- [x] 完了したタスク\n\n```rust\nfn 関数() -> 文字列 {}\n```\n"
                .to_string(),
        );

        // -- CRLF / no trailing newline / BOM / NUL / control chars --
        push(
            "crlf throughout, mixed constructs",
            "# Title\r\n\r\nBody line one\r\nBody line two\r\n\r\n\
             - item one\r\n- item two\r\n\r\n```rust\r\nfn a() {}\r\n```\r\n\r\n\
             > quoted\r\n> line two\r\n"
                .to_string(),
        );
        push(
            "no trailing newline, plain text",
            "just text, no newline at all".to_string(),
        );
        push(
            "no trailing newline, heading",
            "# Title, no newline".to_string(),
        );
        push(
            "no trailing newline, fenced code",
            "```\ncode\n```".to_string(),
        );
        push("no trailing newline, list item", "- one\n- two".to_string());
        push(
            "bom prefixed document",
            "\u{FEFF}# Title\n\nBody\n".to_string(),
        );
        push("nul byte embedded", "before\u{0}after\n".to_string());
        push(
            "assorted c0 control chars",
            "col1\u{1}col2\u{2}col3\u{7}bell\u{8}backspace\n".to_string(),
        );

        // -- tab / full-width space / mixed indentation --
        push(
            "tab-indented code block",
            "para\n\n\tline one\n\tline two\n".to_string(),
        );
        push(
            "tab after a list marker",
            "-\ttab then item text\n".to_string(),
        );
        push(
            "fullwidth space, not real indentation",
            "  - looks indented but is U+3000, not ascii space\n".to_string(),
        );
        push(
            "mixed tab and space indentation",
            "- item\n \t - mixed indent nested item\n".to_string(),
        );

        // -- empty / whitespace-only --
        push("empty string", String::new());
        push("single space", " ".to_string());
        push(
            "whitespace only (spaces and tabs)",
            "   \t   \t\t  ".to_string(),
        );
        push("single newline only", "\n".to_string());
        push("many newlines only", "\n\n\n\n\n\n\n\n".to_string());

        // -- escapes: every form this model's own module doc comment discusses --
        for esc in ["\\*", "\\_", "\\[", "\\]", "\\(", "\\)", "\\$", "\\\\"] {
            push(
                &format!("escape {esc:?} mid-text"),
                format!("text {esc} more text\n"),
            );
            push(
                &format!("escape {esc:?} at start of line"),
                format!("{esc} more text\n"),
            );
            push(
                &format!("escape {esc:?} at end of input, no newline"),
                format!("text {esc}"),
            );
        }
        // The one class of bug this codebase has actually hit before (see `CLAUDE.md`'s own record
        // of a `\` + multibyte byte-boundary panic in a *different* scanner, `scan_inline_math`):
        // a backslash immediately followed by a multi-byte character.
        push(
            "backslash immediately before cjk",
            "before \\あ after\n".to_string(),
        );
        push(
            "backslash immediately before emoji",
            "before \\🎉 after\n".to_string(),
        );
        push(
            "backslash immediately before combining mark",
            "before \\\u{0301} after\n".to_string(),
        );
        push(
            "input ends with a lone trailing backslash",
            "text ends with backslash\\".to_string(),
        );
        push(
            "currency dollar, not math (ENABLE_MATH is off anyway)",
            "price is \\$5 not math\n".to_string(),
        );
        push(
            "raw dollar-delimited text, unprocessed",
            "inline $x + y$ and $$z$$ display\n".to_string(),
        );
        push(
            "raw footnote-shaped text, unprocessed",
            "See [^1] here.\n\n[^1]: definition\n".to_string(),
        );

        v
    }

    #[test]
    fn doc_parse_never_panics_and_invariants_hold_across_extreme_inputs() {
        let mut failures: Vec<String> = Vec::new();
        let mut checked = 0usize;
        for (name, src) in extreme_input_corpus() {
            checked += 1;
            // Not a `move` closure: `name`/`src` are only ever borrowed here, so both are still
            // usable afterward to build a failure message — `catch_silent`'s own `f: impl FnOnce()
            // -> T` has no `'static` bound, so a borrowing closure is fine.
            let result = super::super::catch_silent(|| {
                let doc = Doc::parse(&src);
                let mut out = Vec::new();
                check_invariants(&doc.blocks, &src, doc.events.len(), None, &name, &mut out);
                out
            });
            match result {
                None => failures.push(format!("{name:?}: PANICKED")),
                Some(violations) if !violations.is_empty() => {
                    failures.push(format!(
                        "{name:?}: {} invariant violation(s): {violations:?}",
                        violations.len()
                    ));
                }
                Some(_) => {}
            }
        }
        assert!(
            checked > 60,
            "the extreme-input corpus looks suspiciously small ({checked}) — did a `push` call \
             break?"
        );
        assert!(
            failures.is_empty(),
            "{} case(s) failed out of {checked}:\n{}",
            failures.len(),
            failures.join("\n")
        );
    }

    #[test]
    fn doc_parse_never_panics_on_deeply_nested_alternating_containers() {
        // A single, especially adversarial case pulled out on its own (rather than folded silently
        // into the corpus above) so a regression here fails with an obviously specific test name:
        // 15 levels of quote-wrapping-list-wrapping-quote, ending in a task item, a fenced code
        // block, and a table, none of them closed.
        let mut src = String::new();
        for i in 0..15 {
            if i % 2 == 0 {
                src.push_str("> ");
            } else {
                src.push_str("- ");
            }
        }
        src.push_str("- [ ] deep task\n");
        for i in 0..15 {
            let prefix = if i % 2 == 0 { "> " } else { "  " };
            src.push_str(prefix);
        }
        src.push_str("```rust\nfn deep() {}\n");
        let doc = super::super::catch_silent(|| Doc::parse(&src));
        let doc = doc.expect("Doc::parse must not panic on deep, unclosed, alternating nesting");
        let mut out = Vec::new();
        check_invariants(
            &doc.blocks,
            &src,
            doc.events.len(),
            None,
            "deeply_nested_alternating",
            &mut out,
        );
        assert!(out.is_empty(), "{out:?}");
    }

    // ---- `CodeBlock.body_spans` and `Task.state_at` contract, hardened across extreme containers --
    //
    // The two fields a future in-place "copy this code block" / "toggle this checkbox" feature would
    // slice the input directly from — see `BlockKind::CodeBlock.body_spans`'s and `Task::state_at`'s
    // own doc comments. Both are checked here across every combination their own doc comments call
    // out as needing a *list* of spans (rather than one contiguous range) in the first place: fenced
    // and indented, nested inside a list item / block quote / GFM alert / `<details>` body, under
    // CRLF line endings, with a literal tab as *content* (inside a fence, a tab is just a content
    // byte, not indentation), and with CJK content. Every expected reconstruction below was confirmed
    // by first printing `Doc::parse`'s own actual output for that exact source (not merely assumed)
    // before being pinned as an assertion — the reconstruction rules for quote/list continuation-line
    // indentation and CRLF normalization are exactly the subtle, easy-to-get-wrong shape this whole
    // model exists to get right once, in one place (see the module doc comment's own "Why this
    // exists" section).

    #[test]
    fn code_block_body_spans_reconstruct_byte_exact_content_across_extreme_containers() {
        let cases: &[(&str, &str, &str)] = &[
            (
                "fenced code nested inside a block quote",
                "> ```rust\n> fn a() {}\n> ```\n",
                "fn a() {}",
            ),
            (
                "fenced code nested inside a GFM alert",
                "> [!WARNING]\n> ```\n> code in alert\n> ```\n",
                "code in alert",
            ),
            (
                "fenced code nested inside a details body",
                "<details>\n<summary>S</summary>\n\n```rust\nfn a() {}\n```\n\n</details>\n",
                "fn a() {}",
            ),
            (
                "fenced code nested inside a list item, CRLF throughout",
                "- item\r\n\r\n  ```rust\r\n  fn a() {}\r\n  ```\r\n",
                "fn a() {}",
            ),
            (
                "indented code, CRLF throughout",
                "para\r\n\r\n    line one\r\n    line two\r\n",
                "line one\nline two",
            ),
            (
                "indented code nested inside a block quote",
                "> para\n>\n>     indented code\n>     more code\n",
                "indented code\nmore code",
            ),
            (
                "cjk code content",
                "```rust\nfn 関数() -> 文字列 {}\n```\n",
                "fn 関数() -> 文字列 {}",
            ),
            (
                "a literal tab as fenced code content, not indentation",
                "```\n\tindented with tab inside fence\n```\n",
                "\tindented with tab inside fence",
            ),
            (
                "empty fenced code nested inside a list item",
                "- item\n\n  ```\n  ```\n",
                "",
            ),
        ];
        for (name, src, expected) in cases {
            let doc = Doc::parse(src);
            let mut spans_by_block: Vec<Vec<Range<usize>>> = Vec::new();
            code_block_bodies_ignoring_quote_flag(&doc.blocks, &mut spans_by_block);
            assert_eq!(
                spans_by_block.len(),
                1,
                "case {name:?}: expected exactly one code block"
            );
            let actual = code_body_text(&spans_by_block[0], src);
            assert_eq!(actual, *expected, "case {name:?}");
            // Every reconstructed span also has to satisfy the checker's own invariants — belt and
            // suspenders on top of the byte-exact content match above.
            let mut violations = Vec::new();
            check_invariants(
                &doc.blocks,
                src,
                doc.events.len(),
                None,
                name,
                &mut violations,
            );
            assert!(violations.is_empty(), "case {name:?}: {violations:?}");
        }
    }

    /// Like `code_block_bodies` above, but collecting only the `body_spans` themselves (not the
    /// quote-nesting flag) — used by the extreme-containers test above, which deliberately *does*
    /// want quote-nested code blocks included (unlike `parser_code_blocks`'s own convention).
    fn code_block_bodies_ignoring_quote_flag(blocks: &[Block], out: &mut Vec<Vec<Range<usize>>>) {
        for b in blocks {
            if let BlockKind::CodeBlock { body_spans, .. } = &b.kind {
                out.push(body_spans.clone());
            }
            code_block_bodies_ignoring_quote_flag(&b.children, out);
        }
    }

    #[test]
    fn task_state_at_contract_holds_across_extreme_containers() {
        let cases = [
            (
                "task list nested inside a block quote",
                "> - [ ] a\n> - [x] b\n> - [X] c\n",
            ),
            (
                "task list nested inside a GFM alert",
                "> [!NOTE]\n> - [ ] a\n> - [x] b\n> - [X] c\n",
            ),
            (
                "task list nested inside a details body",
                "<details>\n<summary>S</summary>\n\n- [ ] a\n- [x] b\n- [X] c\n\n</details>\n",
            ),
            (
                "task list, CRLF throughout",
                "- [ ] a\r\n- [x] b\r\n- [X] c\r\n",
            ),
            (
                "task list, cjk label text",
                "- [ ] 日本語のタスク\n- [x] 完了したタスク\n",
            ),
            (
                "task list nested two list levels deep",
                "- outer\n  - [ ] nested a\n  - [x] nested b\n",
            ),
        ];
        for (name, src) in cases {
            let doc = Doc::parse(src);
            let mut tasks: Vec<Task> = Vec::new();
            collect_tasks(&doc.blocks, &mut tasks);
            assert!(
                !tasks.is_empty(),
                "case {name:?}: expected at least one task item"
            );
            for t in &tasks {
                assert!(
                    src.is_char_boundary(t.state_at),
                    "case {name:?}: state_at {} not on a char boundary",
                    t.state_at
                );
                assert!(
                    src[t.state_at..].starts_with(t.state),
                    "case {name:?}: byte at state_at does not match state {:?}",
                    t.state
                );
                assert_eq!(
                    src.as_bytes().get(t.state_at - 1),
                    Some(&b'['),
                    "case {name:?}: byte before state_at is not '['"
                );
                assert_eq!(
                    src.as_bytes().get(t.state_at + 1),
                    Some(&b']'),
                    "case {name:?}: byte after state_at is not ']'"
                );
            }
            // Same belt-and-suspenders as the code-block test above: `check_invariants` itself must
            // also see the whole tree as clean.
            let mut violations = Vec::new();
            check_invariants(
                &doc.blocks,
                src,
                doc.events.len(),
                None,
                name,
                &mut violations,
            );
            assert!(violations.is_empty(), "case {name:?}: {violations:?}");
        }
    }

    fn collect_tasks(blocks: &[Block], out: &mut Vec<Task>) {
        for b in blocks {
            if let BlockKind::ListItem { task: Some(t) } = &b.kind {
                out.push(*t);
            }
            collect_tasks(&b.children, out);
        }
    }
}