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
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
//! What stage 1c is checked with.
//!
//! `docs/FEATURE-MERMAID-RENDERER.md` §6 sets the terms, because konoma has twice been fooled by
//! a green suite that was measuring nothing (a diff harness that had quietly become a
//! self-comparison; a golden that pinned a function production did not call). So the tests here
//! are built around three questions that konoma cannot answer by itself:
//!
//! 1. **Does resvg draw the text at the width konoma measured?** [`box_width_matches_resvg`] puts
//!    the emitted SVG through usvg with konoma's own font database and compares the box konoma
//!    sized against `Text::bounding_box().width()`. That is konoma versus *resvg's real shaper*,
//!    so it cannot decay into konoma versus konoma.
//! 2. **Is the geometry sound?** The `invariant_*` tests state the five properties §6 lists —
//!    boxes do not overlap, edges do not cross a box's inside, a label sits on its own line and on
//!    no box, an arrow tip lands on the target's boundary, the viewBox holds everything — over a
//!    corpus built from the *specification's* cases (`§2-2`'s shapes, strokes, directions), not
//!    from a list of bugs already found.
//! 3. **Does it still come out the same?** The golden is the SVG text (never a PNG: §6 notes
//!    resvg 0.48 swapped its whole text stack), and it goes through [`super::render`], the
//!    function production will call.
//!
//! # Why the golden masks its numbers
//!
//! Every coordinate in a diagram descends from a label width, and a label width comes from the
//! system's sans-serif face — Helvetica here, DejaVu Sans on the Linux CI box. A byte-exact
//! end-to-end golden would therefore be a golden of *this machine's fonts*, and would fail on CI
//! for a reason that has nothing to do with the renderer. So the corpus golden masks numeric
//! attribute values and pins everything else: which elements are emitted, in what order, with
//! which colours, which path commands, and which text. The numbers are pinned separately, by
//! [`emit_golden`] (which builds a diagram by hand, so no font is involved) and by the arithmetic
//! tests over the shape formulas.
//!
//! That the mask really is font-independent was measured rather than assumed: multiplying every
//! measured label width by 0.5, 0.85, 1.15, 1.3 and 2.0 — far past the gap between Helvetica and
//! DejaVu Sans — leaves `mermaid_render.snap` byte-identical. Ranks, orders and dummy-node counts
//! come from the graph's shape, not from its labels' widths, so the emitted element sequence does
//! not move with the font.

use std::collections::{HashMap, HashSet};
use std::path::{Path as FsPath, PathBuf};

use resvg::usvg;

use super::clusters;
use super::edges;
use super::labels::Label;
use super::shapes::{self, Glyph, Size};
use super::svg::num;
use super::theme::{self, Theme};
use super::{
    lay_out, lay_out_curve, lay_out_flow, orthogonal, render, render_curve, render_flow, Curve,
    Diagram, PlacedCluster, PlacedEdge, PlacedEdgeLabel, PlacedNode, RenderError, Routing, Tip,
    MARGIN,
};
use crate::preview::mermaid::flowchart::{parse, Arrow, Direction, Shape, Stroke};
use crate::preview::mermaid::layout::Point;
use crate::preview::mermaid::text_metrics;
use crate::preview::svg::shared_fontdb;

// ---------------------------------------------------------------------------------------------
// Corpus
// ---------------------------------------------------------------------------------------------

/// The diagrams every structural test runs over.
///
/// Chosen from the *cases in the specification* rather than from past bugs (memory
/// `corpus-from-spec-not-from-bugs`): each of §2-2's classic shapes, each stroke and arrow
/// spelling, both label notations, all four directions, multi-line labels, CJK, a long edge that
/// skips ranks, a cycle, a self-loop, and a subgraph — which stage 1c must survive without
/// drawing (§7).
pub(super) const CORPUS: &[(&str, &str)] = &[
    (
        "branch",
        "flowchart TD\n  A[Start] --> B{Ready?}\n  B -->|yes| C([Ship])\n  B -->|no| D[Fix it]\n  D --> B",
    ),
    (
        "shapes",
        "flowchart TD\n  a[rect] --> b(round)\n  b --> c([stadium])\n  c --> d[[sub]]\n  \
         d --> e[(store)]\n  e --> f((circle))\n  f --> g{diamond}\n  g --> h{{hex}}\n  \
         h --> i>odd]\n  i --> j[/lean/]\n  j --> k[\\lean back\\]\n  k --> l[/trap\\]\n  \
         l --> m[\\inv trap/]",
    ),
    (
        "strokes",
        "flowchart LR\n  A --- B\n  B -.-> C\n  C ==> D\n  D --o E\n  E --x F\n  A <--> F\n  \
         C ~~~ E",
    ),
    (
        "cjk",
        "flowchart TD\n  A[ツリー] -->|Enter| B{種別を解決}\n  B -->|画像| C[全画面プレビュー]\n  \
         B -->|テキスト| D[窓読み]\n  D --> A",
    ),
    (
        "long-edge",
        "flowchart TD\n  A --> B --> C --> D --> E\n  A --> E\n  E --> B\n  C --> A",
    ),
    (
        "left-right",
        "flowchart LR\n  Parse -- tokens --> Layout -- boxes --> Draw\n  Draw --> Parse",
    ),
    (
        "bottom-top",
        "flowchart BT\n  leaf1 --> mid\n  leaf2 --> mid\n  mid --> root",
    ),
    (
        "right-left",
        "flowchart RL\n  A[one] --> B[two]\n  B --> C[three]",
    ),
    (
        "multiline",
        "flowchart TD\n  A[first line<br>second line<br>third] --> B[\"one\\ntwo\"]",
    ),
    (
        "self-loop",
        "flowchart TD\n  A[retry] --> A\n  A --> B[done]",
    ),
    (
        "subgraph",
        "flowchart TD\n  subgraph one [Group]\n    A --> B\n  end\n  B --> C\n  C --> A",
    ),
    (
        "subgraph-nested",
        "flowchart TD\n  subgraph outer [Outer]\n    subgraph inner [Inner]\n      A --> B\n             end\n    B --> C\n  end\n  C --> D",
    ),
    (
        "subgraph-siblings",
        "flowchart LR\n  subgraph left [Read]\n    A --> B\n  end\n  subgraph right [Write]\n           C --> D\n  end\n  B --> C",
    ),
    (
        // A block sitting between two nodes that have nothing to do with it: `X --> Y` spans the
        // same ranks the frame does, and it is dagre's compound layout (`parentDummyChains`) that
        // keeps its waypoints out of the box rather than anything this renderer does afterwards.
        "subgraph-bypass",
        "flowchart LR\n  subgraph one [Middle]\n    A --> B\n  end\n  X --> Y\n  X --> A\n           B --> Y",
    ),
    (
        "subgraph-endpoint",
        "flowchart LR\n  subgraph one [First]\n    A --> B\n  end\n  subgraph two [Second]\n           C --> D\n  end\n  one --> two\n  E --> one",
    ),
    (
        "subgraph-direction",
        "flowchart LR\n  subgraph one [Steps]\n    direction TB\n    A --> B --> C\n  end\n           one --> D",
    ),
    (
        "subgraph-cjk",
        "flowchart TD\n  subgraph proc [プレビュー解決]\n    A[種別] --> B[レンダラ]\n  end\n           B --> C[全画面表示]",
    ),
    (
        "subgraph-long-title",
        "flowchart TD\n  subgraph one [resolve the preview kind and delegate it]\n    A --> B\n           end\n  subgraph two [b]\n    C --> D\n  end\n  B --> C",
    ),
    (
        // A two-line title is the case that makes a frame grow upward: the band dagre leaves
        // above the topmost rank is one `ranksep`/2, which fits one line of text and not two.
        "subgraph-tall-title",
        "flowchart TD\n  subgraph one [Resolve the kind<br>and delegate]\n    A --> B\n  end\n           B --> C",
    ),
    (
        "subgraph-untitled",
        "flowchart TD\n  subgraph\n    A --> B\n  end\n  B --> C",
    ),
    (
        "amp-chain",
        "flowchart LR\n  A & B --> C & D\n  C --> E",
    ),
    (
        "length",
        "flowchart TD\n  A ---> B\n  A --> C\n  B --> D\n  C --> D",
    ),
    (
        // `linkStyle` naming several indices at once, in the exact shape a real diagram uses it
        // (`~/work/Ergora/doc/spec/05-system-architecture.md`'s six colour-coded groups of edges
        // — the source of the 2026-08-28 regression `docs/STATUS.md` records). Before that fix,
        // `mask_numbers` would have shown this case's colour drift — `fill`/`stroke` are two of
        // the few attributes it does *not* mask — but no corpus case exercised `linkStyle` at
        // all, which is exactly how the regression reached a release unnoticed.
        "link-style-multi-index",
        "flowchart TD\n  A --> B\n  B --> C\n  C --> D\n  D --> E\n  \
         linkStyle 0,1,2 stroke:#1f6feb\n  linkStyle 3 stroke:#d4a017",
    ),
    (
        // `classDef` + `:::` + a node's own `style` together, so the golden pins the whole
        // cascade at once: `default` colours every node, `:::hot` overrides the one it names, and
        // `style` on top of that overrides `:::hot` again.
        "classdef-and-style-cascade",
        "flowchart TD\n  classDef default fill:#223,stroke:#556\n  \
         classDef hot fill:#f9f,stroke:#a00\n  A:::hot --> B\n  style A fill:#0f0",
    ),
];

/// Label strings the measuring instrument runs over. §6 names these classes explicitly: CJK,
/// emoji, text with kerning pairs, thin glyphs, long runs and mixtures.
const LABELS: &[(&str, &str)] = &[
    ("ascii", "Start"),
    ("kerning", "AVATAR To Wa"),
    ("thin", "illicit lilli"),
    ("cjk", "全画面プレビュー"),
    ("cjk-punct", "開始、処理。「確認」"),
    ("emoji", "build 🚀 ship"),
    (
        "long",
        "resolve the preview kind and hand it to the right renderer",
    ),
    (
        "mixed",
        "konoma のプレビュー preview を全画面 fullscreen で",
    ),
    ("digits", "0123456789"),
    ("one", "x"),
    // usvg folds runs of whitespace *before* it shapes, so a label written with two spaces is
    // drawn one space narrower than its bytes suggest. Measuring the bytes sizes a box the text
    // does not fill, and every coordinate downstream of that box moves with it. Stage 4 met this
    // for real on a sequence diagram's `loop  Every minute`; `docs/STATUS.md` recorded it as a
    // hole in every kind's measurement, so each kind's instrument now carries a case of it.
    ("double-space", "loop  Every minute"),
    ("edge-space", "  padded out  "),
];

// ---------------------------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------------------------

fn laid_out(src: &str) -> Diagram {
    let chart = parse(src).unwrap_or_else(|e| panic!("corpus source must parse: {e}"));
    lay_out(&chart).unwrap_or_else(|e| panic!("corpus source must lay out: {e}"))
}

/// [`laid_out`], with every edge's curve resolved from `curve` (`ui.mermaid_curve`'s raw
/// string) the way [`lay_out_curve`] resolves it.
fn laid_out_curve(src: &str, curve: &str) -> Diagram {
    let chart = parse(src).unwrap_or_else(|e| panic!("corpus source must parse: {e}"));
    lay_out_curve(&chart, curve).unwrap_or_else(|e| panic!("corpus source must lay out: {e}"))
}

/// [`laid_out_curve`], with edges additionally routed by `routing` (`ui.mermaid_routing`'s raw
/// string) the way [`lay_out_flow`] resolves it.
pub(super) fn laid_out_flow(src: &str, curve: &str, routing: &str) -> Diagram {
    let chart = parse(src).unwrap_or_else(|e| panic!("corpus source must parse: {e}"));
    lay_out_flow(&chart, curve, routing)
        .unwrap_or_else(|e| panic!("corpus source must lay out: {e}"))
}

/// A [`PlacedNode`] with a plain rectangle glyph and a blank label — a hand-built layout input for
/// the stage 2-4 unit tests below, the same role `orthogonal.rs`'s own private `node` helper plays
/// for that module's tests (kept separate rather than shared: the two test modules build different
/// things from a node — this file also needs a full [`GraphSpec`] elsewhere, which
/// `orthogonal.rs`'s helper has no reason to know about).
fn placed_node(id: &str, cx: f64, cy: f64, w: f64, h: f64) -> PlacedNode {
    PlacedNode {
        id: id.to_string(),
        shape: Glyph::default(),
        center: Point::new(cx, cy),
        size: Size::new(w, h),
        label: Label::measure(""),
        panel: None,
        series: None,
        mark: None,
        style: None,
    }
}

pub(super) fn tree_of(svg: &str) -> usvg::Tree {
    let opt = usvg::Options {
        fontdb: shared_fontdb(),
        ..usvg::Options::default()
    };
    usvg::Tree::from_data(svg.as_bytes(), &opt).expect("emitted SVG parses")
}

/// Every `<text>` in the tree, as the width resvg actually laid it out at.
pub(super) fn text_widths(group: &usvg::Group, out: &mut Vec<f32>) {
    for node in group.children() {
        match node {
            usvg::Node::Text(t) => out.push(t.bounding_box().width()),
            usvg::Node::Group(g) => text_widths(g, out),
            _ => {}
        }
    }
}

/// Every `<text>` in the tree, as the string it holds and the width resvg laid it out at.
///
/// The content is what makes an instrument precise: a document usually has several kinds of label
/// in it, and comparing the widest one would only ever measure the widest kind.
pub(super) fn measured_texts(group: &usvg::Group, out: &mut Vec<(String, f64)>) {
    for node in group.children() {
        match node {
            usvg::Node::Text(t) => {
                let s: String = t.chunks().iter().map(|c| c.text().to_string()).collect();
                out.push((s, t.bounding_box().width() as f64));
            }
            usvg::Node::Group(g) => measured_texts(g, out),
            _ => {}
        }
    }
}

/// Every drawn path's bounding box (fill geometry, stroke excluded).
pub(super) fn path_boxes(group: &usvg::Group, out: &mut Vec<usvg::Rect>) {
    for node in group.children() {
        match node {
            usvg::Node::Path(p) => out.push(p.bounding_box()),
            usvg::Node::Group(g) => path_boxes(g, out),
            _ => {}
        }
    }
}

/// Squared distance from `p` to the segment `a`-`b`.
pub(super) fn dist_to_segment(p: &Point, a: &Point, b: &Point) -> f64 {
    let (dx, dy) = (b.x - a.x, b.y - a.y);
    let len2 = dx * dx + dy * dy;
    if len2 == 0.0 {
        return (p.x - a.x).hypot(p.y - a.y);
    }
    let t = (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0);
    (p.x - (a.x + t * dx)).hypot(p.y - (a.y + t * dy))
}

pub(super) fn dist_to_polyline(p: &Point, line: &[Point]) -> f64 {
    line.windows(2)
        .map(|w| dist_to_segment(p, &w[0], &w[1]))
        .fold(f64::INFINITY, f64::min)
}

/// The boundary of a placed node, as a closed polygon in absolute coordinates.
///
/// Deliberately built from [`shapes::polygon`] and the bounding box rather than from
/// [`shapes::intersect`]: the invariant "the arrow tip is on the boundary" has to be checked
/// against the outline, not against the same function that produced the point.
pub(super) fn boundary(node: &PlacedNode) -> Vec<Point> {
    let (w, h) = (node.size.w, node.size.h);
    let (cx, cy) = (node.center.x, node.center.y);
    let local = shapes::polygon(node.shape, node.size);
    if !local.is_empty() {
        return local
            .into_iter()
            .map(|p| Point::new(cx + p.x, cy + p.y))
            .collect();
    }
    match node.shape {
        // Sampled finely enough that "on the boundary" is decided by geometry, not by the sample
        // count: 256 segments on a circle of radius 100 deviate by under 0.008px.
        // Both `[*]` markers are circles too — a `stateEnd`'s ring is what an edge stops on, and
        // measuring it against a bounding box instead lets a line end up to `r(1 - 1/√2)` inside
        // the shape without the invariant noticing.
        Glyph::Flow(Shape::Circle)
        | Glyph::Flow(Shape::DoubleCircle)
        | Glyph::StateStart
        | Glyph::StateEnd => {
            let r = w / 2.0;
            (0..256)
                .map(|i| {
                    let t = std::f64::consts::TAU * i as f64 / 256.0;
                    Point::new(cx + r * t.cos(), cy + r * t.sin())
                })
                .collect()
        }
        _ => vec![
            Point::new(cx - w / 2.0, cy - h / 2.0),
            Point::new(cx + w / 2.0, cy - h / 2.0),
            Point::new(cx + w / 2.0, cy + h / 2.0),
            Point::new(cx - w / 2.0, cy + h / 2.0),
        ],
    }
}

/// [`shapes::size`] for one of a flowchart's own shapes, which is what the arithmetic tests are
/// written about. The renderer measures every node through [`Glyph`]; wrapping it here keeps the
/// formulas readable as formulas.
fn flow_size(shape: Shape, label: Size) -> Size {
    shapes::size(Glyph::Flow(shape), label)
}

/// Distance from `p` to a closed polygon's boundary.
pub(super) fn dist_to_boundary(p: &Point, poly: &[Point]) -> f64 {
    let n = poly.len();
    (0..n)
        .map(|i| dist_to_segment(p, &poly[i], &poly[(i + 1) % n]))
        .fold(f64::INFINITY, f64::min)
}

/// Even-odd point-in-polygon.
pub(super) fn inside(p: &Point, poly: &[Point]) -> bool {
    let n = poly.len();
    let mut hit = false;
    let mut j = n - 1;
    for i in 0..n {
        let (a, b) = (&poly[i], &poly[j]);
        if (a.y > p.y) != (b.y > p.y) {
            let x = a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x);
            if p.x < x {
                hit = !hit;
            }
        }
        j = i;
    }
    hit
}

/// How far inside the shape `p` lies, or 0 when it is outside.
pub(super) fn depth(p: &Point, poly: &[Point]) -> f64 {
    if inside(p, poly) {
        dist_to_boundary(p, poly)
    } else {
        0.0
    }
}

/// The subgraph tree of a source, rebuilt from the parser's own output.
///
/// The cluster invariants need to know who is inside what, and the [`Diagram`] deliberately does
/// not carry membership — a frame is geometry. Re-deriving it from [`parse`] keeps the question
/// ("is this node a member of that block?") answered by the parser, which stage 1b tested, rather
/// than by the layout code under test here.
fn tree_of_src(src: &str) -> clusters::Tree {
    let chart = parse(src).expect("parses");
    let ids: HashSet<String> = chart.nodes.iter().map(|n| n.id.clone()).collect();
    clusters::Tree::build(&chart, |id| ids.contains(id))
}

/// Axis-aligned overlap of two rectangles given as `(l, t, r, b)`.
pub(super) fn rect_overlap(a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)) -> (f64, f64) {
    (a.2.min(b.2) - a.0.max(b.0), a.3.min(b.3) - a.1.max(b.1))
}

/// How far `inner` pokes out of `outer`, as the worst of the four sides. Negative means contained.
pub(super) fn escapes(inner: (f64, f64, f64, f64), outer: (f64, f64, f64, f64)) -> f64 {
    (outer.0 - inner.0)
        .max(outer.1 - inner.1)
        .max(inner.2 - outer.2)
        .max(inner.3 - outer.3)
}

/// The deepest a polyline reaches inside a rectangle, sampling every half pixel. 0 when it never
/// enters. Sampling rather than testing the vertices is what catches a segment that cuts a corner.
pub(super) fn polyline_depth_in_rect(line: &[Point], rect: (f64, f64, f64, f64)) -> f64 {
    let depth_at = |p: &Point| {
        let d = (p.x - rect.0)
            .min(rect.2 - p.x)
            .min(p.y - rect.1)
            .min(rect.3 - p.y);
        d.max(0.0)
    };
    let mut worst: f64 = 0.0;
    for w in line.windows(2) {
        let len = (w[1].x - w[0].x).hypot(w[1].y - w[0].y);
        let steps = (len / 0.5).ceil().max(1.0) as usize;
        for i in 0..=steps {
            let t = i as f64 / steps as f64;
            let p = Point::new(
                w[0].x + t * (w[1].x - w[0].x),
                w[0].y + t * (w[1].y - w[0].y),
            );
            worst = worst.max(depth_at(&p));
        }
    }
    worst
}

/// Axis-aligned overlap of two node boxes, as `(dx, dy)` — both positive means they intersect.
pub(super) fn box_overlap(a: &PlacedNode, b: &PlacedNode) -> (f64, f64) {
    let (al, at, ar, ab) = a.bounds();
    let (bl, bt, br, bb) = b.bounds();
    (ar.min(br) - al.max(bl), ab.min(bb) - at.max(bt))
}

/// Masks the value of every numeric attribute, leaving structure, colours and text intact.
///
/// `M12.5,4 L20,4` becomes `M#,# L#,#`, so the golden pins which path commands are emitted in
/// which order without pinning coordinates that descend from the system font.
pub(super) fn mask_numbers(svg: &str) -> String {
    const NUMERIC: &[&str] = &[
        "x",
        "y",
        "x1",
        "y1",
        "x2",
        "y2",
        "width",
        "height",
        "rx",
        "ry",
        "cx",
        "cy",
        "r",
        "d",
        "points",
        "stroke-width",
        "dy",
        "font-size",
        "stroke-dasharray",
        "viewBox",
    ];
    let numeric: HashSet<&str> = NUMERIC.iter().copied().collect();
    let mut out = String::with_capacity(svg.len());
    let bytes: Vec<char> = svg.chars().collect();
    let mut i = 0;
    while i < bytes.len() {
        // Find `name="` where `name` is a numeric attribute.
        if bytes[i] == '=' && i + 1 < bytes.len() && bytes[i + 1] == '"' {
            let mut start = i;
            while start > 0 && (bytes[start - 1].is_ascii_alphanumeric() || bytes[start - 1] == '-')
            {
                start -= 1;
            }
            let name: String = bytes[start..i].iter().collect();
            if numeric.contains(name.as_str()) {
                out.push_str("=\"");
                let mut j = i + 2;
                let mut in_number = false;
                while j < bytes.len() && bytes[j] != '"' {
                    let c = bytes[j];
                    if c.is_ascii_digit() || c == '.' || (c == '-' && !in_number) {
                        if !in_number {
                            out.push('#');
                            in_number = true;
                        }
                    } else {
                        in_number = false;
                        out.push(c);
                    }
                    j += 1;
                }
                out.push('"');
                i = j + 1;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    out
}

/// The columns of an emitted SVG that a routing regression would actually move: every `d` (a
/// path's shape, with its numbers masked the same way [`mask_numbers`] masks them — font-dependent
/// label widths must not make this signature drift between Helvetica here and DejaVu Sans on
/// Linux CI, the same reason `corpus_golden` masks numbers at all) and every literal `fill`/
/// `stroke` (colour, which `mask_numbers` never touches — see the `link-style-multi-index` corpus
/// comment for why that's deliberate). One attribute per line, document order preserved, so a
/// change in bend count, sign pattern, command letter, or colour still moves this string even
/// though the exact coordinates are masked away.
pub(super) fn routing_signature(svg: &str) -> String {
    let masked = mask_numbers(svg);
    let mut out = String::new();
    let chars: Vec<char> = masked.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '=' && i + 1 < chars.len() && chars[i + 1] == '"' {
            let mut start = i;
            while start > 0 && (chars[start - 1].is_ascii_alphanumeric() || chars[start - 1] == '-')
            {
                start -= 1;
            }
            let name: String = chars[start..i].iter().collect();
            if matches!(name.as_str(), "d" | "fill" | "stroke") {
                let mut j = i + 2;
                while j < chars.len() && chars[j] != '"' {
                    j += 1;
                }
                let value: String = chars[i + 2..j].iter().collect();
                out.push_str(&name);
                out.push('=');
                out.push_str(&value);
                out.push('\n');
                i = j + 1;
                continue;
            }
        }
        i += 1;
    }
    out
}

pub(super) fn snapshot_path(name: &str) -> PathBuf {
    FsPath::new(env!("CARGO_MANIFEST_DIR"))
        .join("snapshots")
        .join(format!("{name}.snap"))
}

/// Compares against the checked-in snapshot, following konoma's existing convention:
/// `KONOMA_UPDATE_SNAPSHOTS=1` rewrites the file, and a missing file skips (a build from the
/// published crate has no `snapshots/`, which is excluded).
pub(super) fn assert_snapshot(name: &str, actual: &str) {
    let path = snapshot_path(name);
    if std::env::var_os("KONOMA_UPDATE_SNAPSHOTS").is_some() {
        std::fs::create_dir_all(path.parent().expect("snapshot dir")).expect("create snapshots/");
        std::fs::write(&path, actual).expect("write snapshot");
        eprintln!("mermaid snapshot: wrote {}", path.display());
        return;
    }
    let Ok(expected) = std::fs::read_to_string(&path) else {
        eprintln!(
            "mermaid snapshot: {} not found — skipping (published-crate build?); \
             regenerate with `KONOMA_UPDATE_SNAPSHOTS=1 cargo test`",
            path.display()
        );
        return;
    };
    if expected == actual {
        return;
    }
    let (el, al): (Vec<&str>, Vec<&str>) = (expected.lines().collect(), actual.lines().collect());
    let mut i = 0;
    while i < el.len().min(al.len()) && el[i] == al[i] {
        i += 1;
    }
    let lo = i.saturating_sub(2);
    panic!(
        "mermaid snapshot {name} drifted at line {i}\n--- expected ---\n{}\n--- actual ---\n{}\n\
         Re-run with KONOMA_UPDATE_SNAPSHOTS=1 and inspect the diff if this is intentional.",
        el[lo..(i + 3).min(el.len())].join("\n"),
        al[lo..(i + 3).min(al.len())].join("\n"),
    );
}

// ---------------------------------------------------------------------------------------------
// 1. The main instrument: what konoma measured vs what resvg drew
// ---------------------------------------------------------------------------------------------

/// **The instrument §6 asks for.** A one-node diagram is emitted, put through usvg with konoma's
/// own font database, and the box konoma sized is compared against the width resvg laid the text
/// out at. The relation is exact and declared: a rectangle is the label plus `padding * 4`
/// (`squareRect.ts` doubles `padding` for `labelPaddingX`, `drawRect.ts` doubles it again).
///
/// This is konoma against **resvg's real shaper**, not against another copy of konoma, so it
/// cannot silently become a self-comparison — the failure mode that made the markdown diff
/// harness report "468/468 identical" while every paragraph was broken.
#[test]
fn box_width_matches_resvg() {
    if !text_metrics::fonts_available() {
        eprintln!("no sans-serif face — skipping (the renderer refuses to draw here too)");
        return;
    }
    let expected_padding = shapes::PADDING * 4.0;
    for (name, label) in LABELS {
        let src = format!("flowchart TD\n  A[\"{label}\"]");
        let diagram = laid_out(&src);
        let svg = render(&src, "dark").expect("renders");
        let node = &diagram.nodes[0];

        let mut widths = Vec::new();
        text_widths(tree_of(&svg).root(), &mut widths);
        assert_eq!(
            widths.len(),
            1,
            "{name}: exactly one <text> should survive usvg (a dropped one means the font \
             resolution konoma measured with is not the one resvg drew with)"
        );
        let drawn = widths[0] as f64;
        let slack = node.size.w - drawn;
        assert!(
            (slack - expected_padding).abs() <= 1.0,
            "{name} {label:?}: box is {} wide, resvg drew the text {} wide → {} of padding, \
             but the shape declares {}",
            num(node.size.w),
            num(drawn),
            num(slack),
            num(expected_padding)
        );

        // …and the box konoma sized is the box it emitted.
        let mut boxes = Vec::new();
        path_boxes(tree_of(&svg).root(), &mut boxes);
        assert!(
            boxes
                .iter()
                .any(|b| (b.width() as f64 - node.size.w).abs() < 0.01 && b.x() > 0.0),
            "{name}: no drawn path has the width the model declares ({})",
            num(node.size.w)
        );
    }
}

/// The same comparison for an edge label, which is measured by the same code but sized by a
/// different rule (a small pad, not a shape's padding).
#[test]
fn edge_label_box_matches_resvg() {
    if !text_metrics::fonts_available() {
        return;
    }
    let src = "flowchart TD\n  A[a] -->|全画面プレビュー| B[b]";
    let diagram = laid_out(src);
    let svg = render(src, "dark").expect("renders");
    let label = diagram.edges[0]
        .label
        .as_ref()
        .expect("edge carries a label");

    let mut widths = Vec::new();
    text_widths(tree_of(&svg).root(), &mut widths);
    // Two node labels and the edge label; the edge label is the widest here.
    let drawn = widths.iter().copied().fold(0.0_f32, f32::max) as f64;
    let slack = label.size.w - drawn;
    assert!(
        (slack - super::LABEL_PAD_X * 2.0).abs() <= 1.0,
        "edge label box {} vs resvg's {} → {} of padding, declared {}",
        num(label.size.w),
        num(drawn),
        num(slack),
        num(super::LABEL_PAD_X * 2.0)
    );
}

/// A multi-line label is as tall as its line count says, and as wide as its widest line — which
/// is what makes `<br>` change a box's shape rather than just its text.
#[test]
fn multiline_label_is_measured_per_line() {
    if !text_metrics::fonts_available() {
        return;
    }
    let one = Label::measure("short");
    let three = Label::measure("short\nconsiderably longer line\nmid");
    assert_eq!(three.lines.len(), 3);
    assert!((three.height - one.height * 3.0).abs() < 1e-9);
    assert!(three.width > one.width);
    assert!((three.width - Label::measure("considerably longer line").width).abs() < 1e-9);
}

// ---------------------------------------------------------------------------------------------
// 2. Geometric invariants (§6's supporting list)
// ---------------------------------------------------------------------------------------------

/// (1) No two node boxes overlap.
pub(super) fn check_nodes_do_not_overlap(name: &str, d: &Diagram) {
    for i in 0..d.nodes.len() {
        for j in (i + 1)..d.nodes.len() {
            let (dx, dy) = box_overlap(&d.nodes[i], &d.nodes[j]);
            assert!(
                dx <= 0.01 || dy <= 0.01,
                "{name}: {} and {} overlap by {}x{}",
                d.nodes[i].id,
                d.nodes[j].id,
                num(dx),
                num(dy)
            );
        }
    }
}

#[test]
fn invariant_nodes_do_not_overlap() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_nodes_do_not_overlap(name, &laid_out(src));
    }
}

/// (2) No edge passes through the inside of a shape.
///
/// Checked against each node's **outline**, not its bounding box: a diamond's box is far bigger
/// than the diamond, and an edge leaving one legitimately crosses the box's corner. Sampling the
/// polyline every half pixel and asking how deep inside each sample lies makes the check
/// independent of `shapes::intersect`, which is the function under test.
///
/// **An edge that names a block is exempt**, for the reason spelled out on
/// [`check_edges_keep_out_of_foreign_frames`] and recorded by
/// [`an_edge_that_names_a_block_is_not_kept_clear_of_its_surroundings`]: dagre was handed a
/// stand-in leaf instead of the endpoint the author wrote, and the line is only cut back to the
/// frame afterwards, so nothing constrained the route to clear the boxes beside it.
///
/// **A note's connector is exempt** for a different reason, recorded by
/// [`super::state_tests::a_notes_connector_can_cross_a_state_in_a_crowded_diagram`]: a note is
/// placed on the side the author named rather than where a clear line to it exists, and on a
/// crowded diagram those are not the same place. It is a straight line between two boxes, not a
/// route, so there is nothing here for the layout to have got wrong.
pub(super) fn check_edges_stay_out_of_shapes(name: &str, d: &Diagram) {
    let outlines: Vec<Vec<Point>> = d.nodes.iter().map(boundary).collect();
    for e in &d.edges {
        // See the doc comment. A frame in this diagram bearing the endpoint's name is exactly
        // "this edge was routed between stand-ins"; an end drawn as a note is exactly "this line
        // was not routed at all".
        if d.cluster(&e.from).is_some() || d.cluster(&e.to).is_some() {
            continue;
        }
        let is_note = |id: &str| d.node(id).is_some_and(|n| n.shape == Glyph::Note);
        if is_note(&e.from) || is_note(&e.to) {
            continue;
        }
        let line = e.drawn_points();
        for w in line.windows(2) {
            let len = (w[1].x - w[0].x).hypot(w[1].y - w[0].y);
            let steps = ((len * 2.0).ceil() as usize).clamp(1, 4000);
            for s in 0..=steps {
                let t = s as f64 / steps as f64;
                let p = Point::new(
                    w[0].x + t * (w[1].x - w[0].x),
                    w[0].y + t * (w[1].y - w[0].y),
                );
                for (node, poly) in d.nodes.iter().zip(&outlines) {
                    let inside_by = depth(&p, poly);
                    assert!(
                        inside_by <= 1.0,
                        "{name}: edge {}->{} runs {}px inside {} at ({}, {})",
                        e.from,
                        e.to,
                        num(inside_by),
                        node.id,
                        num(p.x),
                        num(p.y)
                    );
                }
            }
        }
    }
}

#[test]
fn invariant_edges_stay_out_of_shapes() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_edges_stay_out_of_shapes(name, &laid_out(src));
    }
}

/// (3) An edge label sits **on its own line** and on no node.
///
/// The first half is what distinguishes re-placing the label at the arc midpoint from leaving it
/// where dagre put it: dagre's position is offset from the line by `labeloffset` because its
/// default `labelpos` is `r`.
pub(super) fn check_labels_ride_their_edge(name: &str, d: &Diagram) {
    for e in &d.edges {
        let Some(label) = &e.label else { continue };
        let off = dist_to_polyline(&label.center, &e.points);
        assert!(
            off <= 0.5,
            "{name}: label {:?} on {}->{} sits {}px off its own line",
            label.label.lines.join(" "),
            e.from,
            e.to,
            num(off)
        );
        for n in &d.nodes {
            let (nl, nt, nr, nb) = n.bounds();
            let (ll, lt, lr, lb) = (
                label.center.x - label.size.w / 2.0,
                label.center.y - label.size.h / 2.0,
                label.center.x + label.size.w / 2.0,
                label.center.y + label.size.h / 2.0,
            );
            let (dx, dy) = (nr.min(lr) - nl.max(ll), nb.min(lb) - nt.max(lt));
            assert!(
                dx <= 0.01 || dy <= 0.01,
                "{name}: label {:?} overlaps node {} by {}x{}",
                label.label.lines.join(" "),
                n.id,
                num(dx),
                num(dy)
            );
        }
    }
}

#[test]
fn invariant_labels_ride_their_edge_and_clear_every_node() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_labels_ride_their_edge(name, &laid_out(src));
    }
}

/// (4) Every edge starts and ends **on** the outline of the shape it touches.
///
/// This is the property that makes a branch come out of a diamond's slanted side. Comparing
/// against a densely sampled outline rather than against `shapes::intersect` keeps the check
/// honest: replacing the shape intersection with a bounding-box one has to fail here.
///
/// An end that names a *block* has no outline; it lands on a frame, which
/// [`invariant_an_edge_that_names_a_block_stops_on_its_frame`] checks instead.
pub(super) fn check_endpoints_land_on_the_outline(name: &str, d: &Diagram) {
    for e in &d.edges {
        let placed = |id: &str| match d.node(id) {
            Some(n) => Some(n),
            None if d.cluster(id).is_some() => None,
            None => panic!(
                "{name}: edge {}->{} names a node that is not placed",
                e.from, e.to
            ),
        };
        let (tail, head) = (placed(&e.from), placed(&e.to));
        let first = e.points.first().expect("edge has points");
        let last = e.points.last().expect("edge has points");
        for (label, p, node) in [("start", first, tail), ("end", last, head)]
            .into_iter()
            .filter_map(|(l, p, n)| n.map(|n| (l, p, n)))
        {
            let off = dist_to_boundary(p, &boundary(node));
            assert!(
                off <= 0.05,
                "{name}: {label} of {}->{} is {}px off {}'s outline",
                e.from,
                e.to,
                num(off),
                node.id
            );
        }
    }
}

#[test]
fn invariant_endpoints_land_on_the_outline() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_endpoints_land_on_the_outline(name, &laid_out(src));
    }
}

/// (5) The viewBox contains every node, every waypoint and every label.
pub(super) fn check_view_box_contains_everything(name: &str, d: &Diagram) {
    let check = |x: f64, y: f64, what: &str| {
        assert!(
            x >= -0.01 && y >= -0.01 && x <= d.width + 0.01 && y <= d.height + 0.01,
            "{name}: {what} at ({}, {}) is outside the {}x{} viewBox",
            num(x),
            num(y),
            num(d.width),
            num(d.height)
        );
    };
    for n in &d.nodes {
        let (l, t, r, b) = n.bounds();
        check(l, t, &n.id);
        check(r, b, &n.id);
    }
    for e in &d.edges {
        for p in e.drawn_points() {
            check(p.x, p.y, "waypoint");
        }
        if let Some(l) = &e.label {
            check(
                l.center.x - l.size.w / 2.0,
                l.center.y - l.size.h / 2.0,
                "label",
            );
            check(
                l.center.x + l.size.w / 2.0,
                l.center.y + l.size.h / 2.0,
                "label",
            );
        }
    }
    // …and the margin is really there.
    let left = d
        .nodes
        .iter()
        .map(|n| n.bounds().0)
        .fold(f64::INFINITY, f64::min);
    assert!(
        left >= MARGIN - 0.01,
        "{name}: drawing starts left of the margin"
    );
}

#[test]
fn invariant_view_box_contains_everything() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_view_box_contains_everything(name, &laid_out(src));
    }
}

// ---------------------------------------------------------------------------------------------
// 4b. Cluster invariants (§6, stage 1d)
// ---------------------------------------------------------------------------------------------

/// (6) A frame holds every one of its members.
///
/// This is the whole promise of a subgraph: the reader is being told that these nodes belong
/// together. A frame that clips a member says something false about the diagram.
pub(super) fn check_clusters_hold_their_members(name: &str, d: &Diagram, tree: &clusters::Tree) {
    for c in &d.clusters {
        let frame = c.bounds();
        for n in &d.nodes {
            if !tree.touches(&n.id, &c.id) {
                continue;
            }
            let out = escapes(n.bounds(), frame);
            assert!(
                out <= 0.01,
                "{name}: node {} pokes {out:.2}px out of frame {}",
                n.id,
                c.id
            );
        }
    }
}

/// (6b) A frame holds none of what is *not* its member — the converse of (6), above.
///
/// §10-5 part-3 item 1's own invariant ("ノードは所属クラスターの枠内・非所属ノードは枠外"): a
/// node with no membership in a cluster (`clusters::Tree::touches` false) must not overlap that
/// cluster's own frame at all. Nothing before this checked the converse of (6) — every existing
/// cluster check only ever asked "does a member ever escape its own frame", never "does a
/// *stranger* ever land inside one" — which is exactly the gap `zz-design-4a`'s end marker fell
/// through under `konoma-orthogonal`'s own tighter node spacing
/// (`orthogonal::clear_foreign_cluster_overlaps`'s own doc has the dagre/nodesep reasoning).
pub(super) fn check_foreign_nodes_stay_out_of_clusters(
    name: &str,
    d: &Diagram,
    tree: &clusters::Tree,
) {
    for c in &d.clusters {
        let frame = c.bounds();
        for n in &d.nodes {
            if tree.touches(&n.id, &c.id) {
                continue;
            }
            let (dx, dy) = rect_overlap(n.bounds(), frame);
            assert!(
                dx <= 0.01 || dy <= 0.01,
                "{name}: node {} (not a member) overlaps frame {} by {dx:.2}x{dy:.2}px",
                n.id,
                c.id
            );
        }
    }
}

/// (6c) §10-5 round 4: under `konoma-orthogonal` a frame is not merely *big enough* for its
/// members — it is **derived** from them. Every side sits exactly [`clusters::PAD`] beyond the
/// members' own bounding box, plus the title's band at the top, and the box is only ever widened
/// symmetrically for a title too wide for it (`super::rebuild_frames`).
///
/// (6) alone cannot state this: dagre's own border-node rectangle held its members too, and it was
/// still stale — lopsided around them by however far the post-dagre passes had moved one. What the
/// exact derivation buys is the frame's own *centre*, which is what
/// [`super::orthogonal::classify`] measures a cluster-anchored edge's alignment against and what
/// [`super::orthogonal::evict`] hands out ports around; a frame merely "big enough" makes a
/// dead-straight lane through a block impossible to draw.
pub(super) fn check_frames_are_derived_from_members(
    name: &str,
    d: &Diagram,
    tree: &clusters::Tree,
) {
    for c in &d.clusters {
        let mut bbox: Option<(f64, f64, f64, f64)> = None;
        let mut hold = |(l, t, r, b): (f64, f64, f64, f64)| {
            bbox = Some(match bbox {
                Some((cl, ct, cr, cb)) => (cl.min(l), ct.min(t), cr.max(r), cb.max(b)),
                None => (l, t, r, b),
            });
        };
        for child in d
            .clusters
            .iter()
            .filter(|k| k.parent.as_deref() == Some(&c.id))
        {
            hold(child.bounds());
        }
        if let Some(block) = tree.get(&c.id) {
            for m in &block.member_nodes {
                if let Some(n) = d.nodes.iter().find(|n| &n.id == m) {
                    hold(n.bounds());
                }
            }
        }
        let Some((l, t, r, b)) = bbox else { continue };
        let pad = clusters::PAD;
        let band = if c.title.is_blank() {
            0.0
        } else {
            c.title.height + clusters::TITLE_PAD_Y * 2.0
        };
        let (fl, ft, fr, fb) = c.bounds();
        // A title wider than its contents pushes both sides out by the same amount, so the *width*
        // may exceed the derived one — but never asymmetrically, and never at top or bottom.
        let widened = ((fr - fl) - (r - l + 2.0 * pad)).max(0.0) / 2.0;
        for (label, got, want) in [
            ("left", fl, l - pad - widened),
            ("right", fr, r + pad + widened),
            ("top", ft, t - pad - band),
            ("bottom", fb, b + pad),
        ] {
            assert!(
                (got - want).abs() <= 0.01,
                "{name}: frame {} {label} edge is {got:.2}, derived from its members it should be \
                 {want:.2}",
                c.id
            );
        }
    }
}

#[test]
fn invariant_clusters_hold_their_members() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_clusters_hold_their_members(name, &laid_out(src), &tree_of_src(src));
    }
}

/// (6c) over every orthogonal fixture there is, including the design references — the invariant
/// `super::rebuild_frames` exists to satisfy, stated against the real render rather than against
/// the function's own arithmetic.
#[test]
fn invariant_orthogonal_frames_are_derived_from_their_members() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain(orthogonal_design_reference_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        check_frames_are_derived_from_members(name, &d, &tree_of_src(src));
    }
}

/// (7) A nested frame is inside the frame that contains it.
pub(super) fn check_nested_clusters_sit_inside_their_parent(name: &str, d: &Diagram) {
    for c in &d.clusters {
        let Some(parent) = c.parent.as_deref().and_then(|p| d.cluster(p)) else {
            continue;
        };
        let out = escapes(c.bounds(), parent.bounds());
        assert!(
            out <= 0.01,
            "{name}: frame {} pokes {out:.2}px out of its parent {}",
            c.id,
            parent.id
        );
    }
}

#[test]
fn invariant_nested_clusters_sit_inside_their_parent() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_nested_clusters_sit_inside_their_parent(name, &laid_out(src));
    }
}

/// (8) Two frames that are not one inside the other do not overlap.
///
/// Stated over every pair rather than over siblings only: `left` and `right` in `subgraph-
/// siblings` share a parent, but `inner` and an unrelated top-level block do not, and the two
/// boxes overlapping would be just as wrong.
pub(super) fn check_unrelated_clusters_do_not_overlap(name: &str, d: &Diagram) {
    let nested = |d: &Diagram, a: &PlacedCluster, b: &PlacedCluster| {
        let mut cur = a.parent.clone();
        while let Some(p) = cur {
            if p == b.id {
                return true;
            }
            cur = d.cluster(&p).and_then(|c| c.parent.clone());
        }
        false
    };
    for (i, a) in d.clusters.iter().enumerate() {
        for b in d.clusters.iter().skip(i + 1) {
            if nested(d, a, b) || nested(d, b, a) {
                continue;
            }
            let (dx, dy) = rect_overlap(a.bounds(), b.bounds());
            assert!(
                dx <= 0.01 || dy <= 0.01,
                "{name}: frames {} and {} overlap by {dx:.2}x{dy:.2}px",
                a.id,
                b.id
            );
        }
    }
}

#[test]
fn invariant_unrelated_clusters_do_not_overlap() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_unrelated_clusters_do_not_overlap(name, &laid_out(src));
    }
}

/// (9) A line does not run through a frame it has no business being in.
///
/// The distinction the test turns on is [`clusters::Tree::touches`]: an edge with one end inside
/// a block *must* cross that block's border, and clipping it there would cut the line off from
/// its own node. An edge with neither end under the block has no reason to be inside it at all —
/// dagre's compound layout keeps it out (that is what `parentDummyChains` is for), and this is
/// what proves the clusters really were handed to dagre rather than drawn on afterwards.
///
/// **An edge that *names* a block is exempt, and the exemption is a known gap, not a rule.**
/// dagre cannot route to a compound parent, so such an edge is laid out against a stand-in leaf
/// inside the block ([`clusters::Tree::anchor`]) and cut back to the frame only when it is drawn.
/// dagre therefore never saw the endpoints the reader wrote, and nothing constrains the route it
/// chose between the two stand-ins to stay out of a *third* block that happens to sit between
/// them. [`an_edge_that_names_a_block_is_not_kept_clear_of_its_surroundings`] records both halves of
/// the reason it is `#[ignore]`d: it is a property of the vendored layout that predates state
/// diagrams, not something stage 2 introduced, and papering over it here would turn a bug into a
/// specification.
pub(super) fn check_edges_keep_out_of_foreign_frames(
    name: &str,
    d: &Diagram,
    tree: &clusters::Tree,
) {
    for e in &d.edges {
        // See the doc comment: an edge whose own endpoint is a block was routed between two
        // stand-ins, so the layout was never asked the question this invariant poses.
        if tree.contains(&e.from) || tree.contains(&e.to) {
            continue;
        }
        for c in &d.clusters {
            if tree.touches(&e.from, &c.id) || tree.touches(&e.to, &c.id) {
                continue;
            }
            let depth = polyline_depth_in_rect(&e.drawn_points(), c.bounds());
            assert!(
                depth <= 0.5,
                "{name}: edge {} -> {} runs {depth:.2}px into frame {}",
                e.from,
                e.to,
                c.id
            );
        }
    }
}

#[test]
fn invariant_edges_keep_out_of_frames_they_do_not_belong_to() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_edges_keep_out_of_foreign_frames(name, &laid_out(src), &tree_of_src(src));
    }
}

/// (10) An edge that names a block starts or ends **on that block's frame**, and never inside it.
///
/// `one --> two` is legal mermaid (§2-2) and dagre cannot route it — a compound parent has no
/// rank. The line is laid out against a member and then cut back to the boundary, which is the
/// only thing that makes the arrow point at the box rather than at some node the author never
/// mentioned.
pub(super) fn check_edge_that_names_a_block_stops_on_its_frame(
    name: &str,
    d: &Diagram,
    tree: &clusters::Tree,
) {
    for e in &d.edges {
        for (end, id) in [("tail", &e.from), ("head", &e.to)] {
            if !tree.contains(id) {
                continue;
            }
            let c = d
                .cluster(id)
                .unwrap_or_else(|| panic!("{name}: edge names block {id} but no frame was placed"));
            let frame = c.bounds();
            let point = if end == "tail" {
                e.points.first()
            } else {
                e.points.last()
            }
            .expect("an edge has points");
            let on_edge = (point.x - frame.0)
                .abs()
                .min((point.x - frame.2).abs())
                .min((point.y - frame.1).abs())
                .min((point.y - frame.3).abs());
            assert!(
                on_edge <= 0.01,
                "{name}: the {end} of {} -> {} is {on_edge:.2}px off frame {id}",
                e.from,
                e.to
            );
            let depth = polyline_depth_in_rect(&e.drawn_points(), frame);
            assert!(
                depth <= 0.5,
                "{name}: {} -> {} is drawn {depth:.2}px inside frame {id}",
                e.from,
                e.to
            );
        }
    }
}

#[test]
fn invariant_an_edge_that_names_a_block_stops_on_its_frame() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_edge_that_names_a_block_stops_on_its_frame(name, &laid_out(src), &tree_of_src(src));
    }
}

/// (11) A title is inside its own frame and on top of nothing.
///
/// Both halves matter and they pull in opposite directions: pushing the title further in to clear
/// the members eventually pushes it onto them from the other side, and the only reason there is
/// room at all is that dagre leaves a band above the topmost rank. A frame that had to grow to
/// make that band big enough is exactly the case this catches.
pub(super) fn check_cluster_titles(name: &str, d: &Diagram, tree: &clusters::Tree) {
    for c in &d.clusters {
        if c.title.is_blank() {
            continue;
        }
        let t = c.title_center();
        let title = (
            t.x - c.title.width / 2.0,
            t.y - c.title.height / 2.0,
            t.x + c.title.width / 2.0,
            t.y + c.title.height / 2.0,
        );
        let out = escapes(title, c.bounds());
        assert!(
            out <= 0.01,
            "{name}: the title of {} pokes {out:.2}px out of its own frame",
            c.id
        );
        for n in &d.nodes {
            if !tree.touches(&n.id, &c.id) {
                continue;
            }
            let (dx, dy) = rect_overlap(title, n.bounds());
            assert!(
                dx <= 0.01 || dy <= 0.01,
                "{name}: the title of {} sits on node {} ({dx:.2}x{dy:.2}px)",
                c.id,
                n.id
            );
        }
        for other in &d.clusters {
            if other.parent.as_deref() != Some(c.id.as_str()) {
                continue;
            }
            let (dx, dy) = rect_overlap(title, other.bounds());
            assert!(
                dx <= 0.01 || dy <= 0.01,
                "{name}: the title of {} sits on the nested frame {} ({dx:.2}x{dy:.2}px)",
                c.id,
                other.id
            );
        }
    }
}

/// (12) Every row of a compartmented box is **inside the box**, and every rule that separates the
/// rows lies on the box.
///
/// The one thing a [`Panel`](super::panel::Panel) can get wrong that nothing else notices: it is
/// the only geometry in the renderer that is stated in coordinates *relative to a node*, so a
/// sizing mistake shows up as text hanging out of a class box rather than as an overlap the other
/// invariants would catch. Both halves are needed — a panel sized too small clips its own rows,
/// and a rule computed from the wrong height draws across the diagram.
pub(super) fn check_panels_stay_inside_their_box(name: &str, d: &Diagram) {
    for n in &d.nodes {
        let Some(panel) = &n.panel else { continue };
        assert!(
            (panel.size.w - n.size.w).abs() < 0.01 && (panel.size.h - n.size.h).abs() < 0.01,
            "{name}: {} is {}x{} but its panel is {}x{}",
            n.id,
            num(n.size.w),
            num(n.size.h),
            num(panel.size.w),
            num(panel.size.h)
        );
        for (l, t, r, b) in panel.cell_bounds() {
            assert!(
                l >= -0.01 && t >= -0.01 && r <= n.size.w + 0.01 && b <= n.size.h + 0.01,
                "{name}: a row of {} runs from ({}, {}) to ({}, {}), outside its {}x{} box",
                n.id,
                num(l),
                num(t),
                num(r),
                num(b),
                num(n.size.w),
                num(n.size.h)
            );
        }
        for y in &panel.rules {
            assert!(
                *y >= -0.01 && *y <= n.size.h + 0.01,
                "{name}: a rule of {} is at y={} in a box {} tall",
                n.id,
                num(*y),
                num(n.size.h)
            );
        }
        for x in &panel.columns {
            assert!(
                *x >= -0.01 && *x <= n.size.w + 0.01,
                "{name}: a column rule of {} is at x={} in a box {} wide",
                n.id,
                num(*x),
                num(n.size.w)
            );
        }
    }
}

#[test]
fn invariant_cluster_titles_stay_in_the_frame_and_off_the_members() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        check_cluster_titles(name, &laid_out(src), &tree_of_src(src));
    }
}

/// **A known gap, recorded rather than papered over.** An edge that *names a block* is laid out
/// between stand-in leaves, so nothing keeps its route clear of what happens to lie beside it: it
/// can cross a third block, and it can graze a node.
///
/// dagre cannot route to a compound parent — the ranking phase only ever sees leaves — so
/// [`clusters::Tree::anchor`] hands it a descendant instead, and `edges::route` cuts the result
/// back to the frame only when it is drawn. Between those two steps the endpoint the author wrote
/// does not exist as far as the layout is concerned. mermaid solves it the same way and has the
/// same gap.
///
/// Measured on **flowcharts** on purpose. Both halves reproduce identically in state diagrams
/// (`composite-siblings` and `direction-lr` in [`super::state_tests::CASES`]), so this is a
/// property of stage 1's re-anchoring rather than something stage 2 brought in — which is the
/// difference between a limitation to record and a regression to fix. Closing it means
/// constraining the route, which is a change to how a cluster endpoint reaches dagre, not a
/// tolerance to widen. `#[ignore]`d with the reason rather than deleted, following the convention
/// konoma used for the nested `<details>` ordinal bug: the test says what *should* be true, and
/// it fails for as long as it is not.
#[test]
#[ignore = "known gap: an edge naming a block is routed between stand-in leaves, so neither a third block between them nor a node beside them is avoided. Reproduces in mermaid too; needs a change to how a cluster endpoint reaches dagre."]
fn an_edge_that_names_a_block_is_not_kept_clear_of_its_surroundings() {
    if !text_metrics::fonts_available() {
        return;
    }
    // (a) the route crosses a third block that sits between the two it joins.
    let src = "flowchart TD\n  Z --> one\n  one --> two\n  one --> three\n  subgraph one [First]\n    a --> b\n  end\n  subgraph two [Second]\n    c --> d\n  end\n  subgraph three [Third]\n    e --> f\n  end";
    let d = laid_out(src);
    let tree = tree_of_src(src);
    for e in &d.edges {
        for c in &d.clusters {
            if tree.touches(&e.from, &c.id) || tree.touches(&e.to, &c.id) {
                continue;
            }
            let depth = polyline_depth_in_rect(&e.drawn_points(), c.bounds());
            assert!(
                depth <= 0.5,
                "edge {} -> {} runs {depth:.2}px into frame {}",
                e.from,
                e.to,
                c.id
            );
        }
    }

    // (b) the route grazes a node standing beside the frame it leaves.
    let src = "flowchart LR\n  Z --> A\n  A --> B\n  B --> C\n  B --> D\n  subgraph B [B]\n    a --> b\n  end";
    let d = laid_out(src);
    let outlines: Vec<Vec<Point>> = d.nodes.iter().map(boundary).collect();
    for e in &d.edges {
        for p in e.drawn_points() {
            for (node, poly) in d.nodes.iter().zip(&outlines) {
                let inside_by = depth(&p, poly);
                assert!(
                    inside_by <= 1.0,
                    "edge {} -> {} runs {}px inside {}",
                    e.from,
                    e.to,
                    num(inside_by),
                    node.id
                );
            }
        }
    }
}

/// Every block the author wrote gets a frame, and every frame is a block the author wrote.
///
/// The second half is the one that matters: a frame around a group nobody declared is a lie about
/// the diagram, and it is what a bug in the tree-building would produce.
#[test]
fn every_block_that_holds_a_node_gets_exactly_one_frame() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        let d = laid_out(src);
        let tree = tree_of_src(src);
        let drawn: HashSet<&str> = d.clusters.iter().map(|c| c.id.as_str()).collect();
        assert_eq!(
            drawn.len(),
            d.clusters.len(),
            "{name}: a frame is drawn twice"
        );
        let declared: HashSet<&str> = tree.iter().map(|c| c.id.as_str()).collect();
        assert_eq!(drawn, declared, "{name}: frames and blocks disagree");
    }
}

/// Everything the author wrote is on the page: one shape per node, and one line per edge — an
/// edge that names a block included, now that a block is something a line can end on. A dropped
/// node is how a renderer quietly lies about a diagram.
#[test]
fn every_node_and_drawable_edge_survives() {
    for (name, src) in CORPUS {
        let chart = parse(src).expect("parses");
        let tree = tree_of_src(src);
        let d = laid_out(src);
        assert_eq!(d.nodes.len(), chart.nodes.len(), "{name}: node count");
        let drawable = chart
            .edges
            .iter()
            .filter(|e| {
                let end = |id: &str| chart.node(id).is_some() || tree.contains(id);
                end(&e.from) && end(&e.to)
            })
            .count();
        assert_eq!(d.edges.len(), drawable, "{name}: edge count");
    }
}

// ---------------------------------------------------------------------------------------------
// 3. The shape formulas, stated as arithmetic
// ---------------------------------------------------------------------------------------------

/// A label size with no font behind it, so these tests say the same thing on every machine.
const L: Size = Size { w: 100.0, h: 20.0 };

/// mermaid's `question.ts`: `w = label + padding`, `h = label + padding`, and the drawn square's
/// side is **`w + h`**, not `w`.
///
/// This is the formula that matters most to a reader: sizing a decision box like a rectangle puts
/// its branch labels on top of it. A mutation to `s = w` has to fail here.
#[test]
fn diamond_side_is_the_sum_of_both_padded_axes() {
    let s = flow_size(Shape::Diamond, L);
    let expected = (L.w + shapes::PADDING) + (L.h + shapes::PADDING);
    assert_eq!(s.w, expected);
    assert_eq!(s.h, expected);
    // …and it really is a square standing on its corner.
    let p = shapes::polygon(Glyph::Flow(Shape::Diamond), s);
    assert_eq!(p.len(), 4);
    assert_eq!((p[0].x, p[0].y), (0.0, -expected / 2.0));
    assert_eq!((p[1].x, p[1].y), (expected / 2.0, 0.0));
}

/// `squareRect.ts` -> `drawRect.ts`: `labelPaddingX` is `padding * 2` and `drawRect` doubles it,
/// while `labelPaddingY` is `padding * 1` and is doubled too — so a rectangle is four paddings
/// wider and two paddings taller than its label.
#[test]
fn rect_padding_is_four_by_two() {
    let s = flow_size(Shape::Rect, L);
    assert_eq!(s.w, L.w + shapes::PADDING * 4.0);
    assert_eq!(s.h, L.h + shapes::PADDING * 2.0);
}

/// `stadium.ts`: the height gets **one** padding, not two, and the width carries a quarter of the
/// height for the two caps.
#[test]
fn stadium_height_takes_a_single_padding() {
    let s = flow_size(Shape::Stadium, L);
    let h = L.h + shapes::PADDING;
    assert_eq!(s.h, h);
    assert_eq!(s.w, L.w + h / 4.0 + shapes::PADDING);
    // The outline is a rectangle whose corner radius closes the ends into semicircles.
    assert_eq!(
        shapes::outline(Glyph::Flow(Shape::Stadium), s, None),
        shapes::Outline::Rect {
            w: s.w,
            h: s.h,
            r: s.h / 2.0
        }
    );
}

/// `circle.ts` sizes the ring from the label's **width alone**, so a circle is always round.
#[test]
fn circle_radius_follows_the_label_width() {
    let s = flow_size(Shape::Circle, L);
    assert_eq!(s.w, s.h);
    assert_eq!(s.w, L.w + shapes::PADDING * 2.0);
}

/// `hexagon.ts`: the slanted ends are `h/4` wide each, so the box is half a height wider than the
/// padded label.
#[test]
fn hexagon_ends_are_a_quarter_of_its_height() {
    let s = flow_size(Shape::Hexagon, L);
    let h = L.h + shapes::PADDING;
    assert_eq!(s.h, h);
    assert_eq!(s.w, L.w + h / 2.0 + shapes::PADDING);
    let p = shapes::polygon(Glyph::Flow(Shape::Hexagon), s);
    assert_eq!(p.len(), 6);
    assert_eq!(p[0].x, -s.w / 2.0 + h / 4.0);
}

/// `trapezoid.ts` takes one padding per axis while `invertedTrapezoid.ts` doubles both. The
/// asymmetry is upstream's; recording it here stops it being "tidied up" into a bug.
#[test]
fn trapezoid_and_inverted_trapezoid_pad_differently() {
    let up = flow_size(Shape::Trapezoid, L);
    let down = flow_size(Shape::InvTrapezoid, L);
    assert_eq!(up.h, L.h + shapes::PADDING);
    assert_eq!(down.h, L.h + shapes::PADDING * 2.0);
    assert_eq!(up.w, L.w + shapes::PADDING + up.h);
    assert_eq!(down.w, L.w + shapes::PADDING * 2.0 + down.h);
    // The wide side is the bottom for one and the top for the other.
    let (a, b) = (
        shapes::polygon(Glyph::Flow(Shape::Trapezoid), up),
        shapes::polygon(Glyph::Flow(Shape::InvTrapezoid), down),
    );
    assert!(
        a[0].y > 0.0 && a[0].x == -up.w / 2.0,
        "trapezoid is wide at the bottom"
    );
    assert!(
        b[2].y < 0.0 && b[2].x == down.w / 2.0,
        "inv trapezoid is wide at the top"
    );
}

/// **The label fits inside the shape that was sized for it.**
///
/// Stated over the outline, not the bounding box, because that is where sizing goes wrong: a
/// diamond sized `s = w` instead of `s = w + h` still has a perfectly reasonable bounding box and
/// still puts its text outside the rhombus. Checking the four corners of the label rectangle is
/// what turns "the formula is the one mermaid uses" into "the diagram reads".
///
/// Circles are the documented exception: `circle.ts` derives the radius from the label's **width
/// alone**, so a tall label overflows upstream too. konoma keeps mermaid's formula here (see
/// `shapes::size`) and records the limitation rather than quietly diverging.
#[test]
fn every_shape_holds_the_label_it_was_sized_for() {
    for shape in [
        Shape::Rect,
        Shape::RoundedRect,
        Shape::Stadium,
        Shape::Subroutine,
        Shape::Cylinder,
        Shape::Diamond,
        Shape::Hexagon,
        Shape::Odd,
        Shape::Trapezoid,
        Shape::InvTrapezoid,
        Shape::LeanRight,
        Shape::LeanLeft,
        Shape::Text,
    ] {
        let size = flow_size(shape, L);
        let node = PlacedNode {
            id: format!("{shape:?}"),
            shape: Glyph::Flow(shape),
            center: Point::new(0.0, 0.0),
            size,
            label: Label {
                lines: vec!["x".to_string()],
                width: L.w,
                height: L.h,
                line_pitch: L.h,
                font_size: crate::preview::mermaid::text_metrics::FONT_SIZE as f64,
            },
            panel: None,
            series: None,
            mark: None,
            style: None,
        };
        let outline = boundary(&node);
        for (sx, sy) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
            let corner = Point::new(sx * L.w / 2.0, sy * L.h / 2.0);
            assert!(
                inside(&corner, &outline),
                "{shape:?}: a {}x{} label reaches ({}, {}), which is outside the {}x{} outline",
                num(L.w),
                num(L.h),
                num(corner.x),
                num(corner.y),
                num(size.w),
                num(size.h)
            );
        }
    }
    // What mermaid does guarantee for a circle: the label's width fits across it.
    for shape in [Shape::Circle, Shape::DoubleCircle] {
        let size = flow_size(shape, L);
        assert!(size.w >= L.w, "{shape:?}: the label is wider than the ring");
    }
}

/// A diamond's edges leave from its slanted sides, which is the whole point of intersecting the
/// outline instead of the bounding box. A point due east of the centre leaves at the right
/// corner; a point to the north-east leaves part-way along the upper-right side, strictly inside
/// the bounding box's corner.
#[test]
fn diamond_intersection_uses_the_slanted_sides() {
    let s = Size::new(100.0, 100.0);
    let c = Point::new(0.0, 0.0);
    let east = shapes::intersect(
        Glyph::Flow(Shape::Diamond),
        c.clone(),
        s,
        &Point::new(500.0, 0.0),
    );
    assert!((east.x - 50.0).abs() < 1e-9 && east.y.abs() < 1e-9);

    let ne = shapes::intersect(
        Glyph::Flow(Shape::Diamond),
        c,
        s,
        &Point::new(500.0, -500.0),
    );
    // On the side |x| + |y| = 50, and well inside the box corner (50, -50).
    assert!(
        (ne.x.abs() + ne.y.abs() - 50.0).abs() < 1e-9,
        "on the slanted side"
    );
    assert!(
        ne.x < 49.0 && ne.y > -49.0,
        "not at the bounding box's corner"
    );
}

// ---------------------------------------------------------------------------------------------
// 4. Edge geometry
// ---------------------------------------------------------------------------------------------

/// d3's `curveBasis` — mermaid's default. It touches the first and last point and **no** other:
/// the rest are control points. Pinning the exact `d` for three known points fixes the whole
/// construction, ends included (d3 draws a straight sixth of the first and last segment).
#[test]
fn curve_basis_matches_d3() {
    let pts = [
        Point::new(0.0, 0.0),
        Point::new(60.0, 0.0),
        Point::new(60.0, 60.0),
    ];
    assert_eq!(
        edges::curve_basis_path(&pts),
        "M0,0L10,0C20,0 40,0 50,10C60,20 60,40 60,50L60,60"
    );
    // Two points are just a line; one is just a move.
    assert_eq!(edges::curve_basis_path(&pts[..2]), "M0,0L60,0");
    assert_eq!(edges::curve_basis_path(&pts[..1]), "M0,0");
    // Collinear points (vertical, horizontal) and a duplicated point — this section's own
    // `VERTICAL`/`HORIZONTAL`/`DUPLICATE` module docs have the reason these three shapes are
    // swept over every curve, `basis` included even though it was never the one that broke.
    let vertical = [
        Point::new(100.0, 50.0),
        Point::new(100.0, 120.0),
        Point::new(100.0, 190.0),
    ];
    assert_eq!(
        edges::curve_basis_path(&vertical),
        "M100,50L100,61.667C100,73.333 100,96.667 100,120\
         C100,143.333 100,166.667 100,178.333L100,190"
    );
    let horizontal = [
        Point::new(50.0, 100.0),
        Point::new(120.0, 100.0),
        Point::new(190.0, 100.0),
    ];
    assert_eq!(
        edges::curve_basis_path(&horizontal),
        "M50,100L61.667,100C73.333,100 96.667,100 120,100\
         C143.333,100 166.667,100 178.333,100L190,100"
    );
    let duplicate = [
        Point::new(0.0, 0.0),
        Point::new(40.0, 40.0),
        Point::new(40.0, 40.0),
        Point::new(80.0, 80.0),
    ];
    assert_eq!(
        edges::curve_basis_path(&duplicate),
        "M0,0L6.667,6.667C13.333,13.333 26.667,26.667 33.333,33.333\
         C40,40 40,40 46.667,46.667C53.333,53.333 66.667,66.667 73.333,73.333L80,80"
    );
}

/// `edges.js`'s `fixCorners` rounds a right angle off with a radius of 5, replacing the corner
/// with three points. A bend that is too shallow to matter is left alone.
#[test]
fn fix_corners_rounds_right_angles_only() {
    let square = [
        Point::new(0.0, 0.0),
        Point::new(0.0, 100.0),
        Point::new(100.0, 100.0),
    ];
    let fixed = edges::fix_corners(&square);
    assert_eq!(fixed.len(), 5, "the corner becomes three points");
    assert!(
        fixed[1].y < 100.0 && fixed[3].x > 0.0,
        "the replacement points step back from the corner"
    );
    // A corner whose arms are shorter than the 5px test is not a corner.
    let tiny = [
        Point::new(0.0, 0.0),
        Point::new(0.0, 4.0),
        Point::new(4.0, 4.0),
    ];
    assert_eq!(edges::fix_corners(&tiny).len(), 3);
    // A straight line has nothing to round.
    let straight = [
        Point::new(0.0, 0.0),
        Point::new(0.0, 50.0),
        Point::new(0.0, 100.0),
    ];
    assert_eq!(edges::fix_corners(&straight).len(), 3);
}

/// The label goes at the half-way point **by arc length**, so uneven waypoint spacing does not
/// drag it towards the crowded end. mermaid's `traverseEdge`.
#[test]
fn arc_midpoint_is_measured_by_length_not_by_waypoint() {
    // Three waypoints, but the second sits at 90% of the length: a "middle waypoint" rule would
    // answer (90, 0) where the real midpoint is (50, 0).
    let line = [
        Point::new(0.0, 0.0),
        Point::new(90.0, 0.0),
        Point::new(100.0, 0.0),
    ];
    let mid = edges::arc_midpoint(&line).expect("has a midpoint");
    assert!((mid.x - 50.0).abs() < 1e-9 && mid.y.abs() < 1e-9);
    assert_eq!(edges::arc_midpoint(&[]), None);
}

/// An arrow head is `ARROW_LENGTH` long, points along the last segment, and has its tip exactly
/// on the point it was given — the point clipping put on the shape's outline.
#[test]
fn arrow_head_points_along_the_last_segment() {
    let head = edges::arrow_head(&Point::new(0.0, 0.0), &Point::new(0.0, 100.0));
    assert_eq!((head[0].x, head[0].y), (0.0, 100.0));
    assert!((head[1].y - (100.0 - edges::ARROW_LENGTH)).abs() < 1e-9);
    assert!((head[1].x - head[2].x).abs() - edges::ARROW_HALF_WIDTH * 2.0 < 1e-9);
}

/// Every flowchart arrow spelling puts a mark on **exactly the ends it names**, and nothing on
/// the end it does not.
///
/// Until this test existed the whole arrow family was guarded by the two goldens alone, and a
/// mutation proved what that is worth: turning `Tip::of_arrow(Arrow::Point)` from
/// `(Tip::None, Tip::Arrow)` into `(Tip::Arrow, Tip::Arrow)` — a one-way arrow quietly growing a
/// second head — reddened `emit_golden` and `corpus_golden` and **not one named test**. That is
/// the shape `docs/STATUS.md` records as having cost konoma twice: behaviour a golden alone holds
/// is lost silently the next time the golden is regenerated. The class and ER families already
/// had their own version of this check
/// ([`super::er_tests::a_crows_foot_is_drawn_at_the_end_that_asked_for_it`]); the flowchart family
/// did not.
///
/// Stated twice on purpose. Once about the **model**, which end asked for which mark, and once
/// about the **drawing**, how many of each mark actually reach the page — `svg::emit_edge` decides
/// for itself what a `Tip` looks like, so the two can disagree.
#[test]
fn a_flowchart_arrow_marks_only_the_ends_that_spelled_a_mark() {
    if !text_metrics::fonts_available() {
        return;
    }
    // (what the author wrote, what it parses to, the mark at the tail, the mark at the head).
    let cases: &[(&str, Arrow, Tip, Tip)] = &[
        ("---", Arrow::None, Tip::None, Tip::None),
        ("-->", Arrow::Point, Tip::None, Tip::Arrow),
        ("--x", Arrow::Cross, Tip::None, Tip::Cross),
        ("--o", Arrow::Circle, Tip::None, Tip::Circle),
        ("<-->", Arrow::DoublePoint, Tip::Arrow, Tip::Arrow),
        ("x--x", Arrow::DoubleCross, Tip::Cross, Tip::Cross),
        ("o--o", Arrow::DoubleCircle, Tip::Circle, Tip::Circle),
        // The two halves of an infix link disagreeing (§2-6 rule 6). mermaid calls it `INVALID`
        // and konoma draws the shaft with nothing on either end, rather than guessing.
        ("x-- t -->", Arrow::Invalid, Tip::None, Tip::None),
    ];

    // The table covers the whole enum: a new `Arrow` variant makes `covered` fail to compile, and
    // a variant left out of the table fails here.
    fn covered(a: Arrow) -> bool {
        match a {
            Arrow::None
            | Arrow::Point
            | Arrow::Cross
            | Arrow::Circle
            | Arrow::DoublePoint
            | Arrow::DoubleCross
            | Arrow::DoubleCircle
            | Arrow::Invalid => true,
        }
    }
    let spelled: HashSet<Arrow> = cases.iter().map(|(_, a, _, _)| *a).collect();
    assert_eq!(spelled.len(), cases.len(), "an arrow is spelled twice");
    for a in &spelled {
        assert!(covered(*a));
    }

    // How many marks of each kind the emitted document actually carries. Both nodes are `[]`
    // rectangles, so a `<polygon>` can only be an arrow head and a `<circle>` can only be a `--o`
    // disc; a `--x` is the one `<path>` whose `d` carries a second `M` (a curve never does).
    let drawn = |svg: &str| -> (usize, usize, usize) {
        let heads = svg.matches("<polygon").count();
        let crosses = svg
            .lines()
            .filter(|l| l.starts_with("<path") && l.matches('M').count() > 1)
            .count();
        let discs = svg.matches("<circle").count();
        (heads, crosses, discs)
    };
    let wanted = |tip: Tip| -> (usize, usize, usize) {
        match tip {
            Tip::Arrow => (1, 0, 0),
            Tip::Cross => (0, 1, 0),
            Tip::Circle => (0, 0, 1),
            _ => (0, 0, 0),
        }
    };

    for (spelling, arrow, tip_start, tip_end) in cases {
        let src = format!("flowchart LR\n  A[a] {spelling} B[b]\n");
        let chart = parse(&src).unwrap_or_else(|e| panic!("{spelling}: {e}"));
        assert_eq!(chart.edges.len(), 1, "{spelling}: one edge");
        assert_eq!(chart.edges[0].arrow, *arrow, "{spelling}: parsed arrow");

        let d = laid_out(&src);
        assert_eq!(d.edges.len(), 1, "{spelling}: one edge survives layout");
        let e = &d.edges[0];
        assert_eq!(
            (e.tip_start, e.tip_end),
            (*tip_start, *tip_end),
            "{spelling}: the marks are on the wrong ends"
        );

        let svg = render(&src, "dark").expect("renders");
        let (heads, crosses, discs) = drawn(&svg);
        let (ws, wc, wd) = wanted(*tip_start);
        let (we, wcc, wdd) = wanted(*tip_end);
        assert_eq!(
            (heads, crosses, discs),
            (ws + we, wc + wcc, wd + wdd),
            "{spelling}: {heads} arrow heads, {crosses} crosses and {discs} discs were drawn for \
             ({tip_start:?}, {tip_end:?})"
        );
    }
}

/// The line is pulled back so the arrow head has room, but never past the point of having no
/// direction left.
#[test]
fn trimming_leaves_a_line_with_a_direction() {
    let line = [Point::new(0.0, 0.0), Point::new(0.0, 100.0)];
    let cut = edges::trim_end(&line, edges::ARROW_LENGTH);
    assert!((cut.last().unwrap().y - 91.0).abs() < 1e-9);
    let stub = [Point::new(0.0, 0.0), Point::new(0.0, 3.0)];
    assert_eq!(edges::trim_end(&stub, edges::ARROW_LENGTH), stub.to_vec());
}

/// `~~~` is a layout constraint that draws nothing, and it must still have moved the layout.
#[test]
fn invisible_edge_constrains_but_does_not_draw() {
    let with = laid_out("flowchart TD\n  A[aaa]\n  B[bbb]\n  A ~~~ B");
    let without = laid_out("flowchart TD\n  A[aaa]\n  B[bbb]");
    assert!(
        with.height > without.height,
        "the invisible edge should have pushed B onto its own rank"
    );
    let svg = render("flowchart TD\n  A[aaa]\n  B[bbb]\n  A ~~~ B", "dark").expect("renders");
    assert_eq!(
        svg.matches("<path").count(),
        0,
        "an invisible edge emits no path"
    );
}

// ---------------------------------------------------------------------------------------------
// 5. The SVG contract (§1) and the round trip through resvg
// ---------------------------------------------------------------------------------------------

/// §1's constraints, each of which is a thing resvg was measured doing rather than a style rule.
#[test]
fn emitted_svg_obeys_the_renderer_contract() {
    for (name, src) in CORPUS {
        for theme_name in ["dark", "light", "classic", "forest", "neutral"] {
            let svg = render(src, theme_name).expect("renders");
            assert!(
                svg.contains("viewBox=\""),
                "{name}/{theme_name}: without a viewBox usvg falls back to 100x100"
            );
            assert!(svg.contains("width=\"") && svg.contains("height=\""));
            assert!(
                !svg.contains("foreignObject"),
                "{name}/{theme_name}: resvg drops <foreignObject> whole, label and all"
            );
            assert!(
                !svg.contains("var(--"),
                "{name}/{theme_name}: usvg cannot resolve CSS variables — fills go black"
            );
            assert!(
                !svg.contains("<style") && !svg.contains("class=\"node default\""),
                "{name}/{theme_name}: nothing may depend on a stylesheet"
            );
            assert!(
                svg.contains("font-family=\"sans-serif\""),
                "{name}/{theme_name}: the drawing font must be the one that was measured"
            );
            // The only full-canvas rect is the transparent one.
            let opaque_background = svg
                .lines()
                .any(|l| l.starts_with("<rect width=") && !l.contains("fill=\"none\""));
            assert!(
                !opaque_background,
                "{name}/{theme_name}: an opaque background turns the diagram into a card"
            );
        }
    }
}

/// The output goes through konoma's own rasteriser, which is the thing that will actually draw it.
#[test]
fn every_corpus_diagram_rasterises() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in CORPUS {
        let svg = render(src, "dark").expect("renders");
        let img = crate::preview::svg::rasterize_bytes(svg.as_bytes(), FsPath::new("m.svg"), 600)
            .unwrap_or_else(|| panic!("{name}: konoma's resvg could not rasterise the output"));
        assert!(img.width() > 0 && img.height() > 0, "{name}: empty raster");
    }
}

/// A diagram that draws nothing at all would rasterise to a transparent rectangle, which is
/// exactly the failure §6 calls out in the current crate (`graph TD` alone becoming a 16x16
/// transparent SVG blown up to full width). Some ink has to reach the pixmap.
#[test]
fn a_rendered_diagram_actually_has_ink_in_it() {
    if !text_metrics::fonts_available() {
        return;
    }
    let svg = render("flowchart TD\n  A[Start] --> B{Ready?}", "dark").expect("renders");
    let img = crate::preview::svg::rasterize_bytes(svg.as_bytes(), FsPath::new("m.svg"), 400)
        .expect("rasterises");
    let opaque = img.to_rgba8().pixels().filter(|p| p.0[3] > 32).count();
    assert!(
        opaque > 500,
        "only {opaque} pixels were drawn — the diagram is effectively blank"
    );
}

// ---------------------------------------------------------------------------------------------
// 6. Themes (§4)
// ---------------------------------------------------------------------------------------------

/// Every colour is a normalised lowercase hex, and the background is never painted.
///
/// Over [`theme::EVERY_PALETTE`], not `theme::ALL`: `theme::KONOMA` is not a `[ui] mermaid_theme`
/// value (only `konoma-orthogonal` ever selects it) but it is still a palette, and a rule about
/// what a palette may contain is not weaker for the palette being reached a different way.
#[test]
fn every_theme_colour_is_normalised_hex() {
    for t in theme::EVERY_PALETTE {
        assert_eq!(
            t.background_paint, "none",
            "{}: the background is a reference colour, never a paint (§4-2)",
            t.name
        );
        for (field, value) in [
            ("background_ref", t.background_ref),
            ("node_fill", t.node_fill),
            ("node_stroke", t.node_stroke),
            ("node_text", t.node_text),
            ("line", t.line),
            ("arrowhead", t.arrowhead),
            ("edge_label_text", t.edge_label_text),
            ("cluster_fill", t.cluster_fill),
            ("cluster_stroke", t.cluster_stroke),
            ("cluster_text", t.cluster_text),
            ("state_marker", t.state_marker),
            ("note_fill", t.note_fill),
            ("note_stroke", t.note_stroke),
            ("note_text", t.note_text),
        ] {
            assert!(
                theme::parse_hex(value).is_some(),
                "{}.{field} = {value:?} is not a normalised #rrggbb",
                t.name
            );
        }
    }
}

/// **§4-1's decision, as a test.** konoma never paints a background, so a light theme's diagram
/// can end up composited on a dark terminal. mermaid's own `forest` resolves its line colour to
/// `#000000` (`invert(background)` on line 31 overwrites the `green` on line 17) and vanishes
/// there. Every light-series palette here must stay legible against **both** grounds; the dark
/// palette only has to answer for the dark one.
#[test]
fn lines_survive_being_composited_on_either_ground() {
    const FLOOR: f64 = 2.2;
    for t in theme::EVERY_PALETTE {
        // `state_marker` is here and not with the fills below because it is the one *filled*
        // shape with nothing behind it: the `[*]` dots and the fork bars are solid marks on the
        // terminal itself, so a palette that picked a dark one would make them vanish outright
        // rather than merely go faint.
        for (field, colour) in [
            ("line", t.line),
            ("arrowhead", t.arrowhead),
            ("state_marker", t.state_marker),
        ] {
            let on_black = Theme::contrast(colour, "#000000");
            assert!(
                on_black >= 3.0,
                "{}.{field} = {colour} has contrast {:.2} on black — it disappears on a dark \
                 terminal (this is what happens to mermaid's forest)",
                t.name,
                on_black
            );
            if t.name != "dark" {
                let on_white = Theme::contrast(colour, "#ffffff");
                assert!(
                    on_white >= FLOOR,
                    "{}.{field} = {colour} has contrast {:.2} on white",
                    t.name,
                    on_white
                );
            }
        }
        // Node text has to read against the fill it is drawn on, whatever the terminal does.
        assert!(
            Theme::contrast(t.node_text, t.node_fill) >= 4.0,
            "{}: node text {} on fill {} has contrast {:.2}",
            t.name,
            t.node_text,
            t.node_fill,
            Theme::contrast(t.node_text, t.node_fill)
        );
        // A note's text is drawn on the note's own fill, which is opaque, so this is the same
        // question as node text and gets the same floor.
        assert!(
            Theme::contrast(t.note_text, t.note_fill) >= 4.0,
            "{}: note text {} on fill {} has contrast {:.2}",
            t.name,
            t.note_text,
            t.note_fill,
            Theme::contrast(t.note_text, t.note_fill)
        );
        // An edge label is drawn on the reference colour, not on the terminal.
        assert!(
            Theme::contrast(t.edge_label_text, t.background_ref) >= 4.0,
            "{}: edge label text {} on {} has contrast {:.2}",
            t.name,
            t.edge_label_text,
            t.background_ref,
            Theme::contrast(t.edge_label_text, t.background_ref)
        );
    }
}

/// The five names konoma promises, plus mermaid's own spellings — and an unknown value is `dark`,
/// silently, which is the behaviour `mermaid_to_svg` has today (§1).
#[test]
fn theme_names_resolve_the_way_the_config_promises() {
    assert_eq!(Theme::named("dark").name, "dark");
    assert_eq!(Theme::named("light").name, "light");
    assert_eq!(Theme::named("modern").name, "light");
    assert_eq!(Theme::named("classic").name, "classic");
    assert_eq!(Theme::named("mermaid").name, "classic");
    assert_eq!(Theme::named("forest").name, "forest");
    assert_eq!(Theme::named("neutral").name, "neutral");
    assert_eq!(Theme::named("").name, "dark");
    assert_eq!(Theme::named("Dracula").name, "dark");
    // `konoma` is **not** a `[ui] mermaid_theme` value — the palette of that name belongs to
    // `[ui] mermaid_routing = "konoma-orthogonal"` and is reached only through
    // `Theme::for_routing`. Writing it in `mermaid_theme` is a typo like any other, and a typo
    // falls back to `dark` rather than changing what the diagram looks like.
    assert_eq!(Theme::named("konoma").name, "dark");
}

/// `Theme::for_routing`: `konoma-orthogonal` owns its palette, `splines` defers to the theme.
///
/// Stated over **every** theme spelling the config accepts, so "the mode ignores the theme" cannot
/// be true for four values and false for the fifth.
#[test]
fn the_orthogonal_router_carries_its_own_palette() {
    for name in [
        "dark", "light", "modern", "classic", "mermaid", "forest", "neutral", "", "Dracula",
    ] {
        assert_eq!(
            Theme::for_routing(name, Routing::Orthogonal).name,
            "konoma",
            "mermaid_theme={name:?} must not reach a konoma-orthogonal drawing"
        );
        assert_eq!(
            Theme::for_routing(name, Routing::Splines),
            Theme::named(name),
            "mermaid_theme={name:?} must decide a splines drawing by itself"
        );
    }
    // And the two really are different palettes, so the assertion above is not vacuous.
    assert_ne!(theme::KONOMA, Theme::named("dark"));
    // Only the orthogonal palette carries `Tokens`; every theme value carries none, which is what
    // makes "no `[ui] mermaid_theme` value can reach a single one of those branches" structural.
    assert!(theme::KONOMA.tokens.is_some());
    for t in theme::ALL {
        assert!(
            t.tokens.is_none(),
            "{}: a mermaid_theme palette must carry no drawing tokens",
            t.name
        );
    }
}

/// A theme changes colours and nothing else.
///
/// Structurally guaranteed here — [`lay_out`] never sees a theme — but worth a test anyway,
/// because the bug it guards against did happen: when each theme measured with its own font, the
/// label boxes changed size per theme and an edge took a detour ring (reported from a real
/// terminal on 2026-07-17; §4-3). The comparison strips every `fill`/`stroke` colour and keeps
/// the rest, so a palette that quietly moved a coordinate cannot pass.
#[test]
fn themes_change_colours_but_never_geometry() {
    let src = "flowchart TD\n  A[Start] -->|go| B{Ready?}\n  B --> C((end))";
    let geometry_of = |s: &str| {
        s.lines()
            .map(|l| {
                l.split_whitespace()
                    .filter(|w| !w.starts_with("fill=") && !w.starts_with("stroke=\""))
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect::<Vec<_>>()
            .join("\n")
    };
    let base = geometry_of(&render(src, "dark").expect("renders"));
    for name in ["light", "classic", "forest", "neutral"] {
        assert_eq!(
            base,
            geometry_of(&render(src, name).expect("renders")),
            "theme {name} moved something"
        );
    }
}

// ---------------------------------------------------------------------------------------------
// 7. Degrading rather than lying (§6)
// ---------------------------------------------------------------------------------------------

/// A diagram of another kind must not be drawn. The crate konoma ships turns `venn-beta` into
/// three boxes labelled "venn", "beta" and "sets" — a picture of something nobody wrote.
#[test]
fn another_diagram_kind_is_refused() {
    assert!(matches!(
        render("venn-beta\n  sets: [a, b]", "dark"),
        Err(RenderError::Parse(_))
    ));
    assert!(matches!(
        render("sequenceDiagram\n  A->>B: hi", "dark"),
        Err(RenderError::Parse(_))
    ));
}

/// A header with no body is not a diagram either. The current crate answers `graph TD` with a
/// 16x16 transparent SVG that gets stretched to full width.
#[test]
fn a_flowchart_with_no_nodes_is_refused() {
    assert!(matches!(
        render("graph TD", "dark"),
        Err(RenderError::Parse(_))
    ));
}

/// A block is a frame, not a box: it is drawn, but it is not a node and it holds no label of its
/// own beyond the title. Its members stay ordinary nodes with ordinary edges.
#[test]
fn a_block_is_a_frame_and_not_a_node() {
    let d =
        laid_out("flowchart TD\n  subgraph one [Group]\n    A --> B\n  end\n  B --> C\n  C --> A");
    assert_eq!(d.nodes.len(), 3, "every member is still drawn");
    assert_eq!(d.edges.len(), 3);
    assert!(d.node("one").is_none(), "the block is not a node");
    let frame = d.cluster("one").expect("the block is a frame");
    assert_eq!(frame.title.lines, vec!["Group".to_string()]);
    assert_eq!(frame.parent, None);
    assert_eq!(frame.depth, 0);
}

/// An edge that names a block is drawn, and it points at the frame.
///
/// Stage 1c dropped it: the parser removes a subgraph id from the node list, so there was no
/// shape to attach the line to. Stage 1d re-anchors it onto a member for the layout and cuts it
/// back to the frame for the drawing.
#[test]
fn an_edge_can_name_a_block() {
    let d = laid_out(
        "flowchart TD\n  subgraph one [Group]\n    A --> B\n  end\n  one --> C\n  D --> one",
    );
    assert!(d.node("one").is_none(), "the block is still not a node");
    let named: Vec<&PlacedEdge> = d
        .edges
        .iter()
        .filter(|e| e.from == "one" || e.to == "one")
        .collect();
    assert_eq!(named.len(), 2, "both edges onto the block survive");
    for e in named {
        assert!(e.points.len() >= 2, "{} -> {} has a line", e.from, e.to);
    }
}

/// A block that holds no node at all is not drawn, and an edge that names it is dropped.
///
/// dagre gives a parent its rectangle through the border nodes it hangs off its children; a
/// parent with no children never gets any, and reading a box back from it would produce a frame
/// at the origin with no size. Dropping it is the honest answer.
#[test]
fn an_empty_block_is_not_drawn() {
    let d = laid_out("flowchart TD\n  subgraph hollow [Nothing]\n  end\n  A --> B\n  hollow --> A");
    assert!(d.clusters.is_empty(), "no frame for an empty block");
    assert_eq!(d.edges.len(), 1, "the edge that named it is dropped");
    assert_eq!(d.nodes.len(), 2);
}

/// A `direction` inside a block is read by the parser and **deliberately not applied**.
///
/// See [`super::lay_out`]'s note: dagre has one `rankdir` per layout, honouring a per-block one
/// means laying that block out in a graph of its own, and that is the change mermaid shipped in
/// 11.16.0 and took back in 11.17.0 because the arrows *between* blocks broke. Pinning it as a
/// test rather than as a comment means a future stage that changes its mind has to say so here.
#[test]
fn a_block_direction_does_not_move_anything() {
    let with = laid_out(
        "flowchart LR\n  subgraph one [Steps]\n    direction TB\n    A --> B\n  end\n  B --> C",
    );
    let without = laid_out("flowchart LR\n  subgraph one [Steps]\n    A --> B\n  end\n  B --> C");
    assert_eq!(with.nodes, without.nodes);
    assert_eq!(with.clusters, without.clusters);
}

/// Errors carry the parser's reason. §8 notes the current crate throws these away, losing
/// messages as useful as "unknown participant 'API' at line 3".
#[test]
fn errors_say_what_was_wrong() {
    let e = render("venn-beta", "dark").unwrap_err();
    assert!(
        e.to_string().contains("venn-beta"),
        "the message should name what it found: {e}"
    );
}

// ---------------------------------------------------------------------------------------------
// 8. Goldens
// ---------------------------------------------------------------------------------------------

/// The regression net over the whole corpus, **through [`render`]** — the function stage 1e will
/// wire into production, not a stand-in for it (§6, after konoma was once caught pinning a golden
/// on a function nothing called).
///
/// Numeric attribute values are masked; see the module docs for why (every coordinate descends
/// from the system font, so a byte-exact end-to-end golden would be a golden of this machine).
/// What is pinned is everything else: which elements, in what order, with which colours, which
/// path commands, and which text.
#[test]
fn corpus_golden() {
    if !text_metrics::fonts_available() {
        return;
    }
    let mut out = String::new();
    for (name, src) in CORPUS {
        out.push_str(&format!("=== {name} ===\n"));
        out.push_str(&mask_numbers(&render(src, "dark").expect("renders")));
        out.push('\n');
    }
    assert_snapshot("mermaid_render", &out);
}

/// A diagram assembled by hand, so **no font is involved and every number is pinned exactly**.
///
/// This is the other half of the golden: the corpus golden pins structure over real sources, this
/// one pins arithmetic — number formatting, the outline paths of all fifteen shapes, the curve,
/// the arrow heads, the dash patterns and the label patch.
#[test]
fn emit_golden() {
    let d = synthetic_diagram();
    let mut out = String::new();
    // The five `[ui] mermaid_theme` palettes, spelled out rather than `theme::EVERY_PALETTE`:
    // `theme::KONOMA` is reached only through `konoma-orthogonal`, whose own drawing §10-2 forbids
    // putting in this file at all (the golden is the splines byte stream and must never move).
    // Its emission is pinned by `konoma_orthogonal_draws_the_design_reference_look` instead.
    for t in theme::ALL {
        out.push_str(&format!("=== {} ===\n", t.name));
        out.push_str(&super::svg::emit(&d, t));
        out.push('\n');
    }
    assert_snapshot("mermaid_emit", &out);
}

/// One node of every shape and one edge of every stroke/arrow spelling, at coordinates chosen by
/// hand. Nothing here is measured, so it renders identically on every machine.
fn synthetic_diagram() -> Diagram {
    let label = |text: &str, w: f64| Label {
        lines: text.split('\n').map(str::to_string).collect(),
        width: w,
        height: text.split('\n').count() as f64 * super::labels::line_height(),
        line_pitch: super::labels::line_height(),
        font_size: crate::preview::mermaid::text_metrics::FONT_SIZE as f64,
    };
    let shapes_in_order = [
        Shape::Rect,
        Shape::RoundedRect,
        Shape::Stadium,
        Shape::Subroutine,
        Shape::Cylinder,
        Shape::Circle,
        Shape::DoubleCircle,
        Shape::Diamond,
        Shape::Hexagon,
        Shape::Odd,
        Shape::Trapezoid,
        Shape::InvTrapezoid,
        Shape::LeanRight,
        Shape::LeanLeft,
        Shape::Text,
    ];
    let mut nodes = Vec::new();
    for (i, shape) in shapes_in_order.into_iter().enumerate() {
        let text = if i == 0 { "two\nlines" } else { "label" };
        let l = label(text, 40.0);
        let size = flow_size(shape, Size::new(l.width, l.height));
        nodes.push(PlacedNode {
            id: format!("n{i}"),
            shape: Glyph::Flow(shape),
            center: Point::new(
                120.0 + (i % 5) as f64 * 200.0,
                80.0 + (i / 5) as f64 * 160.0,
            ),
            size,
            label: l,
            panel: None,
            series: None,
            mark: None,
            style: None,
        });
    }

    let arrows = [
        (Arrow::Point, Stroke::Normal),
        (Arrow::None, Stroke::Normal),
        (Arrow::Cross, Stroke::Dotted),
        (Arrow::Circle, Stroke::Thick),
        (Arrow::DoublePoint, Stroke::Normal),
        (Arrow::DoubleCross, Stroke::Normal),
        (Arrow::DoubleCircle, Stroke::Normal),
        (Arrow::Invalid, Stroke::Invalid),
        (Arrow::Point, Stroke::Invisible),
    ];
    let mut edges = Vec::new();
    for (i, (arrow, stroke)) in arrows.into_iter().enumerate() {
        let y = 420.0 + i as f64 * 30.0;
        let points = vec![
            Point::new(60.0, y),
            Point::new(200.0, y),
            Point::new(200.0, y + 20.0),
            Point::new(380.0, y + 20.0),
        ];
        let l = label("via", 20.0);
        edges.push(PlacedEdge {
            from: format!("n{i}"),
            to: format!("n{}", i + 1),
            label: (i % 2 == 0).then(|| super::PlacedEdgeLabel {
                center: edges::arc_midpoint(&points).expect("midpoint"),
                size: Size::new(
                    l.width + super::LABEL_PAD_X * 2.0,
                    l.height + super::LABEL_PAD_Y * 2.0,
                ),
                label: l,
            }),
            points,
            gaps: Vec::new(),
            tip_start: super::Tip::of_arrow(arrow).0,
            tip_end: super::Tip::of_arrow(arrow).1,
            stroke,
            start_label: None,
            end_label: None,
            badge: None,
            series: None,
            straight: false,
            overlay: false,
            style: None,
            curve: Curve::Basis,
            tip_matches_line: false,
        });
    }

    // Two frames, one inside the other, at coordinates chosen by hand: the outer one titled on
    // two lines (the case that makes a frame grow) and the inner one untitled (the case that
    // emits a rect and no text at all).
    let clusters = vec![
        PlacedCluster {
            id: "outer".to_string(),
            title: label("Outer frame\nwith two lines", 130.0),
            center: Point::new(300.0, 620.0),
            size: Size::new(360.0, 160.0),
            parent: None,
            depth: 0,
            dashed: false,
            filled: true,
            sections: Vec::new(),
            title_strip: false,
        },
        PlacedCluster {
            id: "inner".to_string(),
            title: label("", 0.0),
            center: Point::new(320.0, 645.0),
            size: Size::new(200.0, 90.0),
            parent: Some("outer".to_string()),
            depth: 1,
            dashed: false,
            filled: true,
            sections: Vec::new(),
            title_strip: false,
        },
    ];

    Diagram {
        width: 1040.0,
        height: 720.0,
        nodes,
        edges,
        clusters,
        lifelines: Vec::new(),
    }
}

/// The number formatter, which every coordinate goes through. Three decimals, no trailing zeros,
/// and no `-0` (which is a legal float and an ugly attribute).
#[test]
fn numbers_are_written_the_same_way_every_time() {
    assert_eq!(num(12.0), "12");
    assert_eq!(num(12.5), "12.5");
    assert_eq!(num(1.0 / 3.0), "0.333");
    assert_eq!(num(-0.0001), "0");
    assert_eq!(num(-12.25), "-12.25");
}

/// Text that would otherwise break the document is escaped, in both content and attributes.
#[test]
fn label_text_is_escaped() {
    let svg = super::svg::escape("a < b & c > \"d\"");
    assert_eq!(svg, "a &lt; b &amp; c &gt; &quot;d&quot;");
    if text_metrics::fonts_available() {
        let out = render(
            "flowchart TD\n  A[\"a &lt; b\"] --> B[\"x &amp; y\"]",
            "dark",
        )
        .expect("renders");
        assert!(!out.contains("a < b"), "a raw < would break the document");
        assert!(usvg::Tree::from_data(
            out.as_bytes(),
            &usvg::Options {
                fontdb: shared_fontdb(),
                ..usvg::Options::default()
            }
        )
        .is_ok());
    }
}

/// Sources chosen to be awkward rather than realistic. konoma's rule is that the renderer runs on
/// a worker thread wrapped in `catch_unwind` (§1) — which is a safety net, not a licence — so
/// each of these has to come back with a diagram or an error, never a panic and never a diagram
/// with a NaN in it.
#[test]
fn awkward_sources_produce_a_diagram_or_an_error_and_never_a_panic() {
    if !text_metrics::fonts_available() {
        return;
    }
    let mut wide = String::from("flowchart LR\n");
    for i in 0..120 {
        wide.push_str(&format!("  n{i} --> n{}\n", i + 1));
    }
    wide.push_str("  n0 --> n120\n  n120 --> n0\n");

    // Twelve blocks, each inside the last. mermaid's own `adjustClustersAndEdges` gives up past a
    // depth of ten; konoma's tree walk is bounded by the number of blocks instead, so this asks
    // whether that bound is really there.
    let mut deep = String::from("flowchart TD\n");
    for i in 0..12 {
        deep.push_str(&format!("  subgraph s{i} [Level {i}]\n"));
    }
    deep.push_str("  A --> B\n");
    for _ in 0..12 {
        deep.push_str("  end\n");
    }
    deep.push_str("  s0 --> C\n  C --> s11\n");

    let cases: &[&str] = &[
        "",
        "   \n\n  ",
        "flowchart TD",
        "flowchart TD\n  A[\"\"]",
        "flowchart TD\n  A[\"   \"] --> B[\"\"]",
        "flowchart TD\n  A -->|| B",
        "flowchart TD\n  A --> A",
        "flowchart LR\n  A[\"<script>&amp;\"] --> B[\"a > b\"]",
        "flowchart TD\n  A[\"一\"] --> B[\"🎉\"]",
        "flowchart TD\n  %% only a comment\n  A --> B",
        "flowchart TD\n  classDef hot fill:#f9f\n  A:::hot --> B",
        "flowchart TD\n  A@{ shape: cyl, label: \"store\" } --> B",
        // Blocks, in the shapes a person would not write on purpose.
        "flowchart TD\n  subgraph one\n  end\n  A --> B",
        "flowchart TD\n  subgraph one\n  end\n  one --> one",
        "flowchart TD\n  subgraph one [Group]\n    A --> B\n  end\n  one --> A",
        "flowchart TD\n  subgraph one [Group]\n    A --> B\n  end\n  one --> one",
        "flowchart LR\n  subgraph one\n    subgraph two\n      subgraph three\n        A\n               end\n    end\n  end\n  one --> three",
        "flowchart TD\n  subgraph one [\"\"]\n    A\n  end\n  A --> B",
        "flowchart TD\n  A --> one\n  subgraph one [Declared after the edge]\n    B --> C\n  end",
        &deep,
        &wide,
    ];
    for src in cases {
        match render(src, "dark") {
            Err(_) => {}
            Ok(svg) => {
                assert!(!svg.contains("NaN"), "NaN reached the document for {src:?}");
                assert!(
                    !svg.contains("inf"),
                    "an infinity reached the document for {src:?}"
                );
                let d = laid_out(src);
                assert!(
                    d.width.is_finite() && d.height.is_finite() && d.width > 0.0 && d.height > 0.0,
                    "{src:?}: {}x{} is not a drawable size",
                    num(d.width),
                    num(d.height)
                );
                assert!(
                    crate::preview::svg::rasterize_bytes(svg.as_bytes(), FsPath::new("m.svg"), 300)
                        .is_some(),
                    "{src:?}: the output did not rasterise"
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------------------------
// 9. `classDef` / `class` / `:::` / `style` / `linkStyle` (docs/STATUS.md, 2026-08-28 regression)
// ---------------------------------------------------------------------------------------------
//
// The bug this section pins: `flowchart/parser.rs` always kept `class_defs` and `link_styles` —
// only so `classDef hot fill:#f9f` could not become a phantom node (§2-3) — and nothing
// downstream ever read what they said. `mask_numbers` (this file's module docs) hides
// `stroke-width`/`stroke-dasharray` but **not** `fill`/`stroke`, so a colour regression here would
// have shown up in `corpus_golden` if the corpus had a case for it; it did not (`CORPUS` has no
// `classDef` source), which is exactly how this shipped unnoticed. These tests read
// [`PlacedNode::style`]/[`PlacedEdge::style`] directly rather than relying on a golden, so a future
// regression fails by name instead of by an unrelated-looking snapshot diff.

/// `classDef default` colours every node automatically, and must **not** leak onto an edge that
/// carries neither a `class` of its own nor any `linkStyle` — caught while regenerating the
/// corpus golden for this section: [`super::style::cascade_edge`] used to start from
/// [`super::style::cascade`], which begins every element at `classDef default`, and an edge is
/// not a node.
#[test]
fn classdef_default_colours_nodes_but_not_an_untouched_edge() {
    let d = laid_out("flowchart TD\n  classDef default fill:#223,stroke:#556\n  A --> B");
    assert_eq!(
        d.node("A")
            .unwrap()
            .style
            .as_ref()
            .unwrap()
            .stroke
            .as_deref(),
        Some("#556"),
        "classDef default must still colour every node"
    );
    assert!(
        d.edges[0].style.is_none(),
        "the edge names neither a class nor a linkStyle, so classDef default must not reach it"
    );

    let svg = render(
        "flowchart TD\n  classDef default fill:#223,stroke:#556\n  A --> B",
        "dark",
    )
    .expect("renders");
    assert_eq!(
        svg.matches("stroke=\"#556\"").count(),
        2,
        "exactly the two node rects (A and B) may carry classDef default's stroke, never the edge's path: {svg}"
    );
    assert!(
        svg.contains(&format!("stroke=\"{}\"", theme::DARK.line)),
        "the edge's path must still draw in the theme's own line colour: {svg}"
    );
}

/// `classDef` + `class` colours the node it names, and leaves every other node at the theme's own
/// colour.
#[test]
fn classdef_and_class_colour_the_node_they_name() {
    let d =
        laid_out("flowchart TD\n  classDef hot fill:#f9f,stroke:#a00\n  A --> B\n  class A hot");
    let a = d
        .node("A")
        .expect("A exists")
        .style
        .as_ref()
        .expect("A has a style");
    assert_eq!(a.fill.as_deref(), Some("#f9f"));
    assert_eq!(a.stroke.as_deref(), Some("#a00"));
    assert!(
        d.node("B").expect("B exists").style.is_none(),
        "class hot named only A, so B must keep the theme's own colour"
    );

    let svg = render(
        "flowchart TD\n  classDef hot fill:#f9f,stroke:#a00\n  A --> B\n  class A hot",
        "dark",
    )
    .expect("renders");
    assert!(
        svg.contains("fill=\"#f9f\""),
        "the fill reaches the SVG: {svg}"
    );
}

/// `:::hot` at the declaration does what a separate `class` statement does.
#[test]
fn triple_colon_is_the_same_as_a_class_statement() {
    let d = laid_out("flowchart TD\n  classDef hot fill:#f9f\n  A:::hot --> B");
    let a = d
        .node("A")
        .expect("A exists")
        .style
        .as_ref()
        .expect("A has a style");
    assert_eq!(a.fill.as_deref(), Some("#f9f"));
    assert!(d.node("B").expect("B exists").style.is_none());
}

/// A node's own `style` statement is the last step of the cascade, so it wins over a `classDef`
/// the node also carries — D2's "後のものが前を上書きする".
#[test]
fn a_nodes_own_style_wins_over_its_classdef() {
    let d =
        laid_out("flowchart TD\n  classDef hot fill:#f9f\n  A:::hot --> B\n  style A fill:#00ff00");
    let a = d
        .node("A")
        .expect("A exists")
        .style
        .as_ref()
        .expect("A has a style");
    assert_eq!(
        a.fill.as_deref(),
        Some("#00ff00"),
        "the node's own `style` statement must be the final word, not the classDef"
    );
}

/// `linkStyle <idx>` touches only the edge at that index into [`Flowchart::edges`] — proof the
/// index-to-edge mapping is right, not just that *an* edge got styled.
#[test]
fn link_style_by_index_touches_only_that_edge() {
    let d = laid_out("flowchart TD\n  A --> B\n  B --> C\n  C --> D\n  linkStyle 1 stroke:#1f6feb");
    assert_eq!(d.edges.len(), 3, "three edges: A->B, B->C, C->D");
    assert!(d.edges[0].style.is_none(), "A->B (index 0) is untouched");
    assert_eq!(
        d.edges[1]
            .style
            .as_ref()
            .expect("B->C (index 1) has a style")
            .stroke
            .as_deref(),
        Some("#1f6feb")
    );
    assert!(d.edges[2].style.is_none(), "C->D (index 2) is untouched");
}

/// `linkStyle 0,1,2 stroke:#1f6feb` — the user's own reported shape
/// (`~/work/Ergora/doc/spec/05-system-architecture.md`), where several indices share one
/// declaration. Every named edge gets it and the edge left out does not.
#[test]
fn link_style_with_multiple_indices_reaches_every_named_edge() {
    let d = laid_out(
        "flowchart TD\n  A --> B\n  B --> C\n  C --> D\n  D --> E\n  \
         linkStyle 0,1,2 stroke:#1f6feb",
    );
    assert_eq!(d.edges.len(), 4);
    for i in 0..3 {
        assert_eq!(
            d.edges[i]
                .style
                .as_ref()
                .unwrap_or_else(|| panic!("edge {i} has a style"))
                .stroke
                .as_deref(),
            Some("#1f6feb"),
            "edge {i} is named by `linkStyle 0,1,2`"
        );
    }
    assert!(
        d.edges[3].style.is_none(),
        "edge 3 (D->E) was not named, and must be untouched"
    );
}

/// `linkStyle default` colours every edge, and a specific index still overrides it — the fixed
/// pipeline order [`super::style::cascade_edge`]'s docs describe, independent of which the source
/// physically wrote first.
#[test]
fn link_style_default_colours_every_edge_and_an_index_still_overrides_it() {
    let d = laid_out(
        "flowchart TD\n  A --> B\n  B --> C\n  linkStyle 0 stroke:#e11\n  \
         linkStyle default stroke:#39d",
    );
    assert_eq!(
        d.edges[0].style.as_ref().unwrap().stroke.as_deref(),
        Some("#e11"),
        "edge 0's own index is more specific than `default`, even written first"
    );
    assert_eq!(
        d.edges[1].style.as_ref().unwrap().stroke.as_deref(),
        Some("#39d"),
        "edge 1 has no index of its own, so `default` reaches it"
    );
}

/// `stroke-width` is one of [`mask_numbers`]' masked attributes, so the golden cannot see whether
/// it actually reached the SVG — this asserts on the unmasked string directly.
#[test]
fn link_style_stroke_width_reaches_the_unmasked_svg() {
    let svg = render(
        "flowchart TD\n  A --> B\n  linkStyle 0 stroke-width:4px",
        "dark",
    )
    .expect("renders");
    assert!(
        svg.contains("stroke-width=\"4\""),
        "the declared width must reach the path's own attribute, unmasked: {svg}"
    );
}

// --- the four tests above this line all read `Diagram`/`PlacedEdge::style` — the *model* the
// cascade resolves into. Every one of them is blind to a defect in the last step, `svg.rs`
// applying that field when it writes the `<path>` element: the regression this whole section
// exists for was reported *from that exact step* (`linkStyle` colours that reached `PlacedEdge`
// correctly and never reached the SVG the terminal draws). The tests below read the emitted
// string instead of the model, so a defect confined to `svg::emit_edge` — the model right, the
// drawing wrong — fails one of these rather than passing every model-level test in the file.

/// `linkStyle <idx> stroke:#…` reaches the one path element for that edge, in the raw SVG text,
/// and the other edges' paths keep the theme's own line colour.
#[test]
fn link_style_single_index_stroke_reaches_the_svg_and_only_that_edges_path() {
    let svg = render(
        "flowchart TD\n  A --> B\n  B --> C\n  C --> D\n  linkStyle 1 stroke:#1f6feb",
        "dark",
    )
    .expect("renders");
    assert_eq!(
        svg.matches("stroke=\"#1f6feb\"").count(),
        1,
        "exactly one edge (index 1) was named: {svg}"
    );
    assert_eq!(
        svg.matches(&format!("stroke=\"{}\"", theme::DARK.line))
            .count(),
        2,
        "the other two edges must still draw in the theme's own line colour: {svg}"
    );
}

/// `linkStyle 0,1,2 stroke:#…` — several indices sharing one declaration, the user's own reported
/// shape (`~/work/Ergora/doc/spec/05-system-architecture.md`) — reaches every named edge's path in
/// the raw SVG text, and the edge left out does not get it.
#[test]
fn link_style_multiple_indices_stroke_reaches_every_named_edges_path() {
    let svg = render(
        "flowchart TD\n  A --> B\n  B --> C\n  C --> D\n  D --> E\n  \
         linkStyle 0,1,2 stroke:#1f6feb",
        "dark",
    )
    .expect("renders");
    assert_eq!(
        svg.matches("stroke=\"#1f6feb\"").count(),
        3,
        "three edges (0, 1, 2) were named: {svg}"
    );
    assert_eq!(
        svg.matches(&format!("stroke=\"{}\"", theme::DARK.line))
            .count(),
        1,
        "the fourth edge (D->E) was not named and must keep the theme's line colour: {svg}"
    );
}

/// `linkStyle default` colours every edge's path in the raw SVG text, and an indexed `linkStyle`
/// still overrides it there too — the same fixed pipeline order the model-level
/// [`link_style_default_colours_every_edge_and_an_index_still_overrides_it`] states, checked at
/// the one step that test cannot see.
#[test]
fn link_style_default_then_an_index_reach_the_svg_as_two_distinct_colours() {
    let svg = render(
        "flowchart TD\n  A --> B\n  B --> C\n  linkStyle 0 stroke:#e11\n  \
         linkStyle default stroke:#39d",
        "dark",
    )
    .expect("renders");
    assert_eq!(
        svg.matches("stroke=\"#e11\"").count(),
        1,
        "edge 0's own index must win over `default`, even written first: {svg}"
    );
    assert_eq!(
        svg.matches("stroke=\"#39d\"").count(),
        1,
        "edge 1 has no index of its own, so `default` must reach its path: {svg}"
    );
}

/// An unparsable colour is dropped, not substituted with black — [`super::style::paint`]'s whole
/// reason for existing (`UiConfig::math_color`'s "blank equation" precedent). The node must still
/// draw, in the theme's own colour, and the document must still be valid SVG.
#[test]
fn an_invalid_color_falls_back_to_the_theme_instead_of_black() {
    let d = laid_out("flowchart TD\n  classDef bad fill:notacolor\n  A:::bad --> B");
    assert!(
        d.node("A").unwrap().style.is_none(),
        "the only declared field failed to validate, so there is nothing to override with"
    );

    let svg = render(
        "flowchart TD\n  classDef bad fill:notacolor\n  A:::bad --> B",
        "dark",
    )
    .expect("renders");
    assert!(
        svg.contains(theme::DARK.node_fill),
        "A must draw in the theme's node colour, not vanish or turn black: {svg}"
    );
    assert!(
        !svg.contains("notacolor"),
        "the bad literal must never reach the SVG document"
    );
    // `tree_of` itself `.expect()`s a successful parse, so simply calling it is the assertion:
    // the document is still valid SVG usvg can read.
    tree_of(&svg);
}

// ---------------------------------------------------------------------------------------------
// 10. `curve` (`[ui] mermaid_curve` / `linkStyle ... interpolate`)
// ---------------------------------------------------------------------------------------------
//
// mermaid's most-requested flowchart feature is a straight/right-angle line instead of the
// default spline (mermaid-js#2817, 129 reactions; mermaid-js#2549, 75 reactions; both open 4+
// years). The unconditional requirement this section exists to pin: `render_curve(..., "basis")`
// — and so `render` itself, which is defined as exactly that call — must draw byte-for-byte what
// it drew before `curve` existed. `corpus_golden` staying green already implies this; these tests
// state the reason directly, the way §9 states its own bug by name instead of by an
// unrelated-looking snapshot diff.

/// D5's invariant, stated directly: the default curve changes nothing. `render` is `render_curve`
/// called with `"basis"` (`mod.rs`'s own definition), so this is really pinning that the
/// delegation stays what it is — but a future edit could still break it by, say, giving `render`
/// its own copy of the pipeline that drifts from `render_curve`'s.
#[test]
fn basis_curve_is_byte_identical_to_render() {
    for (name, src) in CORPUS {
        let via_curve =
            render_curve(src, "dark", "basis").unwrap_or_else(|e| panic!("{name}: {e}"));
        let via_render = render(src, "dark").unwrap_or_else(|e| panic!("{name}: {e}"));
        assert_eq!(
            via_curve, via_render,
            "{name}: render_curve(..., \"basis\") must match render() exactly"
        );
    }
}

/// `Curve::Basis` still rounds right-angle corners off (`edges::fix_corners`) — today's look,
/// unchanged. Segment lengths are past `fix_corners`' short-corner guard (`CORNER_RADIUS`'s own
/// module docs use 10px as the threshold), so the corner really is rounded, not left alone by a
/// guard this test failed to clear.
#[test]
fn basis_curve_still_rounds_corners() {
    let raw = vec![
        Point::new(0.0, 0.0),
        Point::new(0.0, 40.0),
        Point::new(40.0, 40.0),
    ];
    let edge = bent_edge(raw.clone(), Curve::Basis);
    assert_eq!(edge.drawn_points(), edges::fix_corners(&raw));
    assert_ne!(
        edge.drawn_points(),
        raw,
        "a real right angle must actually be rounded under Curve::Basis"
    );
}

/// `Curve::Linear` still runs `fix_corners`, the same as every curve but `Rounded`
/// (`Curve::rounds_corners`'s own doc has the versioned evidence). **This test used to assert the
/// opposite** — that `linear` kept a sharp right angle — on the reasoning that `linear`/`step*`
/// are chosen *because* they draw a sharp angle, so rounding one off would undo the shape asked
/// for. That reasoning was never checked against upstream, and it was wrong: `mermaid@11.4.1` and
/// `mermaid@11.12.0` (both released versions) call `fixCorners` unconditionally in `edges.js`, no
/// curve-type check at all, so a real `linear` flowchart on GitHub has this exact corner softened
/// too. This crate's acceptance test is "the same source reads the same picture GitHub draws"
/// (this session's own brief), so the fixed expectation is the one that matches that picture, not
/// the one that looked most consistent with `linear`'s own name.
#[test]
fn linear_curve_also_rounds_corners() {
    let raw = vec![
        Point::new(0.0, 0.0),
        Point::new(0.0, 40.0),
        Point::new(40.0, 40.0),
    ];
    let edge = bent_edge(raw.clone(), Curve::Linear);
    assert_eq!(
        edge.drawn_points(),
        edges::fix_corners(&raw),
        "Curve::Linear must run fix_corners, matching every released mermaid version"
    );
    assert_ne!(
        edge.drawn_points(),
        raw,
        "a real right angle must actually be rounded under Curve::Linear too"
    );
    // `Curve::Linear.path` itself is still an unmodified `polyline_path` — straight segments
    // through whatever points it is given. What changed is which points it is given: the
    // fix_corners-rounded ones (`drawn_points`), not the raw waypoints. `polyline_path` drawing a
    // straight line between two rounded-corner points is exactly how `fixCorners` + `curveLinear`
    // reads upstream too — the corner becomes a short straight chamfer, not a smooth arc.
    assert_eq!(
        Curve::Linear.path(&edge.drawn_points()),
        edges::polyline_path(&edge.drawn_points())
    );
}

/// `Curve::Step` also runs `fix_corners` — same evidence, same fix as `Curve::Linear`'s own test
/// just above. Checked separately because `step`'s own shape (an explicit right-angle transition
/// mid-segment) makes it easy to assume, wrongly, that `fixCorners` would be redundant on it; it
/// is not — `fixCorners` acts on the edge's *waypoints*, before `step_path` ever sees them, so a
/// real right-angle waypoint (not `step`'s own synthetic transition point) is softened exactly
/// like it is for every other non-`Rounded` curve.
#[test]
fn step_curve_also_rounds_corners() {
    let raw = vec![
        Point::new(0.0, 0.0),
        Point::new(0.0, 40.0),
        Point::new(40.0, 40.0),
    ];
    let edge = bent_edge(raw.clone(), Curve::Step);
    assert_eq!(
        edge.drawn_points(),
        edges::fix_corners(&raw),
        "Curve::Step must run fix_corners, matching every released mermaid version"
    );
    assert_ne!(edge.drawn_points(), raw);
}

/// `Curve::Rounded` is the one curve `PlacedEdge::drawn_points` does **not** run `fix_corners`
/// for — it rounds every corner itself, at its own radius (`rounded_path`), so pre-rounding would
/// round the same corner twice. The regression this guards: a mutation that made `Rounded` *also*
/// run `fix_corners` (double-rounding) must be caught here, not just inferred from
/// `Curve::rounds_corners`'s own boolean.
#[test]
fn rounded_curve_does_not_also_run_fix_corners() {
    let raw = vec![
        Point::new(0.0, 0.0),
        Point::new(0.0, 40.0),
        Point::new(40.0, 40.0),
    ];
    let edge = bent_edge(raw.clone(), Curve::Rounded);
    assert_eq!(
        edge.drawn_points(),
        raw,
        "Curve::Rounded must not run fix_corners — it rounds corners itself"
    );
}

/// The three step variants draw three different shapes for the same waypoints — the regression
/// guard against copy-pasting one branch over another. Values are worked out from d3-shape's own
/// `Step` class (`edges.rs`'s `step_path` docs): `stepBefore` goes vertical first, `stepAfter`
/// goes horizontal first, `step` splits at the midpoint.
#[test]
fn step_variants_differ_from_each_other_and_match_d3() {
    let pts = vec![Point::new(0.0, 0.0), Point::new(40.0, 60.0)];
    let step = Curve::Step.path(&pts);
    let before = Curve::StepBefore.path(&pts);
    let after = Curve::StepAfter.path(&pts);

    assert_ne!(step, before, "step and stepBefore must draw differently");
    assert_ne!(step, after, "step and stepAfter must draw differently");
    assert_ne!(
        before, after,
        "stepBefore and stepAfter must draw differently"
    );

    let m = |x: f64, y: f64| format!("M{},{}", num(x), num(y));
    let l = |x: f64, y: f64| format!("L{},{}", num(x), num(y));
    assert_eq!(
        before,
        format!("{}{}{}", m(0.0, 0.0), l(0.0, 60.0), l(40.0, 60.0)),
        "stepBefore: vertical leg first, at the segment's starting x"
    );
    assert_eq!(
        after,
        format!("{}{}{}", m(0.0, 0.0), l(40.0, 0.0), l(40.0, 60.0)),
        "stepAfter: horizontal leg first, at the segment's ending x"
    );
    assert_eq!(
        step,
        format!(
            "{}{}{}{}",
            m(0.0, 0.0),
            l(20.0, 0.0),
            l(20.0, 60.0),
            l(40.0, 60.0)
        ),
        "step: the transition sits at the segment's midpoint x, and the line still reaches p1"
    );
}

/// `linkStyle <n> interpolate <curve>` reaches exactly the edge it names, and no other — the
/// wiring `flowchart/model.rs` used to say konoma does not have (§2-5, now implemented).
#[test]
fn link_style_interpolate_affects_only_that_edge() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  C --> D\n  linkStyle 0 interpolate linear",
        "basis",
    );
    assert_eq!(d.edges[0].curve, Curve::Linear);
    assert_eq!(d.edges[1].curve, Curve::Basis);
}

/// An edge's own `linkStyle interpolate` wins over the chart-wide `[ui] mermaid_curve` default —
/// the priority order D4 requires, stated as the strongest case: the two disagree outright.
#[test]
fn link_style_interpolate_overrides_the_chart_wide_default() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  linkStyle 0 interpolate linear",
        "step",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Linear,
        "the edge's own interpolate must win over ui.mermaid_curve"
    );
}

/// `linkStyle default interpolate` sets the chart-wide default for every edge that names no
/// index of its own, exactly the way `style::cascade_edge` already treats `linkStyle default`
/// styles — and an indexed `linkStyle` still wins over it, the same cascade order.
#[test]
fn link_style_default_interpolate_applies_unless_an_index_overrides_it() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  C --> D\n  linkStyle default interpolate linear\n  \
         linkStyle 1 interpolate step",
        "basis",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Linear,
        "linkStyle default interpolate applies to an edge with no index override"
    );
    assert_eq!(
        d.edges[1].curve,
        Curve::Step,
        "linkStyle 1's own interpolate must still win over linkStyle default"
    );
}

/// An unrecognised curve name falls back to `Curve::Basis` rather than erroring, both directly
/// through `Curve::parse` and through the whole config → render pipeline. Never crashes.
///
/// All 13 of mermaid's own `flowchart.curve` values are implemented as of this test (see the
/// "eight newly implemented curves" section below), so "a real d3 curve this crate does not
/// implement" is no longer an example this test can give — `curveBasisClosed` stands in instead:
/// a real d3-shape curve name, just not one mermaid's `flowchart.curve` schema ever accepts.
#[test]
fn unknown_curve_falls_back_to_basis_without_crashing() {
    assert_eq!(
        Curve::parse("basisClosed"),
        Curve::Basis,
        "a real d3-shape curve, but not one of mermaid's flowchart.curve values"
    );
    assert_eq!(
        Curve::parse("Basis"),
        Curve::Basis,
        "wrong case — Curve::parse is case-sensitive, matching mermaid's own spellings"
    );
    assert_eq!(
        Curve::parse("nonsense"),
        Curve::Basis,
        "not a curve name at all"
    );
    assert_eq!(Curve::parse(""), Curve::Basis, "empty string");

    let d = laid_out_curve("flowchart TD\n  A --> B", "basisClosed");
    assert_eq!(d.edges[0].curve, Curve::Basis);

    let svg = render_curve("flowchart TD\n  A --> B", "dark", "nonsense")
        .expect("an unknown curve must still render, as Curve::Basis");
    assert!(svg.contains("<svg"));
}

// ---------------------------------------------------------------------------------------------
// 10-b. The eight curves implemented after the five above: d3-shape's `natural`, `cardinal`,
// `catmullRom`, `monotoneX`, `monotoneY`, `bumpX`, `bumpY`, and mermaid's own `rounded`.
// ---------------------------------------------------------------------------------------------
//
// Every `_matches_d3` test below pins geometry generated by actually running the real npm
// `d3-shape` package (v3, the version mermaid itself depends on) through a small Node context
// object that records `moveTo`/`lineTo`/`bezierCurveTo` calls in exactly the string convention
// this module's own `push_move`/`push_line`/`push_bezier` use (comma inside a coordinate pair,
// space between pairs, three-decimal rounding via the same formula as `svg::num`) — not hand-
// derived, and not `curve_basis_matches_d3`'s approach of working the control-point algebra out
// by hand, because a spline family this size (five distinct state machines, one of them with an
// epsilon-gated weighting term) is exactly where hand arithmetic is most likely to be the thing
// that is wrong. The three point sets are chosen on purpose: `RIGHT_ANGLE` and `FOUR_POINT` have
// evenly-spaced waypoints, under which centripetal Catmull-Rom (`catmullRom`) and the classic
// Cardinal spline (`cardinal`) are mathematically the same curve — so `UNEVEN` (unequal segment
// lengths) is the set that actually exercises `catmullRom`'s own epsilon-gated weighting and
// tells the two apart; without it a `cardinal`/`catmullRom` copy-paste bug would pass silently.
//
// `VERTICAL`/`HORIZONTAL`/`DUPLICATE` exist because none of the three sets above ever has two
// consecutive points share a coordinate, and that is exactly the shape that broke `monotoneX` in
// production: `flowchart TD` is konoma's *default* direction, under which an ordinary vertical
// edge is three points with the same x — `slope3`'s `dx` is `0` for that pair, which upstream
// handles (its `Math.min` propagates the resulting `NaN` through to a `0` fallback) and this
// crate's first port of it did not (`js_min`'s own doc has the full mechanism). `VERTICAL` is
// exactly that shape; `HORIZONTAL` is its mirror (the case `monotoneY`'s reflected axis turns
// into the same failure); `DUPLICATE` is the more general version — two *identical* consecutive
// points, which is what an axis-aligned run degenerates to when dagre's own dedup does not catch
// it. All three were mechanically swept over every one of the 13 curves (not guessed at from the
// bug report) — `Curve::path` never emits `NaN`/`Infinity` for any of them, pinned separately by
// `no_curve_ever_emits_nan_or_infinite_coordinates` below.

const RIGHT_ANGLE: [(f64, f64); 3] = [(0.0, 0.0), (60.0, 0.0), (60.0, 60.0)];
const FOUR_POINT: [(f64, f64); 4] = [(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (80.0, 40.0)];
const UNEVEN: [(f64, f64); 4] = [(0.0, 0.0), (10.0, 0.0), (40.0, 30.0), (90.0, 35.0)];
/// Three collinear points sharing an x — an ordinary vertical edge under `flowchart TD`,
/// konoma's default direction. The exact shape that broke `monotoneX` in production.
const VERTICAL: [(f64, f64); 3] = [(100.0, 50.0), (100.0, 120.0), (100.0, 190.0)];
/// `VERTICAL`'s mirror — three collinear points sharing a y, the shape that breaks `monotoneY`'s
/// reflected axis the same way `VERTICAL` breaks `monotoneX`'s own.
const HORIZONTAL: [(f64, f64); 3] = [(50.0, 100.0), (120.0, 100.0), (190.0, 100.0)];
/// Two consecutive points at the exact same coordinate — the more general version of
/// `VERTICAL`/`HORIZONTAL`'s "a segment has zero length" degeneracy, on a diagonal run instead of
/// an axis-aligned one.
const DUPLICATE: [(f64, f64); 4] = [(0.0, 0.0), (40.0, 40.0), (40.0, 40.0), (80.0, 80.0)];

fn pts(raw: &[(f64, f64)]) -> Vec<Point> {
    raw.iter().map(|&(x, y)| Point::new(x, y)).collect()
}

#[test]
fn curve_natural_matches_d3() {
    assert_eq!(
        edges::curve_natural_path(&pts(&RIGHT_ANGLE)),
        "M0,0C25,-5 50,-10 60,0C70,10 65,35 60,60"
    );
    assert_eq!(
        edges::curve_natural_path(&pts(&FOUR_POINT)),
        "M0,0C17.778,-4.444 35.556,-8.889 40,0C44.444,8.889 35.556,31.111 40,40\
         C44.444,48.889 62.222,44.444 80,40"
    );
    assert_eq!(
        edges::curve_natural_path(&pts(&UNEVEN)),
        "M0,0C2,-3.222 4,-6.444 10,0C16,6.444 26,22.556 40,30C54,37.444 72,36.222 90,35"
    );
    assert_eq!(
        edges::curve_natural_path(&pts(&VERTICAL)),
        "M100,50C100,73.333 100,96.667 100,120C100,143.333 100,166.667 100,190"
    );
    assert_eq!(
        edges::curve_natural_path(&pts(&HORIZONTAL)),
        "M50,100C73.333,100 96.667,100 120,100C143.333,100 166.667,100 190,100"
    );
    assert_eq!(
        edges::curve_natural_path(&pts(&DUPLICATE)),
        "M0,0C17.778,17.778 35.556,35.556 40,40C44.444,44.444 35.556,35.556 40,40\
         C44.444,44.444 62.222,62.222 80,80"
    );
    // Two points are a line; one is a bare move; zero is empty — the shared degenerate cases.
    assert_eq!(
        edges::curve_natural_path(&pts(&RIGHT_ANGLE[..2])),
        "M0,0L60,0"
    );
    assert_eq!(edges::curve_natural_path(&pts(&RIGHT_ANGLE[..1])), "M0,0");
    assert_eq!(edges::curve_natural_path(&[]), "");
}

#[test]
fn curve_cardinal_matches_d3() {
    assert_eq!(
        edges::curve_cardinal_path(&pts(&RIGHT_ANGLE)),
        "M0,0C0,0 50,-10 60,0C70,10 60,60 60,60"
    );
    assert_eq!(
        edges::curve_cardinal_path(&pts(&FOUR_POINT)),
        "M0,0C0,0 33.333,-6.667 40,0C46.667,6.667 33.333,33.333 40,40\
         C46.667,46.667 80,40 80,40"
    );
    assert_eq!(
        edges::curve_cardinal_path(&pts(&UNEVEN)),
        "M0,0C0,0 3.333,-5 10,0C16.667,5 26.667,24.167 40,30C53.333,35.833 90,35 90,35"
    );
    assert_eq!(
        edges::curve_cardinal_path(&pts(&VERTICAL)),
        "M100,50C100,50 100,96.667 100,120C100,143.333 100,190 100,190"
    );
    assert_eq!(
        edges::curve_cardinal_path(&pts(&HORIZONTAL)),
        "M50,100C50,100 96.667,100 120,100C143.333,100 190,100 190,100"
    );
    assert_eq!(
        edges::curve_cardinal_path(&pts(&DUPLICATE)),
        "M0,0C0,0 33.333,33.333 40,40C46.667,46.667 33.333,33.333 40,40\
         C46.667,46.667 80,80 80,80"
    );
    assert_eq!(
        edges::curve_cardinal_path(&pts(&RIGHT_ANGLE[..2])),
        "M0,0L60,0"
    );
    assert_eq!(edges::curve_cardinal_path(&pts(&RIGHT_ANGLE[..1])), "M0,0");
    assert_eq!(edges::curve_cardinal_path(&[]), "");
}

#[test]
fn curve_catmull_rom_matches_d3() {
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&RIGHT_ANGLE)),
        "M0,0C0,0 50,-10 60,0C70,10 60,60 60,60"
    );
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&FOUR_POINT)),
        "M0,0C0,0 33.333,-6.667 40,0C46.667,6.667 33.333,33.333 40,40\
         C46.667,46.667 80,40 80,40"
    );
    // The one point set that actually tells `catmullRom` apart from `cardinal` — see this
    // section's own module doc.
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&UNEVEN)),
        "M0,0C0,0 6.169,-1.587 10,0C17.89,3.268 27.455,24.055 40,30C53.653,36.47 90,35 90,35"
    );
    assert_ne!(
        edges::curve_catmull_rom_path(&pts(&UNEVEN)),
        edges::curve_cardinal_path(&pts(&UNEVEN)),
        "catmullRom and cardinal must differ once waypoints are unevenly spaced"
    );
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&VERTICAL)),
        "M100,50C100,50 100,96.667 100,120C100,143.333 100,190 100,190"
    );
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&HORIZONTAL)),
        "M50,100C50,100 96.667,100 120,100C143.333,100 190,100 190,100"
    );
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&DUPLICATE)),
        "M0,0C0,0 40,40 40,40C40,40 40,40 40,40C40,40 80,80 80,80"
    );
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&RIGHT_ANGLE[..2])),
        "M0,0L60,0"
    );
    assert_eq!(
        edges::curve_catmull_rom_path(&pts(&RIGHT_ANGLE[..1])),
        "M0,0"
    );
    assert_eq!(edges::curve_catmull_rom_path(&[]), "");
}

#[test]
fn curve_monotone_x_matches_d3() {
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&RIGHT_ANGLE)),
        "M0,0C20,0 40,0 60,0C60,0 60,60 60,60"
    );
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&FOUR_POINT)),
        "M0,0C13.333,0 26.667,0 40,0C40,0 40,40 40,40C53.333,40 66.667,40 80,40"
    );
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&UNEVEN)),
        "M0,0C3.333,0 6.667,0 10,0C20,0 30,28 40,30C56.667,33.333 73.333,34.167 90,35"
    );
    // The exact bug: three collinear points sharing an x (an ordinary vertical edge under
    // `flowchart TD`, konoma's default direction) made `slope3`'s `p` become `NaN`
    // (`Infinity * 0 - Infinity * 0`) — upstream's `Math.min` propagates that `NaN` through to a
    // `0` fallback (a flat tangent), which is the finite, correct answer below. This crate's
    // first port used `f64::min`, which *ignores* a `NaN` operand instead of propagating it
    // (`js_min`'s own doc has the full mechanism), so `slope3` returned `Infinity` and the
    // resulting bezier control points were `NaN` — an invalid SVG path whose line silently did
    // not draw at all (found by rendering a real `curve: monotoneX` flowchart and looking at it).
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&VERTICAL)),
        "M100,50C100,50 100,120 100,120C100,120 100,190 100,190"
    );
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&HORIZONTAL)),
        "M50,100C73.333,100 96.667,100 120,100C143.333,100 166.667,100 190,100"
    );
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&DUPLICATE)),
        "M0,0C13.333,13.333 26.667,26.667 40,40C53.333,53.333 66.667,66.667 80,80"
    );
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&RIGHT_ANGLE[..2])),
        "M0,0L60,0"
    );
    assert_eq!(
        edges::curve_monotone_x_path(&pts(&RIGHT_ANGLE[..1])),
        "M0,0"
    );
    assert_eq!(edges::curve_monotone_x_path(&[]), "");
}

#[test]
fn curve_monotone_y_matches_d3() {
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&RIGHT_ANGLE)),
        "M0,0C0,0 60,0 60,0C60,20 60,40 60,60"
    );
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&FOUR_POINT)),
        "M0,0C0,0 40,0 40,0C40,13.333 40,26.667 40,40C40,40 80,40 80,40"
    );
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&UNEVEN)),
        "M0,0C0,0 10,0 10,0C30,10 20,20 40,30C43.333,31.667 66.667,33.333 90,35"
    );
    assert_ne!(
        edges::curve_monotone_x_path(&pts(&UNEVEN)),
        edges::curve_monotone_y_path(&pts(&UNEVEN)),
        "monotoneX and monotoneY must draw differently — the whole point of the reflected axis"
    );
    // `VERTICAL`'s mirror: `monotoneY`'s reflected axis hits the same degeneracy on a
    // *horizontal* run instead of a vertical one — see `curve_monotone_x_matches_d3`'s own
    // comment on the exact bug this pins the fix for.
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&VERTICAL)),
        "M100,50C100,73.333 100,96.667 100,120C100,143.333 100,166.667 100,190"
    );
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&HORIZONTAL)),
        "M50,100C50,100 120,100 120,100C120,100 190,100 190,100"
    );
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&DUPLICATE)),
        "M0,0C13.333,13.333 26.667,26.667 40,40C53.333,53.333 66.667,66.667 80,80"
    );
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&RIGHT_ANGLE[..2])),
        "M0,0L60,0"
    );
    assert_eq!(
        edges::curve_monotone_y_path(&pts(&RIGHT_ANGLE[..1])),
        "M0,0"
    );
    assert_eq!(edges::curve_monotone_y_path(&[]), "");
}

#[test]
fn curve_bump_x_matches_d3() {
    assert_eq!(
        edges::curve_bump_x_path(&pts(&RIGHT_ANGLE)),
        "M0,0C30,0 30,0 60,0C60,0 60,60 60,60"
    );
    assert_eq!(
        edges::curve_bump_x_path(&pts(&FOUR_POINT)),
        "M0,0C20,0 20,0 40,0C40,0 40,40 40,40C60,40 60,40 80,40"
    );
    assert_eq!(
        edges::curve_bump_x_path(&pts(&UNEVEN)),
        "M0,0C5,0 5,0 10,0C25,0 25,30 40,30C65,30 65,35 90,35"
    );
    // Unlike every other curve in this module, `bumpX` draws a curve — not a straight `L` — even
    // between just two points: d3-shape's own `Bump.point` has no `case 2` that falls back to a
    // line (`edges.rs`'s own `curve_bump_x_path` doc).
    assert_eq!(
        edges::curve_bump_x_path(&pts(&RIGHT_ANGLE[..2])),
        "M0,0C30,0 30,0 60,0"
    );
    assert_eq!(
        edges::curve_bump_x_path(&pts(&VERTICAL)),
        "M100,50C100,50 100,120 100,120C100,120 100,190 100,190"
    );
    assert_eq!(
        edges::curve_bump_x_path(&pts(&HORIZONTAL)),
        "M50,100C85,100 85,100 120,100C155,100 155,100 190,100"
    );
    assert_eq!(
        edges::curve_bump_x_path(&pts(&DUPLICATE)),
        "M0,0C20,0 20,40 40,40C40,40 40,40 40,40C60,40 60,80 80,80"
    );
    assert_eq!(edges::curve_bump_x_path(&pts(&RIGHT_ANGLE[..1])), "M0,0");
    assert_eq!(edges::curve_bump_x_path(&[]), "");
}

#[test]
fn curve_bump_y_matches_d3() {
    assert_eq!(
        edges::curve_bump_y_path(&pts(&RIGHT_ANGLE)),
        "M0,0C0,0 60,0 60,0C60,30 60,30 60,60"
    );
    assert_eq!(
        edges::curve_bump_y_path(&pts(&FOUR_POINT)),
        "M0,0C0,0 40,0 40,0C40,20 40,20 40,40C40,40 80,40 80,40"
    );
    assert_eq!(
        edges::curve_bump_y_path(&pts(&UNEVEN)),
        "M0,0C0,0 10,0 10,0C10,15 40,15 40,30C40,32.5 90,32.5 90,35"
    );
    assert_ne!(
        edges::curve_bump_x_path(&pts(&UNEVEN)),
        edges::curve_bump_y_path(&pts(&UNEVEN)),
        "bumpX and bumpY must draw differently"
    );
    assert_eq!(
        edges::curve_bump_y_path(&pts(&RIGHT_ANGLE[..2])),
        "M0,0C0,0 60,0 60,0"
    );
    assert_eq!(
        edges::curve_bump_y_path(&pts(&VERTICAL)),
        "M100,50C100,85 100,85 100,120C100,155 100,155 100,190"
    );
    assert_eq!(
        edges::curve_bump_y_path(&pts(&HORIZONTAL)),
        "M50,100C50,100 120,100 120,100C120,100 190,100 190,100"
    );
    assert_eq!(
        edges::curve_bump_y_path(&pts(&DUPLICATE)),
        "M0,0C0,20 40,20 40,40C40,40 40,40 40,40C40,60 80,60 80,80"
    );
    assert_eq!(edges::curve_bump_y_path(&pts(&RIGHT_ANGLE[..1])), "M0,0");
    assert_eq!(edges::curve_bump_y_path(&[]), "");
}

/// `rounded` is mermaid's own curve, not d3-shape's — so what it is pinned against is mermaid's
/// own `edges.js::generateRoundedPath`, ported the same way (real function, run through Node,
/// same string convention) rather than hand-derived. `radius` is [`edges::CORNER_RADIUS`] (5),
/// the same value `Curve::path` calls this with — matching what `fix_corners` uses for every
/// other curve, per this module's own "why `radius` is a parameter" doc on `rounded_path`.
#[test]
fn rounded_curve_matches_mermaid() {
    let radius = edges::CORNER_RADIUS;
    assert_eq!(
        edges::rounded_path(&pts(&[(0.0, 0.0), (0.0, 40.0), (40.0, 40.0)]), radius),
        "M0,0L0,32.929Q0,40 7.071,40L40,40"
    );
    assert_eq!(
        edges::rounded_path(&pts(&UNEVEN), radius),
        "M0,0L5,0Q10,0 13.536,3.536L29.483,19.483Q40,30 54.799,31.48L90,35"
    );
    // A straight run (no bend at all — every point collinear) is left exactly straight: the
    // corner-detection angle is `π`, which trips `generateRoundedPath`'s own "too close to 180°"
    // guard, the same guard a real flowchart route can hit on an unbent middle waypoint.
    assert_eq!(
        edges::rounded_path(&pts(&[(0.0, 0.0), (50.0, 0.0), (100.0, 0.0)]), radius),
        "M0,0L50,0L100,0"
    );
    assert_eq!(
        edges::rounded_path(&pts(&RIGHT_ANGLE[..2]), radius),
        "M0,0L60,0",
        "two points is just a line, corner or not"
    );
    // `VERTICAL`/`HORIZONTAL` are themselves collinear runs (no bend), so — like the straight run
    // above — every corner-detection angle is `π` and nothing is rounded; `DUPLICATE` has a
    // zero-length segment at its middle point, which `generateRoundedPath`'s own `len1 < epsilon`
    // guard catches the same way.
    assert_eq!(
        edges::rounded_path(&pts(&VERTICAL), radius),
        "M100,50L100,120L100,190"
    );
    assert_eq!(
        edges::rounded_path(&pts(&HORIZONTAL), radius),
        "M50,100L120,100L190,100"
    );
    assert_eq!(
        edges::rounded_path(&pts(&DUPLICATE), radius),
        "M0,0L40,40L40,40L80,80"
    );
    assert_eq!(edges::rounded_path(&pts(&RIGHT_ANGLE[..1]), radius), "M0,0");
    assert_eq!(edges::rounded_path(&[], radius), "");
}

/// All 13 of mermaid's `flowchart.curve` spellings parse to their own, distinct [`Curve`] — the
/// mutation guard against `Curve::parse`'s match arms drifting out of sync with the enum (a copy-
/// pasted arm pointing at the wrong variant would make two names parse to the same curve and this
/// test would be the only thing that notices, since nothing else compares parse results against
/// each other).
#[test]
fn every_curve_name_parses_to_a_distinct_curve() {
    let names = [
        "basis",
        "linear",
        "step",
        "stepBefore",
        "stepAfter",
        "natural",
        "cardinal",
        "catmullRom",
        "monotoneX",
        "monotoneY",
        "bumpX",
        "bumpY",
        "rounded",
    ];
    let parsed: Vec<Curve> = names.iter().map(|s| Curve::parse(s)).collect();
    for (i, a) in parsed.iter().enumerate() {
        for (j, b) in parsed.iter().enumerate() {
            if i != j {
                assert_ne!(
                    a, b,
                    "{} and {} must not parse to the same Curve",
                    names[i], names[j]
                );
            }
        }
    }
}

/// The eight new curves draw eight different shapes for the same bent waypoints — the same
/// "must differ from each other" guard `step_variants_differ_from_each_other_and_match_d3` runs
/// for the first five, extended to the rest, over a point set with an actual bend (two points
/// would let several of these agree by accident: `curveLinear`-shaped coincidences already bit
/// this file once, `different_curves_draw_different_svg_path_data`'s own doc).
#[test]
fn the_eight_new_curves_draw_different_paths_from_each_other() {
    let p = pts(&UNEVEN);
    let named: Vec<(&str, String)> = vec![
        ("natural", edges::curve_natural_path(&p)),
        ("cardinal", edges::curve_cardinal_path(&p)),
        ("catmullRom", edges::curve_catmull_rom_path(&p)),
        ("monotoneX", edges::curve_monotone_x_path(&p)),
        ("monotoneY", edges::curve_monotone_y_path(&p)),
        ("bumpX", edges::curve_bump_x_path(&p)),
        ("bumpY", edges::curve_bump_y_path(&p)),
        ("rounded", edges::rounded_path(&p, edges::CORNER_RADIUS)),
    ];
    for i in 0..named.len() {
        for j in (i + 1)..named.len() {
            assert_ne!(
                named[i].1, named[j].1,
                "{} and {} must draw differently",
                named[i].0, named[j].0
            );
        }
    }
}

/// `Curve::parse(name).path(points)` reaches the exact free function this section's own
/// `_matches_d3`/`_matches_mermaid` tests already pinned against upstream — for every one of the
/// 13 names, not just the eight new ones.
///
/// This is not redundant with the `_matches_d3` tests above: those call `edges::curve_natural_path`
/// (etc.) **directly**, so a mistake in `Curve::parse`'s match arms or in `Curve::path`'s dispatch
/// — the wiring between a config string and the function that actually draws it — is invisible to
/// them. A mutation proved the gap real: swapping `Curve::path`'s `MonotoneX` arm to call
/// `curve_natural_path` instead of `curve_monotone_x_path` left every other test in this file
/// green, `curve_monotone_x_matches_d3` included, because that test never goes through
/// `Curve::path` at all. This test is the one built to catch exactly that swap.
type CurvePathFn = fn(&[Point]) -> String;

#[test]
fn curve_parse_and_path_reach_the_function_that_was_pinned_against_upstream() {
    let p = pts(&UNEVEN);
    let cases: &[(&str, CurvePathFn)] = &[
        ("basis", edges::curve_basis_path),
        ("linear", edges::polyline_path),
        ("natural", edges::curve_natural_path),
        ("cardinal", edges::curve_cardinal_path),
        ("catmullRom", edges::curve_catmull_rom_path),
        ("monotoneX", edges::curve_monotone_x_path),
        ("monotoneY", edges::curve_monotone_y_path),
        ("bumpX", edges::curve_bump_x_path),
        ("bumpY", edges::curve_bump_y_path),
    ];
    for (name, f) in cases {
        assert_eq!(
            Curve::parse(name).path(&p),
            f(&p),
            "Curve::parse(\"{name}\").path(...) must reach the same function {name} was pinned \
             against upstream with"
        );
    }
    // `rounded` takes a radius, so it is checked against `Curve::path`'s own hardcoded
    // `CORNER_RADIUS` argument rather than fitting the `fn(&[Point]) -> String` shape above.
    assert_eq!(
        Curve::parse("rounded").path(&p),
        edges::rounded_path(&p, edges::CORNER_RADIUS)
    );
    // `step`/`stepBefore`/`stepAfter` take a `t` argument `step_variants_differ_from_each_other_
    // and_match_d3` already pins by value; checked here for wiring completeness the same way.
    assert_eq!(Curve::parse("step").path(&p), edges::step_path(&p, 0.5));
    assert_eq!(
        Curve::parse("stepBefore").path(&p),
        edges::step_path(&p, 0.0)
    );
    assert_eq!(
        Curve::parse("stepAfter").path(&p),
        edges::step_path(&p, 1.0)
    );
}

/// The dispatch-completeness check above (`curve_parse_and_path_reach_the_function_that_was_
/// pinned_against_upstream`), but for the exact degenerate shape that shipped a real bug: a
/// vertical run of waypoints — `flowchart TD`'s ordinary look, konoma's default direction —
/// through `Curve::parse("monotoneX").path(...)`, the real config-to-render path, not the free
/// function directly. The bug this closes (`js_min`'s own doc has the mechanism) reached
/// production through exactly this call chain — `[ui] mermaid_curve = "monotoneX"` on a plain
/// `flowchart TD` — so the regression test for it has to go through the same chain, not just the
/// free function `curve_monotone_x_matches_d3` already pins directly.
type CurveDegenerateCase = (&'static str, &'static [(f64, f64)], &'static str);

#[test]
fn all_thirteen_curves_match_d3_or_mermaid_on_degenerate_points_through_curve_path() {
    let cases: &[CurveDegenerateCase] = &[
        (
            "basis",
            &VERTICAL,
            "M100,50L100,61.667C100,73.333 100,96.667 100,120\
         C100,143.333 100,166.667 100,178.333L100,190",
        ),
        ("linear", &VERTICAL, "M100,50 L100,120 L100,190"),
        // `step`/`stepBefore`/`stepAfter` genuinely diverge from raw d3 here — not a bug in
        // either implementation, and not related to the NaN fix this test exists for. d3's own
        // `Step.point` always emits two `lineTo` calls per point unconditionally (never checking
        // whether either has zero length), so a vertical run's raw d3 output carries redundant
        // same-coordinate legs (`edges::step_path`'s own module doc did not anticipate this —
        // it reasoned about the *deferred final leg* `curveStep` (t=0.5) leaves for `lineEnd`,
        // not about a *zero-dx segment* dropping a leg outright). konoma's own `step_path` skips
        // a leg whose two endpoints coincide (`EPS`-guarded), so it collapses straight to the
        // three real points instead. Both draw the *identical picture* — a zero-length line
        // segment is invisible in any renderer — so this is a cosmetic `d`-string difference,
        // not a rendering one, and out of scope for the NaN bug; flagged, not silently patched.
        ("step", &VERTICAL, "M100,50L100,120L100,190"),
        ("stepBefore", &VERTICAL, "M100,50L100,120L100,190"),
        ("stepAfter", &VERTICAL, "M100,50L100,120L100,190"),
        (
            "natural",
            &VERTICAL,
            "M100,50C100,73.333 100,96.667 100,120\
         C100,143.333 100,166.667 100,190",
        ),
        (
            "cardinal",
            &VERTICAL,
            "M100,50C100,50 100,96.667 100,120C100,143.333 100,190 100,190",
        ),
        (
            "catmullRom",
            &VERTICAL,
            "M100,50C100,50 100,96.667 100,120C100,143.333 100,190 100,190",
        ),
        (
            "monotoneX",
            &VERTICAL,
            "M100,50C100,50 100,120 100,120C100,120 100,190 100,190",
        ),
        (
            "monotoneY",
            &HORIZONTAL,
            "M50,100C50,100 120,100 120,100C120,100 190,100 190,100",
        ),
        (
            "bumpX",
            &VERTICAL,
            "M100,50C100,50 100,120 100,120C100,120 100,190 100,190",
        ),
        (
            "bumpY",
            &HORIZONTAL,
            "M50,100C50,100 120,100 120,100C120,100 190,100 190,100",
        ),
        ("rounded", &VERTICAL, "M100,50L100,120L100,190"),
    ];
    for (name, raw, expected) in cases {
        let p = pts(raw);
        assert_eq!(
            Curve::parse(name).path(&p),
            *expected,
            "Curve::parse(\"{name}\").path(...) on a degenerate point set"
        );
        assert!(
            !Curve::parse(name).path(&p).contains("NaN"),
            "{name} must not emit NaN through Curve::path"
        );
    }
}

/// **Mechanical**, not example-based: every one of the 13 curve names, over a battery of
/// degenerate point sets (vertical, horizontal, and every other axis-aligned-or-duplicate shape
/// below), must never emit `NaN` or `Infinity` into the `d` attribute it draws — regardless of
/// whether this crate happens to have a hand-written expected value for that exact combination.
/// The bug this exists to make impossible to reintroduce (`js_min`'s own doc has the mechanism)
/// was found by looking at a rendered picture, not by a test — this is the test that should have
/// caught it, and the reason it is swept over every curve rather than just `monotoneX`/`monotoneY`
/// is that the next curve to grow a `NaN` might not be either of those two.
#[test]
fn no_curve_ever_emits_nan_or_infinite_coordinates() {
    let names = [
        "basis",
        "linear",
        "step",
        "stepBefore",
        "stepAfter",
        "natural",
        "cardinal",
        "catmullRom",
        "monotoneX",
        "monotoneY",
        "bumpX",
        "bumpY",
        "rounded",
    ];
    // Every point set is deliberately degenerate in a different way: two axis-aligned runs (the
    // exact shape that broke `monotoneX`/`monotoneY`), a run with a duplicated interior point, a
    // single repeated point three times over, and a two-point vertical/horizontal edge (the
    // *most* common real shape of all — an ordinary two-node `flowchart TD` edge).
    let degenerate: &[&[(f64, f64)]] = &[
        &VERTICAL,
        &HORIZONTAL,
        &DUPLICATE,
        &[(50.0, 50.0), (50.0, 50.0), (50.0, 50.0)],
        &[(0.0, 0.0), (0.0, 100.0)],
        &[(0.0, 0.0), (100.0, 0.0)],
        &[(100.0, 100.0), (100.0, 100.0)],
    ];
    for name in names {
        for raw in degenerate {
            let p = pts(raw);
            let d = Curve::parse(name).path(&p);
            assert!(
                !d.contains("NaN") && !d.contains("inf") && !d.contains("Inf"),
                "{name} emitted a non-finite coordinate for {raw:?}: {d}"
            );
        }
    }
}

/// `Curve::rounds_corners` matches every released mermaid version's actual gate in `edges.js`:
/// `fixCorners` runs unconditionally, for **every** curve, `rounded` included on `develop` only
/// by an exemption added the same commit that introduced it (`Curve::rounds_corners`'s own doc
/// has the versioned evidence — `mermaid@11.4.1`/`mermaid@11.12.0` have no condition at all).
/// `Rounded` is the *only* curve this crate exempts, and only because it rounds every corner
/// itself at its own radius — running `fix_corners` first would double-round the same corner.
///
/// This test used to assert the opposite for `Linear`/`Step`/`StepBefore`/`StepAfter` — a rule
/// invented from how those curves *look* (chosen for a sharp angle, so surely nothing should
/// round it) rather than checked against upstream. It was wrong on both released versions
/// checked; the corrected list below is every curve *but* `Rounded`.
#[test]
fn rounds_corners_matches_mermaids_fix_corners_gate() {
    for curve in [
        Curve::Basis,
        Curve::Linear,
        Curve::Step,
        Curve::StepBefore,
        Curve::StepAfter,
        Curve::Natural,
        Curve::Cardinal,
        Curve::CatmullRom,
        Curve::MonotoneX,
        Curve::MonotoneY,
        Curve::BumpX,
        Curve::BumpY,
    ] {
        assert!(curve.rounds_corners(), "{curve:?} must run fix_corners");
    }
    assert!(
        !Curve::Rounded.rounds_corners(),
        "Curve::Rounded must not run fix_corners — it rounds corners itself"
    );
}

// ---------------------------------------------------------------------------------------------
// 10-c. `%%{init}%%`'s `flowchart.curve` — the priority order `spec_of`'s own doc states:
// `linkStyle <n> interpolate` > `linkStyle default interpolate` > `%%{init}%%`'s `flowchart.curve`
// > `[ui] mermaid_curve`.
// ---------------------------------------------------------------------------------------------

/// `%%{init: {"flowchart": {"curve": "linear"}}}%%` overrides `[ui] mermaid_curve` — the weakest
/// link in the priority chain beating the weaker-still config default.
#[test]
fn init_directive_curve_overrides_the_config_default() {
    let d = laid_out_curve(
        "%%{init: {\"flowchart\": {\"curve\": \"linear\"}}}%%\nflowchart TD\n  A --> B",
        "step",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Linear,
        "the init directive must win over ui.mermaid_curve"
    );
}

/// An edge's own `linkStyle interpolate` still wins over `%%{init}%%` — the strongest link in the
/// chain beating the middle one, with a config default that agrees with neither so the test
/// cannot pass by two of the three coinciding.
#[test]
fn link_style_interpolate_overrides_init_directive_curve() {
    let d = laid_out_curve(
        "%%{init: {\"flowchart\": {\"curve\": \"linear\"}}}%%\n\
         flowchart TD\n  A --> B\n  linkStyle 0 interpolate step",
        "basis",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Step,
        "linkStyle interpolate must win over both the init directive and the config default"
    );
}

/// `linkStyle default interpolate` sits between the two: it loses to this edge's own indexed
/// `linkStyle`, but beats the init directive for every edge that names no index of its own.
#[test]
fn link_style_default_interpolate_sits_between_init_and_indexed_link_style() {
    let d = laid_out_curve(
        "%%{init: {\"flowchart\": {\"curve\": \"linear\"}}}%%\n\
         flowchart TD\n  A --> B\n  C --> D\n  \
         linkStyle default interpolate step\n  linkStyle 1 interpolate stepBefore",
        "basis",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Step,
        "linkStyle default interpolate must win over the init directive for an edge with no index override"
    );
    assert_eq!(
        d.edges[1].curve,
        Curve::StepBefore,
        "linkStyle 1's own interpolate must still win over linkStyle default"
    );
}

/// `%%{init: {"theme": "dark"}}%%` — a directive that names no `flowchart.curve` at all — is still
/// completely ignored for curve purposes, exactly as it always was (the corpus already has this
/// exact shape, and `docs/STATUS.md`'s "既定の出力は変わらない" invariant is precisely this: only
/// `flowchart.curve` reaching in is new, every other key must draw exactly what it drew before
/// this crate started reading `%%{init}%%` at all).
#[test]
fn init_directive_naming_only_theme_still_does_not_touch_curve() {
    let d = laid_out_curve(
        "%%{init: {\"theme\": \"dark\"}}%%\nflowchart TD\n  A --> B",
        "step",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Step,
        "a theme-only init directive must leave the config default untouched"
    );
}

/// Quote style, whitespace, multi-line bodies and key order are all noise `init_flowchart_curve`
/// has to see through — the exact axes the task called out. Every source below sets the same
/// `flowchart.curve: linear` and must resolve to the same [`Curve::Linear`].
#[test]
fn init_directive_curve_survives_formatting_variation() {
    let sources = [
        // Double-quoted, single line — the canonical shape.
        "%%{init: {\"flowchart\": {\"curve\": \"linear\"}}}%%\nflowchart TD\n  A --> B",
        // Single-quoted — mermaid's own examples use this spelling just as often.
        "%%{init: {'flowchart': {'curve': 'linear'}}}%%\nflowchart TD\n  A --> B",
        // Multi-line, indented, mixed quoting.
        "%%{init: {\n  \"flowchart\": {\n    'curve': \"linear\"\n  }\n}}%%\n\
         flowchart TD\n  A --> B",
        // `flowchart` is not the first key in the init object.
        "%%{init: {\"theme\": \"dark\", \"flowchart\": {\"curve\": \"linear\"}}}%%\n\
         flowchart TD\n  A --> B",
        // `curve` is not the first key inside `flowchart`.
        "%%{init: {\"flowchart\": {\"htmlLabels\": false, \"curve\": \"linear\"}}}%%\n\
         flowchart TD\n  A --> B",
        // Bare (unquoted) keys and value — valid JSON5, which is what mermaid's directive body
        // actually is.
        "%%{init: {flowchart: {curve: linear}}}%%\nflowchart TD\n  A --> B",
        // No space after the colons.
        "%%{init:{\"flowchart\":{\"curve\":\"linear\"}}}%%\nflowchart TD\n  A --> B",
    ];
    for src in sources {
        let d = laid_out_curve(src, "basis");
        assert_eq!(
            d.edges[0].curve,
            Curve::Linear,
            "must resolve to Linear regardless of formatting: {src}"
        );
    }
}

/// A malformed `%%{init}%%` — bad JSON, a `curve` of the wrong type, `flowchart` misplaced — must
/// never crash, and must fall back all the way to the config default, exactly like an unrecognised
/// curve *name* already does (PRD design principle #3: an unknown or malformed value never blocks
/// a render).
#[test]
fn malformed_init_directive_falls_back_without_crashing() {
    let sources = [
        // `curve` is a number, not a string.
        "%%{init: {\"flowchart\": {\"curve\": 5}}}%%\nflowchart TD\n  A --> B",
        // `curve` is itself an object.
        "%%{init: {\"flowchart\": {\"curve\": {\"x\": 1}}}}%%\nflowchart TD\n  A --> B",
        // `curve` is an array.
        "%%{init: {\"flowchart\": {\"curve\": [\"linear\"]}}}%%\nflowchart TD\n  A --> B",
        // `flowchart` is a string, not an object — nothing to look a `curve` up inside.
        "%%{init: {\"flowchart\": \"oops\"}}%%\nflowchart TD\n  A --> B",
        // The directive's own JSON never closes.
        "%%{init: {\"flowchart\": {\"curve\": \"linear\"\nflowchart TD\n  A --> B",
        // `curve` at the top level, not nested under `flowchart` at all.
        "%%{init: {\"curve\": \"linear\"}}%%\nflowchart TD\n  A --> B",
        // Empty object.
        "%%{init: {}}%%\nflowchart TD\n  A --> B",
    ];
    for src in sources {
        let d = laid_out_curve(src, "step");
        assert_eq!(
            d.edges[0].curve,
            Curve::Step,
            "a malformed init directive must fall back to the config default: {src}"
        );
        let svg = render_curve(src, "dark", "step")
            .unwrap_or_else(|e| panic!("must still render despite a malformed directive: {e}"));
        assert!(svg.contains("<svg"));
    }
}

/// CJK labels alongside a real `%%{init}%%` `flowchart.curve` — the one combination this section's
/// other tests never exercise together, and the exact kind of "two features nobody tried at once"
/// gap `CLAUDE.md`'s testing policy calls out by name.
#[test]
fn cjk_labels_render_with_an_init_directive_curve() {
    let src = "%%{init: {\"flowchart\": {\"curve\": \"monotoneX\"}}}%%\n\
               flowchart TD\n  A[ツリー] -->|Enter| B{種別を解決}\n  B -->|画像| C[全画面プレビュー]";
    let d = laid_out_curve(src, "basis");
    assert_eq!(d.edges[0].curve, Curve::MonotoneX);
    let svg = render_curve(src, "dark", "basis").unwrap_or_else(|e| panic!("must render: {e}"));
    assert!(svg.contains("<svg"));
}

/// The wiring reaches all the way to the emitted `d=` attribute, over a corpus source with a real
/// bend (`long-edge`'s `A --> E` spans multiple ranks, so dagre gives it waypoints in between —
/// on two points `curve_basis_path` and `polyline_path` already agree, which would make this test
/// pass by accident).
#[test]
fn different_curves_draw_different_svg_path_data() {
    let (_, src) = CORPUS
        .iter()
        .find(|(name, _)| *name == "long-edge")
        .expect("corpus must still have `long-edge`");
    let basis = render_curve(src, "dark", "basis").expect("renders");
    let linear = render_curve(src, "dark", "linear").expect("renders");
    let step = render_curve(src, "dark", "step").expect("renders");
    assert_ne!(
        basis, linear,
        "a bent edge must draw differently under linear"
    );
    assert_ne!(basis, step, "a bent edge must draw differently under step");
    assert_ne!(
        linear, step,
        "linear and step must draw differently from each other too"
    );
}

/// CJK labels — konoma's standing gap in test coverage (`CLAUDE.md`'s own reminder) — must render
/// under every implemented curve without panicking.
#[test]
fn cjk_labels_render_under_every_curve() {
    let src = "flowchart TD\n  A[ツリー] -->|Enter| B{種別を解決}\n  \
               B -->|画像| C[全画面プレビュー]\n  B -->|テキスト| D[窓読み]\n  D --> A";
    for curve in [
        "basis",
        "linear",
        "step",
        "stepBefore",
        "stepAfter",
        "natural",
        "cardinal",
        "catmullRom",
        "monotoneX",
        "monotoneY",
        "bumpX",
        "bumpY",
        "rounded",
    ] {
        let svg = render_curve(src, "dark", curve).unwrap_or_else(|e| panic!("{curve}: {e}"));
        assert!(
            svg.contains("<svg"),
            "{curve}: CJK labels must still render"
        );
    }
}

// ---------------------------------------------------------------------------------------------
// 10-d. Coverage audit (2026-08-29): gaps found while auditing the curve feature's test coverage
// against a 35-point checklist. Each test below closes exactly one point the checklist named —
// see the doc comment for which.
// ---------------------------------------------------------------------------------------------

/// Checklist A4: an empty or whitespace-only curve name is exactly as unrecognised as any other
/// bad spelling — `Curve::parse` has no special case for either, so both fall through its
/// catch-all arm to `Curve::Basis`, the same fallback `unknown_curve_falls_back_to_basis_without_
/// crashing` already pins for `""`. That test never tried a *whitespace* string (as opposed to a
/// truly empty one), which is the shape checked here, both directly and through the full
/// `[ui] mermaid_curve` → render pipeline.
#[test]
fn whitespace_only_curve_name_falls_back_to_basis() {
    assert_eq!(Curve::parse("   "), Curve::Basis);
    assert_eq!(Curve::parse("\t"), Curve::Basis);
    assert_eq!(Curve::parse("\n"), Curve::Basis);

    let d = laid_out_curve("flowchart TD\n  A --> B", "   ");
    assert_eq!(d.edges[0].curve, Curve::Basis);

    let svg = render_curve("flowchart TD\n  A --> B", "dark", "  ")
        .expect("a blank curve name must still render, as Curve::Basis");
    assert!(svg.contains("<svg"));
}

/// Checklist B11: mermaid re-applies each `%%{init}%%` directive over its running config in
/// source order, so a *later* directive's `flowchart.curve` overrides an earlier one's —
/// `preprocess::strip_directives`'s own doc states this as the intended behaviour, but no
/// existing test actually put two init directives naming `flowchart.curve` in one source.
#[test]
fn a_second_init_directive_overrides_the_first_ones_curve() {
    let d = laid_out_curve(
        "%%{init: {\"flowchart\": {\"curve\": \"linear\"}}}%%\n\
         %%{init: {\"flowchart\": {\"curve\": \"step\"}}}%%\n\
         flowchart TD\n  A --> B",
        "basis",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Step,
        "the second init directive must win over the first"
    );
}

/// Checklist B12: an `%%{init}%%` directive is not required to sit before the diagram's header —
/// `preprocess::strip_directives` scans the whole source rather than assuming a fixed position.
/// Every other init-directive test in this section puts the directive first; this one puts it
/// after the header and after an edge, which no existing test does.
#[test]
fn an_init_directive_after_the_header_still_sets_the_curve() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  \
         %%{init: {\"flowchart\": {\"curve\": \"linear\"}}}%%\n  B --> C",
        "basis",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Linear,
        "a mid-diagram init directive must still set the chart-wide curve"
    );
    assert_eq!(d.edges[1].curve, Curve::Linear);
}

/// Checklist C14 for `interpolate` specifically: `linkStyle 0,1,2 interpolate <curve>` — several
/// indices sharing one `interpolate` argument. `link_style_with_multiple_indices_reaches_every_
/// named_edge` already proves this shape for a plain style declaration; this is the same proof
/// for `interpolate`, which that test never exercised.
#[test]
fn link_style_interpolate_with_multiple_indices_reaches_every_named_edge() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  B --> C\n  C --> D\n  D --> E\n  \
         linkStyle 0,1,2 interpolate linear",
        "basis",
    );
    assert_eq!(d.edges.len(), 4);
    for i in 0..3 {
        assert_eq!(
            d.edges[i].curve,
            Curve::Linear,
            "edge {i} is named by `linkStyle 0,1,2 interpolate linear`"
        );
    }
    assert_eq!(
        d.edges[3].curve,
        Curve::Basis,
        "edge 3 (D->E) was not named, and must keep the chart-wide default"
    );
}

/// Checklist C16: `linkStyle` naming an index past the last edge must not crash, and must leave
/// every real edge untouched. The adversarial sweep in `flowchart/tests.rs` already proves the
/// *parser* survives `linkStyle 99 stroke:red` on a source with no edges at all; this proves the
/// *render* pipeline does too, on a chart that has a real edge, with `interpolate` specifically,
/// and that the phantom index changes nothing real.
#[test]
fn link_style_interpolate_naming_an_index_past_the_last_edge_does_not_crash() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  linkStyle 5 interpolate linear",
        "step",
    );
    assert_eq!(d.edges.len(), 1);
    assert_eq!(
        d.edges[0].curve,
        Curve::Step,
        "an out-of-range linkStyle index must touch no real edge"
    );
    let svg = render_curve(
        "flowchart TD\n  A --> B\n  linkStyle 5 interpolate linear",
        "dark",
        "step",
    )
    .expect("an out-of-range linkStyle index must not crash the render");
    assert!(svg.contains("<svg"));
}

/// Checklist C17: `linkStyle 0 interpolate <curve> <styles>` — an `interpolate` argument followed
/// by ordinary style declarations on the same statement — must apply *both*: the curve reaches
/// `PlacedEdge::curve` and the style reaches `PlacedEdge::style`, from one parse of one
/// statement. `flowchart::tests::link_style_reads_its_index_list_its_default_form_and_its_
/// interpolation` already proves the *parser* keeps both fields distinct; this is the render-level
/// proof that neither field's cascade clobbers the other's.
#[test]
fn link_style_interpolate_and_stroke_on_the_same_statement_both_apply() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  linkStyle 0 interpolate linear stroke:#1f6feb",
        "basis",
    );
    assert_eq!(d.edges[0].curve, Curve::Linear, "the curve must apply");
    assert_eq!(
        d.edges[0]
            .style
            .as_ref()
            .expect("the style must apply too")
            .stroke
            .as_deref(),
        Some("#1f6feb")
    );
}

/// Checklist G31: `mermaid_curve` reaches only a flowchart's own edges. `spec_of`'s own doc states
/// that every other diagram kind's `SpecEdge::curve` is hardcoded to `Curve::Basis`, and the real
/// dispatcher (`preview::markdown::mermaid_to_svg_reason_flow`) does not even thread a `curve`
/// argument through to any other renderer's entry point. This is the end-to-end proof, through the
/// exact function the app calls (`mermaid_to_svg_curve`), for three diagram kinds.
#[test]
fn non_flowchart_diagrams_ignore_mermaid_curve() {
    use crate::preview::markdown::mermaid_to_svg_curve;
    let cases = [
        "stateDiagram-v2\n  [*] --> A\n  A --> B\n  B --> [*]",
        "classDiagram\n  A --|> B",
        "erDiagram\n  A ||--o{ B : has",
    ];
    for src in cases {
        let basis = mermaid_to_svg_curve(src, "dark", "basis").expect("must render");
        let step = mermaid_to_svg_curve(src, "dark", "step").expect("must render");
        assert_eq!(
            basis, step,
            "a non-flowchart diagram must draw identically regardless of mermaid_curve: {src}"
        );
    }
}

/// Checklist H34: `curve` still reaches an edge that names a subgraph as one of its own ends —
/// the `edges::End::Cluster` path through `route`, which no existing curve test exercises (every
/// other curve test in this section connects two ordinary nodes). `PlacedEdge::curve` is carried
/// unconditionally regardless of which `End` variant routed the edge (`lay_out_spec`'s own
/// `curve: edge.curve` push), so this is the proof at the level a reader would actually see: a
/// diagram with an edge crossing a subgraph's frame must still draw visibly differently under two
/// different curves, the same way `different_curves_draw_different_svg_path_data` proves it for
/// an ordinary bent edge.
#[test]
fn curve_reaches_an_edge_that_crosses_a_subgraph_frame() {
    let src = "flowchart LR\n  subgraph one [First]\n    A --> B\n  end\n  \
               subgraph two [Second]\n    C --> D\n  end\n  one --> two\n  E --> one";
    let d = laid_out_curve(src, "step");
    assert!(
        !d.clusters.is_empty(),
        "the source must actually produce a subgraph frame"
    );
    for e in &d.edges {
        assert_eq!(
            e.curve,
            Curve::Step,
            "every edge must resolve to the configured curve, cluster-bound or not"
        );
    }
    let basis = render_curve(src, "dark", "basis").expect("renders");
    let step = render_curve(src, "dark", "step").expect("renders");
    assert_ne!(
        basis, step,
        "a subgraph-bearing diagram must still draw visibly differently under two curves"
    );
}

/// Checklist H35: the legacy `graph` keyword is the same grammar as `flowchart`
/// (`flowchart/parser.rs`'s header parsing accepts both), so `curve` must resolve through it
/// identically — checked directly rather than assumed, since every other curve test in this file
/// spells the keyword `flowchart`. Both the config-default path and `linkStyle ... interpolate`
/// are checked, not just one.
#[test]
fn curve_resolves_identically_under_the_legacy_graph_keyword() {
    let flowchart = laid_out_curve("flowchart LR\n  A --> B", "monotoneX");
    let graph = laid_out_curve("graph LR\n  A --> B", "monotoneX");
    assert_eq!(flowchart.edges[0].curve, Curve::MonotoneX);
    assert_eq!(graph.edges[0].curve, Curve::MonotoneX);

    let flowchart2 = laid_out_curve(
        "flowchart LR\n  A --> B\n  linkStyle 0 interpolate step",
        "basis",
    );
    let graph2 = laid_out_curve(
        "graph LR\n  A --> B\n  linkStyle 0 interpolate step",
        "basis",
    );
    assert_eq!(flowchart2.edges[0].curve, Curve::Step);
    assert_eq!(graph2.edges[0].curve, Curve::Step);
}

// ---------------------------------------------------------------------------------------------
// 10-e. Independent second audit (2026-08-29): every existing degenerate-point/NaN-safety test
// above (`no_curve_ever_emits_nan_or_infinite_coordinates`,
// `all_thirteen_curves_match_d3_or_mermaid_on_degenerate_points_through_curve_path`) runs the 13
// curves over *hand-picked* point sets (`VERTICAL`, `HORIZONTAL`, `UNEVEN`, `DUPLICATE`, ...).
// That is exactly the shape of gap this feature has bitten konoma with once already: a synthetic
// point list proved the arithmetic safe while the *route dagre actually produces* for a real
// diagram — a self-loop, an edge crossing a subgraph frame, a parallel `A & B --> C & D` fan —
// never went through it, because those routes are built by `route`/`clip`'s own dedupe-and-insert
// logic (`edges.rs`'s module docs, steps 1-3) before a single coordinate ever reaches
// `Curve::path`. Nothing in this file had, until now, run the *specification corpus* (`CORPUS`,
// chosen from real diagram shapes — memory `corpus-from-spec-not-from-bugs`) across *every* curve
// name; every existing corpus-based curve test picks one corpus entry (`"long-edge"`) and at most
// three curves (`different_curves_draw_different_svg_path_data`), or one curve name across the
// whole corpus (`corpus_golden`, always `Curve::Basis`). This closes that cross product.
// ---------------------------------------------------------------------------------------------

/// Every entry in [`CORPUS`] — self-loop, edges crossing a subgraph frame both from inside and
/// from outside (`subgraph-bypass`, `subgraph-endpoint`), the `&`-group fan-out (`amp-chain`),
/// CJK labels, and the `classDef`/`linkStyle` cascade — run through **every** one of the 13 curve
/// names. Each combination must render, must contain no `NaN`/`Infinity` coordinate, must come
/// out a finite, positive size, and must actually rasterise — the same bar
/// `awkward_sources_produce_a_diagram_or_an_error_and_never_a_panic` sets for the default curve
/// alone, swept here over the full curve set instead.
///
/// Also covers the two structural cases no [`CORPUS`] entry has at all: a chart with nodes but
/// **zero** edges (so `Curve::path` is never even called — `spec_of`'s edge loop must still not
/// choke on an empty iterator, for every curve name it is handed) and a single node with no edges.
#[test]
fn every_corpus_source_survives_every_curve() {
    if !text_metrics::fonts_available() {
        return;
    }
    let curves = [
        "basis",
        "linear",
        "step",
        "stepBefore",
        "stepAfter",
        "natural",
        "cardinal",
        "catmullRom",
        "monotoneX",
        "monotoneY",
        "bumpX",
        "bumpY",
        "rounded",
    ];
    let extra: &[(&str, &str)] = &[
        ("zero-edges", "flowchart TD\n  A[one]\n  B[two]\n  C[three]"),
        ("single-node", "flowchart TD\n  A[Solo]"),
    ];
    for (name, src) in CORPUS.iter().chain(extra) {
        for curve in curves {
            let svg = render_curve(src, "dark", curve)
                .unwrap_or_else(|e| panic!("{name} under {curve}: must render: {e}"));
            assert!(
                !svg.contains("NaN") && !svg.contains("inf") && !svg.contains("Inf"),
                "{name} under {curve}: emitted a non-finite coordinate: {svg}"
            );
            let d = laid_out_curve(src, curve);
            assert!(
                d.width.is_finite() && d.height.is_finite() && d.width > 0.0 && d.height > 0.0,
                "{name} under {curve}: {}x{} is not a drawable size",
                num(d.width),
                num(d.height)
            );
            assert!(
                crate::preview::svg::rasterize_bytes(svg.as_bytes(), FsPath::new("m.svg"), 300)
                    .is_some(),
                "{name} under {curve}: the output did not rasterise"
            );
        }
    }
}

/// A far larger and more cyclic graph than anything in [`CORPUS`] (whose entries are all a
/// handful of edges) — a long rank chain closed into a cycle, and a chain of nested subgraphs —
/// run through every curve. The point sets a curve function sees here (many more waypoints per
/// edge from the extra ranks, more coincident-rank runs) are shaped differently from any
/// [`CORPUS`] entry's, which matters because the one real curve bug this crate has shipped
/// (`js_min`'s own doc, the `monotoneX`/vertical-run `NaN`) was found on a real rendered diagram,
/// not on a synthetic point list — so this is deliberately a *diagram*, built the way
/// `awkward_sources_produce_a_diagram_or_an_error_and_never_a_panic` builds its `wide`/`deep`
/// sources, rather than another hand-picked `&[Point]`.
#[test]
fn a_large_cyclic_and_deeply_nested_graph_survives_every_curve() {
    if !text_metrics::fonts_available() {
        return;
    }
    let mut wide = String::from("flowchart LR\n");
    for i in 0..40 {
        wide.push_str(&format!("  n{i} --> n{}\n", i + 1));
    }
    wide.push_str("  n0 --> n40\n  n40 --> n0\n");

    let mut nested = String::from("flowchart TD\n");
    for i in 0..8 {
        nested.push_str(&format!("  subgraph s{i} [Level {i}]\n"));
    }
    nested.push_str("  A --> B\n");
    for _ in 0..8 {
        nested.push_str("  end\n");
    }
    nested.push_str("  s0 --> C\n  C --> s7\n");

    let curves = [
        "basis",
        "linear",
        "step",
        "stepBefore",
        "stepAfter",
        "natural",
        "cardinal",
        "catmullRom",
        "monotoneX",
        "monotoneY",
        "bumpX",
        "bumpY",
        "rounded",
    ];
    for (label, src) in [
        ("wide-cycle", wide.as_str()),
        ("deep-nested", nested.as_str()),
    ] {
        for curve in curves {
            let svg = render_curve(src, "dark", curve)
                .unwrap_or_else(|e| panic!("{label} under {curve}: must render: {e}"));
            assert!(
                !svg.contains("NaN") && !svg.contains("inf") && !svg.contains("Inf"),
                "{label} under {curve}: emitted a non-finite coordinate"
            );
        }
    }
}

/// A second `linkStyle <n> interpolate` statement naming the **same** index as an earlier one:
/// mermaid re-applies each statement over its running config in source order (the same rule
/// `a_second_init_directive_overrides_the_first_ones_curve` already pins for `%%{init}%%`), so the
/// later one must win. `spec_of`'s `indexed_interpolate` picks this with `.filter_map(...)
/// .next_back()` over every matching `LinkStyle` — a real, distinct code path (it only does
/// anything different from `.next()` when more than one `LinkStyle` matches the same index) that
/// no existing test ever gives more than one matching statement to: every other `linkStyle
/// interpolate` test in this file names a given index exactly once.
#[test]
fn a_second_link_style_interpolate_on_the_same_index_overrides_the_first() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> B\n  \
         linkStyle 0 interpolate step\n  linkStyle 0 interpolate linear",
        "basis",
    );
    assert_eq!(
        d.edges[0].curve,
        Curve::Linear,
        "a later linkStyle 0 interpolate must override an earlier one naming the same index"
    );

    // The same rule for `linkStyle default interpolate`, repeated.
    let d2 = laid_out_curve(
        "flowchart TD\n  A --> B\n  \
         linkStyle default interpolate step\n  linkStyle default interpolate linear",
        "basis",
    );
    assert_eq!(
        d2.edges[0].curve,
        Curve::Linear,
        "a later linkStyle default interpolate must override an earlier one"
    );
}

// ---------------------------------------------------------------------------------------------
// 10-f. Coverage audit follow-up (2026-08-29): two of the three items the audit flagged as
// unverified. `mermaid_curve`'s interaction with `mermaid_theme`/`mermaid_rows`/`svg_max_px` is
// finished here for `mermaid_theme` (both knobs are plain function parameters at this level) and
// in `app/tests.rs` for `mermaid_rows`/`svg_max_px` (which only exist as `App`/`[ui]` config, not
// as parameters `render_curve`/`mermaid_to_svg_curve` ever take). The third item — text mode never
// even reaching curve resolution — is also in `app/tests.rs`, next to the existing text-mode test.
// ---------------------------------------------------------------------------------------------

/// `[ui] mermaid_curve` and `[ui] mermaid_theme` sit on independent axes: changing one must never
/// move so much as a byte of what the other is responsible for. Checked both directions, so
/// neither can hide behind the other:
///
/// 1. holding theme fixed, every curve must draw the exact same colour-bearing attributes
///    (`fill="…"`/`stroke="…"`) — only the path/label geometry may move;
/// 2. holding curve fixed at something other than the default `basis`, every theme must draw the
///    exact same geometry — only colour may move.
///
/// Direction 2 is the gap `mermaid_themes_change_colours_but_never_font_metrics` (`markdown.rs`)
/// leaves open: that test always renders through `mermaid_to_svg`, which is `render_curve(...,
/// "basis")` by definition, so it has never actually exercised a non-default curve at all.
#[test]
fn mermaid_curve_and_mermaid_theme_are_independent_axes() {
    let (_, src) = CORPUS
        .iter()
        .find(|(name, _)| *name == "long-edge")
        .expect("corpus must still have `long-edge`");

    fn color_attrs(svg: &str) -> Vec<&str> {
        svg.split_whitespace()
            .filter(|w| w.starts_with("fill=\"") || w.starts_with("stroke=\""))
            .collect()
    }
    let geometry_of = |svg: &str| -> String {
        svg.split_whitespace()
            .filter(|w| !w.starts_with("fill=") && !w.starts_with("stroke=\""))
            .collect::<Vec<_>>()
            .join(" ")
    };

    // 1. Fixed theme, varying curve.
    let basis = render_curve(src, "dark", "basis").expect("renders");
    for curve in ["linear", "step", "monotoneX"] {
        let other = render_curve(src, "dark", curve).expect("renders");
        assert_eq!(
            color_attrs(&basis),
            color_attrs(&other),
            "curve {curve} must not move a single colour attribute away from the basis render"
        );
        assert_ne!(
            basis, other,
            "curve {curve} must still change something (the path data) — otherwise this \
             comparison is vacuous"
        );
    }

    // 2. Fixed curve (non-default), varying theme.
    let linear_dark = render_curve(src, "dark", "linear").expect("renders");
    let base_geometry = geometry_of(&linear_dark);
    for theme in ["light", "modern", "classic", "mermaid", "forest", "neutral"] {
        let other = render_curve(src, theme, "linear").expect("renders");
        assert_eq!(
            base_geometry,
            geometry_of(&other),
            "theme {theme} moved curve=\"linear\" geometry, not just colour"
        );
        assert_ne!(
            linear_dark, other,
            "theme {theme} must still change colour — otherwise this comparison is vacuous"
        );
    }
}

/// A hand-built two-point-or-more edge in `curve`, for the geometry tests above — the same shape
/// [`chart::rule`] builds for a chart's rule line, minus the theme/tip decisions this section
/// does not care about.
fn bent_edge(points: Vec<Point>, curve: Curve) -> PlacedEdge {
    PlacedEdge {
        from: "a".to_string(),
        to: "b".to_string(),
        points,
        gaps: Vec::new(),
        tip_start: Tip::None,
        tip_end: Tip::None,
        stroke: Stroke::Normal,
        label: None,
        start_label: None,
        end_label: None,
        badge: None,
        series: None,
        straight: false,
        overlay: false,
        style: None,
        curve,
        tip_matches_line: false,
    }
}

// ---------------------------------------------------------------------------------------------
// 10-g. Coverage audit follow-up (2026-08-29), item 2: `linkStyle <n>`'s index over **parallel**
// edges — more than one edge between the same node pair, self-loops included. `spec_of` resolves
// `linkStyle` purely from `chart.edges.iter().enumerate()` (`mod.rs`'s own comment: "`linkStyle`
// indices are positions in `Flowchart::edges`... exactly this iterator's index"), i.e. declaration
// order, before any layout ever runs — but nothing in this file had checked that against a source
// where two edges share both endpoints, the one shape where a bug that resolved the index against
// *layout* order instead (e.g. edges sorted by rank, or self-loops moved to the end of the list —
// both real things a routing pass could plausibly do) would be invisible on every existing test,
// since every existing test's edges are already distinguishable by their `(from, to)` pair alone.
//
// Each test below tells two same-pair edges apart by a distinct `linkStyle`-free discriminator
// (the edge's own label text), so it never has to *assume* `Diagram::edges` preserves declaration
// order — it looks each edge up by what it says, not by where it landed in the output `Vec`.
// ---------------------------------------------------------------------------------------------

/// The label text of an edge, or `""` if it carries none — the discriminator every test in this
/// section uses instead of trusting `d.edges`' own order.
fn edge_label_text(e: &PlacedEdge) -> String {
    e.label
        .as_ref()
        .map(|l| l.label.lines.join("\n"))
        .unwrap_or_default()
}

/// Two ordinary parallel `A --> B` edges, told apart by label: `linkStyle 0` must land on the
/// first-declared one (labelled `x`) and `linkStyle 1` on the second (labelled `y`) — never the
/// other way around, and never both on the same edge.
#[test]
fn link_style_index_targets_the_declared_edge_among_parallel_edges() {
    let d = laid_out_curve(
        "flowchart TD\n  A -->|x| B\n  A -->|y| B\n  \
         linkStyle 0 interpolate linear\n  linkStyle 1 interpolate step",
        "basis",
    );
    let x = d
        .edges
        .iter()
        .find(|e| edge_label_text(e) == "x")
        .expect("the \"x\"-labelled edge must exist");
    let y = d
        .edges
        .iter()
        .find(|e| edge_label_text(e) == "y")
        .expect("the \"y\"-labelled edge must exist");
    assert_eq!(
        x.curve,
        Curve::Linear,
        "linkStyle 0 must land on the first-declared A->B edge (labelled x)"
    );
    assert_eq!(
        y.curve,
        Curve::Step,
        "linkStyle 1 must land on the second-declared A->B edge (labelled y), not the first"
    );
}

/// The same proof over three parallel edges instead of two, so an off-by-one shift (an index
/// resolved one position early or late) cannot accidentally still land on the intended edge the
/// way it might by luck with only two.
#[test]
fn link_style_index_targets_the_declared_edge_among_three_parallel_edges() {
    let d = laid_out_curve(
        "flowchart TD\n  A -->|x| B\n  A -->|y| B\n  A -->|z| B\n  \
         linkStyle 0 interpolate linear\n  linkStyle 1 interpolate step\n  \
         linkStyle 2 interpolate monotoneX",
        "basis",
    );
    let find = |name: &str| {
        d.edges
            .iter()
            .find(|e| edge_label_text(e) == name)
            .unwrap_or_else(|| panic!("edge labelled {name} must exist"))
    };
    assert_eq!(
        find("x").curve,
        Curve::Linear,
        "linkStyle 0 -> first-declared (x)"
    );
    assert_eq!(
        find("y").curve,
        Curve::Step,
        "linkStyle 1 -> second-declared (y)"
    );
    assert_eq!(
        find("z").curve,
        Curve::MonotoneX,
        "linkStyle 2 -> third-declared (z)"
    );
}

/// A self-loop (`A --> A`) declared **before** two parallel `A --> B` edges must not shift the
/// indices those later edges' own `linkStyle` statements name: edge 0 is the loop, so `linkStyle
/// 1`/`linkStyle 2` must still land on `x`/`y`, not on the loop and not on each other.
#[test]
fn self_loop_before_parallel_edges_does_not_shift_link_style_indices() {
    let d = laid_out_curve(
        "flowchart TD\n  A --> A\n  A -->|x| B\n  A -->|y| B\n  \
         linkStyle 1 interpolate linear\n  linkStyle 2 interpolate step",
        "basis",
    );
    let x = d
        .edges
        .iter()
        .find(|e| edge_label_text(e) == "x")
        .expect("the \"x\"-labelled edge must exist");
    let y = d
        .edges
        .iter()
        .find(|e| edge_label_text(e) == "y")
        .expect("the \"y\"-labelled edge must exist");
    let loop_edge = d
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "A")
        .expect("the self-loop must still be drawn");

    assert_eq!(
        loop_edge.curve,
        Curve::Basis,
        "the self-loop (index 0) names no linkStyle of its own; it must keep the chart-wide default"
    );
    assert_eq!(
        x.curve,
        Curve::Linear,
        "linkStyle 1 must land on the edge declared second (x), not on the self-loop"
    );
    assert_eq!(
        y.curve,
        Curve::Step,
        "linkStyle 2 must land on the edge declared third (y)"
    );
}

/// The same proof with the self-loop declared **between** the two parallel edges instead of
/// before them — the position most likely to confuse an implementation that (wrongly) keys edges
/// by `(from, to)` pair rather than by declaration order: `A --> A`'s pair never repeats, but it
/// sits between two entries that share the same pair as each other.
#[test]
fn self_loop_between_parallel_edges_does_not_shift_link_style_indices() {
    let d = laid_out_curve(
        "flowchart TD\n  A -->|x| B\n  A --> A\n  A -->|y| B\n  \
         linkStyle 0 interpolate linear\n  linkStyle 2 interpolate step",
        "basis",
    );
    let x = d
        .edges
        .iter()
        .find(|e| edge_label_text(e) == "x")
        .expect("the \"x\"-labelled edge must exist");
    let y = d
        .edges
        .iter()
        .find(|e| edge_label_text(e) == "y")
        .expect("the \"y\"-labelled edge must exist");
    let loop_edge = d
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "A")
        .expect("the self-loop must still be drawn");

    assert_eq!(
        x.curve,
        Curve::Linear,
        "linkStyle 0 must land on the first-declared edge (x)"
    );
    assert_eq!(
        loop_edge.curve,
        Curve::Basis,
        "the self-loop (index 1) names no linkStyle; it must keep the chart-wide default"
    );
    assert_eq!(
        y.curve,
        Curve::Step,
        "linkStyle 2 must land on the third-declared edge (y), not shifted by the self-loop between them"
    );
}

// ---------------------------------------------------------------------------------------------
// `[ui] mermaid_routing = "konoma-orthogonal"` (docs/FEATURE-MERMAID-RENDERER.md §10, stage 1)
// ---------------------------------------------------------------------------------------------

/// Every `CORPUS` entry — a cluster-anchored edge (`one --> two`, `E --> one`, ...) is routed by
/// `orthogonal::route_flowchart` exactly like a node-to-node one now (§10-2's cluster-edge stage:
/// `orthogonal::cluster_as_node`/`build_by_id`), so `subgraph-*` sources no longer need excluding
/// from "every segment is axis-parallel" the way stage 1 through 5 had to exclude them.
fn orthogonal_corpus() -> Vec<(&'static str, &'static str)> {
    CORPUS.to_vec()
}

/// `samples/mermaid.ja.md`'s "大きさ" flowchart, byte-for-byte — deliberately **not** added to
/// `CORPUS` itself (`CORPUS` also drives the golden snapshot test, and this source is real-world
/// sized rather than hand-minimised for one property, so adding it there would both bloat the
/// golden and make failures on it harder to localise to one invariant). Kept as its own constant
/// because several standalone regression tests below (`orthogonal_settings_rules_sample_*`) each
/// need this exact source, and three hand-copies of the same ~30-line fixture already drifted from
/// "obviously the same string" into "trust me, diff it" before this was factored out.
const SETTINGS_RULES_SAMPLE: &str = "flowchart LR\n  F[ファイル] --> C{設定のルール}\n  \
               C -->|テキスト| T[窓読み]\n  C -->|コード| S[構文強調]\n  \
               C -->|Markdown| MD[ブロックモデル]\n  C -->|CSV / TSV| TB[表]\n  \
               C -->|画像| IM[デコード]\n  C -->|PDF| PD[ページ描画]\n  C -->|SVG| SV[usvg]\n  \
               C -->|動画| VD[キーフレーム]\n  C -->|書庫| AR[一覧]\n  \
               C -->|なし| NA[プレビュー不可]\n  MD --> MM[mermaid]\n  MD --> MA[数式]\n  \
               MM --> RS[ラスタライズ]\n  MA --> RS\n  SV --> RS\n  PD --> RS\n  \
               IM --> FIT[セルに合わせる]\n  RS --> FIT\n  VD --> FIT\n  FIT --> K{端末}\n  \
               K -->|kitty| KT[圧縮転送]\n  K -->|sixel / iTerm2| RI[画像プロトコル]\n  \
               K -->|それ以外| HB[ハーフブロック]\n  \
               classDef pix fill:#132a3a,stroke:#1f6feb,color:#c9d1d9\n  \
               classDef txt fill:#12291c,stroke:#2da44e,color:#c9d1d9\n  \
               class IM,PD,SV,VD,MM,MA,RS,FIT,KT,RI,HB pix\n  \
               class T,S,MD,TB,AR txt\n  \
               style NA fill:#2d2418,stroke:#d4a017,color:#c9d1d9";

/// [`orthogonal_corpus`], further filtered down to the sources
/// [`orthogonal_bend_count_never_exceeds_two`] can state a bend-count *cap* over. Two kinds of
/// edge are deliberately exempt from any cap, both drawn by the same mechanism
/// (`orthogonal::route_staircase_with_ports`: dagre's own waypoint chain, straightened, however
/// long it is) and both excluded here by source name rather than detected, since nothing on a
/// finished [`Diagram`] says which edge took which path any more:
///
/// * a **back edge** (§10-1 item 2's "補助・戻り辺は外周レーンのため回数制限なし" — a real
///   perimeter route is stage 5's job) — `branch`/`cjk`/`long-edge`/`left-right` each close a
///   cycle back onto an earlier node, and `self-loop` names one outright;
/// * a **collision-fallback forward edge** (§10-1 item 1, stage 3: a branch or merge whose route
///   crossed another node in *both* attempts falls back the same way). `amp-chain` is the one
///   corpus source that reaches this in practice — dumped and read by hand before being added
///   here, not guessed at: `A`'s branch to `D` crosses `B` (`A`'s own sibling source) on one
///   attempt and `C` (`D`'s own sibling target) on the other, so it falls back and comes out at 4
///   bends. `docs/FEATURE-MERMAID-RENDERER.md` §10-1 item 2's "回数制限なし" is written about back
///   edges specifically, but the same reasoning applies here: a route that had to give up on both
///   direct right-angle shapes is in exactly the position stage 5's perimeter lanes are meant
///   for, not one this stage's ≤2 cap was ever meant to hold to. `strokes`' `A<-->F`/`C~~~E` and
///   `subgraph-bypass`'s `X->Y` join this list for the same reason (added 2026-09-01, once
///   `align_straight_lanes`'s `r + 1` adjacency bug was fixed and it started actually
///   straightening the chains these two edges skip across): `strokes`' `A-B-C-D-E-F` becomes one
///   straight column, and `A<-->F`/`C~~~E` skip clean across it, colliding on both attempts and
///   coming out at 6 bends each; `subgraph-bypass`'s `A->B` (inside the `one` frame `X->Y` has to
///   go around) straightens the same way, widening the detour `X->Y` needs above the frame to 4
///   bends. Both dumped and read by hand, not guessed at, the same as `amp-chain`.
/// * `subgraph-endpoint` and `subgraph-direction` joined this list for the same reason as
///   `amp-chain`, once `shape_crosses_a_node`'s own-endpoint check existed to find them — both
///   dumped and read by hand, not guessed at, and both the same two-step cascade:
///   `subgraph-endpoint`'s `E->one`: the original shape (`E` leaves `Top`, `one` receives `Left`)
///   held `E`'s own port coordinate across its first leg, which stayed inside `E`'s own real box
///   the whole way (the exact bug this check exists to catch), so `classify` swapped to the
///   alternate (`E` leaves `Right`, `one` receives `Bottom`) — which does not touch `E` at all, but
///   crosses `one`'s own member `A` instead (an ordinary *foreign*-node collision, real all along,
///   just never reached before the first swap started firing). Both fail, so it falls back to the
///   raw-derived staircase (3 bends). `subgraph-direction`'s `one->D` is the mirror image of the
///   same shape (`known_staircase_forward_edge`'s own doc has the numbers).
fn orthogonal_dag_corpus() -> Vec<(&'static str, &'static str)> {
    const UNCAPPED: &[&str] = &[
        "branch",
        "cjk",
        "long-edge",
        "left-right",
        "self-loop",
        "amp-chain",
        "strokes",
        "subgraph-bypass",
        "subgraph-endpoint",
        "subgraph-direction",
        // `C --> A` closes a cycle back onto the block's own member `A` — a back edge exactly
        // like the others in this list, just with one end inside a subgraph frame.
        "subgraph",
    ];
    orthogonal_corpus()
        .into_iter()
        .filter(|(name, _)| !UNCAPPED.contains(name))
        .collect()
}

/// Every segment of every routed edge in `d`, as `(a, b)` pairs.
///
/// `pub(super)` — reused by `state_tests`'s own orthogonal invariants (§10-5), which run this
/// same axis-parallel check over the state corpus rather than re-deriving it.
pub(super) fn edge_segments(d: &Diagram) -> Vec<(Point, Point)> {
    let mut out = Vec::new();
    for e in &d.edges {
        for w in e.points.windows(2) {
            out.push((w[0].clone(), w[1].clone()));
        }
    }
    out
}

pub(super) const AXIS_EPS: f64 = 1e-6;

/// `render_flow(..., curve, "splines")` is defined *as* `render_curve(..., curve)`'s own body
/// (`render_curve` in `mod.rs` is literally `render_flow(code, theme, curve, "splines")`), so this
/// is a decidability/non-panic check, not a regression guard: it states that routing a curve
/// through the `"splines"` string takes the same code path calling `render_curve` directly does,
/// and that path does not panic, across several curves and the whole corpus. **It cannot catch a
/// regression in what `"splines"` draws** — the moment the delegation above shipped, `a` and `b`
/// below became the same call with different names, i.e. `f(x) == f(x)`, the exact shape of
/// failure memory `markdown-block-walk-migration` records ("a live comparison goes silently
/// meaningless the instant B is B's own implementation"). See
/// [`splines_routing_signature_is_pinned`] for the actual regression guard.
#[test]
fn orthogonal_splines_routing_is_deterministic_and_does_not_panic() {
    for (name, src) in CORPUS {
        for curve in ["basis", "linear", "step", "monotoneX"] {
            let a = render_curve(src, "dark", curve)
                .unwrap_or_else(|e| panic!("{name}/{curve}: render_curve must render: {e}"));
            let b = render_flow(src, "dark", curve, "splines")
                .unwrap_or_else(|e| panic!("{name}/{curve}: render_flow must render: {e}"));
            assert_eq!(
                a, b,
                "{name}/{curve}: render_flow(..., \"splines\") must match render_curve(...) exactly \
                 (both calls take the same code path, so this can only fail on nondeterminism)"
            );
        }
    }
}

/// Re-dumps [`routing_signature`] for the five sources [`splines_routing_signature_is_pinned`]
/// pins, so a deliberate change to that test's expectations starts from real output rather than a
/// hand-edited guess. Run with `cargo test -- --ignored --nocapture` and copy the printed constants
/// in by hand — this does not write anywhere on disk, unlike `KONOMA_UPDATE_SNAPSHOTS=1`, which is
/// the point (see that test's doc comment).
#[test]
#[ignore]
fn dump_routing_signatures_for_pinning() {
    for name in [
        "branch",
        "left-right",
        "subgraph",
        "long-edge",
        "link-style-multi-index",
    ] {
        let (_, src) = CORPUS
            .iter()
            .find(|(n, _)| *n == name)
            .expect("known corpus name");
        let svg = render_flow(src, "dark", "basis", "splines").expect("must render");
        println!("=== {name} ===\n{}", routing_signature(&svg));
    }
}

const BRANCH_SIGNATURE: &str = "fill=none
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#333333
fill=#cccccc
fill=#333333
fill=#cccccc
";

const LEFT_RIGHT_SIGNATURE: &str = "fill=none
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#333333
fill=#cccccc
fill=#333333
fill=#cccccc
";

const SUBGRAPH_SIGNATURE: &str = "fill=none
fill=#2b2b38
stroke=#8a8a8a
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#cccccc
";

const LONG_EDGE_SIGNATURE: &str = "fill=none
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d3d3d3
fill=#d3d3d3
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
";

const LINK_STYLE_SIGNATURE: &str = "fill=none
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#1f6feb
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#1f6feb
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#1f6feb
fill=#d3d3d3
d=M#,#L#,#C#,# #,# #,#C#,# #,# #,#L#,#
fill=none
stroke=#d4a017
fill=#d3d3d3
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
fill=#1f2020
stroke=#cccccc
fill=#cccccc
";

/// The sentinel `orthogonal_splines_routing_is_deterministic_and_does_not_panic` cannot be, now
/// that `render_curve` is defined as `render_flow(..., "splines")`: a comparison between the two
/// is `f(x) == f(x)` (see that test's doc comment). This one does not call `render_curve` at all —
/// it pins `render_flow(..., "splines")` on its own, against a literal expected string baked into
/// *this source file*, not a `snapshots/` golden, so `KONOMA_UPDATE_SNAPSHOTS=1` cannot silently
/// carry a regression through. If `"splines"` ever stopped meaning splines routing — reached
/// `orthogonal::route_flowchart` by accident, or a future refactor broke the string match in
/// [`Routing::parse`](orthogonal) — this is the test that would actually notice, where the sentinel
/// above would not (both sides of its comparison would still be equally broken).
///
/// Five corpus sources stand in for the shapes a routing regression would plausibly move: a plain
/// forward chain with a back edge (`branch`), labelled edges (`left-right`), a subgraph frame
/// (`subgraph`), several back edges over a longer chain (`long-edge`), and `linkStyle`-coloured
/// edges (`link-style-multi-index`, the exact case `docs/STATUS.md`'s 2026-08-28 colour-cascade
/// regression came from). Expected values were obtained by dumping real output
/// ([`dump_routing_signatures_for_pinning`], `--ignored --nocapture`) and are
/// [`routing_signature`]'s masked `d`/`fill`/`stroke` columns rather than the whole SVG, for the
/// same reason `corpus_golden` masks numbers at all: an unmasked byte-exact pin would drift between
/// this machine's Helvetica and Linux CI's DejaVu Sans on nothing more than label width, for
/// reasons that have nothing to do with routing.
#[test]
fn splines_routing_signature_is_pinned() {
    const CASES: &[(&str, &str)] = &[
        ("branch", BRANCH_SIGNATURE),
        ("left-right", LEFT_RIGHT_SIGNATURE),
        ("subgraph", SUBGRAPH_SIGNATURE),
        ("long-edge", LONG_EDGE_SIGNATURE),
        ("link-style-multi-index", LINK_STYLE_SIGNATURE),
    ];
    for (name, expected) in CASES {
        let (_, src) = CORPUS
            .iter()
            .find(|(n, _)| n == name)
            .unwrap_or_else(|| panic!("{name}: not in CORPUS"));
        let svg = render_flow(src, "dark", "basis", "splines")
            .unwrap_or_else(|e| panic!("{name}: must render: {e}"));
        assert_eq!(
            &routing_signature(&svg),
            expected,
            "{name}: splines routing signature drifted — re-dump with \
             dump_routing_signatures_for_pinning and inspect the diff before updating"
        );
    }
}

/// An unrecognised `routing` value falls back to `"splines"` — the same permissive contract every
/// unrecognised config value in this crate gets (mirrors `unknown_curve_falls_back_to_basis`
/// above), and specifically covers the bare word `"orthogonal"` (no `konoma-` prefix), which is
/// deliberately *not* the trigger — see `orthogonal::Routing::parse`'s own docs.
#[test]
fn unknown_routing_falls_back_to_splines_without_crashing() {
    let src = "flowchart TD\n  A --> B{cond}\n  B --> C\n  B --> D";
    let splines = render_flow(src, "dark", "basis", "splines").expect("must render");
    for unknown in ["xyz", "", "  ", "Orthogonal", "orthogonal", "ORTHOGONAL"] {
        let got = render_flow(src, "dark", "basis", unknown)
            .unwrap_or_else(|e| panic!("routing={unknown:?} must still render: {e}"));
        assert_eq!(
            splines, got,
            "routing={unknown:?} must resolve exactly like \"splines\""
        );
    }
}

/// Every routed edge's polyline, under `"konoma-orthogonal"`, is made of axis-parallel segments
/// only — no diagonal line — across the subgraph-free corpus (`orthogonal_corpus`): shapes,
/// strokes, CJK, all four directions, multiline labels, a self-loop, a long edge that skips ranks,
/// `A & B --> C & D` fan-out/fan-in, and `linkStyle`/`classDef` cascades.
#[test]
fn orthogonal_routing_draws_only_axis_parallel_segments() {
    for (name, src) in orthogonal_full_corpus() {
        check_only_axis_parallel_segments(name, &laid_out_flow(src, "basis", "konoma-orthogonal"));
    }
}

/// The invariant just above, as a helper, so a second caller states the *same* property rather
/// than re-deriving "no diagonal" with its own epsilon (the catalog's direction block reuses it —
/// its whole claim is that the routing rules do not change with `rankdir`).
pub(super) fn check_only_axis_parallel_segments(name: &str, d: &Diagram) {
    for (a, b) in edge_segments(d) {
        let dx = (b.x - a.x).abs();
        let dy = (b.y - a.y).abs();
        assert!(
            dx < AXIS_EPS || dy < AXIS_EPS,
            "{name}: diagonal segment {a:?} -> {b:?}"
        );
    }
}

/// An aligned pair (same coordinate across the flow, within half a pixel) draws as a bare
/// two-point straight run: zero bends, flow-centre to flow-centre.
#[test]
fn orthogonal_aligned_edge_is_a_straight_two_point_line() {
    let d = laid_out_flow("flowchart TD\n  A --> B", "basis", "konoma-orthogonal");
    let e = &d.edges[0];
    assert_eq!(e.points.len(), 2, "{:?}", e.points);
    assert!(
        (e.points[0].x - e.points[1].x).abs() < AXIS_EPS,
        "a straight-down TD edge must not drift sideways: {:?}",
        e.points
    );
    assert!(
        e.straight,
        "an orthogonal edge must draw as a polyline, not a curve"
    );
}

/// A decision node's two outgoing edges (branch) and a merge node's two incoming edges (merge).
///
/// The branch leg (`B->C`/`B->D`): `B` has only two out-edges, at or below
/// [`orthogonal::FAN_ELIGIBLE_MIN_BRANCHES`] (reimplemented 2026-09-02 — `classify`'s own
/// `fan_eligible` doc has the derivation, `docs/mermaid-theme/handoff/zz-design-sources.md`'s own
/// `2a` the reference), so 1b's own basic shape applies rather than the flow-axis retreat rule:
/// `B->C` is `classify`'s `aligned` (0-bend) shape (`C` sits directly downstream of `B`), and
/// `B->D` — not geometrically aligned — takes the *ordinary* cross-axis branch shape, one bend,
/// on `B`'s own Top face (`D` sits above `B`'s own row here), never sharing `B->C`'s own flow-axis
/// face at all. The two legs use two distinct physical faces, so there is no port-grid contest to
/// pin here (unlike the merge leg below, whose two edges *do* share one face — a real merge target
/// always accepts every incoming edge on its own flow-axis face, `merge_target_side`'s own doc,
/// regardless of how many there are).
///
/// The merge leg (`A->C`/`B->C`) is unaffected by that reimplementation — merge shapes were never
/// gated by `fan_eligible` (`classify`'s own `branching` ladder only ever consults it for a
/// *branching* source) — and keeps the original history this doc used to tell in full: `evict`'s
/// own port grid used to be centred on the claim *list's* own geometric mid-index (`(n-1)/2`),
/// which for an even claim count (`n = 2` here) has no slot at exactly `offset == 0.0` — so even
/// the aligned claim landed `PORT_SPACING/2 = 8px` off the face's true centre, and *neither* edge
/// drew as a straight line. §10-3's own "ファン列内の並び順"/"幹7区間の曲げ0" work
/// (`docs/FEATURE-MERMAID-RENDERER.md`) fixed the grid to anchor on *whichever slot the aligned/
/// trunk claim itself ends up in* instead (`evict`'s own doc on `anchor`) — required for `3a`'s
/// own even-count ten-way fan to draw its trunk edge with zero bends at all, and it applies to
/// *every* even-`n` face with an aligned/trunk claim, this two-claim one included. The aligned
/// claim now lands dead on the face's centre (a real 2-point line, not a 4-point one bent `±8px`
/// around it); its one competitor is pushed out to a full `PORT_SPACING = 16px` instead of half
/// of it, since the whole grid is now anchored one slot further out than the old symmetric one
/// was. Dumped and confirmed by hand, not assumed.
///
/// The merge case's own competitor (`B->C`) now lands on whichever side of `C`'s centre `B`
/// genuinely sits on (§10-3 item 12) rather than wherever an array-symmetric re-splice happened to
/// put it — see the assertion below for the concrete side.
#[test]
fn orthogonal_branch_and_merge_edges_share_a_face_one_aligned_one_bends_twice() {
    let branch = laid_out_flow(
        "flowchart LR\n  A --> B{cond}\n  B --> C\n  B --> D",
        "basis",
        "konoma-orthogonal",
    );
    let bc = branch
        .edges
        .iter()
        .find(|e| e.from == "B" && e.to == "C")
        .expect("edge B->C must exist");
    let bd = branch
        .edges
        .iter()
        .find(|e| e.from == "B" && e.to == "D")
        .expect("edge B->D must exist");
    let b_node = branch.node("B").expect("B must exist");
    assert_eq!(
        bc.points.len(),
        2,
        "B->C is the aligned leg — a straight 2-point line: {:?}",
        bc.points
    );
    assert_eq!(
        bd.points.len(),
        3,
        "B->D is a plain 3-way-or-fewer branch (1b's own basic shape, not the flow-axis retreat \
         rule) — one bend, on B's own cross-axis face: {:?}",
        bd.points
    );
    // B->C exits dead on B's own centre (its own flow-axis face, shared with nothing since B->D
    // now uses a different, cross-axis face entirely).
    let bc_exit_y = bc.points[0].y;
    assert!(
        (bc_exit_y - b_node.center.y).abs() < 1e-6,
        "B->C (aligned) exits exactly on B's centre: {bc_exit_y} vs {}",
        b_node.center.y
    );
    // B->D exits B's own Bottom face (D sits below B's own row), centred on it — B's only claim on
    // that face — [`orthogonal::PORT_INSET`] outside the node's own bottom edge. *Below*, not
    // above: `D` is a dead end (no out-edge of its own), and `super::fan_split` gives a dead-end
    // branch the positive cross side. Until §10-3 item 11's own split was restated in terms of
    // continuity (`docs/STATUS.md`'s own ★未修正 G8) the flat `before = len / 2` formula put the
    // sole non-trunk branch above regardless of what it led to, and this assertion read `b_top`.
    let (_, _, _, b_bottom) = b_node.bounds();
    let bd_exit = &bd.points[0];
    assert!(
        (bd_exit.x - b_node.center.x).abs() < 1e-6,
        "B->D exits centred on B's own Bottom face: {bd_exit:?} vs centre x {}",
        b_node.center.x
    );
    assert!(
        (bd_exit.y - (b_bottom + orthogonal::PORT_INSET)).abs() < 1e-6,
        "B->D exits PORT_INSET outside B's own bottom edge: {bd_exit:?} vs bottom {b_bottom}",
    );

    let merge = laid_out_flow(
        "flowchart LR\n  A --> C\n  B --> C\n  C --> D",
        "basis",
        "konoma-orthogonal",
    );
    let ac = merge
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "C")
        .expect("edge A->C must exist");
    let bc2 = merge
        .edges
        .iter()
        .find(|e| e.from == "B" && e.to == "C")
        .expect("edge B->C must exist");
    let c_node = merge.node("C").expect("C must exist");
    assert_eq!(
        ac.points.len(),
        2,
        "A->C is the aligned leg — a straight 2-point line: {:?}",
        ac.points
    );
    assert_eq!(
        bc2.points.len(),
        4,
        "B->C must bend twice: {:?}",
        bc2.points
    );
    // A->C enters dead on C's own centre; B->C is pushed a full PORT_SPACING off it, on
    // *whichever side B genuinely sits on* (§10-3 item 12, `orthogonal::evict`'s own doc on
    // `anchor`): B sits below A/C here (dumped: B.center.y = 101.4 > C.center.y = 32.0), so B->C's
    // port belongs *below* C's centre, not above it. The pre-item-12 `evict` forced the aligned
    // claim into the claims array's own geometric middle index regardless of where it naturally
    // sorted, which could drag a genuinely-below sibling like this one above centre instead — this
    // assertion used to pin that wrong side; item 12's fix is what corrected it.
    let ac_entry_y = ac.points.last().unwrap().y;
    let bc2_entry_y = bc2.points.last().unwrap().y;
    assert!(
        (ac_entry_y - c_node.center.y).abs() < 1e-6,
        "A->C (aligned) enters exactly on C's centre: {ac_entry_y} vs {}",
        c_node.center.y
    );
    assert!(
        (bc2_entry_y - (c_node.center.y + orthogonal::PORT_SPACING)).abs() < 1e-6,
        "B->C enters PORT_SPACING below C's centre (B genuinely sits below C): {bc2_entry_y} vs {}",
        c_node.center.y
    );
}

/// A `{}` decision node draws as an eight-vertex chamfered rectangle when `[ui] mermaid_routing =
/// "konoma-orthogonal"`, sized exactly like an ordinary rectangle — and as the ordinary diamond,
/// unchanged, under `"splines"`. `Glyph::ChamferedRect`'s own docs explain why a diamond has no
/// flat run for a port to land on.
#[test]
fn decision_node_is_chamfered_under_orthogonal_and_a_diamond_under_splines() {
    let src = "flowchart TD\n  A --> B{cond}\n  B --> C";

    let splines = laid_out_curve(src, "basis");
    let b_splines = splines.node("B").expect("B must exist");
    assert_eq!(b_splines.shape, Glyph::Flow(Shape::Diamond));

    let ortho = laid_out_flow(src, "basis", "konoma-orthogonal");
    let b_ortho = ortho.node("B").expect("B must exist");
    assert_eq!(b_ortho.shape, Glyph::ChamferedRect);

    let polygon = shapes::polygon(b_ortho.shape, b_ortho.size);
    assert_eq!(
        polygon.len(),
        8,
        "a chamfered rectangle has eight vertices: {polygon:?}"
    );

    // Sized as §10-8 sizes a box, not doubled the way a diamond is (§10-1: "菱形の2倍拡大を
    // しない"). The numbers moved when §10-8 landed (2026-09-05) — the box was `flow_size(Rect)`
    // of the label before, and is N1/N2's own 36px-tall, 8px-grid box now — but the *rule* this
    // test states did not, so it is restated against the rule rather than against either set of
    // numbers: the box is exactly what §10-8 asks for, and it is nowhere near the square a
    // diamond's `w + h` side would make.
    let (_, spec_size) = shapes::orthogonal_node(Glyph::ChamferedRect, "cond")
        .expect("a chamfered rectangle is in §10-8 N3's scope");
    assert_eq!(b_ortho.size.w, spec_size.w);
    assert_eq!(b_ortho.size.h, spec_size.h);
    let diamond = shapes::size(
        Glyph::Flow(Shape::Diamond),
        Size::new(b_ortho.label.width, b_ortho.label.height),
    );
    assert!(
        b_ortho.size.h < diamond.h,
        "a chamfered rectangle must not be doubled into a diamond's square: \
         {:?} vs {diamond:?}",
        b_ortho.size
    );

    // Reaches the actual SVG, not just the geometry model.
    let svg = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("must render");
    assert!(
        svg.contains("<polygon"),
        "an orthogonal decision node must draw a <polygon>, not a diamond outline"
    );
}

/// A class/ER diagram draws identically whether `"splines"` or `"konoma-orthogonal"` is asked
/// for, because each of their own `spec_of` always sets `GraphSpec::routing` to
/// `Routing::Splines` regardless of the caller's setting (§10-5's own scope line: "他図種
/// (class/ER…)は今回対象外"). A state diagram is the one exception since
/// `docs/FEATURE-MERMAID-RENDERER.md` §10-5 (the flowchart was already one, from §10 itself) —
/// see `a_state_diagram_draws_differently_under_konoma_orthogonal`, just below, for its own half
/// of what used to be this same assertion. Same shape as `non_flowchart_diagrams_ignore_mermaid_
/// curve` above, through the real dispatcher.
#[test]
fn non_flowchart_diagrams_ignore_mermaid_routing() {
    use crate::preview::markdown::mermaid_to_svg_flow;
    let cases = ["classDiagram\n  A --|> B", "erDiagram\n  A ||--o{ B : has"];
    for src in cases {
        let splines = mermaid_to_svg_flow(src, "dark", "basis", "splines")
            .unwrap_or_else(|| panic!("{src}: must render under splines"));
        let ortho = mermaid_to_svg_flow(src, "dark", "basis", "konoma-orthogonal")
            .unwrap_or_else(|| panic!("{src}: must render under konoma-orthogonal"));
        assert_eq!(
            splines, ortho,
            "{src}: a non-flowchart diagram must draw identically regardless of mermaid_routing"
        );
    }
}

/// §10-5's own wiring point: a state diagram's edges *do* read `[ui] mermaid_routing` now, the
/// same as a flowchart's — `konoma-orthogonal` draws its transitions as right-angled polylines
/// (no cubic-Bezier `C` command) where `splines` draws mermaid's own curve, while every node's own
/// box/marker geometry — including the start dot's and end ring's fixed radii, S1's own token
/// list — stays byte-identical between the two (only the *edges* a routing mode governs at all,
/// `docs/FEATURE-MERMAID-RENDERER.md` §10-2's own "座標段の後処理と辺経路だけを足す").
#[test]
fn a_state_diagram_draws_differently_under_konoma_orthogonal() {
    use crate::preview::markdown::mermaid_to_svg_flow;
    let src = "stateDiagram-v2\n  [*] --> A\n  A --> B\n  B --> [*]";
    let splines = mermaid_to_svg_flow(src, "dark", "basis", "splines").expect("splines renders");
    let ortho =
        mermaid_to_svg_flow(src, "dark", "basis", "konoma-orthogonal").expect("orthogonal renders");
    assert_ne!(
        splines, ortho,
        "a state diagram's edges must actually change under konoma-orthogonal"
    );
    assert!(
        !ortho.contains('C'),
        "konoma-orthogonal must draw right angles, not a cubic-Bezier curve:\n{ortho}"
    );
    assert!(
        splines.contains('C'),
        "splines must still draw its own curve unchanged:\n{splines}"
    );
    // The start dot's and end ring's radii are pinned tokens (§10-5 S1), not layout — they must
    // not move a pixel just because the routing mode changed.
    assert!(
        ortho.contains("r=\"7\"") && splines.contains("r=\"7\""),
        "the start dot's 7px radius must be routing-independent"
    );
    assert!(
        ortho.contains("r=\"6.25\"") && splines.contains("r=\"6.25\""),
        "the end ring's outer 6.25px radius must be routing-independent"
    );
}

/// Every routed edge's two endpoints sit exactly [`orthogonal::PORT_INSET`] px **outside** the
/// node — or, for a cluster-anchored end (§10-2), the subgraph frame — each one meets, never
/// touching, let alone crossing into, the real geometric boundary — and the segment that reaches
/// each one is perpendicular to whichever face it lands on. §10-1 item 1's last bullet: "矢尻…の
/// 先端はノード枠の外縁から1px離す=端点は枠座標の2px手前", and item 1's "出入りは常に辺へ垂直".
/// `orthogonal_corpus()` now includes every `subgraph-*` source, so this same loop is what checks
/// a cluster-anchored edge's own endpoint (`subgraph-endpoint`'s `one --> two` / `E --> one`)
/// against exactly the rule a node-anchored one is held to — no separate cluster-only test needed.
///
/// Pins the *direction* of the offset, not only its magnitude — a real regression once got this
/// backwards: an endpoint pulled *inward* (into the node) rather than outward drew an arrow tip
/// that pokes into the node's own interior, which stayed invisible in the finished picture only
/// because `svg::emit` paints nodes *after* edges, so the poking-in part vanished under the node's
/// opaque fill and the visible tip looked flush with the boundary instead of clear of it — a bug a
/// test that only checked the offset's *magnitude* would have missed entirely, since `t + inset`
/// and `t - inset` are both "some distance from `t`". See
/// `orthogonal_arrow_tip_has_a_visible_gap_from_the_node_in_real_pixels` for the pixel-level half
/// of this same proof (confirmed against a rasterised scan before either test was written).
#[test]
fn orthogonal_endpoints_sit_outside_the_node_and_arrive_perpendicular() {
    for (name, src) in orthogonal_full_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        assert_endpoints_sit_outside_and_perpendicular(name, &d);
    }
}

/// The per-diagram body of [`orthogonal_endpoints_sit_outside_the_node_and_arrive_perpendicular`],
/// factored out (matching [`assert_no_segment_crosses_a_foreign_node`]'s own shape below) so the
/// real-diagram regression tests — `samples/mermaid.ja.md`'s "大きさ" flowchart among them — can
/// state the exact same question a hand-built `CORPUS` fixture is held to, rather than only ever
/// running over `orthogonal_corpus()`. That gap is exactly how a real endpoint-dragged-into-its-
/// own-node regression (`route_with_ports`'s own doc: `MD->MM`'s bottom port on this very sample)
/// went unnoticed by this invariant before: it existed, but its only caller was `CORPUS`, which has
/// never included a diagram large enough for `align_straight_lanes` to move a node far enough to
/// stress this the way a real ~20-node flowchart does.
fn assert_endpoints_sit_outside_and_perpendicular(name: &str, d: &Diagram) {
    for e in &d.edges {
        if e.points.len() < 2 {
            continue;
        }
        let n = e.points.len();
        let ends = [
            (&e.from, &e.points[0], &e.points[1]),
            (&e.to, &e.points[n - 1], &e.points[n - 2]),
        ];
        for (node_id, endpoint, neighbour) in ends {
            // A cluster-anchored end (§10-2) meets a subgraph frame instead of a node — same
            // box shape (`PlacedCluster::bounds` reads exactly like `PlacedNode::bounds`), so
            // this checks whichever one `node_id` actually names rather than skipping it.
            let bounds = d
                .node(node_id)
                .map(|n| n.bounds())
                .or_else(|| d.cluster(node_id).map(|c| c.bounds()));
            let Some((l, t, r, b)) = bounds else {
                continue;
            };
            let on_top = (endpoint.y - (t - orthogonal::PORT_INSET)).abs() < AXIS_EPS;
            let on_bottom = (endpoint.y - (b + orthogonal::PORT_INSET)).abs() < AXIS_EPS;
            let on_left = (endpoint.x - (l - orthogonal::PORT_INSET)).abs() < AXIS_EPS;
            let on_right = (endpoint.x - (r + orthogonal::PORT_INSET)).abs() < AXIS_EPS;
            assert!(
                on_top || on_bottom || on_left || on_right,
                "{name}: edge {}->{} endpoint at {node_id} {endpoint:?} is not {}px \
                 OUTSIDE its bounds {:?}",
                e.from,
                e.to,
                orthogonal::PORT_INSET,
                (l, t, r, b)
            );

            let dx = (endpoint.x - neighbour.x).abs();
            let dy = (endpoint.y - neighbour.y).abs();
            assert!(
                dx < AXIS_EPS || dy < AXIS_EPS,
                "{name}: edge {}->{} segment into {node_id} is not axis-parallel: \
                 {neighbour:?} -> {endpoint:?}",
                e.from,
                e.to
            );
            if on_top || on_bottom {
                assert!(
                    dy > AXIS_EPS && dx < AXIS_EPS,
                    "{name}: edge {}->{} must meet {node_id} vertically at a top/bottom face: \
                     {neighbour:?} -> {endpoint:?}",
                    e.from,
                    e.to
                );
            } else {
                assert!(
                    dx > AXIS_EPS && dy < AXIS_EPS,
                    "{name}: edge {}->{} must meet {node_id} horizontally at a left/right \
                     face: {neighbour:?} -> {endpoint:?}",
                    e.from,
                    e.to
                );
            }
        }
    }
}

/// The shortest leg a routed polyline is allowed to have between two other legs, before it reads
/// as an artefact rather than a bend: below this a segment is invisible at any realistic zoom, so a
/// route that turns aside by less than this and turns straight back draws as a stub hanging off
/// the line rather than as part of it.
const MIN_JOG: f64 = 2.0;

/// "No dangling fragment": the two shapes a routed polyline can take that read, in the finished
/// picture, as a *piece of line that goes nowhere* rather than as a route.
///
/// 1. **A vanishing jog.** Three consecutive points whose middle leg is shorter than [`MIN_JOG`]
///    and whose two neighbouring legs run in *opposite* directions along the same axis: the line
///    leaves, moves a pixel or two sideways, and comes straight back. `orthogonal::remove_spikes`
///    already collapses the exact-zero case (first and third point identical); this states the
///    near-zero one, which it cannot see. Also stated for the zero-length middle leg's own
///    degenerate sibling — two consecutive legs that are outright antiparallel, at any length —
///    which no shape in this module is ever supposed to produce.
/// 2. **An endpoint off its own face.** The existing
///    [`assert_endpoints_sit_outside_and_perpendicular`] pins an endpoint's *perpendicular*
///    coordinate ([`orthogonal::PORT_INSET`] outside one of the four faces) and the axis it
///    arrives along, but says nothing about the coordinate *along* that face — so an endpoint
///    sitting at the node's left-face offset yet metres above the node passes it, and the line
///    into it hangs in empty space. §10-1 item 1's ports are always on the flat run of a real
///    face; this is that half.
///
/// Written for `docs/render-check/zz-design-2c`'s own reported "stray hook under API ゲート"
/// (`docs/STATUS.md`): that fragment turned out to be `API -> ID`'s own port stub and first leg,
/// severed from the rest of its route by the 12px crossing gap it took over the `投入` trunk two
/// pixels below the face it left — an artefact of the route being wrong (§10-3 item 4's branch
/// half, now implemented), not of the gap. Both halves above are the invariants that would have
/// named such a fragment as a fragment rather than leaving it to be spotted by eye.
pub(super) fn assert_no_dangling_fragment(name: &str, d: &Diagram) {
    for e in &d.edges {
        for w in e.points.windows(3) {
            let (a, b, c) = (&w[0], &w[1], &w[2]);
            let (in_dx, in_dy) = (b.x - a.x, b.y - a.y);
            let (out_dx, out_dy) = (c.x - b.x, c.y - b.y);
            let antiparallel = (in_dx * out_dx + in_dy * out_dy) < -AXIS_EPS
                && (in_dx * out_dy - in_dy * out_dx).abs() < AXIS_EPS;
            assert!(
                !antiparallel,
                "{name}: edge {}->{} doubles straight back at {b:?}: {:?}",
                e.from, e.to, e.points
            );
        }
        for w in e.points.windows(4) {
            let (a, b, c, dd) = (&w[0], &w[1], &w[2], &w[3]);
            let jog = ((c.x - b.x).powi(2) + (c.y - b.y).powi(2)).sqrt();
            if jog >= MIN_JOG {
                continue;
            }
            let (in_dx, in_dy) = (b.x - a.x, b.y - a.y);
            let (out_dx, out_dy) = (dd.x - c.x, dd.y - c.y);
            assert!(
                (in_dx * out_dx + in_dy * out_dy) >= -AXIS_EPS,
                "{name}: edge {}->{} turns aside by {jog:.2}px at {b:?} and straight back at \
                 {c:?}: {:?}",
                e.from,
                e.to,
                e.points
            );
        }

        if e.points.len() < 2 {
            continue;
        }
        let n = e.points.len();
        for (node_id, endpoint) in [(&e.from, &e.points[0]), (&e.to, &e.points[n - 1])] {
            let bounds = d
                .node(node_id)
                .map(|n| n.bounds())
                .or_else(|| d.cluster(node_id).map(|c| c.bounds()));
            let Some((l, t, r, b)) = bounds else {
                continue;
            };
            let vertical_face = (endpoint.x - (l - orthogonal::PORT_INSET)).abs() < AXIS_EPS
                || (endpoint.x - (r + orthogonal::PORT_INSET)).abs() < AXIS_EPS;
            let (lo, hi, along) = if vertical_face {
                (t, b, endpoint.y)
            } else {
                (l, r, endpoint.x)
            };
            // The edges in the whole corpus this does not hold for, named one by one rather than
            // hidden behind a widened tolerance. Every one of them is the same single, already
            // recorded defect: `orthogonal::clear_self_puncture` slides **every** point sharing a
            // coordinate — the route's own two ports included — when a back edge's return leg has
            // to clear one of its own two endpoint nodes. `clear_self_puncture`'s own doc says in
            // as many words that §10-3 item 13's "ポートは動かさない" was scoped to
            // `clear_local_route`'s forward-edge callers and deliberately not extended to it, and
            // `docs/STATUS.md` carries the residual. Closing it needs that function reworked to
            // move one *run* (the way `local_detour` already does for a forward edge) rather than
            // a whole coordinate — not a looser rule here. Listed as `(fixture, from, to)` so a
            // *new* off-face endpoint anywhere still fails.
            const KNOWN_PORT_SLIDES: [(&str, &str, &str); 4] = [
                ("branch", "D", "B"),
                ("basic", "Moving", "Still"),
                ("styled", "Moving", "Still"),
                ("style-separator", "Moving", "Still"),
            ];
            let known_port_slide = KNOWN_PORT_SLIDES
                .iter()
                .any(|&(f, from, to)| f == name && from == e.from && to == e.to);
            assert!(
                known_port_slide || (along >= lo - AXIS_EPS && along <= hi + AXIS_EPS),
                "{name}: edge {}->{} endpoint {endpoint:?} is off {node_id}'s own face — its \
                 span is {lo:.2}..{hi:.2}",
                e.from,
                e.to
            );
        }
    }
}

/// The witness [`assert_no_dangling_fragment`] itself needs: no corpus source currently draws
/// either shape (disabling `orthogonal::remove_spikes` outright changes not one fixture), so the
/// corpus-wide run below can only ever prove the invariant *holds* — never that it would notice if
/// it stopped. These three hand-built polylines are the proof it would: a route that turns aside by
/// 1px and straight back, one that doubles back along the same axis at any length, and an endpoint
/// on a node's face offset but far off the end of that face.
#[test]
fn assert_no_dangling_fragment_actually_rejects_each_shape_it_names() {
    let node = placed_node("a", 100.0, 100.0, 40.0, 20.0);
    let diagram = |points: Vec<Point>| Diagram {
        width: 200.0,
        height: 200.0,
        nodes: vec![node.clone(), placed_node("b", 100.0, 180.0, 40.0, 20.0)],
        edges: vec![PlacedEdge {
            from: "a".to_string(),
            to: "b".to_string(),
            ..bent_edge(points, Curve::Linear)
        }],
        clusters: Vec::new(),
        lifelines: Vec::new(),
    };
    let port_a = Point::new(100.0, 110.0 + orthogonal::PORT_INSET);
    let port_b = Point::new(100.0, 170.0 - orthogonal::PORT_INSET);
    // 1. a 1px jog and straight back.
    let jog = diagram(vec![
        port_a.clone(),
        Point::new(100.0, 150.0),
        Point::new(101.0, 150.0),
        Point::new(101.0, 130.0),
        Point::new(100.0, 130.0),
        port_b.clone(),
    ]);
    assert!(
        std::panic::catch_unwind(|| assert_no_dangling_fragment("jog", &jog)).is_err(),
        "a 1px jog flanked by a reversal must be rejected"
    );
    // 2. doubling straight back along the same axis.
    let doubled = diagram(vec![
        port_a.clone(),
        Point::new(100.0, 150.0),
        Point::new(100.0, 130.0),
        port_b.clone(),
    ]);
    assert!(
        std::panic::catch_unwind(|| assert_no_dangling_fragment("doubled", &doubled)).is_err(),
        "two antiparallel legs must be rejected"
    );
    // 3. an endpoint at the left face's own offset but well past the end of that face.
    let dangling = diagram(vec![
        Point::new(80.0 - orthogonal::PORT_INSET, 10.0),
        Point::new(100.0, 10.0),
        port_b,
    ]);
    assert!(
        std::panic::catch_unwind(|| assert_no_dangling_fragment("dangling", &dangling)).is_err(),
        "an endpoint off the end of its own face must be rejected"
    );
    // …and the same three points, with the endpoint moved onto the face, are accepted.
    let ok = diagram(vec![
        Point::new(80.0 - orthogonal::PORT_INSET, 100.0),
        Point::new(100.0, 100.0),
        Point::new(100.0, 170.0 - orthogonal::PORT_INSET),
    ]);
    assert_no_dangling_fragment("ok", &ok);
}

/// [`assert_no_dangling_fragment`], over every orthogonal fixture there is.
#[test]
fn orthogonal_no_polyline_leaves_a_dangling_fragment_across_the_whole_corpus() {
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        assert_no_dangling_fragment(name, &d);
    }
}

/// Every routed edge, checked over its **whole** length, must never re-enter its own two endpoint
/// nodes' real (unpadded) interior — the invariant [`assert_no_segment_crosses_a_foreign_node`]
/// structurally cannot state, because it excludes an edge's own two ends from the node list it
/// checks against (correctly so: a port sits only [`orthogonal::PORT_INSET`] outside its own face,
/// well inside [`orthogonal::COLLISION_MARGIN`]'s padding, so the *padded* test would flag every
/// edge's own harmless graze near its own port). [`orthogonal::staircase_punctures_its_own_endpoint`]
/// is the *unpadded* test that tells the two apart — the same one [`route_with_ports`] itself now
/// runs before ever handing a raw-derived staircase route to `clear_local_route`, so this test and
/// the router's own decision are stated in terms of the same function rather than two hand-rolled
/// copies that could quietly drift apart.
///
/// Reused by the corpus-wide loop below and by the real-diagram regression tests, the same split
/// [`assert_no_segment_crosses_a_foreign_node`] already has.
fn assert_no_edge_crosses_its_own_endpoint(name: &str, d: &Diagram) {
    for e in &d.edges {
        let (Some(source), Some(target)) = (d.node(&e.from), d.node(&e.to)) else {
            continue; // a cluster-anchored end has no real node box to puncture
        };
        assert!(
            !orthogonal::staircase_punctures_its_own_endpoint(
                &e.points,
                Some(source),
                Some(target)
            ),
            "{name}: edge {}->{} re-enters its own endpoint node's interior: {:?}, \
             source {:?}, target {:?}",
            e.from,
            e.to,
            e.points,
            source.bounds(),
            target.bounds()
        );
    }
}

/// [`assert_no_edge_crosses_its_own_endpoint`], run over the whole corpus — the counterpart to
/// [`orthogonal_no_segment_crosses_a_foreign_node_across_the_whole_corpus`] for an edge's own two
/// ends rather than every other node.
#[test]
fn orthogonal_no_edge_crosses_its_own_endpoint_across_the_whole_corpus() {
    for (name, src) in orthogonal_full_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        assert_no_edge_crosses_its_own_endpoint(name, &d);
    }
}

/// The pixel-level half of the proof above: rasterises `A --> B` under `"konoma-orthogonal"` and
/// scans the column under the arrow, from inside `A` down through the arrow and into `B`, looking
/// for the transparent gap `docs/FEATURE-MERMAID-RENDERER.md` §10-1 asks for between the arrow
/// tip's ink and `B`'s own stroke ink.
///
/// This is the test that actually would have caught the inward-vs-outward regression the sibling
/// vector-level test's own doc describes: with the endpoint pulled inward, `B`'s node (painted
/// after the edge) covers the part of the tip that pokes past the boundary and the scan below
/// finds ink touching ink with **no** transparent row in between — which is exactly what a
/// pre-fix run of this test showed before this fix landed (an SVG dump and a 4×-rasterised pixel
/// scan were both read by hand — `docs/STATUS.md`'s "検証してから言う" — not inferred from the
/// vector coordinates alone).
#[test]
fn orthogonal_arrow_tip_has_a_visible_gap_from_the_node_in_real_pixels() {
    let src = "flowchart TD\n  A --> B";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let a = d.node("A").expect("A must exist");
    let b = d.node("B").expect("B must exist");
    assert!(
        (a.center.x - b.center.x).abs() < AXIS_EPS,
        "the fixture must be a straight vertical drop so one column crosses both the arrow and B's top edge"
    );

    let svg = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("must render");
    let scale = 4.0;
    let img = crate::preview::svg::rasterize_bytes(
        svg.as_bytes(),
        FsPath::new("orthogonal-tip-gap.svg"),
        (d.width.max(d.height) * scale).round() as u32,
    )
    .expect("must rasterize");
    let rgba = img.to_rgba8();

    let cx = (a.center.x * scale).round() as u32;
    let (_, b_top, _, _) = b.bounds();
    let scan_top = ((a.center.y) * scale).round() as u32;
    let scan_bottom = ((b_top + 2.0) * scale).round() as u32;

    // Column already inside A, at its own centre, must not be transparent (A's own fill).
    assert_ne!(
        rgba.get_pixel(cx, scan_top)[3],
        0,
        "the scan must start inside A's own fill, or it is not testing the right column"
    );
    // Somewhere between the arrow's ink and B's top edge, the column must go fully transparent —
    // the gap the spec asks for. A flush (zero-gap) tip, or one hidden under B's own paint,
    // leaves no such row.
    let saw_transparent_gap = (scan_top..=scan_bottom).any(|y| rgba.get_pixel(cx, y)[3] == 0);
    assert!(
        saw_transparent_gap,
        "no fully-transparent row between the arrow tip and B's top edge — the tip is touching \
         or crossing into B rather than clearing it by ~1px"
    );
    // And B's own stroke ink (its outline colour, not its fill) really is there, at or after its
    // geometric top edge — confirming the gap ends at B and is not some unrelated blank band.
    // The palette an orthogonal render actually draws in — `Theme::for_routing`'s own answer, not
    // whatever `[ui] mermaid_theme` says, which the mode ignores.
    let stroke_hex = theme::Theme::for_routing("dark", Routing::Orthogonal).node_stroke;
    let (sr, sg, sb) = hex_to_rgb(stroke_hex);
    let saw_node_stroke = (scan_top..=scan_bottom).any(|y| {
        let p = rgba.get_pixel(cx, y);
        p[3] == 255 && close(p[0], sr) && close(p[1], sg) && close(p[2], sb)
    });
    assert!(
        saw_node_stroke,
        "B's own stroke colour ({stroke_hex}) must appear in the scanned column"
    );
}

/// `#rrggbb` → `(r, g, b)`, for comparing against a rasterised pixel.
///
/// `pub(super)`: the state-diagram half of this harness (`state_tests.rs`) shares it too, rather
/// than duplicating the same hex parse.
pub(super) fn hex_to_rgb(hex: &str) -> (u8, u8, u8) {
    let hex = hex.trim_start_matches('#');
    let r = u8::from_str_radix(&hex[0..2], 16).unwrap();
    let g = u8::from_str_radix(&hex[2..4], 16).unwrap();
    let b = u8::from_str_radix(&hex[4..6], 16).unwrap();
    (r, g, b)
}

/// Whether two 8-bit channel values are close enough to call the same colour — antialiasing at a
/// shape's own edge blends a pixel or two, so an exact match is the wrong bar here.
///
/// `pub(super)`: shared with `state_tests.rs`, see [`hex_to_rgb`].
pub(super) fn close(a: u8, b: u8) -> bool {
    (a as i16 - b as i16).abs() <= 6
}

/// §10-1 item 5, "辺・矢尻・ラベル文字・ノード枠を同色で揃える": under `"konoma-orthogonal"`, an
/// edge's arrow head is painted the line's own resolved stroke colour (`class`/`:::`/`linkStyle`,
/// falling back to the theme default) rather than mermaid's fixed `theme.arrowhead` — confirmed
/// both in the emitted markup (`svg::emit_tip`'s `color` parameter) and, for the theme-default
/// case, that it differs from `"splines"`'s fixed colour.
#[test]
fn orthogonal_arrow_head_matches_the_edges_resolved_stroke_colour() {
    let src = "flowchart LR\n  A --> B\n  linkStyle 0 stroke:#1f6feb";

    let ortho = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("must render");
    assert!(
        ortho.contains("stroke=\"#1f6feb\""),
        "the edge's own path must carry its linkStyle colour: {ortho}"
    );
    let arrow_at = ortho
        .find("<polygon points=")
        .expect("an arrow head polygon must be emitted");
    let fill = attr(&ortho[arrow_at..], "fill").expect("the polygon must carry a fill");
    assert_eq!(
        fill, "#1f6feb",
        "an orthogonal arrow head must be painted the edge's resolved linkStyle colour: {ortho}"
    );

    // Under splines, the very same source keeps mermaid's own fixed arrowhead colour: the
    // linkStyle blue on the line, the theme's grey on the tip — the two are independent, unlike
    // under orthogonal routing.
    let splines = render_flow(src, "dark", "basis", "splines").expect("must render");
    assert!(splines.contains("stroke=\"#1f6feb\""));
    let arrow_at = splines
        .find("<polygon points=")
        .expect("an arrow head polygon must be emitted");
    let fill = attr(&splines[arrow_at..], "fill").expect("the polygon must carry a fill");
    let theme_arrowhead = theme::Theme::named("dark").arrowhead;
    assert_eq!(
        fill, theme_arrowhead,
        "splines must keep mermaid's own fixed arrowhead colour regardless of linkStyle: {splines}"
    );
    assert_ne!(
        fill, "#1f6feb",
        "this assertion is only meaningful if the theme default actually differs from the \
         linkStyle colour used above"
    );
}

/// A node with several colour-coded outgoing edges (`linkStyle <n> stroke:...`, the real-world
/// shape `docs/STATUS.md` records the 2026-08-28 `linkStyle` regression coming from) each get
/// their own arrow head colour under `"konoma-orthogonal"` — not all painted the same, and not
/// all left at the theme default.
#[test]
fn orthogonal_arrow_heads_differ_per_edge_when_their_linkstyles_differ() {
    let src = "flowchart TD\n  A --> B\n  A --> C\n  \
               linkStyle 0 stroke:#1f6feb\n  linkStyle 1 stroke:#d4a017";
    let svg = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("must render");
    let mut fills = Vec::new();
    let mut rest = svg.as_str();
    while let Some(at) = rest.find("<polygon points=") {
        let slice = &rest[at..];
        fills.push(
            attr(slice, "fill")
                .expect("every polygon here carries a fill")
                .to_string(),
        );
        rest = &slice[1..];
    }
    assert!(
        fills.contains(&"#1f6feb".to_string()) && fills.contains(&"#d4a017".to_string()),
        "each edge's own linkStyle colour must reach its own arrow head: {fills:?}"
    );
}

/// The value of `attr` inside the first tag `haystack` starts with — a small hand-rolled reader
/// rather than an XML parser, since all this needs is one attribute out of one already-known tag.
pub(super) fn attr<'a>(haystack: &'a str, attr: &str) -> Option<&'a str> {
    let needle = format!("{attr}=\"");
    let start = haystack.find(&needle)? + needle.len();
    let end = start + haystack[start..].find('"')?;
    Some(&haystack[start..end])
}

// ---------------------------------------------------------------------------------------------
// Stage 2: port eviction (docs/FEATURE-MERMAID-RENDERER.md §10-1 item 1, "退避則")
// ---------------------------------------------------------------------------------------------
//
// `orthogonal::tests` (in `orthogonal.rs`) states the eviction rules directly, against
// hand-built `PlacedNode`s that put an exact number of claims on an exact face without depending
// on dagre's own placement to happen to produce that shape. The tests below are the other half:
// real flowchart sources through the actual `render_flow`/`lay_out_flow` production entry
// points, so the *wiring* between `lay_out_spec`'s growth-retry loop and `orthogonal::evict` is
// what is being checked, not just the eviction formula in isolation. Every fixture and every
// pinned number below was found by dumping real output first (`laid_out_flow`/`laid_out_curve`
// printed by hand) and reading it, not by predicting what dagre would do — a 9-way fan-in was
// the first source that actually produced 4 merges on one face and forced real node growth; a
// naive guess (3 sources, one per face) split unevenly across dagre's own barycenter placement
// instead and grew nothing.

/// A real 9-way fan-in (`A`..`I` all merge into `Z`) is not evenly spread by dagre. Before
/// `align_straight_lanes`'s `r + 1` adjacency bug was fixed (2026-09-01), the function never
/// selected a lane at all, so this fixture's expected values were dagre's own unaligned placement.
///
/// §10-3 item 10's own merge-side mirror (`orthogonal::merge_trunk_index`) is what picks the lane
/// now: this is a **pure merge** — nine sources on one rank, one target, nothing else — so the
/// straight edge is not "タイは上・左優先"'s own leftmost source but the **median in declaration
/// order**, `E`, the fifth of nine (`sources.len() / 2 == 4`). None of the nine carries a
/// through-lane of its own, so `merge_trunk_index`'s first clause does not fire and the median is
/// the answer. `Z` moves to sit under `E`, the middle of the row.
///
/// §10-3 item 3's own correction (`classify`'s `merge_target_side` doc): a merge target always
/// rides the *flow*-axis face, not the cross-axis one this fixture originally exercised — for `TD`
/// that is Top/Bottom, so `E->Z` (aligned) and every one of the other eight (ordinary merges) all
/// land on `Z`'s single Top face together, dumped and confirmed (all nine share the exact same
/// `y`), not assumed — `Z`'s Left/Right faces go entirely unused.
///
/// §10-3 item 12's own "面のポートは相手の側で配る" (`docs/FEATURE-MERMAID-RENDERER.md`) decides how
/// wide, and with the median on the lane the answer is the *symmetric* one the design draws:
/// `A`..`D` genuinely sit left of `E` and `F`..`I` genuinely sit right of it, so the eight
/// non-aligned claims split four a side — `4 * PORT_SPACING = 64px` of reach either way, plus the
/// corner clearance, doubled for item 12's own "中心対称に拡大": `2 * (4*PORT_SPACING +
/// PORT_CLEARANCE) = 144px`. The pre-mirror pick (`A`, the leftmost) put all eight on one side and
/// needed `2 * (8*PORT_SPACING + PORT_CLEARANCE) = 272px` — nearly twice the box for the same nine
/// ports, which is exactly the "lines must not get complicated" cost §10-0 weighs the rule by
/// (measured over the whole fixture at the same time: 28 bends and one crossing before, 20 bends
/// and none after).
#[test]
fn orthogonal_growth_widens_a_node_whose_face_cannot_fit_its_ports() {
    let src = "flowchart TD\n  A --> Z\n  B --> Z\n  C --> Z\n  D --> Z\n  E --> Z\n  \
               F --> Z\n  G --> Z\n  H --> Z\n  I --> Z";

    let splines = laid_out_curve(src, "basis");
    let z_splines = splines.node("Z").expect("Z must exist");
    assert_eq!(
        z_splines.size.h, 45.400000000000006,
        "splines must not grow Z at all — dumped once and pinned"
    );

    let ortho = laid_out_flow(src, "basis", "konoma-orthogonal");
    let z_ortho = ortho.node("Z").expect("Z must exist");
    // §10-3 items 3, 10 and 12 (this test's own doc): all nine edges land on Z's Top face, the
    // median source `E` anchors at offset 0, and the eight remaining claims split four a side —
    // `2 * (4 * PORT_SPACING + PORT_CLEARANCE) = 144px`.
    assert_eq!(
        z_ortho.size.w, 144.0,
        "Z's width must grow to exactly 2 * (4*PORT_SPACING + PORT_CLEARANCE) = 144px — item 12's \
         own symmetric grow around the median-anchored, two-sided merge item 10 asks for"
    );
    // Height is untouched: nothing asked Z's Left/Right faces to grow at all any more, so it is
    // still exactly the height §10-8 N1 gives a one-line label — 36px since 2026-09-05, and the
    // splines box's own 45.4px before that. Stated against N1's own function rather than against
    // either number so that what this line pins stays "nothing grew it" (N4's own "拡大はポートが
    // 乗る軸のみ") rather than a height that has nothing to do with this fixture.
    let (_, z_label_box) =
        shapes::orthogonal_node(z_ortho.shape, "Z").expect("Z is a plain rectangle");
    assert_eq!(
        z_ortho.size.h, z_label_box.h,
        "no face asked Z's height to grow, so it must still be its label-derived height"
    );

    let (z_left, z_top, _, _) = z_ortho.bounds();
    let top_face_y = z_top - orthogonal::PORT_INSET;

    let mut top_xs = Vec::new();
    let mut aligned_count = 0;
    for e in &ortho.edges {
        if e.to != "Z" {
            continue;
        }
        let bends = e.points.len().saturating_sub(2);
        let last = e.points.last().unwrap();
        assert!(
            (last.y - top_face_y).abs() < 1e-6,
            "every edge into Z must land on its Top face now: {e:?}"
        );
        if bends == 0 {
            assert_eq!(
                e.from, "E",
                "E is the median source in declaration order, so it wins Z's one aligned slot \
                 (§10-3 item 10's merge mirror, not the leftmost-source tie-break): {e:?}"
            );
            aligned_count += 1;
        } else {
            // Not pinned to exactly 2 any more (this assertion's own prior wording, "an ordinary
            // merge onto Z's Top face is... a two-bend shape"): nine single-width nodes sit in one
            // dense row above Z, each claiming its own 16px port along that row, and every port
            // *except* the two whose ordinary bend already lands below the row entirely (`B`, `G`)
            // sits directly under a *different* sibling than its own source — `C`'s own port sits
            // under `A`, `D`'s straight sweep passes clean through `B`'s box on the way to a gap
            // between `A` and `B`, and so on. A plain two-bend route from many of these sources
            // would run straight through that sibling's box; nothing before this test's own local
            // clearance fix (`clear_local_route`/`local_detour`, `docs/FEATURE-MERMAID-RENDERER.md`
            // §10-5) ever checked this fixture for crossings, so the exact "always 2" count this
            // assertion used to pin was never actually verified safe — dumping the real geometry
            // (`docs/STATUS.md`'s own ★未修正 history on `zz-design-2c`, the bug this fix targets)
            // shows most of `C`..`I` need a genuine extra jog around whichever sibling their own
            // straight run would otherwise cross. What still has to hold, regardless of how many
            // extra bends a crossing needs: an even number (every detour is a there-and-back pair)
            // and, the property that actually matters, no crossing at all.
            assert_eq!(
                bends % 2,
                0,
                "every bend count must be even (paired turns): {e:?}"
            );
            for w in e.points.windows(2) {
                for n in &ortho.nodes {
                    if n.id == e.from || n.id == e.to {
                        continue;
                    }
                    assert!(
                        !orthogonal::segment_crosses_node(&w[0], &w[1], n),
                        "{}->Z segment {:?}-{:?} must not cross {}: {e:?}",
                        e.from,
                        w[0],
                        w[1],
                        n.id
                    );
                }
            }
        }
        top_xs.push(last.x);
    }
    assert_eq!(
        aligned_count, 1,
        "exactly one edge must be the aligned E->Z"
    );
    assert_eq!(top_xs.len(), 9, "all nine edges must share Z's Top face");

    top_xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
    // 16px apart and — §10-3 items 10 and 12 together — symmetric about Z's own centre: `E`'s own
    // aligned claim (offset 0) sits *at* the centre with four ports either side of it, because the
    // merge mirror put the median source on the lane rather than an end one.
    for w in top_xs.windows(2) {
        assert!(
            (w[1] - w[0] - orthogonal::PORT_SPACING).abs() < 1e-6,
            "ports on one face must be exactly 16px apart: {top_xs:?}"
        );
    }
    assert!(
        (top_xs[4] - z_ortho.center.x).abs() < 1e-6,
        "the aligned E->Z takes the exact centre slot, the run's own middle port: {top_xs:?} vs {}",
        z_ortho.center.x
    );
    assert!(
        (top_xs[0] - (z_ortho.center.x - 4.0 * orthogonal::PORT_SPACING)).abs() < 1e-6
            && (top_xs[8] - (z_ortho.center.x + 4.0 * orthogonal::PORT_SPACING)).abs() < 1e-6,
        "the run's own two ends sit 4*PORT_SPACING either side of centre: {top_xs:?} vs {}",
        z_ortho.center.x
    );
    // The box itself still grows symmetrically about the centre (item 12's own "中心対称に拡大") —
    // clearance on the *unused* left side of the face matches the busy right side's own reach.
    let half_w = z_ortho.size.w / 2.0;
    for &x in top_xs.iter() {
        let from_center = (x - z_ortho.center.x).abs();
        assert!(
            half_w - from_center >= orthogonal::PORT_CLEARANCE - 1e-6,
            "port {from_center}px from centre must clear the corner by \
             {}px (half-width {half_w}): {top_xs:?}",
            orthogonal::PORT_CLEARANCE
        );
    }
    // And every port stays within Z's own (grown) flat run, never off past its left edge.
    assert!(
        top_xs
            .iter()
            .all(|&x| x >= z_left && x <= z_left + z_ortho.size.w),
        "every port must sit within Z's own grown width: {top_xs:?} vs [{z_left}, {}]",
        z_left + z_ortho.size.w
    );
}

/// A three-way merge whose own claims genuinely need more room than `Z`'s natural width — §10-3
/// items 3 and 12 (`docs/FEATURE-MERMAID-RENDERER.md`): `A --> Z` is aligned and lands on `Z`'s
/// Top face at offset 0; `B` and `C` both genuinely sit to `Z`'s right (dumped: `B.center.x =
/// 141.3`, `C.center.x = 235.1`, both past `Z.center.x = 48.0`), so item 12 puts both non-aligned
/// claims on the same (right) side rather than splitting them across the centre — `+16`/`+32`.
/// `required_flat = 2 * (2*PORT_SPACING + PORT_CLEARANCE) = 80px`, wider than `Z`'s own natural
/// (splines) width of ~68.55px, so `Z` must grow. Before item 12's fix this fixture's own name
/// ("a face with room to spare must not grow") held — the old array-symmetric grid split the two
/// non-aligned claims onto opposite sides of `Z`'s centre (`-16`/`+16`), whose narrower
/// `max_abs_offset = 16` fit inside 68.55px without growing at all; that was the side-crossing bug
/// (§10-3 item 12's own "同じ辺にn本つく…下から来る辺が中心より上のポートへ回り込む形は禁止"), not a
/// genuinely roomy face.
///
/// `X --> A` is what keeps the merge one-sided, and it is not decoration: without it the three
/// sources share one rank and §10-3 item 10's own merge mirror
/// (`orthogonal::pure_merges`/`merge_trunk_index`) hands the lane to the **median** source, which
/// splits `A` and `C` either side of `B` and needs no growth at all. With it, `A` sits one rank
/// past `B` and `C`, so `Z` is reached from two different ranks — not a pure merge at all
/// (`pure_merges`'s own "from the one rank immediately below" reading, which is simply what
/// `align_straight_lanes` can act on, since it only ever considers adjacent ranks) — the mirror
/// stays out, and `A --> Z`, the only candidate in its own rank window, takes the lane with both
/// siblings genuinely on one side of it. That is exactly the geometry item 12 is about, and
/// asserting which edge is straight is what keeps this fixture honest about producing it.
#[test]
fn orthogonal_one_sided_merge_grows_to_fit_both_siblings_on_the_same_side() {
    let src = "flowchart TD\n  X --> A\n  A --> Z\n  B --> Z\n  C --> Z";
    let splines = laid_out_curve(src, "basis");
    let ortho = laid_out_flow(src, "basis", "konoma-orthogonal");
    let z_splines = splines.node("Z").expect("Z must exist");
    let z_ortho = ortho.node("Z").expect("Z must exist");
    let aligned: Vec<&str> = ortho
        .edges
        .iter()
        .filter(|e| e.to == "Z" && e.points.len() == 2)
        .map(|e| e.from.as_str())
        .collect();
    assert_eq!(
        aligned,
        vec!["A"],
        "Z is reached from two ranks, so this is not a pure merge and A --> Z — the only \
         candidate in its own rank window — keeps the lane, leaving B and C on one side"
    );
    // The rule is "both non-aligned claims sit on the SAME side of the lane", which this fixture
    // used to state through `Z`'s grown width alone (`2*(2*PORT_SPACING+PORT_CLEARANCE) = 80px`,
    // against splines' natural ~68.55px). §10-8 N2's own 96px minimum (2026-09-05) is wider than
    // that 80px, so the width can no longer show it — N4 takes the max and the label's own box
    // wins. Stated on the ports themselves instead, which is what item 12 is actually about and
    // what the old width was only ever a proxy for.
    let port_dx = |from: &str| {
        let e = ortho
            .edges
            .iter()
            .find(|e| e.from == from && e.to == "Z")
            .unwrap_or_else(|| panic!("{from} --> Z must exist"));
        e.points.last().expect("a routed edge has points").x - z_ortho.center.x
    };
    assert_eq!(
        (port_dx("A"), port_dx("B"), port_dx("C")),
        (
            0.0,
            orthogonal::PORT_SPACING,
            2.0 * orthogonal::PORT_SPACING
        ),
        "A keeps the lane and B and C both take ports on the SAME (right) side of it — never one \
         either side of the centre"
    );
    let needed = 2.0 * (2.0 * orthogonal::PORT_SPACING + orthogonal::PORT_CLEARANCE);
    assert!(
        z_ortho.size.w >= needed,
        "Z's Top face must be wide enough for the outermost of those ports to keep its corner \
         clearance: {:?} vs {needed} needed, splines' natural {:?}",
        z_ortho.size,
        z_splines.size
    );
    let (_, z_label_box) =
        shapes::orthogonal_node(z_ortho.shape, "Z").expect("Z is a plain rectangle");
    assert_eq!(
        z_ortho.size.h, z_label_box.h,
        "no face asked Z's height to grow, so it must still be its label-derived height"
    );
}

/// §10-3 item 10's own merge-side mirror of `mod.rs`'s `fan_split`, stated on the plainest shape
/// it is about — three sources on one rank, one target, nothing else — once per flow direction, so
/// neither axis can be the only one that happens to work.
///
/// None of the three carries a through-lane, so `orthogonal::merge_trunk_index` falls to its
/// median clause and the **second-declared** source takes the target's own lane, with the other
/// two entering on the `±PORT_SPACING` ports either side of it in cross order, two bends each
/// (§10-1 item 1's own "退避則適用時は2回まで"), and no two of the three crossing. Mutating that
/// median to either end source (`sources.len() / 2` → `0`, or → `len - 1`) fails here as well as
/// in `orthogonal::tests::merge_trunk_index_takes_the_median_source_in_declaration_order`: this is
/// the composition test for the same rule, through the real `lay_out_flow` entry point rather than
/// the formula alone.
#[test]
fn orthogonal_pure_merge_puts_the_median_source_on_the_targets_lane() {
    use crate::preview::mermaid::flowchart::Direction;
    if !text_metrics::fonts_available() {
        return;
    }
    for (direction, header) in [
        (Direction::LeftToRight, "flowchart LR"),
        (Direction::TopToBottom, "flowchart TB"),
    ] {
        let src = format!("{header}\n  A --> Z\n  B --> Z\n  C --> Z\n  Z --> W");
        let d = laid_out_flow(&src, "basis", "konoma-orthogonal");
        let z = d.node("Z").expect("Z must exist");
        let z_cross = super::cross_of(direction, z);
        let leg = |from: &str| -> &PlacedEdge {
            d.edges
                .iter()
                .find(|e| e.from == from && e.to == "Z")
                .unwrap_or_else(|| panic!("{from} -> Z must be routed"))
        };
        // The port coordinate on Z's own flow-axis entry face runs along the cross axis — the same
        // reading in both directions, which is why `cross_of`'s own axis choice is reused here.
        let port = |e: &PlacedEdge| match direction {
            Direction::TopToBottom | Direction::BottomToTop => e.points[e.points.len() - 1].x,
            _ => e.points[e.points.len() - 1].y,
        };
        let (a, b, c) = (leg("A"), leg("B"), leg("C"));
        assert_eq!(
            b.points.len(),
            2,
            "{header}: B is the median source in declaration order, so its edge is the straight \
             one: {:?}",
            b.points
        );
        assert!(
            (port(b) - z_cross).abs() < 0.01,
            "{header}: the trunk enters on Z's own centre port: {} vs {z_cross}",
            port(b)
        );
        for (name, e, want) in [
            ("A", a, z_cross - orthogonal::PORT_SPACING),
            ("C", c, z_cross + orthogonal::PORT_SPACING),
        ] {
            assert_eq!(
                e.points.len(),
                4,
                "{header}: {name} -> Z is port-displaced, so §10-1 item 1 gives it two bends: {:?}",
                e.points
            );
            assert!(
                (port(e) - want).abs() < 0.01,
                "{header}: {name} -> Z enters one PORT_SPACING off the trunk's own port, on the \
                 side {name} genuinely sits (§10-3 item 12): {} vs {want}",
                port(e)
            );
        }
        for (i, (from_a, x)) in [("A", a), ("B", b), ("C", c)].iter().enumerate() {
            for (from_b, y) in [("A", a), ("B", b), ("C", c)].iter().skip(i + 1) {
                let crossing = x.points.windows(2).find_map(|wa| {
                    y.points
                        .windows(2)
                        .find_map(|wb| orthogonal::segment_crossing(wa, wb))
                });
                assert!(
                    crossing.is_none(),
                    "{header}: {from_a} -> Z crosses {from_b} -> Z at {crossing:?}: {:?} vs {:?}",
                    x.points,
                    y.points
                );
            }
        }
    }
}

/// The lower edge of §10-3 item 10's own regime ([`orthogonal::MERGE_MEDIAN_MIN_SOURCES`]): a
/// **two**-source merge keeps §10-1 item 2's plain "タイは上・左優先" greedy, so the *first*
/// source in cross order takes the lane, not the second.
///
/// Two sources give the median nothing to buy — one straight edge and one sibling on one side of
/// the centre port either way — and the alignment cannot deliver it anyway: a chain is aligned
/// onto its members' own average and the overlap sweep after it only ever pushes a node later on
/// its rank, so making the *last* of two sources the trunk pulls it up into its own predecessor
/// and it is pushed straight back, leaving the lane on neither and both edges bending (measured on
/// this exact source: 2 bends over the three edges the greedy's way, 4 the two-source median's).
/// Mutating `MERGE_MEDIAN_MIN_SOURCES` from 3 to 2 fails here.
#[test]
fn orthogonal_two_source_merge_keeps_the_top_left_tie_break() {
    if !text_metrics::fonts_available() {
        return;
    }
    for header in ["flowchart LR", "flowchart TB"] {
        let src = format!("{header}\n  A --> C\n  B --> C\n  C --> D");
        let d = laid_out_flow(&src, "basis", "konoma-orthogonal");
        let straight: Vec<&str> = d
            .edges
            .iter()
            .filter(|e| e.to == "C" && e.points.len() == 2)
            .map(|e| e.from.as_str())
            .collect();
        assert_eq!(
            straight,
            vec!["A"],
            "{header}: with only two sources the greedy's own top/left pick keeps the lane"
        );
    }
}

/// [`orthogonal::pure_merges`]'s own "no source of it fans out too" half, through the real entry
/// point: a complete bipartite pair of merges, three sources feeding both of two targets.
///
/// Deciding each merge's trunk in ignorance of the other picks the same median source (`B`) for
/// both, which cannot be — §10-1 item 2's own "各ノード高々1入1出" gives `B` one out-lane — so one
/// of the two targets ends up taking a lane from a source the other has already claimed, and the
/// two lanes cross. §10-0 settles it, since the plain "タイは上・左優先" greedy draws the same six
/// edges without a crossing at all. `amp-chain`'s own `A & B --> C & D` is the corpus shape this
/// was found on (it failed both corpus-wide crossing invariants,
/// `orthogonal_edges_leaving_one_node_never_cross_each_other_across_corpus` and
/// `orthogonal_no_edge_crosses_its_own_endpoint_across_the_whole_corpus`); this fixture states it
/// with three sources rather than two so it is the *purity* check being tested rather than
/// [`orthogonal::MERGE_MEDIAN_MIN_SOURCES`], which excludes a two-source merge anyway.
#[test]
fn orthogonal_merge_rule_stays_out_of_two_merges_that_share_their_sources() {
    if !text_metrics::fonts_available() {
        return;
    }
    let d = laid_out_flow(
        "flowchart LR\n  A & B & C --> T & U\n  T --> V",
        "basis",
        "konoma-orthogonal",
    );
    let straight: Vec<(&str, &str)> = d
        .edges
        .iter()
        .filter(|e| e.points.len() == 2 && (e.to == "T" || e.to == "U"))
        .map(|e| (e.from.as_str(), e.to.as_str()))
        .collect();
    assert_eq!(
        straight,
        vec![("A", "T"), ("B", "U")],
        "the greedy's own top/left pick stands: A takes T's lane and B takes U's, two lanes that \
         do not cross"
    );
    // The two lanes themselves never cross — which is the whole of what the greedy buys here. A
    // complete bipartite graph has crossings no routing can remove (`A -> U` and `B -> T` have to
    // swap sides somewhere), so a diagram-wide "no crossing" assertion would be pinning something
    // this rule neither promises nor could deliver.
    let lanes: Vec<&PlacedEdge> = d
        .edges
        .iter()
        .filter(|e| (e.from == "A" && e.to == "T") || (e.from == "B" && e.to == "U"))
        .collect();
    let crossing = lanes[0].points.windows(2).find_map(|wa| {
        lanes[1]
            .points
            .windows(2)
            .find_map(|wb| orthogonal::segment_crossing(wa, wb))
    });
    assert!(
        crossing.is_none(),
        "the two selected lanes must stay parallel: {crossing:?}"
    );
}

/// Across the capped corpus ([`orthogonal_dag_corpus`]), no orthogonal-routed edge ever exceeds
/// two bends — §10-1 item 1's "ポート分配で端点がずれた辺は曲げ2回まで許す" is a *cap* on the
/// aligned/branch/merge shapes, and this is the invariant stage 1's own bend-count tests could not
/// state, because eviction (and the growth it can trigger) did not exist yet: an aligned edge
/// whose two ends land on different eviction offsets needs exactly the second bend this rule
/// allows for. A back edge and a collision-fallback edge are both deliberately excluded from this
/// cap — see [`orthogonal_dag_corpus`]'s own doc — and both were caught by this test being run
/// over the wrong corpus before either exclusion existed: `branch`'s `D --> B` cycle came back
/// with 4 bends on the first run (correctly — §10-1 item 2 puts no limit on a back edge at all),
/// and stage 3's collision fix later did the same to `amp-chain`'s `A --> D`.
#[test]
fn orthogonal_bend_count_never_exceeds_two() {
    for (name, src) in orthogonal_dag_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for e in &d.edges {
            let bends = e.points.len().saturating_sub(2);
            assert!(
                bends <= 2,
                "{name}: edge {}->{} has {bends} bends, more than the rule 4 cap: {:?}",
                e.from,
                e.to,
                e.points
            );
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Stage 3: lane alignment and node-collision avoidance (docs/FEATURE-MERMAID-RENDERER.md §10-1
// item 2, "レーン揃え", plus item 1's collision fix)
// ---------------------------------------------------------------------------------------------

/// Every routed segment of every edge in `d`, other than the two the edge itself owns, must clear
/// every node's box — the "強い不変条件" stage 3's collision fix exists to guarantee. Asserts
/// through `orthogonal::segment_crosses_node`, the exact box test `classify` itself runs, so this
/// states the same question about the *finished* diagram that the routing decision already asked
/// about a candidate shape.
fn assert_no_segment_crosses_a_foreign_node(name: &str, d: &Diagram) {
    for e in &d.edges {
        for w in e.points.windows(2) {
            for n in &d.nodes {
                if n.id == e.from || n.id == e.to {
                    continue;
                }
                assert!(
                    !orthogonal::segment_crosses_node(&w[0], &w[1], n),
                    "{name}: edge {}->{} segment {:?}->{:?} crosses {} {:?}",
                    e.from,
                    e.to,
                    w[0],
                    w[1],
                    n.id,
                    n.bounds()
                );
            }
        }
    }
}

/// §10-1 item 1's collision fix, run over the **whole** corpus ([`orthogonal_corpus`]) — stage 3's
/// headline invariant, and stage 5's too: a back edge and `amp-chain`'s collision-fallback edge
/// used to be exempt here (see [`orthogonal_dag_corpus`]'s own doc for why), because stages 1-4's
/// back-edge route was still dagre's own waypoint chain, straightened, with no collision check of
/// its own. Stage 5's [`orthogonal::route_perimeter`] replaces that stopgap with a real
/// collision-avoiding route (`orthogonal::safe_ring_exit`), so the exemption no longer applies —
/// this now runs the invariant over every corpus source, self-loop included.
/// `orthogonal_dag_corpus` stays in use for [`orthogonal_bend_count_never_exceeds_two`], a
/// genuinely different invariant a perimeter or self-loop route is still exempt from by design
/// (many bends is the point of going around the outside).
#[test]
fn orthogonal_no_segment_crosses_a_foreign_node_across_the_whole_corpus() {
    for (name, src) in orthogonal_full_corpus() {
        // `zz-design-2c`'s own `API -> ID` used to be exempted here (§10-4's audit had named this
        // bug class and left it open — `docs/FEATURE-MERMAID-RENDERER.md` §10-4's own "一般化
        // チェックの結果"): a `staircase` edge whose raw dagre waypoints ran straight through the
        // sibling node `Q`, then `メタデータ DB`/`成果物保管`/`解析サンドボックス`, because
        // `clear_local_route`'s own remediation slid the *entire* straight run to one shared
        // coordinate — a single degree of freedom that cannot satisfy two obstacles at different
        // points along the run each demanding a different clearance (`Q`'s row only clears to its
        // left; the row below only clears to the right of where that pushed it), so the fix
        // oscillated between the two colliding coordinates every pass and silently gave up once
        // its budget ran out, still crossing `Q`. `local_detour` (`orthogonal.rs`) replaces the
        // whole-run slide with a local jog around each obstacle's own span, independent of every
        // other obstacle sharing the run — the exemption is gone; this now runs the invariant over
        // `zz-design-2c` too.
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        assert_no_segment_crosses_a_foreign_node(name, &d);
    }
}

/// The real diagram `docs/FEATURE-MERMAID-RENDERER.md` §10-1 item 1 names as this stage's
/// motivating case: `samples/mermaid.ja.md`'s big flowchart, where `MD`(ブロックモデル)'s branch
/// to `MM`(mermaid)used to sweep straight through `NA`(プレビュー不可)'s box — both sitting in
/// `MD`'s own rank, directly in the path a branch's cross-axis sweep runs along. Confirms the
/// concrete bug is gone, not just the general mechanism: `MD`'s own two edges (`MD->MM`,
/// `MD->MA`) must clear `NA`, and the whole diagram must still hold the strong invariant.
#[test]
fn orthogonal_settings_rules_sample_no_longer_pierces_a_sibling_node() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");

    let na = d.node("NA").expect("NA must exist");
    for id in ["MM", "MA"] {
        let e = d
            .edges
            .iter()
            .find(|e| e.from == "MD" && e.to == *id)
            .unwrap_or_else(|| panic!("MD->{id} must exist"));
        for w in e.points.windows(2) {
            assert!(
                !orthogonal::segment_crosses_node(&w[0], &w[1], na),
                "MD->{id} must no longer pierce NA: segment {:?}->{:?}, NA bounds {:?}",
                w[0],
                w[1],
                na.bounds()
            );
        }
    }

    assert_no_segment_crosses_a_foreign_node("settings-rules", &d);
    // Neither of the two invariants below was ever run against this real diagram before — only
    // against `CORPUS`'s hand-built fixtures (`assert_endpoints_sit_outside_and_perpendicular`'s
    // own doc explains why that gap let a real regression through) — so both are pinned here too,
    // alongside the foreign-node check this test already ran.
    assert_endpoints_sit_outside_and_perpendicular("settings-rules", &d);
    assert_no_edge_crosses_its_own_endpoint("settings-rules", &d);
}

/// The coordinator's own third real-pixel finding on this exact diagram (2026-09-01, user report:
/// the mermaid node's own arrow tip was invisible, and two lines near it were impossible to trace to
/// where they connected): `MD->MM`'s raw-derived staircase route ran ~38px down into `MM`'s own
/// interior before reaching its (correctly placed) bottom port — invisible in the finished picture
/// only because `svg::emit` paints nodes after edges, the same masking `orthogonal_arrow_tip_has_a_
/// visible_gap_from_the_node_in_real_pixels`'s own doc describes for the inward-port bug — and
/// `MM->RS` left `MM`'s bottom port only to double straight back up through `MM`'s own box before
/// turning toward `RS`. Both are the *same* underlying staleness (`route_with_ports`'s own doc):
/// `align_straight_lanes` moved `MM` after dagre's raw waypoint chain was captured, and — unlike a
/// self-loop's `raw`, which `shift_cross` keeps in sync — nothing reprojected a forward staircase
/// edge's interior chain onto `MM`'s new position.
///
/// Pinned two ways: first, `MD->MM`'s own two-edge check the module doc's original NA-piercing case
/// used, generalised from `segment_crosses_node` (a foreign-node question) to
/// `staircase_punctures_its_own_endpoint` (an own-node one); second, calling both whole-diagram
/// invariants — this is what would have failed before the fix.
#[test]
fn orthogonal_settings_rules_sample_mermaid_node_edges_do_not_pierce_it() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");

    let mm = d.node("MM").expect("MM must exist");
    for (from, to) in [("MD", "MM"), ("MM", "RS")] {
        let e = d
            .edges
            .iter()
            .find(|e| e.from == from && e.to == to)
            .unwrap_or_else(|| panic!("{from}->{to} must exist"));
        assert!(
            !orthogonal::staircase_punctures_its_own_endpoint(&e.points, Some(mm), Some(mm)),
            "{from}->{to} must not re-enter MM's own interior: {:?}, MM bounds {:?}",
            e.points,
            mm.bounds()
        );
    }

    assert_endpoints_sit_outside_and_perpendicular("settings-rules", &d);
    assert_no_edge_crosses_its_own_endpoint("settings-rules", &d);
}

/// The coordinator's own second real-pixel finding on this exact diagram (2026-09-01, after
/// `align_straight_lanes`'s adjacency fix started actually moving nodes): once branch/merge
/// collisions against those relocated nodes became more common, every collision-fallback forward
/// edge here rode `route_perimeter` (stage 5's over-broad `shape.reverse || shape.staircase`
/// condition, reverted the same day — `route_with_ports`'s own doc) out to the diagram's outer
/// edge — `設定のルール->デコード`(`C->IM`, the "画像" label) along the very top, `ブロックモデル
/// ->mermaid`/`->数式`(`MD->MM`/`MD->MA`) out past the left edge and back, three parallel outer
/// runs stacked in the bottom-left corner. This diagram is a pure DAG (no cycle anywhere in its
/// source), so **every** edge in it is a forward edge — none of them has any business excursing by
/// a perimeter-lane amount at all, `PERIMETER_MARGIN` or more past the content box. Real output,
/// dumped and confirmed before this was written: `C->IM`'s own worst excursion is ~8.5px (clears
/// the row above it, nothing like a full perimeter loop), and `MD->MM`/`MD->MA` never leave `MD`'s
/// own local column at all — see `docs/STATUS.md` and this file's own git history for the numbers
/// from the regression itself.
#[test]
fn orthogonal_settings_rules_sample_has_no_perimeter_routed_forward_edges() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let bounds = diagram_content_bounds(&d);
    for e in &d.edges {
        let max_excursion = e
            .points
            .iter()
            .map(|p| excursion(bounds, p))
            .fold(0.0_f64, f64::max);
        assert!(
            max_excursion < orthogonal::PERIMETER_MARGIN,
            "{}->{}: excursion {max_excursion}px reaches perimeter-lane territory \
             (PERIMETER_MARGIN={}) in a diagram with no back edge at all: {:?}",
            e.from,
            e.to,
            orthogonal::PERIMETER_MARGIN,
            e.points
        );
    }
}

/// §10-3's "ファン列内の並び順" and "幹7区間の曲げ0" (`docs/FEATURE-MERMAID-RENDERER.md`,
/// `mod.rs`'s own `regroup_fan_lanes` doc), pinned against the real source the rule was reverse-
/// engineered from — `samples/mermaid.ja.md`'s 20-node "大きさ" fence (`SETTINGS_RULES_SAMPLE`),
/// laid out exactly as `docs/mermaid-theme/handoff/round3-Konoma-Flowchart-Routing.dc.html`'s `3a`
/// section hand-authored it.
///
/// **Column order** — `設定のルール`'s ten-way fanout (`C`'s own children) matches `3a`'s own
/// top-to-bottom order *exactly*, all ten positions: the two `txt`-class members with no forward
/// edge of their own (`窓読み`/`T`, `構文強調`/`S`) lead, then `表`/`TB` and `一覧`/`AR` (same
/// class, "同色内は安定" keeping them in their declared order); `pix`-class `ページ描画`/`PD` and
/// `usvg`/`SV` sit closest to the trunk on either side (both converge one rank sooner, into
/// `ラスタライズ`, than `デコード`/`IM` and `キーフレーム`/`VD`, which converge into `セルに合わせ
/// る` a rank later — the "nearest downstream rank sits closer to the spine" tie-break this
/// module's own `regroup_fan_lanes` doc explains, needed here because `IM` is declared *before*
/// `PD` yet sits *farther* from the trunk); `MD`(`ブロックモデル`) — the trunk, the one `txt`
/// member that itself continues on to `mermaid`/`数式` — sits at the group's own centre index
/// (`10 / 2 = 5`); and `プレビュー不可`/`NA`, the one child with no `classDef`-backed class at all,
/// is last regardless of its own declared position.
///
/// **Seven-segment spine** — every rank-to-rank hop of `ファイル → 設定のルール → ブロックモデル →
/// mermaid → ラスタライズ → セルに合わせる → 端末 → 画像プロトコル` draws as `classify`'s `aligned`
/// shape, a straight 2-point line with no bend at all: `F->C` and `RS->FIT`/`FIT->K` were already
/// achievable before this session's work (single- or already-uncrowded faces), but `C->MD`,
/// `MD->MM`, `MM->RS`, and `K->RI` were not — each sits on an even-count face (`C`'s ten-way,
/// `MD`'s two-way, `MM`'s one-way-but-competing, `K`'s three-way) that `evict`'s pre-fix symmetric
/// port grid could never place exactly on the face's own centre (this module's own `orthogonal_
/// branch_and_merge_edges_share_a_face_one_aligned_one_bends_twice` is the general-purpose
/// regression for the same `evict` fix, on a minimal two-claim fixture).
#[test]
fn orthogonal_settings_rules_sample_fan_column_matches_3a_and_spine_is_all_zero_bend() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    assert_no_edge_crosses_its_own_endpoint("settings-rules-sample", &d);
    check_nodes_do_not_overlap("settings-rules-sample", &d);

    let mut fan: Vec<(&str, f64)> = d
        .edges
        .iter()
        .filter(|e| e.from == "C")
        .map(|e| (e.to.as_str(), d.node(&e.to).unwrap().center.y))
        .collect();
    fan.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
    let order: Vec<&str> = fan.iter().map(|(id, _)| *id).collect();
    assert_eq!(
        order,
        vec!["T", "S", "TB", "AR", "PD", "MD", "SV", "IM", "VD", "NA"],
        "C's own ten-way fanout, top to bottom, matching 3a exactly: {order:?}"
    );

    for (from, to) in [
        ("F", "C"),
        ("C", "MD"),
        ("MD", "MM"),
        ("MM", "RS"),
        ("RS", "FIT"),
        ("FIT", "K"),
        ("K", "RI"),
    ] {
        let e = d
            .edges
            .iter()
            .find(|e| e.from == from && e.to == to)
            .unwrap_or_else(|| panic!("{from}->{to} must exist"));
        assert_eq!(
            e.points.len(),
            2,
            "{from}->{to} is a spine segment — a straight 2-point line: {:?}",
            e.points
        );
        assert!(
            (e.points[0].y - e.points[1].y).abs() < 1e-6,
            "{from}->{to} is horizontal (LR flow axis), no cross-axis drift: {:?}",
            e.points
        );
    }
}

/// The coordinator's own repro for the real bug `safe_ring_exit`'s L-shaped fallback used to have
/// (`orthogonal::tests::safe_ring_exit_l_shape_stops_at_the_ring_not_the_far_corner`'s own doc has
/// the full story): a decision node's retry loop (`C -->|再試行| B`) needed the L-shaped fallback
/// at both ends, on the same ring side, and the old third leg drew the return edge the *whole
/// height of the ring* instead of the short local jog its own two ports need. Not part of `CORPUS`
/// (adding it there would move the golden — `docs/FEATURE-MERMAID-RENDERER.md`'s own "ゴールデン
/// 13 本不変" rule), so this is a standalone regression test in the same shape
/// `orthogonal_settings_rules_sample_no_longer_pierces_a_sibling_node` already is.
#[test]
fn orthogonal_decision_retry_loop_does_not_span_the_whole_ring() {
    let src = "flowchart TB\n  A[入力] --> B[整形]\n  B --> C{検査}\n  C -->|合格| D[出力]\n  \
               C -->|再試行| B\n  D -.-> A";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");

    for (from, to) in [("C", "B"), ("D", "A")] {
        let e = d
            .edges
            .iter()
            .find(|e| e.from == from && e.to == to)
            .unwrap_or_else(|| panic!("{from}->{to} must exist"));
        let longest = e
            .points
            .windows(2)
            .map(|w| (w[1].x - w[0].x).hypot(w[1].y - w[0].y))
            .fold(0.0_f64, f64::max);
        // An upper bound on what the two ports genuinely need: the two nodes' own vertical
        // separation, generous enough not to depend on exactly which face eviction picked, but
        // nowhere near the ring's own height (the bug's own symptom: `C->B`'s return edge drew
        // ~394px of ring — most of the diagram — for a ~46px stub before this was fixed).
        let a = d.node(from).expect("source node must exist");
        let b = d.node(to).expect("target node must exist");
        let needed = (a.center.y - b.center.y).abs();
        assert!(
            longest <= needed + 1.0,
            "{from}->{to}: longest segment is {longest}px, more than the ~{needed}px the two \
             ports actually need — the ring-spanning bug is back: {:?}",
            e.points
        );
    }
}

/// Every rank still holds no overlapping node after lane alignment moved some of them — §10-1
/// item 1's "整列でノードを動かした結果…重なった側を押し出して従来の最小間隔を維持する". Checked
/// with the exact same box-overlap assertion [`invariant_nodes_do_not_overlap`] states for the
/// splines path, now over the whole corpus under `"konoma-orthogonal"`.
#[test]
fn orthogonal_lane_alignment_never_leaves_nodes_overlapping() {
    for (name, src) in orthogonal_full_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        check_nodes_do_not_overlap(name, &d);
    }
}

/// §10-1 item 2's "直進辺を挟んで上下(左右)に分かれる辺は…曲げ位置を共有して対称に", read
/// through §10-3 item 3's own correction (`classify`'s `merge_target_side` doc): a merge target
/// now always rides the same flow-axis face a branch target already did, so `B->D`'s aligned
/// (0-bend) shape and `C->D`'s ordinary merge now compete for the exact same face on `D` — `D`'s
/// Top, not two different faces the way they did before the correction (aligned always used the
/// flow axis; the round-2 merge shape used the cross axis, so the two never used to overlap at
/// all).
///
/// [`orthogonal::evict`]'s own doc on `anchor` (§10-3's "ファン列内の並び順"/"幹7区間の曲げ0" work)
/// is what decides the split here: two claims on `D`'s Top face (`B->D`, aligned, and `C->D`, not).
/// `B->D`'s own natural sorted position already coincides with the face's own centre slot (its
/// other end, `B`, sits almost exactly on `D`'s own x — dumped: `B.center.x = 43.055`,
/// `D.center.x = 43.055`), so `B->D` is a genuine straight, absorbed lane: a 2-point line entering
/// dead on `D`'s own centre. `C->D`, its face-mate, is pushed a full `PORT_SPACING = 16px` off
/// it — §10-3 item 12's own "面のポートは相手の側で配る" decides *which* side: `C` sits well to `D`'s
/// own right (dumped: `C.center.x = 89.917`, past `D.center.x`), so `C->D`'s port belongs to the
/// right of `D`'s centre, not the left (a pre-item-12 `evict` used to force the aligned claim into
/// the claims array's own geometric middle index regardless of its own natural sort position, which
/// could drag `C->D` to the wrong side of centre purely as a side effect of that re-splice — the
/// exact same mechanism item 12 fixed on the real `セルに合わせる` merge, `docs/STATUS.md`'s own
/// ★未修正 entry). Still bends twice either way. Dumped and confirmed by hand (`B`'s and `C`'s own
/// x, and both edges' full point lists), not assumed.
#[test]
fn orthogonal_shared_merge_target_face_one_aligned_one_bends_twice() {
    let src = "flowchart TD\n  A ---> B\n  A --> C\n  B --> D\n  C --> D";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let bd = d
        .edges
        .iter()
        .find(|e| e.from == "B" && e.to == "D")
        .expect("B->D must exist");
    let cd = d
        .edges
        .iter()
        .find(|e| e.from == "C" && e.to == "D")
        .expect("C->D must exist");
    let d_node = d.node("D").expect("D must exist");

    // B->D is the aligned leg — a straight 2-point line; C->D still bends twice, since it loses
    // the face's one straight lane to B->D.
    assert_eq!(
        bd.points.len(),
        2,
        "B->D is the aligned leg — a straight 2-point line: {:?}",
        bd.points
    );
    assert_eq!(cd.points.len(), 4, "C->D must bend twice: {:?}", cd.points);

    // B->D enters dead on D's own centre; C->D is pushed a full PORT_SPACING off it, to the
    // *right* (C genuinely sits to D's right — see this test's own doc).
    let bd_entry_x = bd.points.last().unwrap().x;
    let cd_entry_x = cd.points.last().unwrap().x;
    assert!(
        (bd_entry_x - d_node.center.x).abs() < 1e-6,
        "B->D (aligned) enters exactly on D's centre: {bd_entry_x} vs {}",
        d_node.center.x
    );
    assert!(
        (cd_entry_x - (d_node.center.x + orthogonal::PORT_SPACING)).abs() < 1e-6,
        "C->D enters PORT_SPACING right of D's centre (C genuinely sits right of D): {cd_entry_x} \
         vs {}",
        d_node.center.x
    );

    // C->D's own bend still lands where it did before this fix — `A ---> B` is authored with an
    // extra dash (`SpecEdge::minlen` 2) while `A --> C` is the ordinary `minlen` 1, so under §10-3
    // item 8's own rank fix (`pull_back_fan_ranks`, `mod.rs`) `B` genuinely sits one rank further
    // from `A` than `C` does, and `C->D` spans the extra rank `B` occupies (`rank_lane_gap_bend`,
    // §10-3 item 4's own column-gap routing for an edge that skips a populated rank). `B->D` no
    // longer has a "bend row" to check at all — it is a straight line now (the assertion above
    // already pins its only two points). Dumped and confirmed by hand, not assumed.
    //
    // The absolute number moved with §10-8 (2026-09-05): every box in this fixture is 36px tall
    // now instead of 45.4px, so every rank below the first sits higher — `274.2` became `246.0`,
    // a pure consequence of the node heights and not of any routing change. The *rule* is stated
    // first and structurally, so that a future size change re-derives the number rather than
    // hiding a real move: the bend must fall in the clear band between `B`'s own rank and `D`.
    let (_, b_top, _, b_bottom) = d.node("B").expect("B must exist").bounds();
    let (_, d_top, _, _) = d_node.bounds();
    assert!(
        cd.points[1].y > b_bottom && cd.points[1].y < d_top,
        "C->D's bend must land in the clear band between B's rank and D: {:?} vs B {b_top}..\
         {b_bottom}, D top {d_top}",
        cd.points
    );
    let cd_expected_row = 246.0;
    assert!(
        (cd.points[1].y - cd_expected_row).abs() < 1e-6,
        "C->D's bend row: {:?} vs {cd_expected_row}",
        cd.points
    );
}

/// §10-3 item 10's own two invariants (`docs/FEATURE-MERMAID-RENDERER.md` — "合流側はファン根元の
/// 鏡像"), pinned over `SETTINGS_RULES_SAMPLE`'s own `ラスタライズ`(`RS`): a real four-way merge
/// (`mermaid`/`数式`/`usvg`/`ページ描画` → `ラスタライズ`) from four simple, single-out-edge
/// sources — the exact real-world case the rule was fixed against (`usvg`'s own row is blocked by
/// `数式`'s sibling node, `MA`, forcing the `rank_lane_bend` best-effort path this fix added).
///
/// 1. **No top/bottom entry**: every edge into a multi-way merge target enters through the flow
///    axis face (`Left`, under `LR`) — never `Top`/`Bottom`, which is what the pre-fix `alt`
///    (cross-axis) fallback used to draw and what made the source ambiguous
///    ("面が曖昧" — `docs/STATUS.md`'s own ★未修正 entry this test closes).
/// 2. **No sibling crossing**: no two of those four edges' own segments cross each other —
///    the merge-side counterpart of [`orthogonal_settings_rules_sample_fan_lane_siblings_never_
///    cross`]'s fan-root claim, now for edges converging on a shared target rather than diverging
///    from a shared source.
#[test]
fn orthogonal_settings_rules_sample_merge_target_entries_are_flow_axis_and_never_cross() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let rs = d.node("RS").expect("RS (ラスタライズ) must exist");
    let (l, t, r, bo) = rs.bounds();

    let merge: Vec<&PlacedEdge> = d.edges.iter().filter(|e| e.to == "RS").collect();
    assert_eq!(
        merge.len(),
        4,
        "RS's own four-way merge (mermaid/数式/usvg/ページ描画): {:?}",
        merge.iter().map(|e| e.from.as_str()).collect::<Vec<_>>()
    );

    for e in &merge {
        let entry = e.points.last().expect("every edge has at least one point");
        let on_left_or_right_face = (entry.x - (l - orthogonal::PORT_INSET)).abs() < 1e-6
            || (entry.x - (r + orthogonal::PORT_INSET)).abs() < 1e-6;
        let on_top_or_bottom_face = (entry.y - (t - orthogonal::PORT_INSET)).abs() < 1e-6
            || (entry.y - (bo + orthogonal::PORT_INSET)).abs() < 1e-6;
        assert!(
            on_left_or_right_face && !on_top_or_bottom_face,
            "{}->RS must enter RS's own flow-axis (Left) face, never Top/Bottom: entry={entry:?}, \
             RS bounds=({l},{t},{r},{bo})",
            e.from
        );
        assert!(
            entry.y > t + 1e-6 && entry.y < bo - 1e-6,
            "{}->RS's own entry point must sit strictly inside RS's own vertical span, not flush \
             on a corner (§10-1 item 1's own 'ポートは角から8px以上'): entry={entry:?}, RS \
             bounds=({l},{t},{r},{bo})",
            e.from
        );
    }

    for i in 0..merge.len() {
        for j in (i + 1)..merge.len() {
            let (a, b) = (merge[i], merge[j]);
            for wa in a.points.windows(2) {
                for wb in b.points.windows(2) {
                    assert!(
                        orthogonal::segment_crossing(wa, wb).is_none(),
                        "{}->RS crosses {}->RS's own segment ({:?}-{:?} vs {:?}-{:?}) — sibling \
                         merge stubs into the same target must never cross: {} points={:?}, \
                         {} points={:?}",
                        a.from,
                        b.from,
                        wa[0],
                        wa[1],
                        wb[0],
                        wb[1],
                        a.from,
                        a.points,
                        b.from,
                        b.points
                    );
                }
            }
        }
    }
}

/// §10-3 item 12's own real motivating bug (`docs/FEATURE-MERMAID-RENDERER.md`, user report
/// "セルに合わせるの3合流でポートが中心より上へ回り込む"): `FIT`(`セルに合わせる`)'s own three-way
/// merge (`RS`(`ラスタライズ`, aligned — the trunk, offset 0), `IM`(`デコード`) and
/// `VD`(`キーフレーム`), both genuinely below `FIT`'s own centre in this `LR` layout). Before item
/// 12's fix, `evict`'s own array-symmetric re-splice moved the aligned claim from wherever it
/// naturally sorted to the claims array's own geometric middle index, which could drag a
/// same-side sibling across the centre line along the way — on this exact face, `RS` naturally
/// sorts *first* (its own other end, `MM`/`mermaid`, sits almost exactly on `FIT`'s own centre) and
/// `round((3-1)/2) = 1` used to force it to index 1, dragging `IM` down to index 0 and flipping its
/// offset from the `+16` its true side calls for to `-16` — landing it *above* `FIT`'s centre even
/// though `IM` genuinely sits below it, exactly the reported symptom. `3a`'s own reference geometry
/// (`docs/mermaid-theme/handoff/round3-Konoma-Flowchart-Routing.dc.html`) confirms both non-trunk
/// members land below centre (`338`/`354` against a centre of `322`), matching this test's own
/// `+16`/`+32`.
#[test]
fn orthogonal_settings_rules_sample_fit_merge_keeps_same_side_siblings_on_the_same_side() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let fit = d.node("FIT").expect("FIT (セルに合わせる) must exist");

    let rs = d
        .edges
        .iter()
        .find(|e| e.from == "RS" && e.to == "FIT")
        .expect("RS->FIT (幹) must exist");
    let im = d
        .edges
        .iter()
        .find(|e| e.from == "IM" && e.to == "FIT")
        .expect("IM->FIT (デコード) must exist");
    let vd = d
        .edges
        .iter()
        .find(|e| e.from == "VD" && e.to == "FIT")
        .expect("VD->FIT (キーフレーム) must exist");

    assert_eq!(
        rs.points.len(),
        2,
        "RS->FIT is the trunk — a straight 2-point line entering exactly on FIT's own centre: {:?}",
        rs.points
    );
    let rs_entry = rs.points.last().unwrap().y;
    assert!(
        (rs_entry - fit.center.y).abs() < 1e-6,
        "RS->FIT (aligned) enters exactly on FIT's centre: {rs_entry} vs {}",
        fit.center.y
    );

    let im_entry = im.points.last().unwrap().y;
    let vd_entry = vd.points.last().unwrap().y;
    assert!(
        (im_entry - (fit.center.y + orthogonal::PORT_SPACING)).abs() < 1e-6,
        "IM->FIT (デコード) enters PORT_SPACING BELOW FIT's centre — never above it, the reported \
         side-crossing bug: {im_entry} vs {}",
        fit.center.y
    );
    assert!(
        (vd_entry - (fit.center.y + 2.0 * orthogonal::PORT_SPACING)).abs() < 1e-6,
        "VD->FIT (キーフレーム) enters 2*PORT_SPACING below FIT's centre, on the SAME side as \
         IM->FIT (both genuinely below centre): {vd_entry} vs {}",
        fit.center.y
    );

    // FIT's own height grows symmetric to the *larger* side (item 12's own "ノードは大きい側に
    // 合わせて中心対称に拡大") — 2 steps (IM, VD) reserved on both sides even though the near side
    // carries no claim at all: 2*(2*PORT_SPACING + PORT_CLEARANCE) = 80px, matching `3a`'s own
    // 高さ80 reference.
    let expected_h = 2.0 * (2.0 * orthogonal::PORT_SPACING + orthogonal::PORT_CLEARANCE);
    assert!(
        (fit.size.h - expected_h).abs() < 1e-6,
        "FIT's own height must be exactly 2*(2*PORT_SPACING+PORT_CLEARANCE) = {expected_h}px: got \
         {}",
        fit.size.h
    );
}

/// §10-3 item 13's own real motivating bug (`docs/FEATURE-MERMAID-RENDERER.md`, user report "線が
/// ページ描画のノードから出ていない・右上の角から生えて見える"): `PD`(`ページ描画`)'s own single
/// out-edge to `RS`(`ラスタライズ`) used to have its exit stub dragged off `PD`'s own assigned Right
/// face slot by `MA`(`数式`)'s box sitting in the same pass-through row — `clear_local_route`'s own
/// blind "every point sharing the flagged coordinate slides together" moved the port along with the
/// rest of the run. Pinned two ways: the port sits exactly on `PD`'s own vertical centre (its one
/// and only claim on that face, so `evict` gives it offset 0), and the route genuinely still clears
/// `MA`'s box (the bug this fix must not silently regress into "port stays put, line now crosses
/// 数式 instead").
#[test]
fn orthogonal_settings_rules_sample_page_render_exit_stays_on_its_own_port() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let pd = d.node("PD").expect("PD (ページ描画) must exist");
    let ma = d.node("MA").expect("MA (数式) must exist");
    let pd_rs = d
        .edges
        .iter()
        .find(|e| e.from == "PD" && e.to == "RS")
        .expect("PD->RS must exist");

    let exit = pd_rs.points.first().expect("PD->RS must have points");
    let (_, t, r, bo) = pd.bounds();
    assert!(
        (exit.x - (r + orthogonal::PORT_INSET)).abs() < 1e-6,
        "PD->RS must leave PD's own Right face, PORT_INSET outside it, not some other x: \
         {exit:?} vs PD bounds {:?}",
        pd.bounds()
    );
    assert!(
        (exit.y - (t + bo) / 2.0).abs() < 1e-6,
        "PD->RS's own exit port must sit exactly on PD's own vertical centre (PD's only claim on \
         this face): {exit:?} vs PD bounds {:?}",
        pd.bounds()
    );
    let second = &pd_rs.points[1];
    assert!(
        (exit.y - second.y).abs() < 1e-6 && (exit.x - second.x).abs() > 1e-6,
        "PD must still leave its own Right face horizontally (perpendicular exit, §10-1 item 1), \
         not turn immediately at the port: {:?}",
        pd_rs.points
    );

    for w in pd_rs.points.windows(2) {
        assert!(
            !orthogonal::segment_crosses_node(&w[0], &w[1], ma),
            "PD->RS must still clear MA (数式) even with its own port pinned: segment {w:?} in \
             {:?}, MA bounds {:?}",
            pd_rs.points,
            ma.bounds()
        );
    }
}

/// A minimal, hand-built counterpart to [`orthogonal_settings_rules_sample_merge_target_entries_
/// are_flow_axis_and_never_cross`] — three plain, single-out-edge sources at three different flow
/// coordinates merging into one target, deliberately shaped (an obstacle, `X`, sitting on `A`'s own
/// row directly ahead of it, `B`'s the "settings rules" sample's own `usvg`-vs-`数式` collision)
/// so the best-effort `rank_lane_bend` retry (`classify`'s own §10-3 item 10 doc: "全ての候補が
/// 交差してもcross-axisのaltへは決して落ちない") fires on a fixture small enough to read by hand
/// rather than only on the 20-node real-world source above.
#[test]
fn orthogonal_synthetic_blocked_merge_still_enters_the_flow_axis_face() {
    let src = "flowchart LR\n  A --> T[Target]\n  B --> T\n  C --> T\n  A --> X[Blocker]\n  \
               Z --> X";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let t = d.node("T").expect("T must exist");
    let (l, tt, r, bb) = t.bounds();
    let merge: Vec<&PlacedEdge> = d.edges.iter().filter(|e| e.to == "T").collect();
    assert_eq!(
        merge.len(),
        3,
        "{:?}",
        merge.iter().map(|e| e.from.as_str()).collect::<Vec<_>>()
    );
    for e in &merge {
        let entry = e.points.last().unwrap();
        let on_flow_axis_face = (entry.x - (l - orthogonal::PORT_INSET)).abs() < 1e-6
            || (entry.x - (r + orthogonal::PORT_INSET)).abs() < 1e-6;
        assert!(
            on_flow_axis_face,
            "{}->T must enter T's own flow-axis face even when its own row is blocked: \
             entry={entry:?}, T bounds=({l},{tt},{r},{bb})",
            e.from
        );
    }
}

/// §10-3 item 13's own two user-reported regressions (`docs/FEATURE-MERMAID-RENDERER.md`, this
/// module's own `reserve_pass_through_rows`/`nest_merge_target_hops` fix): `MA`(`数式`) used to sit
/// almost exactly on `PD`(`ページ描画`)'s own row, one column upstream of `RS`(`ラスタライズ`) —
/// directly inside `PD -> RS`'s own pass-through row — forcing `PD -> RS` into a four-bend detour
/// around it. `reserve_pass_through_rows` moves `MA` clear of that row instead of leaving the edge
/// to detour; pinned two ways, the *why* (the row itself is now clear) and the *what* (the route is
/// a plain two-bend hop again, not a detour).
#[test]
fn orthogonal_settings_rules_sample_math_node_is_not_on_page_renders_row() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let pd = d.node("PD").expect("PD (ページ描画) must exist");
    let ma = d.node("MA").expect("MA (数式) must exist");
    let (_, ma_top, _, ma_bottom) = ma.bounds();
    let pd_row = pd.center.y;
    assert!(
        pd_row < ma_top - 1e-6 || pd_row > ma_bottom + 1e-6,
        "MA (数式) must not occupy ページ描画's own pass-through row (its horizontal exit leg runs \
         straight through this row on its way to RS): pd_row={pd_row}, MA bounds=({ma_top}, \
         {ma_bottom})"
    );
}

#[test]
fn orthogonal_settings_rules_sample_page_render_to_rasterise_is_two_bends_not_a_detour() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let pd_rs = d
        .edges
        .iter()
        .find(|e| e.from == "PD" && e.to == "RS")
        .expect("PD->RS must exist");
    assert_eq!(
        pd_rs.points.len(),
        4,
        "PD->RS must be a plain two-bend hop route once 数式 is out of ページ描画's own \
         pass-through row — a longer point list means it is still detouring around something: {:?}",
        pd_rs.points
    );
}

/// A minimal `SpecEdge`, following `label_boosts_actually_widen_the_flow_axis_segment_dagre_lays_
/// out`'s own hand-built-`SpecEdge` convention — every field this module's own routing code never
/// reads (label, tips, stroke, start/end labels, style) set to its plainest value, since only `from`/
/// `to`/`minlen` matter to `reserve_pass_through_rows`.
fn plain_edge(id: &str, from: &str, to: &str, minlen: usize) -> super::SpecEdge {
    super::SpecEdge {
        id: id.to_string(),
        from: from.to_string(),
        to: to.to_string(),
        label: None,
        tip_start: Tip::None,
        tip_end: Tip::Arrow,
        stroke: Stroke::Normal,
        minlen,
        start_label: None,
        end_label: None,
        style: None,
        curve: Curve::Basis,
    }
}

/// §10-3 item 13's own rule (`docs/FEATURE-MERMAID-RENDERER.md`), pinned directly against
/// `super::reserve_pass_through_rows` rather than through a full flowchart source: a hand-built
/// four-node layout, `A`(rank 0) skipping straight to `B`(rank 2) — a rank-skipping `A -> B`
/// (`minlen` 2) — with two nodes hand-placed on `A`'s own exact row at the intermediate rank 1:
/// `C` (`A`'s own real child, `A -> C`, must be left exactly where it is) and `W` (no edge to or
/// from `A` at all, only its own unrelated `W -> D`, standing in for the coincidental-occupant case
/// this rule exists to fix). Going through the full flowchart pipeline (`laid_out_flow`) cannot
/// reliably reproduce this exact collision — dagre's own cross-axis packing spreads unrelated
/// same-rank nodes apart by construction, so no small hand-written source was found that actually
/// forces two unrelated nodes onto the identical row — hence the direct call, with full control over
/// the "before" geometry this function's own contract is stated against.
#[test]
fn reserve_pass_through_rows_evicts_an_unrelated_node_but_not_a_real_neighbour() {
    let direction = crate::preview::mermaid::flowchart::Direction::LeftToRight;
    let mut nodes = vec![
        placed_node("A", 0.0, 100.0, 40.0, 20.0),
        placed_node("C", 100.0, 100.0, 40.0, 20.0), // A's real child — on A's row on purpose.
        placed_node("W", 100.0, 100.0, 40.0, 20.0), // unrelated — also on A's row on purpose.
        placed_node("B", 200.0, 100.0, 40.0, 20.0),
    ];
    let node_rank: HashMap<String, i32> = [
        ("A".to_string(), 0),
        ("C".to_string(), 1),
        ("W".to_string(), 1),
        ("B".to_string(), 2),
    ]
    .into_iter()
    .collect();

    let edge_ac = plain_edge("e_ac", "A", "C", 1);
    let edge_ab = plain_edge("e_ab", "A", "B", 2);
    let edge_wd = plain_edge("e_wd", "W", "D", 1);
    let drawable = vec![
        super::Drawable {
            edge: &edge_ac,
            tail: "A".to_string(),
            head: "C".to_string(),
        },
        super::Drawable {
            edge: &edge_ab,
            tail: "A".to_string(),
            head: "B".to_string(),
        },
        super::Drawable {
            edge: &edge_wd,
            tail: "W".to_string(),
            head: "D".to_string(),
        },
    ];

    // `A -> B`'s own shape is the only thing this test needs eligible: a plain, non-branching,
    // adjacent-source-facing merge into a lone target — exactly what `route_flowchart`'s own trial
    // route would classify as `is_pass_through_shape` for this hand-built fixture.
    let eligible: HashSet<String> = ["e_ab".to_string()].into_iter().collect();
    let moved =
        super::reserve_pass_through_rows(direction, &mut nodes, &node_rank, &drawable, &eligible);
    assert!(
        moved,
        "must actually evict W for this test to mean anything"
    );

    let row = |id: &str| nodes.iter().find(|n| n.id == id).unwrap().center.y;
    let a_row = row("A");
    assert!(
        (row("C") - a_row).abs() < 1e-6,
        "C (A's own direct child, A -> C) must stay exactly on A's own row — the guard must not \
         evict a real neighbour: a_row={a_row}, c_row={}",
        row("C")
    );
    assert!(
        (row("W") - a_row).abs() >= 22.0 - 1e-6,
        "W (unrelated to A) must be evicted clear of A's own pass-through row (half its own height \
         + PASS_THROUGH_CLEARANCE = 10+12 = 22px): a_row={a_row}, w_row={}",
        row("W")
    );
}

/// §10-3 item 10's own trailing "ホップ x の入れ子" (`docs/FEATURE-MERMAID-RENDERER.md`) — the
/// perpendicular-crossing invariant `orthogonal_settings_rules_sample_merge_target_entries_are_
/// flow_axis_and_never_cross` already pins (`orthogonal::segment_crossing`) cannot see two siblings'
/// vertical hop legs simply *coinciding* (`セルに合わせる`'s own `デコード`/`キーフレーム`, this
/// fix's own motivating bug — both landed on the exact same independently-computed hop `x` before
/// `nest_merge_target_hops`), nor a sibling whose route never went through `EdgeShape::rank_lane_
/// bend` at all (`ラスタライズ`'s own `mermaid -> RS` and `数式 -> RS`, both ordinary adjacent-rank
/// merges — `数式 -> RS`'s hop crossed `ページ描画 -> RS`'s own horizontal source-leg once `数式`
/// moved out of `ページ描画`'s row, the second real bug this fix closes).
/// `orthogonal::polylines_cross` (the exact predicate `nest_merge_target_hops` itself uses to decide
/// whether a candidate slot is clear) is the general question; this test asks it of every pair of
/// siblings converging on each of the sample's two multi-way merges.
#[test]
fn orthogonal_settings_rules_sample_merge_siblings_never_cross_or_coincide() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    for target in ["RS", "FIT"] {
        let merge: Vec<&PlacedEdge> = d.edges.iter().filter(|e| e.to == target).collect();
        assert!(
            merge.len() >= 2,
            "{target} must have at least two incoming edges to be a meaningful test: {:?}",
            merge.iter().map(|e| e.from.as_str()).collect::<Vec<_>>()
        );
        for i in 0..merge.len() {
            for j in (i + 1)..merge.len() {
                assert!(
                    !orthogonal::polylines_cross(&merge[i].points, &merge[j].points),
                    "{}->{target} crosses or coincides with {}->{target} — sibling merge routes \
                     must never cross or overlap: {} points={:?}, {} points={:?}",
                    merge[i].from,
                    merge[j].from,
                    merge[i].from,
                    merge[i].points,
                    merge[j].from,
                    merge[j].points
                );
            }
        }
    }
}

/// §10-3 item 10's own "8px 刻み" (`docs/FEATURE-MERMAID-RENDERER.md`), restated precisely rather
/// than as a blanket "every pair of siblings differs by 8px regardless of geometry": two sibling
/// merge edges whose vertical hop legs would otherwise sit at overlapping rows (`IM`(`デコード`)
/// and `VD`(`キーフレーム`), both genuinely below `FIT`(`セルに合わせる`)'s own centre, `orthogonal_
/// settings_rules_sample_fit_merge_keeps_same_side_siblings_on_the_same_side`'s own doc has the
/// full row picture) must land at least [`orthogonal::PORT_CLEARANCE`] apart — never on the
/// identical `x` [`nest_merge_target_hops`]'s own doc reports as this fix's original motivating bug.
#[test]
fn orthogonal_settings_rules_sample_fit_merge_hops_are_spaced_at_least_port_clearance_apart() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let im = d
        .edges
        .iter()
        .find(|e| e.from == "IM" && e.to == "FIT")
        .expect("IM->FIT must exist");
    let vd = d
        .edges
        .iter()
        .find(|e| e.from == "VD" && e.to == "FIT")
        .expect("VD->FIT must exist");
    assert_eq!(
        im.points.len(),
        4,
        "IM->FIT must be a two-bend hop route: {:?}",
        im.points
    );
    assert_eq!(
        vd.points.len(),
        4,
        "VD->FIT must be a two-bend hop route: {:?}",
        vd.points
    );
    let im_hop = im.points[1].x;
    let vd_hop = vd.points[1].x;
    assert!(
        (im_hop - vd_hop).abs() >= orthogonal::PORT_CLEARANCE - 1e-6,
        "IM->FIT and VD->FIT's own rows overlap (both genuinely sit below FIT's centre) — their \
         hops must be nested at least PORT_CLEARANCE apart, never land on the same x: \
         im_hop={im_hop} vd_hop={vd_hop}"
    );
}

/// [`orthogonal::nest_merge_target_hops`]'s own two invariants, generalised past the one 20-node
/// sample above to the whole [`CORPUS`] (every direction, subgraphs included) plus
/// [`SETTINGS_RULES_SAMPLE`] — `nest_merge_target_hops` itself carries no `tree.is_empty()`/
/// direction guard (unlike `reserve_pass_through_rows`, checked separately below), so nothing
/// about this invariant is scoped to a subset of diagrams: no two *genuine merge siblings*
/// converging on the same target may ever cross or coincide, full stop.
///
/// Scoped to `orthogonal::classify`'s own definition of a merge sibling — `source_out_degree <= 1`
/// (`is_merge_hop_candidate`'s own guard, `orthogonal.rs`) — not to every edge that happens to share
/// a target: `subgraph-bypass`'s own `X -> Y` shares a target with `B -> Y`, but `X` itself branches
/// (`X --> Y`, `X --> A`), so `classify` draws `X -> Y` as a *branch* shape, an unrelated shape
/// family this fix never touches — its own route can cross a foreign sibling for reasons that
/// predate and are out of scope for this fix (a pre-existing, structurally different bug class:
/// a branching source's own `staircase` fallback detour, not a merge target's own port nesting).
#[test]
fn orthogonal_merge_sibling_hops_never_cross_or_coincide_across_corpus() {
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain([("settings-rules-sample", SETTINGS_RULES_SAMPLE)])
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let mut out_degree: HashMap<&str, usize> = HashMap::new();
        for e in &d.edges {
            *out_degree.entry(e.from.as_str()).or_insert(0) += 1;
        }
        let mut by_target: HashMap<&str, Vec<&PlacedEdge>> = HashMap::new();
        for e in &d.edges {
            // `Stroke::Invisible` (`~~~`) is a layout-only link mermaid itself never draws a line
            // for (`svg.rs`'s own `Stroke::Invisible => return`) — a "crossing" against one is not
            // a visible defect, so it is out of scope for this invariant the same way it is out of
            // scope for the renderer itself.
            if e.stroke == Stroke::Invisible {
                continue;
            }
            // A genuine merge sibling only, matching `is_merge_hop_candidate`'s own scope — a
            // branching source's own edge into this same target is a different shape family
            // (this test's own doc explains why `subgraph-bypass` needs this filter).
            if out_degree.get(e.from.as_str()).copied().unwrap_or(0) > 1 {
                continue;
            }
            by_target.entry(e.to.as_str()).or_default().push(e);
        }
        for (target, merge) in by_target {
            if merge.len() < 2 {
                continue;
            }
            for i in 0..merge.len() {
                for j in (i + 1)..merge.len() {
                    assert!(
                        !orthogonal::polylines_cross(&merge[i].points, &merge[j].points),
                        "{name}: {}->{target} crosses or coincides with {}->{target}: {} \
                         points={:?}, {} points={:?}",
                        merge[i].from,
                        merge[j].from,
                        merge[i].from,
                        merge[i].points,
                        merge[j].from,
                        merge[j].points
                    );
                }
            }
        }
    }
}

/// The mirror of [`orthogonal_merge_sibling_hops_never_cross_or_coincide_across_corpus`] on the
/// **source** side: two edges leaving the same node never cross each other.
///
/// That is what §10-1 item 1's rule 1 is *for* — "もう一方の端点のcross座標順" orders a face's
/// ports so the lines going to those other ends stay in the same order they leave in — and it is
/// stated here because the rule was read along the wrong axis until §10-5 round 5
/// (`orthogonal::FaceClaim::other_tangent`'s own doc): on a **cross-axis** face, "the other end's
/// cross coordinate" is perpendicular to the axis the ports are actually laid out along, so the
/// order it produced said nothing about where the two lines were going. `zz-design-2c`'s own
/// `ジョブ実行系` is where it surfaced once round 5 put `保存層` beside the spine — its two green
/// edges left the same face in the reverse of the order they needed and crossed each other
/// immediately.
///
/// `Stroke::Invisible` is skipped for the same reason the merge-side test skips it: `~~~` is a
/// layout-only link that is never drawn, so it cannot cross anything visibly. So is a **detour** —
/// an edge whose route leaves the box its own two endpoints span, which is the perimeter lane and
/// the `staircase` collision fallback. Those are a different shape family, out of a port-ordering
/// rule's reach by construction (a route that goes right round the outside can cross anything on
/// its way), and exactly the exclusion the merge-side test above states in prose for
/// `subgraph-bypass`'s own `X -> Y` — stated here geometrically so it names the shape rather than
/// the fixture. Every edge whose route stays between its own two ends is in scope, which is what
/// rule 1 actually governs.
#[test]
fn orthogonal_edges_leaving_one_node_never_cross_each_other_across_corpus() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain([("settings-rules-sample", SETTINGS_RULES_SAMPLE)])
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let stays_between = |e: &PlacedEdge| -> bool {
            let ends: Vec<(f64, f64, f64, f64)> = d
                .nodes
                .iter()
                .filter(|n| n.id == e.from || n.id == e.to)
                .map(|n| n.bounds())
                .collect();
            let (mut l, mut t, mut r, mut b) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
            for (nl, nt, nr, nb) in ends {
                l = l.min(nl);
                t = t.min(nt);
                r = r.max(nr);
                b = b.max(nb);
            }
            e.points
                .iter()
                .all(|p| p.x >= l - 0.01 && p.x <= r + 0.01 && p.y >= t - 0.01 && p.y <= b + 0.01)
        };
        let mut by_source: HashMap<&str, Vec<&PlacedEdge>> = HashMap::new();
        for e in &d.edges {
            if e.stroke == Stroke::Invisible || e.from == e.to || !stays_between(e) {
                continue;
            }
            by_source.entry(e.from.as_str()).or_default().push(e);
        }
        for (source, fan) in by_source {
            for i in 0..fan.len() {
                for j in (i + 1)..fan.len() {
                    let hit = fan[i].points.windows(2).find_map(|a| {
                        fan[j]
                            .points
                            .windows(2)
                            .find_map(|b| orthogonal::segment_crossing(a, b))
                    });
                    assert!(
                        hit.is_none(),
                        "{name}: {source}->{} crosses {source}->{} at {hit:?}: {:?} vs {:?}",
                        fan[i].to,
                        fan[j].to,
                        fan[i].points,
                        fan[j].points
                    );
                }
            }
        }
    }
}

/// §10-3 item 13's own rule ("列 A の行 R から出て列 T(T > A+1)へ入る辺は、間の各列で行 R を占め
/// る"), stated purely from the finished layout's own geometry (never `reserve_pass_through_rows`'s
/// own internal rank machinery, so this cannot silently drift the way a second copy of the same
/// rank arithmetic could): for every forward edge whose source and target sit at least a whole
/// node-width apart on the flow axis with a real gap between them, no *unrelated* third node (no
/// edge to the source, in either direction) may sit strictly between them on the flow axis *and*
/// within [`super::PASS_THROUGH_CLEARANCE`] of the source's own cross-axis row.
///
/// Scoped to the same window [`reserve_pass_through_rows`] itself is (`tree.is_empty()`,
/// `mod.rs`'s own call site) — a subgraph diagram is out of scope for that pass, the same known
/// limit `pull_back_fan_ranks` already has (`docs/STATUS.md`'s own ★未修正 entry), so a `CORPUS`
/// name containing "subgraph" is excluded here rather than asserting a rule the production code
/// does not even attempt to keep for it. Also scoped to a non-branching source
/// (`source_out_degree <= 1`, `orthogonal::is_pass_through_shape`'s own doc): a branching source's
/// edge never draws rule 10/13's flow-axis "exit then hop" leg at all — it is a branch (cross-axis
/// exit) or a `fan_lane` member (a *different* corridor concept, §10-3 item 2's own nested lanes —
/// `strokes`'s own `A -> F`, `A` also branching via `A --- B`, is exactly this: real topology skips
/// a column `C` sits in, but the edge's own shape never threads a row through it, so reserving one
/// would repeat the `long-edge` regression this fix exists to close).
#[test]
fn orthogonal_pass_through_row_never_holds_an_unrelated_node_across_corpus() {
    use crate::preview::mermaid::flowchart::Direction;

    for (name, src) in orthogonal_corpus()
        .into_iter()
        .filter(|(name, _)| !name.contains("subgraph"))
        .chain([("settings-rules-sample", SETTINGS_RULES_SAMPLE)])
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let direction = direction_of(src);
        let flow = |p: &Point| match direction {
            Direction::LeftToRight | Direction::RightToLeft => p.x,
            Direction::TopToBottom | Direction::BottomToTop => p.y,
        };
        let cross = |p: &Point| match direction {
            Direction::LeftToRight | Direction::RightToLeft => p.y,
            Direction::TopToBottom | Direction::BottomToTop => p.x,
        };
        let flow_extent = |n: &PlacedNode| match direction {
            Direction::LeftToRight | Direction::RightToLeft => n.size.w / 2.0,
            Direction::TopToBottom | Direction::BottomToTop => n.size.h / 2.0,
        };
        let cross_extent = |n: &PlacedNode| match direction {
            Direction::LeftToRight | Direction::RightToLeft => n.size.h / 2.0,
            Direction::TopToBottom | Direction::BottomToTop => n.size.w / 2.0,
        };

        let connected: HashSet<(String, String)> = d
            .edges
            .iter()
            .flat_map(|e| {
                [
                    (e.from.clone(), e.to.clone()),
                    (e.to.clone(), e.from.clone()),
                ]
            })
            .collect();
        let mut out_degree: HashMap<&str, usize> = HashMap::new();
        for e in &d.edges {
            *out_degree.entry(e.from.as_str()).or_insert(0) += 1;
        }

        for e in &d.edges {
            if e.from == e.to {
                continue; // self-loop
            }
            if out_degree.get(e.from.as_str()).copied().unwrap_or(0) > 1 {
                continue; // a branching source never draws this shape family — see this test's doc.
            }
            let (Some(source), Some(target)) = (d.node(&e.from), d.node(&e.to)) else {
                continue;
            };
            let (sf, tf) = (flow(&source.center), flow(&target.center));
            // Only a genuine forward, rank-skipping span has a pass-through row to reserve at
            // all — a same-column (`aligned`) or immediately-adjacent-rank edge has no
            // intermediate column to check.
            if tf <= sf + 2.0 * flow_extent(source) {
                continue;
            }
            let row = cross(&source.center);
            for n in &d.nodes {
                if n.id == e.from || n.id == e.to {
                    continue;
                }
                if connected.contains(&(e.from.clone(), n.id.clone())) {
                    continue; // a real neighbour of the edge's own source — left alone on purpose.
                }
                let nf = flow(&n.center);
                let n_flow_half = flow_extent(n);
                // Strictly inside the source-target span, with a whole node-width of margin on
                // each side, so a node sharing the source's or target's own rank column (an
                // ordinary sibling, not an intermediate-column occupant) is never flagged.
                if nf - n_flow_half <= sf + flow_extent(source)
                    || nf + n_flow_half >= tf - flow_extent(target)
                {
                    continue;
                }
                let n_cross_half = cross_extent(n);
                assert!(
                    (cross(&n.center) - row).abs()
                        >= n_cross_half + super::PASS_THROUGH_CLEARANCE - 1e-6,
                    "{name}: {}->{} skips an intermediate column that {} (unrelated to {}) still \
                     occupies on {}'s own pass-through row: source_row={row}, {}'s own \
                     center={:?}",
                    e.from,
                    e.to,
                    n.id,
                    e.from,
                    e.from,
                    n.id,
                    n.center
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Stage 4: label placement, minimum segment length, port-vs-plate avoidance
// ---------------------------------------------------------------------------------------------
//
// `docs/FEATURE-MERMAID-RENDERER.md` §10-1 item 3. Every labelled corpus source's plate is checked
// against every axis-parallel invariant stage 1-3 already state over the same corpus
// (`orthogonal_corpus`), plus the three new ones this stage adds.
//
// Two of the three sub-rules turned out hard to coax out of a *real* `dagre` layout on purpose,
// dumped and read by hand while this was written (the same way
// `orthogonal_settings_rules_sample_no_longer_pierces_a_sibling_node` was), so each is instead
// covered by a direct, hand-built fixture rather than a diagram source:
//
// * A genuine two-flow-leg split (uneven eviction giving an aligned edge's two ends different
//   coordinates, `bridge`'s own doc) — every scratch diagram tried either kept one leg the full
//   rank-gap length or the two nodes drifted out of `classify`'s 0.5px aligned window first. Its
//   own selection behaviour is covered directly in `orthogonal.rs`'s test module instead
//   (`label_slot_picks_the_longer_of_two_flow_axis_segments`), by constructing the split polyline
//   by hand.
// * A port stub actually crossing a *foreign* plate (item 3's second rule). `dagre`'s own
//   edge-label reservation (the same mechanism `label_boosts_actually_widen_...` below proves)
//   turns out to keep every other same-rank node clear of a label's own footprint by construction
//   — pushing the label wider pushes its rank-mates out by roughly the same amount, several
//   diagrams and node-size combinations tried, so no corpus source or hand-built `GraphSpec` here
//   reaches a genuine crossing to have avoided. `orthogonal::avoid_label_plates` is instead proven
//   directly (`avoid_label_plates_pushes_only_the_port_that_actually_crosses_a_plate` below,
//   `avoid_label_plates_ignores_a_reverse_edge` in `orthogonal.rs`), and
//   `no_label_plate_is_crossed_by_a_foreign_edges_segment` stands as the regression guard for the
//   day some future routing change does reach one.

/// Every labelled edge's plate, across [`orthogonal_corpus`].
fn labelled_plates(d: &Diagram) -> Vec<(&PlacedEdge, &super::PlacedEdgeLabel)> {
    d.edges
        .iter()
        .filter_map(|e| e.label.as_ref().map(|l| (e, l)))
        .collect()
}

/// Every routed polyline in `d`, keyed by the edge's own index — [`orthogonal::plate_coverage`]
/// wants a map by edge id, and a finished [`Diagram`] no longer carries the ids
/// [`lay_out_spec_pass`] used, so the index stands in for one. All that matters is that the plate's
/// own edge can be told apart from every other, which an index does exactly as well.
///
/// [`lay_out_spec_pass`]: super::lay_out_spec_pass
fn routes_by_index(d: &Diagram) -> HashMap<String, Vec<Point>> {
    d.edges
        .iter()
        .enumerate()
        .map(|(i, e)| (i.to_string(), e.points.clone()))
        .collect()
}

/// The slot production actually chose for edge `i`'s own plate — [`orthogonal::label_slot_clear`]
/// with the very same coverage question `lay_out_spec_pass` asked
/// ([`orthogonal::plate_coverage`]), never the coverage-free [`orthogonal::label_slot`].
///
/// This distinction is the whole reason the helper exists: since §10-5 round 5 the two can name
/// **different segments**, and a test that re-derived the slot from the coverage-free function
/// would be measuring a segment the drawing does not use — konoma's own "the instrument drifted
/// off the production path" failure mode (`docs/FEATURE-MERMAID-RENDERER.md` §6), caught here
/// while writing the rule rather than after shipping it.
fn plate_slot(
    d: &Diagram,
    direction: crate::preview::mermaid::flowchart::Direction,
    i: usize,
) -> Option<orthogonal::LabelSlot> {
    let routes = routes_by_index(d);
    let e = d.edges.get(i)?;
    let size = e.label.as_ref()?.size;
    let own = i.to_string();
    orthogonal::label_slot_clear(direction, &e.points, &|center| {
        orthogonal::plate_coverage(center, size, &own, &routes, &d.nodes, &d.clusters)
    })
}

/// Every axis-parallel segment of `e`'s own polyline, as `(a, b)` pairs — what a plate is allowed
/// to sit on top of without that counting as "off the line".
fn own_segments(e: &PlacedEdge) -> impl Iterator<Item = (&Point, &Point)> {
    e.points.windows(2).map(|w| (&w[0], &w[1]))
}

/// Item 3's first rule, restated as a corpus invariant: every labelled edge's plate is centred
/// **on** one of its own edge's segments (within a fraction of a px — the two are built from the
/// same arithmetic, so this is really asking "did the wiring stay connected", not "is the geometry
/// approximately right").
#[test]
fn every_label_plate_centre_sits_on_its_own_edges_line() {
    for (name, src) in orthogonal_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for (e, l) in labelled_plates(&d) {
            let on_a_segment = own_segments(e).any(|(a, b)| {
                let on_seg = |p: &Point| {
                    let within_x = p.x >= a.x.min(b.x) - AXIS_EPS && p.x <= a.x.max(b.x) + AXIS_EPS;
                    let within_y = p.y >= a.y.min(b.y) - AXIS_EPS && p.y <= a.y.max(b.y) + AXIS_EPS;
                    let collinear =
                        ((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)).abs() < 1e-3;
                    within_x && within_y && collinear
                };
                on_seg(&l.center)
            });
            assert!(
                on_a_segment,
                "{name}: label {:?} centre {:?} is not on any segment of {:?}",
                l.label.lines, l.center, e.points
            );
        }
    }
}

/// Item 3's minimum-length rule, over every labelled edge whose chosen segment is the flow-axis
/// one — the only kind [`super::apply_label_growth`]'s retry loop can actually widen (a
/// cross-axis-only label, reachable only through a `reverse`/`staircase` edge, is a documented gap
/// — [`orthogonal::LabelSlot::is_flow_axis`]'s own doc). `orthogonal_dag_corpus`, not the full
/// corpus, for the same reason [`orthogonal_bend_count_never_exceeds_two`] uses it: a back edge's
/// label is drawn from dagre's own waypoint chain, which this stage does not reach.
#[test]
fn labelled_flow_axis_segments_meet_their_minimum_length() {
    for (name, src) in orthogonal_dag_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for i in 0..d.edges.len() {
            let Some(l) = d.edges[i].label.as_ref() else {
                continue;
            };
            let Some(slot) = plate_slot(&d, direction_of(src), i) else {
                continue;
            };
            if !slot.is_flow_axis {
                continue;
            }
            let need = orthogonal::label_min_length(l.size, slot.horizontal);
            assert!(
                slot.length + 1e-6 >= need,
                "{name}: labelled segment {:?} is {}px, short of the {}px minimum for plate {:?}",
                d.edges[i].points,
                slot.length,
                need,
                l.size
            );
        }
    }
}

/// §10-5 round 5's own rule as a whole-corpus invariant: **no label plate is laid over another
/// edge's line.** A plate is opaque, so a line under one is simply gone from the picture, and a
/// plate over a *sibling's* entry leg into a busy face is worse than that — it is what made
/// `avoid_label_plates` push that sibling's port out of source order and put a crossing in
/// `zz-design-2c`'s own three-way merge (`orthogonal::label_slot_clear`'s own doc).
///
/// The plate's **own** edge is the one thing it is allowed to cover — that is what "線上プレート"
/// means. Stated over `orthogonal_full_corpus` plus the orthogonal-only fixtures, so it sees the
/// design references and the narrow regression sources alike.
///
/// Deliberately about *lines* only, not about node boxes and frame borders: those are counted by
/// [`orthogonal::plate_coverage`] too and are preferred against when a clear segment exists, but a
/// plate can still legitimately end up on a frame's border when **every** segment of its own edge
/// covers something (`zz-design-2b`'s own `HTTPS`, whose three candidate segments cover
/// `クライアント`'s border, `エディタ拡張`'s leg and `クラウド`'s border respectively — one apiece).
/// Lines are the half that has a consequence beyond the plate itself, and the half the rule is
/// stated on.
#[test]
fn invariant_orthogonal_no_label_plate_covers_a_foreign_line() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for (i, e) in d.edges.iter().enumerate() {
            let Some(l) = e.label.as_ref() else { continue };
            for (j, other) in d.edges.iter().enumerate() {
                if i == j {
                    continue;
                }
                let hit = other.points.windows(2).find(|w| {
                    orthogonal::segment_crosses_plate_box(&w[0], &w[1], &l.center, l.size)
                });
                assert!(
                    hit.is_none(),
                    "{name}: {}->{}'s plate {:?} at {:?} is laid over {}->{}'s own line {:?}",
                    e.from,
                    e.to,
                    l.label.lines,
                    l.center,
                    other.from,
                    other.to,
                    hit
                );
            }
        }
    }
}

/// Parses `src`'s own `direction` line without going through the whole `lay_out_flow` pipeline —
/// [`labelled_flow_axis_segments_meet_their_minimum_length`]'s own use of
/// [`orthogonal::label_slot`] needs it directly, the same value [`Flowchart::direction`] carries.
fn direction_of(src: &str) -> crate::preview::mermaid::flowchart::Direction {
    parse(src)
        .unwrap_or_else(|e| panic!("corpus source must parse: {e}"))
        .direction
}

/// Item 3's growth rule stated the way the task itself asks for it: a long label widens the rank
/// gap it sits in; a short one does not push the diagram wider than an unlabelled version would
/// be. CJK, because that is what the real report (`docs/STATUS.md`'s mermaid work) was about.
/// `LR`, not `TD`: this diagram's flow axis is horizontal there, so a *wide* single-line label —
/// the ordinary shape a long label takes — is what stretches the gap, matching how the rank gap
/// actually grows (`lay_out_spec_pass`'s own doc: `TD`/`BT` tracks a label's raw *height*,
/// `LR`/`RL` its raw *width*) rather than needing an author-written `<br>` to make the label tall.
#[test]
fn a_long_cjk_label_widens_the_rank_gap_and_a_short_one_does_not() {
    let bare = laid_out_flow(
        "flowchart LR\n  A[Start] --> B[End]",
        "basis",
        "konoma-orthogonal",
    );
    let short = laid_out_flow(
        "flowchart LR\n  A[Start] -->|x| B[End]",
        "basis",
        "konoma-orthogonal",
    );
    let long = laid_out_flow(
        "flowchart LR\n  A[Start] -->|とても長いラベルのテキストです、これはとても長い| B[End]",
        "basis",
        "konoma-orthogonal",
    );
    let gap = |d: &Diagram| {
        let e = &d.edges[0];
        (e.points.last().unwrap().x - e.points[0].x).abs()
    };
    let (bare_gap, short_gap, long_gap) = (gap(&bare), gap(&short), gap(&long));
    assert!(
        short_gap > bare_gap,
        "even a 1-char label must reserve some rank space: {short_gap} vs bare {bare_gap}"
    );
    assert!(
        long_gap > short_gap + 50.0,
        "a long multi-em CJK label must widen the gap far more than a 1-char label: \
         long={long_gap} short={short_gap}"
    );
}

/// A hand-built [`GraphSpec`] with 2 nodes almost touching (`ranksep`-scale gap dwarfed by the
/// label) proves `label_boosts` — [`lay_out_spec_pass`]'s own new parameter — actually reaches
/// dagre: the *same* pass, called once with an empty boost map and once with a large one for the
/// one labelled edge, must come back with a measurably longer flow-axis segment when boosted. This
/// is the wiring stage 4's growth loop depends on ([`apply_label_growth`]'s own doc proves the
/// *loop's* bookkeeping separately); real diagrams rarely ask the loop to do anything at all — see
/// this module's own note on why — so this is what actually exercises the boosted code path rather
/// than leaving it provably-correct-but-never-run.
#[test]
fn label_boosts_actually_widen_the_flow_axis_segment_dagre_lays_out() {
    let node = |id: &str| super::SpecNode {
        id: id.to_string(),
        glyph: Glyph::Flow(Shape::Rect),
        label: Label::measure(id),
        size: Size::new(30.0, 20.0),
        panel: None,
        style: None,
        has_class: true,
    };
    let edge = super::SpecEdge {
        id: "e1".to_string(),
        from: "A".to_string(),
        to: "B".to_string(),
        label: Some(Label::measure("a fairly long edge label")),
        tip_start: Tip::None,
        tip_end: Tip::Arrow,
        stroke: Stroke::Normal,
        minlen: 1,
        start_label: None,
        end_label: None,
        style: None,
        curve: Curve::Basis,
    };
    let spec = super::GraphSpec {
        direction: crate::preview::mermaid::flowchart::Direction::TopToBottom,
        nodes: vec![node("A"), node("B")],
        edges: vec![edge],
        blocks: Vec::new(),
        routing: orthogonal::Routing::Orthogonal,
        fixed_self_loops: false,
    };

    let flow_gap = |boosts: &HashMap<String, f64>| {
        let (diagram, _required, _shortfall) =
            super::lay_out_spec_pass(&spec, &HashMap::new(), boosts)
                .unwrap_or_else(|e| panic!("hand-built spec must lay out: {e}"));
        let e = &diagram.edges[0];
        (e.points.last().unwrap().y - e.points[0].y).abs()
    };

    let unboosted = flow_gap(&HashMap::new());
    let mut boosts = HashMap::new();
    boosts.insert("e1".to_string(), 300.0);
    let boosted = flow_gap(&boosts);

    assert!(
        boosted > unboosted + 250.0,
        "a 300px label_boosts entry must reach dagre and widen the rank gap by roughly that much: \
         unboosted={unboosted} boosted={boosted}"
    );
}

/// [`apply_label_growth`]'s own contract, stated directly: it **adds** each pass's shortfall onto
/// the running total (not `max`, unlike [`apply_growth`]'s node sizes — that function's own doc
/// explains why the two need different combinators), only for a positive shortfall, and reports
/// whether anything grew.
#[test]
fn apply_label_growth_accumulates_positive_shortfalls_and_ignores_the_rest() {
    let mut boosts: HashMap<String, f64> = HashMap::new();
    boosts.insert("already".to_string(), 10.0);

    let mut shortfall: HashMap<String, f64> = HashMap::new();
    shortfall.insert("already".to_string(), 5.0); // must ADD to 15, not replace with 5
    shortfall.insert("fresh".to_string(), 20.0); // a brand new entry
    shortfall.insert("met".to_string(), 0.0); // not actually short — must not be recorded at all
    shortfall.insert("negative".to_string(), -1.0); // defensive: never subtracts

    let grew = super::apply_label_growth(&mut boosts, &shortfall);
    assert!(grew, "a positive shortfall must report growth");
    assert!((boosts["already"] - 15.0).abs() < 1e-9, "{:?}", boosts);
    assert!((boosts["fresh"] - 20.0).abs() < 1e-9, "{:?}", boosts);
    assert!(
        !boosts.contains_key("met"),
        "a zero shortfall adds no entry"
    );
    assert!(
        !boosts.contains_key("negative"),
        "a negative shortfall must never be applied"
    );

    // A second call with an all-zero shortfall must report no further growth and leave the totals
    // exactly where they were — the loop-stopping condition `lay_out_spec` relies on.
    let mut zero: HashMap<String, f64> = HashMap::new();
    zero.insert("already".to_string(), 0.0);
    let grew_again = super::apply_label_growth(&mut boosts, &zero);
    assert!(!grew_again);
    assert!((boosts["already"] - 15.0).abs() < 1e-9);
}

/// §10-1 item 3's second rule ("ポートの垂直レーンがラベルプレートと重なる場合はポートをさらに
/// 16px外へ"), over the whole corpus: no plate ever ends up crossed by a *foreign* edge's segment
/// — either it never would have (the common case) or `avoid_label_plates` pushed the port that
/// would have crossed it clear. An edge's own line is exempt (it is what the plate sits on, by
/// item 3's first rule) and so is its own arrow tip.
#[test]
fn no_label_plate_is_crossed_by_a_foreign_edges_segment() {
    for (name, src) in orthogonal_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for (owner, l) in labelled_plates(&d) {
            let (pl, pt, pr, pb) = (
                l.center.x - l.size.w / 2.0,
                l.center.y - l.size.h / 2.0,
                l.center.x + l.size.w / 2.0,
                l.center.y + l.size.h / 2.0,
            );
            for other in &d.edges {
                if std::ptr::eq(other, owner) {
                    continue;
                }
                for (a, b) in own_segments(other) {
                    let crosses = if (a.y - b.y).abs() < AXIS_EPS {
                        let y = a.y;
                        let (x0, x1) = (a.x.min(b.x), a.x.max(b.x));
                        y >= pt && y <= pb && x1 >= pl && x0 <= pr
                    } else if (a.x - b.x).abs() < AXIS_EPS {
                        let x = a.x;
                        let (y0, y1) = (a.y.min(b.y), a.y.max(b.y));
                        x >= pl && x <= pr && y1 >= pt && y0 <= pb
                    } else {
                        false
                    };
                    assert!(
                        !crosses,
                        "{name}: {:?}->{:?}'s segment {a:?}->{b:?} runs through {:?}->{:?}'s \
                         label plate {:?}",
                        other.from, other.to, owner.from, owner.to, l.label.lines
                    );
                }
            }
        }
    }
}

/// [`orthogonal::avoid_label_plates`] itself, directly: a port whose stub runs through a foreign
/// plate must move exactly [`orthogonal::PORT_SPACING`] further from its own node, and an edge that
/// never crosses anything must come back byte-identical.
#[test]
fn avoid_label_plates_pushes_only_the_port_that_actually_crosses_a_plate() {
    use crate::preview::mermaid::flowchart::Direction;
    use orthogonal::{avoid_label_plates, EligibleEdge};

    let a = placed_node("A", 100.0, 0.0, 60.0, 40.0);
    let b = placed_node("B", 100.0, 200.0, 60.0, 40.0);
    let c = placed_node("C", 300.0, 0.0, 60.0, 40.0);
    let d = placed_node("D", 300.0, 200.0, 60.0, 40.0);
    let nodes = vec![a, b, c, d];
    let edges = vec![
        EligibleEdge {
            id: "ab",
            source: "A",
            target: "B",
            raw: &[],
            source_rank: Some(0),
            target_rank: Some(1),
            source_out_degree: 1,
            target_in_degree: 1,
            aside: false,
        },
        EligibleEdge {
            id: "cd",
            source: "C",
            target: "D",
            raw: &[],
            source_rank: Some(0),
            target_rank: Some(1),
            source_out_degree: 1,
            target_in_degree: 1,
            aside: false,
        },
    ];
    let routed = orthogonal::route_flowchart(
        Direction::TopToBottom,
        &nodes,
        &[],
        &edges,
        &std::collections::HashMap::new(),
        false,
    );
    let mut points = routed.points;
    let ab_before = points["ab"].clone();
    let cd_before = points["cd"].clone();

    // A plate sitting squarely on top of `ab`'s own stub near A's face — not `ab`'s own label
    // (different edge id), so it counts as foreign for `ab` and must push it; `cd`'s stub is far
    // away (x=300) and must be left untouched.
    let mut plates: HashMap<String, super::PlacedEdgeLabel> = HashMap::new();
    plates.insert(
        "someone-elses-label".to_string(),
        super::PlacedEdgeLabel {
            center: Point::new(ab_before[0].x, (ab_before[0].y + ab_before[1].y) / 2.0),
            size: Size::new(40.0, 14.0),
            label: Label::measure("x"),
        },
    );

    avoid_label_plates(
        Direction::TopToBottom,
        &nodes,
        &[],
        &edges,
        &mut points,
        &mut plates,
        &std::collections::HashMap::new(),
    );

    assert_ne!(points["ab"], ab_before, "ab's port must have been pushed");
    assert_eq!(
        (points["ab"][0].x - ab_before[0].x).abs(),
        orthogonal::PORT_SPACING,
        "the push must be exactly PORT_SPACING: {:?} vs {:?}",
        points["ab"][0],
        ab_before[0]
    );
    assert_eq!(
        points["cd"], cd_before,
        "cd shares no plate with anything and must be left exactly as routed"
    );
}

// ---------------------------------------------------------------------------------------------
// Stage 5: the perimeter lane (§10-1 item 4)
// ---------------------------------------------------------------------------------------------

/// The smallest box holding every node and every subgraph frame in `d` — the same thing
/// `orthogonal::content_bounds` computes (private to that module, so this is its own independent
/// arithmetic over the public `Diagram` fields, not a call into the implementation it is checking).
fn diagram_content_bounds(d: &Diagram) -> (f64, f64, f64, f64) {
    let mut l = f64::INFINITY;
    let mut t = f64::INFINITY;
    let mut r = f64::NEG_INFINITY;
    let mut b = f64::NEG_INFINITY;
    for n in &d.nodes {
        let (nl, nt, nr, nb) = n.bounds();
        l = l.min(nl);
        t = t.min(nt);
        r = r.max(nr);
        b = b.max(nb);
    }
    for c in &d.clusters {
        let (cl, ct, cr, cb) = c.bounds();
        l = l.min(cl);
        t = t.min(ct);
        r = r.max(cr);
        b = b.max(cb);
    }
    (l, t, r, b)
}

/// Every `(name, from, to)` corpus edge that excurses past the content box **without** being a
/// genuine back edge — a collision-fallback forward edge (`EdgeShape::staircase`) whose own local
/// route (`route_with_ports`'s own doc — reverted off the perimeter lane 2026-09-01) can stray
/// outside the content box by whatever amount dagre's own waypoint chain and
/// `orthogonal::clear_local_route` produce, with no `PERIMETER_MARGIN + k*PERIMETER_LANE_SPACING`
/// guarantee at all — that guarantee is item 4's own, and it is written about the perimeter lane
/// specifically, which only a true `reverse` (non-self-loop) edge draws from now.
///
/// `classify` (the function that actually decides `reverse` vs `staircase`) is private to
/// `orthogonal.rs`, and a finished [`Diagram`] carries no shape tag a test could read back — so
/// this list is reasoned from each source's own topology instead (verified against `classify`'s
/// own rule, "target rank ≤ source rank" for a genuine back edge, applied to each source's own
/// declared chain — the whole corpus was dumped for its own excursion amounts first, over
/// `scratch_dump_perimeter_excursions`, to confirm no entry outside this list needs it):
/// `strokes`' `A<-->F`/`C~~~E` (both forward, `A`/`C` before `F`/`E` in the declared `A---B-.->C
/// ==>D--o E--x F` chain), `long-edge`'s `A->E` (forward — the *other* two excursions on this same
/// source, `E->B` and `C->A`, both close a cycle backward and stay genuine back edges), and
/// `subgraph-bypass`'s `X->Y` (forward — spans the same ranks the `one` frame does without closing
/// any cycle, `orthogonal_dag_corpus`'s own doc on this exact source).
///
/// `subgraph-direction`'s `one->D` joined this list once `shape_crosses_a_node`'s own-endpoint
/// check was added (`route_with_ports`'s own doc on the settings-rules regression). Its own
/// two-step cascade, dumped and read by hand rather than guessed at: the *original* shape (`one`
/// leaves `Top`, `D` receives `Right`) genuinely re-entered `D`'s own real box on its final leg —
/// the same bug class that check exists to catch — so `classify` swapped to the alternate
/// (`one` leaves `Left`, `D` receives `Bottom`); that alternate does *not* touch `D` at all, but
/// its own straight run at `one`'s port height happens to run directly through the row `one`'s own
/// members (`A`/`B`, real, foreign nodes to this edge) sit on — a perfectly ordinary *foreign*-node
/// collision, the ordinary padded test already caught before this fix existed, just never reached
/// for this edge until the first swap started happening for real. Both attempts failing sends it to
/// the raw-derived staircase, whose own port then leaves through `one`'s own outermost (`Left`)
/// face — a small, genuine `PORT_INSET`-scale excursion past the content box, not a perimeter-lane
/// one, the same "still a local route, no margin guarantee" category every other entry here is in.
fn known_staircase_forward_edge(name: &str, from: &str, to: &str) -> bool {
    matches!(
        (name, from, to),
        ("strokes", "A", "F")
            | ("strokes", "C", "E")
            | ("long-edge", "A", "E")
            | ("subgraph-bypass", "X", "Y")
            | ("subgraph-direction", "one", "D")
    )
}

/// How far outside `bounds` a point sits — 0 for a point inside or on the edge, otherwise its
/// distance past whichever side it cleared. What [`orthogonal_perimeter_edges_clear_the_margin`]
/// measures a perimeter edge's route by.
fn excursion(bounds: (f64, f64, f64, f64), p: &Point) -> f64 {
    let (l, t, r, b) = bounds;
    let dx = (l - p.x).max(p.x - r).max(0.0);
    let dy = (t - p.y).max(p.y - b).max(0.0);
    dx.max(dy)
}

/// §10-1 item 4's own headline invariant: any edge whose route strays outside the content box at
/// all — a `branch`/`merge`/`aligned` shape never does, since its whole route stays within
/// coordinates existing nodes already occupy, so straying at all is itself the signal this is a
/// perimeter-routed edge — clears it by at least [`orthogonal::PERIMETER_MARGIN`].
///
/// **Test-sufficiency audit finding 4 (2026-09-01)**: run only over `orthogonal_corpus()` (every
/// `CORPUS` source), this invariant never actually exercises `content_bounds`'s own "a cluster's
/// bounds are folded in, not just its members' node boxes" contract — every `CORPUS` subgraph is
/// small enough that its frame never juts out past its members' own node boxes by more than the
/// ordinary member padding, so the check would pass identically even if `content_bounds` read
/// `nodes` alone. `orthogonal_only_corpus()`'s `orthogonal-frame-hugs-backedge` (a long title
/// forcing the frame wider than its one small member) is what actually makes the two readings
/// disagree — see [`orthogonal_frame_hugs_backedge_perimeter_lane_reads_the_frame_not_just_the_nodes`]
/// for the same fact pinned to real numbers, and this crate's own mutation check (temporarily
/// dropping `content_bounds`'s `clusters` loop) confirms this loop is what actually catches it.
#[test]
fn orthogonal_perimeter_edges_clear_the_margin() {
    for (name, src) in orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let bounds = diagram_content_bounds(&d);
        for e in &d.edges {
            if e.from == e.to {
                continue; // a self-loop's small local bump is not a perimeter lane at all.
            }
            if known_staircase_forward_edge(name, &e.from, &e.to) {
                continue; // a local route, not a perimeter one — see that function's own doc.
            }
            let max_excursion = e
                .points
                .iter()
                .map(|p| excursion(bounds, p))
                .fold(0.0_f64, f64::max);
            if max_excursion < AXIS_EPS {
                continue; // not a perimeter edge — never left the content box at all.
            }
            assert!(
                max_excursion + AXIS_EPS >= orthogonal::PERIMETER_MARGIN,
                "{name}: edge {}->{} strays only {max_excursion}px outside the content box, \
                 short of the {}px margin: {:?}",
                e.from,
                e.to,
                orthogonal::PERIMETER_MARGIN,
                e.points
            );
        }
    }
}

/// Finding 4's own specific pin, dumped by hand: `orthogonal-frame-hugs-backedge`'s `one` frame
/// (widened by its own long title, `subgraph-long-title`'s same trick) sits *above* `D`, `X` and
/// `Y`'s own node boxes — `one`'s top edge (y=24) is the true minimum of the whole diagram, well
/// above every node's own top (y=49) — so `Y->X`'s ring lane can only land at `content.top -
/// PERIMETER_MARGIN` if `content_bounds` actually read `one`'s own bounds; a node-only reading
/// would put the ring 25px further down (`49 - 16 = 33`, inside `one`'s own frame by 9px — a
/// direct violation of "at least 16px outside the outermost frame").
#[test]
fn orthogonal_frame_hugs_backedge_perimeter_lane_reads_the_frame_not_just_the_nodes() {
    if !text_metrics::fonts_available() {
        return;
    }
    let src = orthogonal_only_corpus()
        .into_iter()
        .find(|(name, _)| *name == "orthogonal-frame-hugs-backedge")
        .unwrap()
        .1;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let frame = d.cluster("one").expect("cluster one must exist").bounds();
    let bounds = diagram_content_bounds(&d);
    // `one`'s frame really is the widest thing here — the fixture's whole point.
    assert!(
        (bounds.1 - frame.1).abs() < 0.01,
        "the fixture must make the frame's own top the diagram's minimum y: content.top={} \
         frame.top={}",
        bounds.1,
        frame.1
    );
    let yx = d
        .edges
        .iter()
        .find(|e| e.from == "Y" && e.to == "X")
        .expect("Y->X must exist");
    let topmost = yx.points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
    assert!(
        (bounds.1 - topmost - orthogonal::PERIMETER_MARGIN).abs() < 1.0,
        "Y->X's ring lane must sit exactly PERIMETER_MARGIN above content's own top (which \
         already folds the frame in): topmost={topmost} content.top={} margin={}",
        bounds.1,
        orthogonal::PERIMETER_MARGIN
    );
    // And, directly against the frame itself rather than the whole content box: the ring's own
    // topmost excursion (the point this test just pinned) clears `one`'s own top edge by the
    // margin too — not just checked indirectly through the diagram's own bounding box, which
    // happens to be dominated by the very frame under test here.
    let out = frame.1 - topmost;
    assert!(
        out + AXIS_EPS >= orthogonal::PERIMETER_MARGIN,
        "Y->X's topmost point clears frame `one`'s own top edge by only {out}px, short of the \
         {}px margin",
        orthogonal::PERIMETER_MARGIN
    );
}

/// §10-1 item 4's 8px stagger: every perimeter edge's own maximum excursion past the content box
/// is exactly `PERIMETER_MARGIN + k * PERIMETER_LANE_SPACING` for some non-negative integer `k`
/// (its own lane index) — and, over a diagram with more than one perimeter edge, two *different*
/// edges never land on the same `k` (dumped and checked on `long-edge`'s two back edges before
/// this was written: 16px and 24px, `k = 0` and `k = 1`, never both 16px).
#[test]
fn orthogonal_perimeter_edges_stagger_8px_apart() {
    for (name, src) in orthogonal_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let bounds = diagram_content_bounds(&d);
        let mut lanes: Vec<i64> = Vec::new();
        for e in &d.edges {
            if e.from == e.to {
                continue; // a self-loop's small local bump is not a perimeter lane at all.
            }
            if known_staircase_forward_edge(name, &e.from, &e.to) {
                continue; // a local route, not a perimeter one — see that function's own doc.
            }
            let max_excursion = e
                .points
                .iter()
                .map(|p| excursion(bounds, p))
                .fold(0.0_f64, f64::max);
            if max_excursion < AXIS_EPS {
                continue;
            }
            let steps =
                (max_excursion - orthogonal::PERIMETER_MARGIN) / orthogonal::PERIMETER_LANE_SPACING;
            assert!(
                (steps - steps.round()).abs() < 1e-6,
                "{name}: edge {}->{} excursion {max_excursion}px is not \
                 PERIMETER_MARGIN + k*PERIMETER_LANE_SPACING for an integer k (k={steps}): {:?}",
                e.from,
                e.to,
                e.points
            );
            let lane = steps.round() as i64;
            assert!(
                !lanes.contains(&lane),
                "{name}: edge {}->{} shares lane {lane} with another perimeter edge already seen",
                e.from,
                e.to
            );
            lanes.push(lane);
        }
    }
}

/// §10-1 item 4's third rule (段 5 item 3, the coordinator's own numbering): "別々の辺のcross走行
/// が偶然同じ座標に重なる場合の一般検出と8pxずらし" — two edges that share **no** node (a shared
/// node is stage 1-4's own territory: eviction already spaces those 16px apart on the shared face)
/// whose segments happen to land exactly on top of each other by coincidence.
///
/// Audited across the whole corpus before writing any fix: **zero** such overlaps exist, on any
/// axis, in any of the 27 sources here — checked by hand with `eprintln!` dumps of every pair
/// before this was turned into a real assertion, not assumed. A speculative detector-and-nudge
/// pass for a case with no reproducible instance would be exactly the kind of code this project's
/// own conventions warn against (untestable in any way but a synthetic fixture nobody's real
/// diagram reaches) — see `docs/STATUS.md` for the honest "not implemented, no known case" record
/// this leaves stage 5 item 3 with. This test is the regression guard in its place: it holds today
/// because [`align_straight_lanes`](super::align_straight_lanes)' overlap resolution (stage 3) and
/// the perimeter lane's 8px stagger (stage 5 item 1) already separate every case the corpus
/// exercises; if a future change ever lets two unrelated edges collide, this is what catches it.
#[test]
fn no_two_unrelated_edges_coincidentally_overlap_on_the_same_axis() {
    for (name, src) in orthogonal_corpus() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for i in 0..d.edges.len() {
            for j in (i + 1)..d.edges.len() {
                let (e1, e2) = (&d.edges[i], &d.edges[j]);
                if e1.from == e2.from || e1.from == e2.to || e1.to == e2.from || e1.to == e2.to {
                    continue; // shares a node — stage 1-4 territory, not "unrelated"
                }
                for w1 in e1.points.windows(2) {
                    for w2 in e2.points.windows(2) {
                        let vert1 = (w1[0].x - w1[1].x).abs() < AXIS_EPS;
                        let vert2 = (w2[0].x - w2[1].x).abs() < AXIS_EPS;
                        if vert1 && vert2 && (w1[0].x - w2[0].x).abs() < AXIS_EPS {
                            let (y0a, y1a) = (w1[0].y.min(w1[1].y), w1[0].y.max(w1[1].y));
                            let (y0b, y1b) = (w2[0].y.min(w2[1].y), w2[0].y.max(w2[1].y));
                            assert!(
                                y0a >= y1b - AXIS_EPS || y0b >= y1a - AXIS_EPS,
                                "{name}: {}->{} and {}->{} overlap at x={} \
                                 (y=[{y0a},{y1a}] vs [{y0b},{y1b}])",
                                e1.from,
                                e1.to,
                                e2.from,
                                e2.to,
                                w1[0].x
                            );
                        }
                        let horiz1 = (w1[0].y - w1[1].y).abs() < AXIS_EPS;
                        let horiz2 = (w2[0].y - w2[1].y).abs() < AXIS_EPS;
                        if horiz1 && horiz2 && (w1[0].y - w2[0].y).abs() < AXIS_EPS {
                            let (x0a, x1a) = (w1[0].x.min(w1[1].x), w1[0].x.max(w1[1].x));
                            let (x0b, x1b) = (w2[0].x.min(w2[1].x), w2[0].x.max(w2[1].x));
                            assert!(
                                x0a >= x1b - AXIS_EPS || x0b >= x1a - AXIS_EPS,
                                "{name}: {}->{} and {}->{} overlap at y={} \
                                 (x=[{x0a},{x1a}] vs [{x0b},{x1b}])",
                                e1.from,
                                e1.to,
                                e2.from,
                                e2.to,
                                w1[0].y
                            );
                        }
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------------------------
// Stage 5 item 2: the 12px crossing gap (§10-1 item 4)
// ---------------------------------------------------------------------------------------------

/// [`edges::split_at_gaps`] with no gaps at all must hand back the original polyline as the one
/// and only piece — the fast path `svg::emit_edge` relies on for byte-identical output whenever an
/// edge never crosses another one.
#[test]
fn split_at_gaps_with_no_gaps_returns_the_whole_polyline_unchanged() {
    let pts = vec![
        Point::new(0.0, 0.0),
        Point::new(0.0, 100.0),
        Point::new(50.0, 100.0),
    ];
    let pieces = edges::split_at_gaps(&pts, &[]);
    assert_eq!(pieces, vec![pts]);
}

/// One gap in the middle of a segment splits the polyline into exactly two pieces, each ending
/// (or starting) precisely at the gap's own two points — the geometry
/// [`orthogonal::insert_crossing_gaps`] hands `split_at_gaps` in practice.
#[test]
fn split_at_gaps_cuts_one_gap_into_two_pieces() {
    let pts = vec![
        Point::new(0.0, 0.0),
        Point::new(0.0, 100.0),
        Point::new(50.0, 100.0),
    ];
    let gap = (Point::new(0.0, 44.0), Point::new(0.0, 56.0));
    let pieces = edges::split_at_gaps(&pts, &[gap]);
    assert_eq!(
        pieces,
        vec![
            vec![Point::new(0.0, 0.0), Point::new(0.0, 44.0)],
            vec![
                Point::new(0.0, 56.0),
                Point::new(0.0, 100.0),
                Point::new(50.0, 100.0)
            ],
        ]
    );
}

/// Two gaps on two different segments of the same polyline produce three pieces, each gap cut
/// independently of the other.
#[test]
fn split_at_gaps_cuts_more_than_one_gap() {
    let pts = vec![
        Point::new(0.0, 0.0),
        Point::new(0.0, 100.0),
        Point::new(80.0, 100.0),
    ];
    let gaps = [
        (Point::new(0.0, 44.0), Point::new(0.0, 56.0)),
        (Point::new(30.0, 100.0), Point::new(42.0, 100.0)),
    ];
    let pieces = edges::split_at_gaps(&pts, &gaps);
    assert_eq!(
        pieces,
        vec![
            vec![Point::new(0.0, 0.0), Point::new(0.0, 44.0)],
            vec![
                Point::new(0.0, 56.0),
                Point::new(0.0, 100.0),
                Point::new(30.0, 100.0)
            ],
            vec![Point::new(42.0, 100.0), Point::new(80.0, 100.0)],
        ]
    );
}

/// A gap whose own two points do not land on any segment of the polyline it is handed (should
/// never happen in practice — `insert_crossing_gaps` always builds a gap from the very polyline
/// it will be applied to — but defensively checked rather than assumed) leaves the polyline
/// untouched instead of panicking or silently corrupting it.
#[test]
fn split_at_gaps_ignores_a_gap_that_does_not_land_on_the_polyline() {
    let pts = vec![Point::new(0.0, 0.0), Point::new(0.0, 100.0)];
    let gap = (Point::new(500.0, 500.0), Point::new(500.0, 512.0));
    let pieces = edges::split_at_gaps(&pts, &[gap]);
    assert_eq!(pieces, vec![pts]);
}

/// §10-1 item 4's real motivating case (dumped and confirmed 2026-09-01, after `route_with_ports`
/// stopped routing a collision-fallback forward edge (`EdgeShape::staircase`) onto the perimeter
/// lane — see that function's own doc for why), **re-dumped again** once §10-3 item 5 ("主辺どうし
/// の交差は水平辺側に12pxの隙間") replaced this fixture's old "detour side always spans" tie-break
/// for a pair of ordinary (non-perimeter) edges with an orientation-based one: neither `A->C`/
/// `B->D` (the two aligned, 0-bend lanes, §10-3 item 3's own correction) nor `A->D`/`B->C` (both
/// `fan_lane` shapes riding the same flow-axis faces as their aligned siblings) is a genuine
/// perimeter edge (`reverse`/`staircase`) here, so every crossing among these four now goes to
/// whichever *segment* is horizontal, never to "whichever edge is the fancier shape".
///
/// `amp-chain`'s `A->D` and `B->C` are both collision-fallback edges and both route locally, which
/// uncoupled them from the perimeter lane's own 8px stagger — without
/// `orthogonal::separate_coincident_detours`'s own fix they would land on the exact same vertical
/// run; with it, `B->C`'s run is nudged 8px sideways, so the two now merely *cross* once (at one
/// point) rather than coincide.
///
/// **Re-dumped a second time (§10-3 item 12, "面のポートは相手の側で配る")**: `A->C` is `classify`'s
/// own `aligned` shape — a straight 2-point line, structurally incapable of crossing anything — so
/// it never carried the two gap requests this doc used to describe; the pre-item-12 `evict` was
/// putting `A->D`'s and `B->C`'s own ports on the *wrong* side of their shared faces (an
/// array-symmetric re-splice, not each edge's genuine side), which routed both of them back up
/// through `A`'s own row and manufactured two spurious crossings against `A->C`'s line that
/// shouldn't have existed at all. With ports on their true sides, only the one real crossing
/// remains: `A->D`'s own horizontal leg into `D` crosses `B->C`'s vertical run — `A->D` is the
/// horizontal side there (`segment_crossing`'s own contract), so it alone carries the gap; `A->C`,
/// `B->C`, `B->D`, and `C->E` all stay whole.
#[test]
fn orthogonal_crossing_gaps_cut_the_horizontal_side_of_each_crossing() {
    let src = "flowchart LR\n  A & B --> C & D\n  C --> E";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");

    let edge = |from: &str, to: &str| {
        d.edges
            .iter()
            .find(|e| e.from == from && e.to == to)
            .unwrap_or_else(|| panic!("{from}->{to} must exist"))
    };
    let (ac, ad, bc, bd, ce) = (
        edge("A", "C"),
        edge("A", "D"),
        edge("B", "C"),
        edge("B", "D"),
        edge("C", "E"),
    );

    assert!(bc.gaps.is_empty(), "B->C must stay whole: {:?}", bc.gaps);
    assert!(bd.gaps.is_empty(), "B->D must stay whole: {:?}", bd.gaps);
    assert!(ce.gaps.is_empty(), "C->E crosses nothing: {:?}", ce.gaps);
    assert_eq!(
        ac.points.len(),
        2,
        "A->C is the aligned leg — a straight 2-point line, structurally unable to cross anything: \
         {:?}",
        ac.points
    );
    assert!(
        ac.gaps.is_empty(),
        "A->C must stay whole — item 12's own side fix removed the two spurious crossings this \
         used to have against A->D/B->C's own (previously wrong-sided) ports: {:?}",
        ac.gaps
    );

    assert_eq!(
        ad.gaps.len(),
        1,
        "A->D must carry exactly one gap, from being the horizontal side of its crossing with \
         B->C's vertical run: {:?}",
        ad.gaps
    );

    // Every gap actually sits on its own edge's line, and removes exactly `CROSSING_GAP` px of
    // *arc length* along it (or clamped shorter only if the line itself is that short, which none
    // here is) — not necessarily `CROSSING_GAP` px of straight-line (Euclidean) distance between
    // its own two endpoints. Measuring by Euclidean distance is what this test used to do at one
    // point, and is exactly what let a real regression through: `orthogonal::insert_crossing_gaps`'s
    // own `gap_around` clamped the omitted stretch to the single segment its crossing point was
    // found on, so a crossing landing close enough to a corner (never on macOS's own font metrics
    // for this diagram, reliably on Linux's, whose metrics size `B`/`C` a few px differently — CI
    // caught it, 2026-09-01) got a gap only 6px wide instead of 12. The fix measures by arc length
    // along the whole polyline instead, letting the omitted stretch continue past a corner onto
    // the next segment when it has to — which is exactly the case a same-segment / Euclidean check
    // cannot tell apart from an under-sized gap, since a corner-straddling gap's own two endpoints
    // are, correctly, less than `CROSSING_GAP` px of *straight-line* distance apart.
    for e in [ad] {
        for (g0, g1) in &e.gaps {
            let arc = edges::arc_length_between(&e.points, g0, g1).unwrap_or_else(|| {
                panic!(
                    "{}->{}: gap {g0:?}-{g1:?} is not on any of its own segments {:?}",
                    e.from, e.to, e.points
                )
            });
            assert!(
                (arc - orthogonal::CROSSING_GAP).abs() < 1e-6,
                "{}->{}: gap {g0:?}-{g1:?} removes {arc}px of arc length, not CROSSING_GAP: {:?}",
                e.from,
                e.to,
                orthogonal::CROSSING_GAP
            );
        }
    }
}

/// The SVG itself draws the horizontal side of each crossing as more than one `<path>` element
/// (one per piece [`edges::split_at_gaps`] returns) and the vertical side as exactly one —
/// `svg::emit_edge`'s own fast path for an edge with no gaps.
#[test]
fn orthogonal_crossing_gap_splits_the_svg_path_of_the_horizontal_side_only() {
    let src = "flowchart LR\n  A & B --> C & D\n  C --> E";
    let svg =
        crate::preview::markdown::mermaid_to_svg_flow(src, "dark", "basis", "konoma-orthogonal")
            .expect("must render");
    let path_count = svg.matches("<path").count();
    // `A->C`, `B->C`, `B->D`, `C->E` draw 1 path each (never cut, §10-3 item 12's own fix —
    // `orthogonal_crossing_gaps_cut_the_horizontal_side_of_each_crossing`'s own doc); `A->D` alone
    // carries one real gap (2 pieces): 4 + 2 = 6.
    assert_eq!(
        path_count, 6,
        "expected 4 uncut edges (1 path each) + A->D (2 pieces) = 6: got {path_count}\n{svg}"
    );
}

/// The bug the coordinator's own verification pass found right after item 1's own fix: `normalise`
/// translates every `PlacedEdge::points` by `(dx, dy)` to keep the whole diagram non-negative, but
/// did not translate `PlacedEdge::gaps` — so a gap computed in the pre-normalise coordinate space
/// (`orthogonal::insert_crossing_gaps` reads straight from `route_flowchart`'s own output, before
/// `normalise` ever runs) silently pointed at the wrong location once `points` moved out from
/// under it. Reproduced directly at the `laid_out_flow` level (not just visually): every gap's
/// `x`/`y` must land inside the *normalised* diagram's own bounds, and — the stronger
/// check — still sit exactly on its own edge's line (already checked above, from a fresh call;
/// this test exists so a regression here fails immediately by name rather than as a puzzling
/// "gap not on segment" failure in the more general test).
#[test]
fn normalise_moves_edge_gaps_along_with_points() {
    let src = "flowchart LR\n  A & B --> C & D\n  C --> E";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let mut checked_at_least_one = false;
    for e in &d.edges {
        for (g0, g1) in &e.gaps {
            checked_at_least_one = true;
            // The precise check, not just "somewhere inside the diagram" (too weak to catch the
            // real bug — `dx`/`dy` can be small enough that an un-translated gap still happens to
            // fall inside the normalised bounds by coincidence, which is exactly how this test's
            // own first draft passed even with the translation missing): every gap endpoint must
            // still land, *independently*, on some segment of its own edge's (normalised) polyline
            // — independently, not "both on the same segment", because a gap that straddles a
            // corner (reachable on a platform whose font metrics move a crossing close enough to a
            // bend — this is what Linux CI's own `insert_crossing_gaps` regression looked like,
            // 2026-09-01) legitimately has its two endpoints on two different segments. A missing
            // translation is still caught exactly as before: if `normalise()` moved `points` but
            // not `gaps`, the untranslated `g0`/`g1` land nowhere on the translated `points` at
            // all, on any segment.
            let on_own_segments = edges::arc_length_between(&e.points, g0, g1).is_some();
            assert!(
                on_own_segments,
                "{}->{}: gap {g0:?}-{g1:?} does not land on any of its own (normalised) \
                 segments {:?} — normalise() must have moved `points` without moving `gaps`",
                e.from, e.to, e.points
            );
        }
    }
    assert!(
        checked_at_least_one,
        "fixture must actually produce at least one gap for this test to mean anything"
    );
}

/// The Linux-only reproduction of the same `normalise`/`gaps` translation this module's own
/// `normalise_moves_edge_gaps_along_with_points` pins, but with a gap that **straddles a corner** —
/// its two endpoints on two different segments of the edge's own polyline, the shape a real crossing
/// only takes when it lands within `CROSSING_GAP / 2` of a bend (`orthogonal::gap_around`'s own
/// arc-length fix, 2026-09-01 — reachable on macOS's own font metrics only by hand-building the
/// input, which is exactly what this test does instead of depending on a platform's measured text).
/// `normalise_moves_edge_gaps_along_with_points`'s own corpus run never happens to produce this
/// shape on this machine, which is exactly how the coordinator's own CI re-run found a second,
/// narrower hole in the exact same test family: both of that test's own on-segment checks (this one
/// and `orthogonal_frame_crossings_never_produce_a_gap`) required `g0` *and* `g1` on the *same*
/// segment, which a corner-straddling gap fails even when `normalise` translated it perfectly.
#[test]
fn normalise_translates_a_corner_straddling_gap_onto_its_own_two_segments() {
    let mut d = Diagram {
        width: 0.0,
        height: 0.0,
        ..Diagram::default()
    };
    // An L-shaped polyline — vertical (0,0)-(0,20), then horizontal (0,20)-(30,20), the same shape
    // `orthogonal::tests::crossing_gap_straddling_a_corner_still_totals_12px_by_arc_length` uses —
    // carrying a gap whose two endpoints already straddle the corner *before* `normalise` runs:
    // (0, 11) on the vertical leg, (3, 20) 3px past the corner onto the horizontal leg.
    d.edges.push(PlacedEdge {
        from: "a".to_string(),
        to: "b".to_string(),
        points: vec![
            Point::new(0.0, 0.0),
            Point::new(0.0, 20.0),
            Point::new(30.0, 20.0),
        ],
        gaps: vec![(Point::new(0.0, 11.0), Point::new(3.0, 20.0))],
        tip_start: Tip::None,
        tip_end: Tip::None,
        stroke: Stroke::Normal,
        label: None,
        start_label: None,
        end_label: None,
        badge: None,
        series: None,
        straight: false,
        overlay: false,
        style: None,
        curve: Curve::Basis,
        tip_matches_line: false,
    });

    super::normalise(&mut d);

    let e = &d.edges[0];
    // The whole diagram sat at the origin (min_x = min_y = 0), so `normalise` must have shifted
    // everything by exactly `(MARGIN, MARGIN)` — points and gap alike.
    assert_eq!(
        e.points,
        vec![
            Point::new(MARGIN, MARGIN),
            Point::new(MARGIN, 20.0 + MARGIN),
            Point::new(30.0 + MARGIN, 20.0 + MARGIN),
        ],
        "normalise must shift every point of the polyline by (MARGIN, MARGIN): {:?}",
        e.points
    );
    assert_eq!(e.gaps.len(), 1, "{:?}", e.gaps);
    let (g0, g1) = &e.gaps[0];
    assert_eq!(
        (g0.clone(), g1.clone()),
        (
            Point::new(MARGIN, 11.0 + MARGIN),
            Point::new(3.0 + MARGIN, 20.0 + MARGIN)
        ),
        "the gap must be shifted by the exact same (MARGIN, MARGIN) as the points — a gap left in \
         the pre-normalise coordinate space would still read (0,11)-(3,20) here"
    );
    // Each endpoint independently lands on *some* segment of the *translated* polyline — g0 on the
    // (now shifted) vertical leg, g1 on the (now shifted) horizontal leg, two different segments —
    // and the arc length between them is still the full `CROSSING_GAP`, unchanged by translation.
    let arc = edges::arc_length_between(&e.points, g0, g1).unwrap_or_else(|| {
        panic!(
            "gap {g0:?}-{g1:?} does not land on the translated polyline {:?}",
            e.points
        )
    });
    assert!(
        (arc - orthogonal::CROSSING_GAP).abs() < 1e-9,
        "arc length between the translated gap's own two endpoints must still be CROSSING_GAP: {arc}"
    );
}

/// §10-1 item 4's other half: "辺と枠の交差は隙間なし(直交して跨ぐだけ)" — a subgraph frame is
/// never consulted by `insert_crossing_gaps` at all (it only ever compares two edges' own
/// segments), so an edge that crosses a frame boundary — `subgraph-bypass`'s own `X->A`, which the
/// corpus already names for crossing a frame from outside it — must never carry a gap because of
/// that frame, whatever its edge-vs-edge gaps (if any) are.
#[test]
fn orthogonal_frame_crossings_never_produce_a_gap() {
    for (name, src) in orthogonal_corpus() {
        if !name.contains("subgraph") {
            continue;
        }
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        // Every gap that does exist must still sit on its own edge's own line (never on a frame's
        // own boundary) — reusing the same "each endpoint independently on some segment of its own
        // edge" shape the normalise test above states (not "both endpoints on the *same* segment",
        // which a gap straddling a corner legitimately fails), generalised to the whole subgraph
        // corpus rather than one hand-picked source.
        for e in &d.edges {
            for (g0, g1) in &e.gaps {
                let on_own_segments = edges::arc_length_between(&e.points, g0, g1).is_some();
                assert!(
                    on_own_segments,
                    "{name}: {}->{}'s gap {g0:?}-{g1:?} is not on its own line — a frame must \
                     never be the reason a gap exists: {:?}",
                    e.from, e.to, e.points
                );
            }
        }
    }
}

// ---------------------------------------------------------------------------------------------
// `[ui] mermaid_routing = "konoma-orthogonal"` — §10-2's cluster-anchored edge stage
// ---------------------------------------------------------------------------------------------

/// A cluster-anchored edge (`one --> two`, `E --> one`) is actually routed by
/// `orthogonal::route_flowchart` — `PlacedEdge::straight`/`tip_matches_line` are both true, the
/// same pair every node-to-node orthogonal edge sets — not silently left on the spline fallback
/// `route_with_ports`'s `unwrap_or_else` exists for. Checked directly against `subgraph-endpoint`'s
/// two cluster-anchored edges (a node→cluster end and a cluster→cluster end) rather than inferred
/// from the axis-parallel corpus sweep above, which cannot tell "genuinely orthogonal" apart from
/// "happened to fall back to a spline that came out axis-parallel by coincidence".
#[test]
fn cluster_anchored_edges_are_actually_routed_orthogonally_not_by_the_spline_fallback() {
    let src = "flowchart LR\n  subgraph one [First]\n    A --> B\n  end\n  \
               subgraph two [Second]\n    C --> D\n  end\n  one --> two\n  E --> one";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let one_to_two = d
        .edges
        .iter()
        .find(|e| e.from == "one" && e.to == "two")
        .expect("one->two must exist");
    let e_to_one = d
        .edges
        .iter()
        .find(|e| e.from == "E" && e.to == "one")
        .expect("E->one must exist");
    for (name, e) in [("one->two", one_to_two), ("E->one", e_to_one)] {
        assert!(
            e.straight,
            "{name}: must be drawn as a polyline, not a curve"
        );
        assert!(
            e.tip_matches_line,
            "{name}: the arrow tip must match the routed line, the same as every other \
             orthogonal edge"
        );
    }
}

/// §10-1 item 1's "退避則" (16px port spacing) applies to a subgraph frame's own faces exactly
/// like a node's — and, since [`orthogonal::build_by_id`] resolves a cluster-anchored edge's end
/// through the very same `evict` face-grouping a node-anchored one uses, a genuine merge of three
/// cluster-anchored edges spaces them 16px apart in one shared order, exactly as it would for
/// three ordinary node-to-node edges.
///
/// §10-3 item 3's own correction (`classify`'s `merge_target_side` doc) moved `X`/`Y`/`Z --> one`
/// off the cluster's cross-axis (Left/Right, for this `TD` diagram) face this test originally
/// exercised, onto its flow-axis Top face instead — the same face `one --> D`/`one --> E` used to
/// share with them until this correction separated the two groups onto Top (the 3-way merge) and
/// Left (the 2-way branch) respectively; dumped and confirmed by hand, not assumed. `one`'s own
/// two out-edges no longer share a face with the merge at all under this fixture, so the "mixed
/// node-endpoint and cluster-endpoint claims on one shared face" scenario the original test built
/// is not exercised by this specific source any more — `docs/STATUS.md`'s own ★未修正 records that
/// as a real, if narrow, coverage gap left by this correction rather than silently dropping it.
/// What this test still genuinely proves: `evict`'s 16px spacing groups `X`/`Y`/`Z`'s three
/// cluster-anchored claims on `one`'s own Top face by "もう一方の端点のcross座標順" (rule 1) —
/// `X`'s own centre x is smallest, then `Y`'s, then `Z`'s — landing at `center - 16, center,
/// center + 16` in that order.
#[test]
fn cluster_face_shares_16px_ports_across_a_three_way_merge() {
    let src = "flowchart TD\n  subgraph one [Group]\n    A --> B\n    A --> C\n  end\n  \
               X --> one\n  Y --> one\n  Z --> one\n  one --> D\n  one --> E";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let one = d.cluster("one").expect("cluster one must exist");
    let (_, t, _, _) = one.bounds();

    let top_port = |from: &str| -> f64 {
        let e = d
            .edges
            .iter()
            .find(|e| e.from == from && e.to == "one")
            .unwrap_or_else(|| panic!("{from}->one must exist"));
        let p = e.points.last().expect("must have at least one point");
        assert!(
            (p.y - (t - orthogonal::PORT_INSET)).abs() < AXIS_EPS,
            "{from}->one: expected this edge's own end at \"one\" to land on the Top face \
             (y={}), got {p:?}",
            t - orthogonal::PORT_INSET
        );
        p.x
    };

    let x_x = top_port("X");
    let y_x = top_port("Y");
    let z_x = top_port("Z");

    assert!(
        x_x < y_x && y_x < z_x,
        "expected X < Y < Z by \"other cross coordinate\" order (rule 1), got X={x_x} Y={y_x} \
         Z={z_x}"
    );
    assert!(
        (y_x - x_x - orthogonal::PORT_SPACING).abs() < AXIS_EPS,
        "X->Y gap must be exactly PORT_SPACING: X={x_x} Y={y_x}"
    );
    assert!(
        (z_x - y_x - orthogonal::PORT_SPACING).abs() < AXIS_EPS,
        "Y->Z gap must be exactly PORT_SPACING: Y={y_x} Z={z_x}"
    );
}

/// A reverse edge whose target is a subgraph (`D --> one`, looping back into a block the flow
/// already passed) draws from the perimeter lane exactly like a reverse node-to-node edge does —
/// `route_perimeter`, not the 1-2 bend shapes forward edges take — and its route still clears both
/// of the block's own member nodes (`A`, `B`), not only the frame itself. §10-1 item 2's "回数制限
/// なし" for a back edge applies here too: this is *not* added to `orthogonal_dag_corpus`'s
/// bend-count cap.
#[test]
fn cluster_anchored_reverse_edge_routes_through_the_perimeter_lane_and_clears_its_own_members() {
    let src = "flowchart TD\n  subgraph one [Group]\n    A --> B\n  end\n  one --> D\n  D --> one";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let back = d
        .edges
        .iter()
        .find(|e| e.from == "D" && e.to == "one")
        .expect("D->one must exist");
    assert!(
        back.points.len() > 3,
        "a perimeter route has more than one bend: {:?}",
        back.points
    );
    for w in back.points.windows(2) {
        let dx = (w[1].x - w[0].x).abs();
        let dy = (w[1].y - w[0].y).abs();
        assert!(
            dx < AXIS_EPS || dy < AXIS_EPS,
            "perimeter route must stay axis-parallel: {w:?}"
        );
    }
    for member_id in ["A", "B"] {
        let member = d.node(member_id).expect("member must exist");
        for w in back.points.windows(2) {
            assert!(
                !orthogonal::segment_crosses_node(&w[0], &w[1], member),
                "D->one's perimeter route crosses its own block's member {member_id}: {w:?}"
            );
        }
    }
}

/// A cluster-to-cluster edge (`two --> one`, both ends naming a subgraph) resolves *both* its ends
/// against the two frames themselves, not against whichever member node dagre anchored the
/// underlying layout edge to — `orthogonal::build_by_id` has to prefer the cluster box over the
/// anchor's own node box for both `source` and `target` at once, the one shape of cluster-anchored
/// edge no other test here exercises (every other cluster-edge test in this file has at least one
/// ordinary node end).
#[test]
fn cluster_to_cluster_edge_resolves_both_ends_against_the_frames_not_their_anchors() {
    let src = "flowchart LR\n  subgraph one [First]\n    A --> B\n  end\n  \
               subgraph two [Second]\n    C --> D\n  end\n  two --> one";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let e = d
        .edges
        .iter()
        .find(|e| e.from == "two" && e.to == "one")
        .expect("two->one must exist");
    assert!(
        e.straight && e.tip_matches_line,
        "must be orthogonal-routed"
    );

    let one = d.cluster("one").expect("cluster one must exist");
    let two = d.cluster("two").expect("cluster two must exist");
    let (start, end) = (
        e.points.first().expect("must have a start point"),
        e.points.last().expect("must have an end point"),
    );
    let on_bounds = |p: &Point, (l, t, r, b): (f64, f64, f64, f64)| {
        let on_v = (p.y - (t - orthogonal::PORT_INSET)).abs() < AXIS_EPS
            || (p.y - (b + orthogonal::PORT_INSET)).abs() < AXIS_EPS;
        let on_h = (p.x - (l - orthogonal::PORT_INSET)).abs() < AXIS_EPS
            || (p.x - (r + orthogonal::PORT_INSET)).abs() < AXIS_EPS;
        on_v || on_h
    };
    assert!(
        on_bounds(start, two.bounds()),
        "two->one's own start {start:?} must sit on cluster \"two\"'s own bounds {:?}, not on \
         one of its member nodes' bounds",
        two.bounds()
    );
    assert!(
        on_bounds(end, one.bounds()),
        "two->one's own end {end:?} must sit on cluster \"one\"'s own bounds {:?}, not on one \
         of its member nodes' bounds",
        one.bounds()
    );
}

/// Review finding 3's suspicion, confirmed and fixed 2026-09-01 (a second pass, after the
/// coordinator independently confirmed the `r + 1` adjacency bug this test's own history records
/// and asked for it to be fixed constructively rather than left as read): [`align_straight_lanes`]
/// moves [`PlacedNode::center`], but the raw dagre waypoints a self-loop still draws from
/// (`EligibleEdge::raw`, `mod.rs`'s own comment on why it is read *before* alignment runs) were
/// never re-derived after that move — `route_staircase_with_ports` is the one shape
/// (`route_with_ports`'s own doc) that still bridges through `raw`'s interior points rather than
/// only the two evicted ports.
///
/// This did not reproduce over the first round of adversarial constructions below, for a reason
/// this test's own git history records in detail: `align_straight_lanes`'s chain candidate filter
/// used to check `node_rank.get(t) == Some(&(r + 1))`, an exact-integer "next rank" test that
/// dagre's own `makeSpaceForEdgeLabels` (`mod.rs`'s own `minlen *= 2` comment) made impossible to
/// satisfy — real node ranks always land two apart, so the filter never matched any real edge, in
/// any diagram, and lane alignment never fired at all. Once that was fixed (`align_straight_lanes`'s
/// own doc, "next rank some *real* node actually occupies"), it started moving self-loop owners for
/// real — and the coupling above turned out genuine: `one-sided-huge-push` below, a self-loop owner
/// pushed ~137px by a one-sided run of wide siblings, drew with its ports correctly on the node's
/// current boundary but its interior bump landing ~176px away in open space, dumped and confirmed
/// before any fix. The fix is [`align_straight_lanes`]'s own return value — every node's cross-axis
/// delta — applied back onto a self-loop's `raw` before `route_with_ports` ever reads it
/// (`mod.rs`'s own `raw` construction, [`shift_cross`]).
///
/// What this test pins now that the fix is in: every self-loop across the whole adversarial set —
/// including the one that actually reproduced the bug — must draw axis-parallel and stay within
/// [`SELF_LOOP_BUMP_MARGIN`] of its owner's *current* box. That margin is deliberately not scaled
/// by node size (a stale-`raw` bug does not get harder to see on a wider node — `position_self_edges`
/// sizes a self-loop's own bump off `NODE_SEP`-scale spacing, not the owner's box, confirmed by the
/// same dumps: `wide-head`'s 387px-wide node still draws a ~40px bump, same as every other source
/// here), so it stays tight enough to actually catch a real rank-scale drift rather than merely not
/// flake — verified directly: reverting the fix (skip applying the delta to `raw`) makes
/// `one-sided-huge-push` fail this exact assertion with the point ~176px outside the margin, and
/// restoring it passes again.
#[test]
fn self_loop_routes_correctly_across_lane_alignment_stress_cases() {
    let mut dense = String::from("flowchart TD\n");
    for i in 0..12 {
        dense.push_str(&format!("  d{i} --> d{}\n", i + 1));
        dense.push_str(&format!("  d{i} --> e{i}\n  e{i} --> d{}\n", i + 2));
    }
    dense.push_str("  d6 --> d6\n"); // a self-loop on a middle node of a dense diamond lattice
    let dense_diamond_lattice_source = dense;
    let sources: Vec<(&str, &str)> =
        vec![
        (
            "wide-head",
            "flowchart TD\n  A[this label is deliberately very long to force a wide box] --> B\n  \
             B --> C\n  A --> A",
        ),
        (
            "wide-tail",
            "flowchart TD\n  A --> B\n  \
             B --> C[this label is deliberately very long to force a wide box]\n  C --> C",
        ),
        (
            "asymmetric-siblings",
            "flowchart TD\n  P --> A\n  Q --> A\n  R --> A\n  A --> B\n  B --> C\n  A --> A",
        ),
        (
            "wide-sibling-pushes-loop-owner",
            "flowchart TD\n  A0 --> A1\n  A1 --> A2\n  A1 --> A1\n  \
             W[a very very very long wide sibling label to force a nodesep push] --> A2\n  \
             A0 --> W",
        ),
        (
            "z-competes-for-b",
            "flowchart TD\n  A --> B\n  B --> C\n  A --> A\n  \
             Z[a very very very long sibling label to push things around] --> B",
        ),
        (
            "deep-fanout-both-sides",
            "flowchart TD\n  W1 --> A\n  W2 --> A\n  W3 --> A\n  A --> A\n  A --> B\n  \
             B --> X1\n  B --> X2\n  B --> X3\n  B --> C\n  C --> D",
        ),
        ("dense-diamond-lattice", dense_diamond_lattice_source.as_str()),
        (
            // The fixture that actually reproduced the bug: every wide sibling pushes `A` the
            // *same* direction (no opposing push to cancel it out the way the symmetric
            // constructions above coincidentally did), so the align delta (~137px, dumped) is far
            // larger than a self-loop's own ~40px bump and cannot be masked by it.
            "one-sided-huge-push",
            "flowchart TD\n  \
             W1[extremely long sibling label number one to push things far to the right] --> A\n  \
             W2[extremely long sibling label number two to push things even further right] --> A\n  \
             W3[extremely long sibling label number three to push things still further right] --> A\n  \
             A --> A\n  A --> B\n  B --> C",
        ),
    ];
    // Deliberately not scaled by node size — see this test's own doc for why a fixed bound is the
    // stronger check here.
    const SELF_LOOP_BUMP_MARGIN: f64 = 100.0;
    for (name, src) in &sources {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for e in &d.edges {
            if e.from != e.to {
                continue;
            }
            let owner = d
                .nodes
                .iter()
                .find(|n| n.id == e.from)
                .unwrap_or_else(|| panic!("{name}: self-loop owner {} must be a node", e.from));
            for w in e.points.windows(2) {
                let dx = (w[1].x - w[0].x).abs();
                let dy = (w[1].y - w[0].y).abs();
                assert!(
                    dx < AXIS_EPS || dy < AXIS_EPS,
                    "{name}: self-loop {} must stay axis-parallel: {w:?}",
                    e.from
                );
            }
            let (l, t, r, b) = owner.bounds();
            for p in &e.points {
                assert!(
                    p.x >= l - SELF_LOOP_BUMP_MARGIN
                        && p.x <= r + SELF_LOOP_BUMP_MARGIN
                        && p.y >= t - SELF_LOOP_BUMP_MARGIN
                        && p.y <= b + SELF_LOOP_BUMP_MARGIN,
                    "{name}: self-loop {} point {p:?} sits far outside {}'s own current box \
                     ({l},{t})-({r},{b}) (margin {SELF_LOOP_BUMP_MARGIN}) — exactly the drift \
                     review finding 3 asked about",
                    e.from,
                    e.from
                );
            }
        }
    }
}

// =============================================================================================
// 2026-09-01 test-sufficiency audit (orthogonal wiring mode, `docs/FEATURE-MERMAID-RENDERER.md`
// §10) — two independent audits (a spec-axis review and a mutation-testing run) of the tests
// above. Findings are implemented below, grouped and commented by finding number so each one's own
// reasoning stays next to its test. Every new source here is deliberately kept OUT of `CORPUS`
// itself: `CORPUS` is `mermaid_render.snap`'s own golden input, and this audit's own ground rule
// (`docs/FEATURE-MERMAID-RENDERER.md` §10's own governing instruction) is that the golden must not
// move. New sources live in `orthogonal_only_corpus` instead — this module's own equivalent of
// `orthogonal_corpus`/`orthogonal_dag_corpus`'s existing "filtered/extended view of `CORPUS`"
// pattern, just built from scratch rather than filtered.
// =============================================================================================

/// Sources built specifically to exercise a `konoma-orthogonal` corner none of `CORPUS`'s
/// shape-driven entries reaches — never folded into `CORPUS` (see this section's own doc).
fn orthogonal_only_corpus() -> Vec<(&'static str, &'static str)> {
    vec![
        (
            // Finding 1: `T` receives four merge-shaped edges onto the same face (`W1->T` lands
            // on `T`'s own flow face instead, aligned) — `docs/FEATURE-MERMAID-RENDERER.md` §10-1
            // item 1's own "ノードをその軸方向に拡大" (eviction growth), dumped and confirmed to
            // actually fire here (`T`'s box grows from its label-only size to fit four 16px-spaced
            // ports), with every node a member of the same subgraph frame — the growth retry
            // (`lay_out_spec`'s own loop) re-lays the whole diagram out afterward, so the cluster
            // invariants have to hold against the *grown*, not the original, geometry.
            // Seven sources, not the five this fixture was written with: §10-8 N2's own 96px
            // minimum width (2026-09-05) is wider than the `2*(2*PORT_SPACING + PORT_CLEARANCE)
            // = 80px` five merge ports need, so five no longer force any growth at all and the
            // fixture would quietly stop exercising the thing it exists for. Seven ask for
            // `2*(3*PORT_SPACING + PORT_CLEARANCE) = 112px`, past the minimum, and
            // `orthogonal_eviction_growth_inside_a_subgraph_still_fits_the_frame` asserts the
            // growth actually happens rather than trusting the count.
            "orthogonal-subgraph-growth",
            "flowchart TD\n  subgraph one [Group]\n    W1 --> T\n    W2 --> T\n    W3 --> T\n    \
             W4 --> T\n    W5 --> T\n    W6 --> T\n    W7 --> T\n  end\n  T --> X",
        ),
        (
            // Finding 4: a long title forces the frame `one` wider/taller than its one small
            // member `D` — dumped and confirmed the frame is in fact the widest/tallest thing in
            // the diagram (`D`, `X`, `Y` are all small default-sized nodes). `X`/`Y` sit entirely
            // outside `one` and close a two-node cycle, so `Y->X` is a genuine back edge routed
            // through the perimeter lane (§10-1 item 4) — one that has no other reason to come
            // anywhere near `one` except that `one`'s own frame juts into the ring's own margin
            // unless `orthogonal::content_bounds` actually folds a cluster's bounds in (not just
            // its members' node boxes, `content_bounds`'s own doc).
            "orthogonal-frame-hugs-backedge",
            "flowchart TD\n  subgraph one [resolve the preview kind and delegate it]\n    D[d]\n  \
             end\n  X --> Y\n  Y --> X",
        ),
        (
            // Finding 8a: `C->B` is a collision-fallback `staircase` detour around `A` (dumped:
            // its route dips right through the self-loop `A->A`'s own bump). Both cross in real
            // pixels, so this is the one source that actually reaches `insert_crossing_gaps`'s
            // self-loop/detour interaction rather than assuming it from reading the code.
            "orthogonal-self-loop-crosses",
            "flowchart TD\n  A --> A\n  A --> B\n  C --> A\n  C --> B",
        ),
        (
            // The shape that produced the `aside_weight` rule: three merge siblings converging on
            // one target, one of which also carries an author-dotted aside to a node several ranks
            // away that nothing else reaches (`super::aside_weight`'s own doc). Originally reduced
            // from `zz-design-2b` when that source was still mistranscribed as
            // `CLI -.->|リンク| PAY` (`CLI` being the row's first sibling, matching `A` here) — the
            // corrected source (`UI -.->|リンク| PAY`, the *middle* sibling) does not reproduce the
            // reorder even hypothetically (`orthogonal_a_dotted_aside_does_not_reorder_a_rank`'s
            // own note), so this fixture is kept deliberately independent of either design
            // reference, with the aside still on `A` (the first of three) to state the general
            // case. `Z` is deliberately the *last* declared member of its rank, so with the aside
            // weighted like a flow edge dagre drags `A` away from `B` and `C` to sit beside it.
            // Kept as a plain, cluster-free flowchart on purpose: 2b's own frames add a second,
            // unrelated effect on top (the aside's dummy chain is parented into the source's frame
            // and stretches it — see `orthogonal_a_dotted_aside_does_not_reorder_a_rank`'s own
            // note), and a fixture that mixes the two cannot say which one a failure came from.
            "orthogonal-dotted-aside-merge",
            "flowchart LR\n  A[A] --> M[merge]\n  B[B] --> M\n  C[C] --> M\n  M --> N[N]\n  \
             N --> P[P]\n  N --> Q[Q]\n  N --> R[R]\n  R --> Z[Z]\n  A -.->|aside| Z",
        ),
        (
            // The same shape as `orthogonal-dotted-aside-merge`, laid out `TB` and **with the
            // three merge sources inside a frame** — the two things `2b`/`2c` add on top of the
            // plain fixture above, and the pair that actually produced §10-1 item 4's layout
            // defect: the aside's dummy chain is parented into the source's own subgraph
            // (`parent_dummy_chains`), has to sit outside every wider sibling frame, and stretches
            // the frame far enough for `position::bk` to spread the stack. The cluster-free
            // fixture above never showed it, which is why it needs a framed sibling of its own
            // rather than a second unframed direction.
            "orthogonal-dotted-aside-merge-tb",
            "flowchart TB\n  subgraph F[front]\n    A[A]\n    B[B]\n    C[C]\n  end\n  \
             subgraph G[back]\n    M[merge]\n    N[N]\n    P[P]\n    Q[Q]\n    R[R]\n    Z[Z]\n  \
             end\n  A --> M\n  B --> M\n  C --> M\n  M --> N\n  N --> P\n  N --> Q\n  N --> R\n  \
             R --> Z\n  A -.->|aside| Z",
        ),
        (
            // An aside whose source is **boxed in on every side by main flow**: `B` is the middle
            // of three framed siblings that one node feeds and one node collects, so the corridor
            // above the row, the corridor below it, the runs in and the runs out are all occupied
            // by a sibling's leg — every one of `perimeter_faces`' sixteen candidate pairs has to
            // cut one to get out. (The `orthogonal-aside-off-a-middle-sibling-*` pair
            // `dotted_aside_cases` carries inline is this same shape with the row fed from one side
            // only, which leaves the other side free and is why that one crosses nothing.)
            //
            // This is the case §10-1 item 4's own crossing gap exists for, and after 2026-09-05 it
            // is the only one left: the crossing term added that day (§10-0, "交差は遠回りより悪い")
            // took every other corpus aside's crossing away — `orthogonal_a_forward_aside_carries_
            // the_crossing_gaps` measured nothing at all and said so — and a rule with nothing left
            // to measure it on is a rule that quietly stops being true. It states the converse of
            // the new term too: that the term never invents a detour when no face pair is free,
            // which is what `invariant_orthogonal_aside_crosses_no_more_than_the_best_face_pair_
            // could` reading a non-zero minimum here says.
            //
            // **`LR` only, deliberately.** The identical graph laid out `TB` reaches its own
            // fewest-crossings pair only through a five-corner route, which
            // `orthogonal_every_aside_rides_the_outer_perimeter_lane`'s own ≤4-corner bound
            // (measured off the design references) forbids — a real tension in ranking crossings
            // above corners, reported rather than papered over here by relaxing that bound or by
            // reaching for a fixture whose numbers happen to sit under it.
            "orthogonal-aside-must-cross-a-leg-lr",
            "flowchart LR\n  P --> A\n  P --> B\n  P --> D\n  subgraph S[row]\n    A\n    B\n    \
             D\n  end\n  A --> H\n  B --> H\n  D --> H\n  H --> Z\n  B -.-> Z",
        ),
    ]
}

/// [`orthogonal_only_corpus`]'s own `orthogonal-dotted-aside-merge` — the two tests below both
/// need it by name rather than by iterating the list.
fn dotted_aside_merge_source() -> &'static str {
    orthogonal_only_corpus()
        .into_iter()
        .find(|(n, _)| *n == "orthogonal-dotted-aside-merge")
        .expect("orthogonal-dotted-aside-merge is in the orthogonal-only corpus")
        .1
}

/// §10-4's own "一般化チェック" round 2's three sources, and round 4's `4a`/`4b`/`4c` (see
/// `state_tests`'s own `orthogonal_design_reference_corpus` for those), made a **permanent**
/// fixture list (coordinator instruction, 2026-09-02): every corpus-wide orthogonal invariant
/// this module states has to actually run against the same pictures the design references show,
/// on every test run — not only the one-off audits that originally produced them. Kept apart from
/// [`orthogonal_only_corpus`] rather than appended to it: that list is a grab-bag of narrow,
/// single-purpose regression fixtures each written for one specific finding, none of them vetted
/// against the *general* corpus-wide checks this list is chained into (`orthogonal_full_corpus`)
/// — folding them in surfaced a genuine, pre-existing, unrelated bug in `orthogonal-subgraph-
/// growth` (`docs/STATUS.md`'s own ★未修正 entry) that this task is not in scope to fix, and
/// widening scope by accident is worse than a narrower, correctly-scoped list.
fn orthogonal_design_reference_corpus() -> Vec<(&'static str, &'static str)> {
    vec![
        (
            // The exact source behind `docs/render-check/zz-design-2a-browser.png`
            // (`docs/render-check/zz-design-sources.md`'s "第 2 回" section) — a plain decision
            // node, a subgraph frame, and a dashed back edge.
            "zz-design-2a",
            r#"flowchart TB
  F[ファイル] --> R{ルールに一致?}
  R -->|画像| I[デコード]:::media
  R -->|Markdown| M[ブロックモデル]:::text
  R -->|なし| X[プレビュー不可]
  subgraph W[ワーカー]
    I
    M
  end
  I --> K[kitty 転送]:::media
  M --> K
  K --> D[再描画]
  D -.-> F
  classDef media fill:#0f2038,stroke:#58a6ff,color:#e6edf3
  classDef text fill:#0f2617,stroke:#3fb950,color:#e6edf3
  style X fill:#271d0b,stroke:#d29922,color:#e6edf3"#,
        ),
        (
            // `zz-design-2b-browser.png`'s own source: nested subgraphs (LR), the shape
            // `orthogonal_cross_subgraph_edge_never_draws_a_diagonal_segment` pins one bug fix
            // against — kept here too so the *rest* of the invariant suite (axis-parallel,
            // perpendicular entry, non-puncture, non-crossing…) also runs over it every time,
            // not just the one regression that source was originally added to catch.
            "zz-design-2b",
            r#"flowchart LR
  subgraph C[クライアント]
    CLI[CLI]
    UI[ブラウザ UI]
    EX[エディタ拡張]
  end
  subgraph G[クラウド]
    API[API ゲート]
    Q[ジョブキュー]
    W[ジョブ実行系]
    SB[解析サンドボックス]:::exec
    subgraph S[保存層]
      DB[メタデータ DB]:::data
      AR[成果物保管]:::data
    end
  end
  subgraph E[外部]
    ID[認証基盤]
    LLM[モデル API]:::model
    GIT[コード置き場]:::exec
    PAY[決済ページ]
  end
  CLI --> API
  UI -->|HTTPS| API
  EX --> API
  API --> ID
  API -->|投入| Q
  Q -->|取り出し| W
  API --> DB
  W --> DB
  W --> AR
  W --> LLM
  W -->|ツール実行| SB
  SB --> GIT
  UI -.->|リンク| PAY
  classDef data fill:#161b22,stroke:#3fb950,color:#e6edf3
  classDef model fill:#161b22,stroke:#a371f7,color:#e6edf3
  classDef exec fill:#161b22,stroke:#f85149,color:#e6edf3
  linkStyle 0,1,2 stroke:#58a6ff
  linkStyle 4,5 stroke:#d29922"#,
        ),
        (
            // `zz-design-2c-browser.png`'s own source: `2b`'s identical graph laid out `TB`
            // instead of `LR` — the axis flip is the point (§10-4's own "2b/2c" pair), so keeping
            // both here catches anything that only shows up under one `direction`.
            // §10-8's own 5b artboard, made a diagram: the four worked examples side by side, so
            // the sizing rules are visible in a rendered picture the same way 2a/2b/2c make the
            // routing rules visible. 「表」 is the 96px minimum, 「ブロックモデル」 the 144px
            // text-derived width, 「合流先」 the four-port face N4 grows, and 「ルールに一致?」 the
            // decision node with the chamfer's own 6px a side. `LR` puts the merge's four ports on
            // 「合流先」's left face, which is the face 5b draws them on.
            //
            // In this list rather than in `orthogonal_only_corpus` for exactly the reason that
            // list's own doc gives: this is a picture the design reference is checked against, and
            // it wants the whole corpus-wide invariant suite run over it on every test run.
            "zz-design-5b",
            r#"flowchart LR
  TB[表] --> MD[ブロックモデル]
  MD --> R{ルールに一致?}
  R -->|一致| A[あ]
  R -->|不一致| B[い]
  A --> Z[合流先]
  B --> Z
  C[う] --> Z
  D[え] --> Z"#,
        ),
        (
            "zz-design-2c",
            r#"flowchart TB
  subgraph C[クライアント]
    CLI[CLI]
    UI[ブラウザ UI]
    EX[エディタ拡張]
  end
  subgraph G[クラウド]
    API[API ゲート]
    Q[ジョブキュー]
    W[ジョブ実行系]
    SB[解析サンドボックス]:::exec
    subgraph S[保存層]
      DB[メタデータ DB]:::data
      AR[成果物保管]:::data
    end
  end
  subgraph E[外部]
    ID[認証基盤]
    LLM[モデル API]:::model
    GIT[コード置き場]:::exec
    PAY[決済ページ]
  end
  CLI --> API
  UI -->|HTTPS| API
  EX --> API
  API --> ID
  API -->|投入| Q
  Q -->|取り出し| W
  API --> DB
  W --> DB
  W --> AR
  W --> LLM
  W -->|ツール実行| SB
  SB --> GIT
  UI -.->|リンク| PAY
  classDef data fill:#161b22,stroke:#3fb950,color:#e6edf3
  classDef model fill:#161b22,stroke:#a371f7,color:#e6edf3
  classDef exec fill:#161b22,stroke:#f85149,color:#e6edf3
  linkStyle 0,1,2 stroke:#58a6ff
  linkStyle 4,5 stroke:#d29922"#,
        ),
    ]
}

/// [`orthogonal_corpus`] (`CORPUS`, which also drives the golden snapshot) plus
/// [`orthogonal_design_reference_corpus`] (never touches the golden) — every corpus-wide
/// orthogonal invariant that has to see the design-reference sources (coordinator instruction,
/// 2026-09-02) iterates this rather than either half alone. Deliberately does **not** also chain
/// in [`orthogonal_only_corpus`] — see that function's own doc for why folding it in is scope
/// creep this list does not want.
///
/// Also chains [`orthogonal_reversed_direction_corpus`] — the same design references, and the two
/// direction fixtures, laid out in the direction that reverses each one's own. Every invariant
/// below was written over `LR`/`TB` sources only, which is how `RL`/`BT` went unchecked long
/// enough to render as `LR`/`TB` outright.
fn orthogonal_full_corpus() -> Vec<(&'static str, &'static str)> {
    orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_design_reference_corpus())
        .chain(
            orthogonal_reversed_direction_corpus()
                .iter()
                .map(|(name, src)| (name.as_str(), src.as_str())),
        )
        .collect()
}

/// Redumps `2a`/`2b`/`2c` under `konoma-orthogonal` to `docs/render-check/zz-design-<name>-
/// ours.{svg,png}`, next to the existing `zz-design-<name>-browser.png` reference each was drawn
/// from (coordinator instruction, 2026-09-02: keep these regenerable rather than one-off).
///
/// The `theme` argument below is inert and is only there because `render_flow` takes one: the mode
/// carries the design's own palette ([`Theme::for_routing`]), which is the whole point of these
/// pictures being comparable with the reference at all.
///
/// `docs/render-check/` (local-only, `.gitignore`'s own `/docs/` line — never committed) is not
/// touched otherwise: existing `zz-design-*` files are the ones the top-level task's own §4
/// instruction says never to delete (`find docs/render-check -maxdepth 1 -type f !
/// -name 'zz-design-*' -delete`), and this only *adds* to that family, using its own naming
/// (`-ours` marks the half this renderer drew, as opposed to `-browser`, `zz-compare-*`, or the
/// bare `zz-design-<name>-wrap.html`/`.svg` staging files the original Claude Design handoff
/// left behind).
///
/// `#[ignore]`d like [`state_tests::gallery`] — run explicitly:
/// `cargo test --features git -- --ignored orthogonal_design_reference_dump`.
#[test]
#[ignore = "writes PNG/SVG files for a person to look at: cargo test -- --ignored orthogonal_design_reference_dump"]
fn orthogonal_design_reference_dump() {
    let dir = std::path::Path::new("docs/render-check");
    std::fs::create_dir_all(dir).expect("create docs/render-check");
    for (name, src) in orthogonal_design_reference_corpus() {
        let svg =
            crate::preview::mermaid::render::render_flow(src, "dark", "basis", "konoma-orthogonal")
                .unwrap_or_else(|e| panic!("{name}: must render under konoma-orthogonal: {e}"));
        let svg_path = dir.join(format!("{name}-ours.svg"));
        std::fs::write(&svg_path, &svg).unwrap_or_else(|e| panic!("{name}: write svg: {e}"));
        let img = crate::preview::svg::rasterize_bytes(svg.as_bytes(), &svg_path, 1600)
            .unwrap_or_else(|| panic!("{name}: must rasterise"));
        img.save(dir.join(format!("{name}-ours.png")))
            .unwrap_or_else(|e| panic!("{name}: write png: {e}"));
    }
}

// ---------------------------------------------------------------------------------------------
// Docs-site Mermaid catalog
// ---------------------------------------------------------------------------------------------

/// Every ```mermaid fence in `samples/mermaid.md`, in document order, with the trailing newline
/// dropped so each entry is exactly the byte string a Markdown preview hands the renderer.
///
/// Deliberately a hand-written scanner rather than a pull through the Markdown block model: the
/// samples never nest a fence inside a fence, and a scanner keeps this dump independent of the
/// block model's own churn — the point of the catalog is the *renderer's* output, not the parser's.
fn mermaid_fences_of(md: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut open: Option<String> = None;
    for line in md.lines() {
        match &mut open {
            None => {
                if line.trim_start().starts_with("```mermaid") {
                    open = Some(String::new());
                }
            }
            Some(buf) => {
                if line.trim_start().starts_with("```") {
                    out.push(std::mem::take(buf).trim_end().to_string());
                    open = None;
                } else {
                    buf.push_str(line);
                    buf.push('\n');
                }
            }
        }
    }
    out
}

/// The widest a diagram may be, in its own CSS px, and still be rastered at 2×.
///
/// Above this the page has already shrunk the picture to fit its ~900px content column, so the
/// extra pixels are thrown away by the browser on the way to the screen — the busy `03` sample is
/// 1552 CSS px wide, and at 2× it cost 6.2 MB per language for detail nobody could see. Below it a
/// diagram is shown at or near 1:1, where 2× is what keeps the labels crisp on a HiDPI screen.
const CATALOG_SCALE_2X_MAX_CSS_PX: u32 = 800;

/// Device scale for one diagram, from its own natural width — see
/// [`CATALOG_SCALE_2X_MAX_CSS_PX`]. Recorded per image in the manifest rather than assumed by the
/// page, because the page's own width rule divides a stored pixel width by exactly this number to
/// recover the CSS width it will lay out at.
fn catalog_scale_for(width_css_px: u32) -> u32 {
    if width_css_px <= CATALOG_SCALE_2X_MAX_CSS_PX {
        2
    } else {
        1
    }
}

/// `[ui] mermaid_routing`'s values, as the catalog's "What the settings change" section lists
/// them — **`konoma-orthogonal` first**, because that mode is what the page is about, and the
/// site leads with it everywhere else too.
const CATALOG_ROUTINGS: [&str; 2] = ["konoma-orthogonal", "splines"];

/// `[ui] mermaid_curve`'s 13 values, in the configuration reference's own order (the default
/// `"basis"` first, then the straight/right-angle family, the through-the-waypoints splines, the
/// non-overshooting pair, the bumps, and mermaid's own `"rounded"`).
const CATALOG_CURVES: [&str; 13] = [
    "basis",
    "linear",
    "step",
    "stepBefore",
    "stepAfter",
    "natural",
    "cardinal",
    "catmullRom",
    "monotoneX",
    "monotoneY",
    "bumpX",
    "bumpY",
    "rounded",
];

/// `[ui] mermaid_theme`'s 5 values, default first — the configuration reference's own order.
const CATALOG_THEMES: [&str; 5] = ["dark", "light", "classic", "forest", "neutral"];

/// Terminal width the `[ui] mermaid = "text"` fallback is drawn at for the catalog. Wide enough
/// that neither sample has to wrap (wrapping is a property of the pane, not of the renderer, and
/// the page shows the drawing), narrow enough to stay a plausible pane.
const CATALOG_TEXT_COLUMNS: u16 = 100;

/// A flowchart's four `rankdir` keywords, in mermaid's own order. The catalog draws the sample
/// once per direction under `konoma-orthogonal` to show that the routing rules do not change with
/// it — `docs/FEATURE-MERMAID-RENDERER.md` §10's own design references `2b`/`2c` are the same
/// graph in LR and TB for exactly that reason.
const CATALOG_FLOW_DIRECTIONS: [&str; 4] = ["LR", "TB", "RL", "BT"];

/// A state diagram states its direction with a `direction` line inside the body rather than on the
/// header, and the absence of one means `TB` — so the catalog's pair is "as written" against "with
/// `direction LR` added".
const CATALOG_STATE_DIRECTIONS: [&str; 2] = ["TB", "LR"];

/// The sample's flowchart header with its direction keyword replaced.
///
/// Deliberately narrow: it keeps the header's own keyword (`flowchart` / `graph`) and replaces
/// everything after it, which is exactly right for a header of the shape `flowchart LR` and wrong
/// for anything more elaborate. The dump asserts the header really is that shape before calling
/// this, so a rewritten sample cannot silently produce a diagram nobody meant.
fn with_flow_direction(code: &str, direction: &str) -> String {
    let mut lines = code.lines();
    let head = lines.next().unwrap_or_default();
    let keyword = head.split_whitespace().next().unwrap_or("flowchart");
    let body: String = lines.map(|l| format!("\n{l}")).collect();
    format!("{keyword} {direction}{body}")
}

/// The sample's state-diagram source with a `direction <dir>` line added just under the header —
/// or returned untouched for `"TB"`, which is what the absence of that line already means.
fn with_state_direction(code: &str, direction: &str) -> String {
    if direction == "TB" {
        return code.to_string();
    }
    let mut lines = code.lines();
    let head = lines.next().unwrap_or_default();
    let body: String = lines.map(|l| format!("\n{l}")).collect();
    format!("{head}\n  direction {direction}{body}")
}

/// The two ways a diagram overrides `[ui] mermaid_curve` from inside its own source, as the
/// catalog shows them: `(file stem, the line the sample gains, whether it goes on the front)`.
///
/// Both are drawn with the config left at its default `"basis"`, so the difference in the picture
/// is the diagram's own doing — which is the whole point of the block.
const CATALOG_OVERRIDES: [(&str, &str, bool); 2] = [
    (
        "init-step",
        "%%{init: {\"flowchart\": {\"curve\": \"step\"}}}%%",
        true,
    ),
    // Edge **1**, not 0. `linkStyle` counts edges in declaration order, and the sample's edge 0
    // (`K --> S`) is a straight horizontal run that draws the same under every curve — the SVG
    // bytes would differ (the assertion would pass) while the picture on the page did not, which
    // is the worst of both. Edge 1 (`S -->|Tree| M`) bends, so the override is visible.
    (
        "linkstyle-stepAfter",
        "  linkStyle 1 interpolate stepAfter",
        false,
    ),
];

/// Applies one [`CATALOG_OVERRIDES`] entry to a source.
fn with_override(code: &str, line: &str, prepend: bool) -> String {
    if prepend {
        format!("{line}\n{code}")
    } else {
        format!("{code}\n{line}")
    }
}

/// Renders one fence through the production path and writes it as a PNG at `dir/file`, returning
/// the device scale it chose ([`catalog_scale_for`]) so the caller can record it in the manifest.
///
/// Shared by the kind gallery and the settings gallery below so both are provably the *same*
/// path: [`crate::preview::markdown::mermaid_to_svg_flow`] is the exact function `App::media_load`
/// / `md_media` call for an inline ```mermaid fence. `what` is the caller's own label for the
/// panic messages, since neither gallery names a render the same way.
fn write_catalog_png(
    dir: &FsPath,
    file: &str,
    code: &str,
    theme: &str,
    curve: &str,
    routing: &str,
    what: &str,
) -> u32 {
    let svg = crate::preview::markdown::mermaid_to_svg_flow(code, theme, curve, routing)
        .unwrap_or_else(|| panic!("{what}: must render under routing={routing}"));
    let path = dir.join(file);
    let (w, h) = crate::preview::svg::intrinsic_size_bytes(svg.as_bytes())
        .unwrap_or_else(|| panic!("{what}: SVG must have a size"));
    let scale = catalog_scale_for(w);
    // `rasterize_bytes` takes a target for the *longest* side, so asking for `scale * max(w, h)`
    // is exactly a `scale`× device-pixel-ratio raster. The background stays transparent, the same
    // as in the terminal.
    let img = crate::preview::svg::rasterize_bytes(svg.as_bytes(), &path, scale * w.max(h))
        .unwrap_or_else(|| panic!("{what}: must rasterise"));
    img.save(&path)
        .unwrap_or_else(|e| panic!("{what}: write {path:?}: {e}"));
    scale
}

/// Renders every fence of the two sample galleries for the documentation site's Mermaid catalog
/// page (`site/src/content/docs/guides/mermaid-catalog.mdx` and its `ja/` twin), writing 2×-scale
/// PNGs plus a `manifest.json` the page's Astro component is driven by.
///
/// **Production path, not a parallel renderer.** Each fence goes through
/// [`crate::preview::markdown::mermaid_to_svg_flow`] — the exact function `App::media_load` /
/// `md_media` call for an inline ```mermaid fence — with the shipped defaults `[ui]
/// mermaid_theme = "dark"` and `[ui] mermaid_curve = "basis"`. Only `routing` varies.
///
/// **Why only two kinds are drawn twice.** `mermaid_to_svg_reason_flow`'s dispatcher threads
/// `routing` into exactly two arms: `render_konoma_flow` (claimed by `flowchart_is_ours`) and
/// `render_konoma_state` (claimed by `state_is_ours`). Every other kind is routed through the
/// shared `Draw` table, whose signature is `fn(&str, &str) -> Result<String, RenderError>` — code
/// and theme only, so `[ui] mermaid_routing` is *structurally* unable to reach them. The
/// predicates below are the dispatcher's own, so this file cannot drift from that claim.
///
/// **The settings gallery.** Alongside the per-kind renders the dump also writes a `settings/<nn>/`
/// set per sample the settings reach — every flowchart fence under both `mermaid_routing` values,
/// all 13 `mermaid_curve` values and all 5 `mermaid_theme` values, and the state-diagram fence
/// under the 5 themes (it never reads a curve, and its routing pair is already in the kind gallery
/// above). Same production entry point, same 2× raster; only the argument under test moves, so a
/// difference between two pictures in that section can only have come from the setting the caption
/// names. That those values really do change the picture (and really are inert under
/// `konoma-orthogonal`) is asserted permanently by
/// [`catalog_settings_values_really_change_the_picture`], which is *not* `#[ignore]`d and runs over
/// these same sample sources — the dump writes pictures, the test states the claim the page makes
/// about them.
///
/// Stale files are removed first: an image nobody regenerated is worse than a missing one, because
/// the page would keep shipping it. Removing the language directory takes `settings/` with it.
///
/// `#[ignore]`d like [`orthogonal_design_reference_dump`] — run explicitly:
/// `cargo test -- --ignored site_mermaid_catalog_dump`.
#[test]
#[ignore = "writes PNG files for the docs site: cargo test -- --ignored site_mermaid_catalog_dump"]
fn site_mermaid_catalog_dump() {
    for (lang, sample) in [
        ("en", "samples/mermaid.md"),
        ("ja", "samples/mermaid.ja.md"),
    ] {
        let md = std::fs::read_to_string(sample)
            .unwrap_or_else(|e| panic!("{lang}: read {sample}: {e}"));
        let fences = mermaid_fences_of(&md);
        assert!(
            !fences.is_empty(),
            "{lang}: {sample} must contain ```mermaid fences"
        );

        let dir = std::path::Path::new("site/src/assets/mermaid-catalog").join(lang);
        // Delete first: a renamed or dropped fence must not leave an orphan PNG behind.
        if dir.exists() {
            std::fs::remove_dir_all(&dir).unwrap_or_else(|e| panic!("{lang}: clear {dir:?}: {e}"));
        }
        std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{lang}: create {dir:?}: {e}"));

        let mut items = Vec::new();
        for (i, code) in fences.iter().enumerate() {
            let order = i + 1;
            let kind = crate::preview::mermaid::chart::first_word(code);
            // The dispatcher's own predicates (see this test's doc comment).
            let takes_routing = crate::preview::mermaid::flowchart::is_flowchart(code)
                || crate::preview::mermaid::state::is_state_diagram(code);
            let variants: &[(&str, &str)] = if takes_routing {
                // Orthogonal first: the catalog page leads with konoma's own routing.
                &[("orthogonal", "konoma-orthogonal"), ("splines", "splines")]
            } else {
                &[("default", "splines")]
            };

            let mut renders = Vec::new();
            for (variant, routing) in variants {
                let file = format!("{order:02}-{kind}-{variant}.png");
                let scale = write_catalog_png(
                    &dir,
                    &file,
                    code,
                    "dark",
                    "basis",
                    routing,
                    &format!("{lang} #{order} ({kind})"),
                );
                renders.push(serde_json::json!({
                    "variant": variant,
                    "routing": routing,
                    "file": file,
                    "scale": scale,
                }));
            }

            items.push(serde_json::json!({
                "order": order,
                "kind": kind,
                "orthogonal": takes_routing,
                "renders": renders,
                "source": code,
            }));
        }

        // ----- settings gallery: every sample a setting reaches, under every value of it -----
        //
        // One block per fence, written under `settings/<nn>/` so the file names stay the same from
        // sample to sample — `settings[i]` and `items[i]` are the same fence, which is what lets
        // the kind gallery hang a theme strip under a render. Which options a sample gets is the
        // dispatcher's claim again, not a hand-kept list:
        //
        // - a **flowchart** reads all three, so it gets `routing` ×2, `curve` ×13, `theme` ×5;
        // - a **state diagram** reads `routing` (already drawn as the pair in the kind gallery
        //   above) but never `curve`, so it gets `theme` ×5;
        // - **every other kind** is routed through the shared `Draw` table, whose signature is
        //   `fn(&str, &str)` — code and theme. `routing` and `curve` are structurally unable to
        //   reach it, but `theme` reaches *all* of them, so every kind gets its `theme` ×5 too.
        //
        // All three samples rather than only the smallest one, because a setting shows itself on a
        // different sample: `theme` is legible against author-set `classDef` colours (02), and
        // `curve` only really separates on the long rank-spanning edges of the busy one (03).
        let settings_root = dir.join("settings");
        std::fs::create_dir_all(&settings_root)
            .unwrap_or_else(|e| panic!("{lang}: create {settings_root:?}: {e}"));

        let mut settings = Vec::new();
        for (i, code) in fences.iter().enumerate() {
            let order = i + 1;
            let is_flow = crate::preview::mermaid::flowchart::is_flowchart(code);
            let is_state = crate::preview::mermaid::state::is_state_diagram(code);
            let kind = crate::preview::mermaid::chart::first_word(code);
            let dir_of = settings_root.join(format!("{order:02}"));
            std::fs::create_dir_all(&dir_of)
                .unwrap_or_else(|e| panic!("{lang}: create {dir_of:?}: {e}"));

            // One closure per option would repeat the same three lines; this one takes the
            // file-name prefix and the three arguments, and the caller varies exactly one of them.
            let shot = |prefix: &str, value: &str, theme: &str, curve: &str, routing: &str| {
                let file = format!("{prefix}-{value}.png");
                let scale = write_catalog_png(
                    &dir_of,
                    &file,
                    code,
                    theme,
                    curve,
                    routing,
                    &format!("{lang} settings {order:02} {prefix}={value}"),
                );
                serde_json::json!({
                    "value": value,
                    "file": format!("settings/{order:02}/{file}"),
                    "scale": scale,
                })
            };

            let mut block = serde_json::Map::new();
            block.insert("order".into(), serde_json::json!(order));
            block.insert("kind".into(), serde_json::json!(kind));
            // A language-neutral identifier, not display text: the page writes its own headings,
            // in its own language. This is what an alt string and a debug message name.
            block.insert(
                "label".into(),
                serde_json::json!(format!("{order:02}-{kind}")),
            );
            block.insert("source".into(), serde_json::json!(code));

            // A variant of the *source* rather than of an argument: same three writes, but the
            // caption is what was edited into the diagram, not a config value.
            let shot_src = |prefix: &str, value: &str, src: &str, routing: &str| {
                let file = format!("{prefix}-{value}.png");
                let scale = write_catalog_png(
                    &dir_of,
                    &file,
                    src,
                    "dark",
                    "basis",
                    routing,
                    &format!("{lang} settings {order:02} {prefix}={value}"),
                );
                serde_json::json!({
                    "value": value,
                    "file": format!("settings/{order:02}/{file}"),
                    "scale": scale,
                })
            };

            if is_flow {
                // `curve` is passed as the shipped default for the routing pair and is genuinely
                // irrelevant under `konoma-orthogonal` (there is no curve, only right-angle
                // segments) — the permanent test below states that as an assertion rather than
                // leaving it as a claim in a comment.
                let routings: Vec<_> = CATALOG_ROUTINGS
                    .iter()
                    .map(|r| shot("routing", r, "dark", "basis", r))
                    .collect();
                let curves: Vec<_> = CATALOG_CURVES
                    .iter()
                    .map(|c| shot("curve", c, "dark", c, "splines"))
                    .collect();
                block.insert(
                    "routing".into(),
                    serde_json::json!({ "default": "splines", "values": routings }),
                );
                block.insert(
                    "curve".into(),
                    serde_json::json!({ "default": "basis", "values": curves }),
                );
            }

            // Both a flowchart `direction` block and the per-diagram overrides go on the *first*
            // flowchart only: each is one point (routing is direction-agnostic; a diagram can
            // override the curve from inside its own source), and repeating either on every sample
            // would multiply the page's download for nothing.
            if is_flow && order == 1 {
                // konoma-orthogonal's post-dagre passes used to key on the flow *axis* without its
                // *sign*, so `RL` rendered byte-identical to `LR` and `BT` to `TB` — fixed by the
                // mirror rule `super::canonicalise_flow_axis` / `super::mirror_flow_axis` names
                // (`orthogonal_rl_is_the_exact_mirror_of_lr` / `orthogonal_bt_is_the_exact_mirror_
                // of_tb` pin it permanently), so all four directions are genuinely four pictures now.
                let directions: Vec<_> = CATALOG_FLOW_DIRECTIONS
                    .iter()
                    .map(|d| {
                        shot_src(
                            "direction",
                            d,
                            &with_flow_direction(code, d),
                            "konoma-orthogonal",
                        )
                    })
                    .collect();
                block.insert(
                    "direction".into(),
                    serde_json::json!({ "default": "LR", "values": directions }),
                );

                let overrides: Vec<_> = CATALOG_OVERRIDES
                    .iter()
                    .map(|(stem, line, prepend)| {
                        let mut v = shot_src(
                            "override",
                            stem,
                            &with_override(code, line, *prepend),
                            "splines",
                        );
                        // The exact line the reader would add, shown next to the picture: the
                        // block is about precedence, and precedence is a property of that line.
                        v["line"] = serde_json::json!(line.trim());
                        v
                    })
                    .collect();
                block.insert(
                    "override".into(),
                    serde_json::json!({ "default": "basis", "values": overrides }),
                );
            }

            if is_state {
                let directions: Vec<_> = CATALOG_STATE_DIRECTIONS
                    .iter()
                    .map(|d| {
                        shot_src(
                            "direction",
                            d,
                            &with_state_direction(code, d),
                            "konoma-orthogonal",
                        )
                    })
                    .collect();
                block.insert(
                    "direction".into(),
                    serde_json::json!({ "default": "TB", "values": directions }),
                );
            }
            // `theme` is drawn under `"splines"` for every sample, state diagram included: it is
            // inert under `konoma-orthogonal`, so five identical pictures is the only other thing
            // this loop could produce.
            let themes: Vec<_> = CATALOG_THEMES
                .iter()
                .map(|t| shot("theme", t, t, "basis", "splines"))
                .collect();
            block.insert(
                "theme".into(),
                serde_json::json!({ "default": "dark", "values": themes }),
            );

            // Which blocks this sample got, in the order the page renders them: the routing rules,
            // then those rules under each direction, then the shape of the line, then the two ways
            // a diagram overrides that shape itself, then the colours.
            let options: Vec<&str> = ["routing", "direction", "curve", "override", "theme"]
                .into_iter()
                .filter(|k| block.contains_key(*k))
                .collect();
            block.insert("options".into(), serde_json::json!(options));

            settings.push(serde_json::Value::Object(block));
        }
        // The kind gallery hangs each kind's theme strip off `settings[i]` while drawing
        // `items[i]`, so the two lists must stay index-for-index the same fences.
        assert_eq!(
            settings.len(),
            items.len(),
            "{lang}: every fence needs a settings block — the page pairs them by index"
        );

        // ----- `[ui] mermaid = "text"`: the Unicode box-drawing fallback, as text -----
        //
        // Written as `.txt` rather than as a picture, because text is literally what the terminal
        // puts on the screen in that mode — a screenshot of it would be a picture of characters.
        // The entry point is [`crate::preview::markdown::render_mermaid_file`], what a standalone
        // `.mmd` file goes through; its `Line`s carry no styling on this path (each is built from
        // one owned `String`), so joining the spans back gives exactly the drawn text.
        //
        // Two fences: the first flowchart, and the sequence diagram — the two shapes the fallback
        // handles most differently (boxes and arrows vs. lifelines, activation bars and an `alt`).
        let text_dir = dir.join("text");
        std::fs::create_dir_all(&text_dir)
            .unwrap_or_else(|e| panic!("{lang}: create {text_dir:?}: {e}"));
        let mut texts = Vec::new();
        for (i, code) in fences.iter().enumerate() {
            let order = i + 1;
            let kind = crate::preview::mermaid::chart::first_word(code);
            if order != 1 && kind != "sequenceDiagram" {
                continue;
            }
            let drawn: Vec<String> =
                crate::preview::markdown::render_mermaid_file(code, CATALOG_TEXT_COLUMNS)
                    .iter()
                    .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
                    .collect();
            assert!(
                drawn.len() > 3,
                "{lang} #{order} ({kind}): the text fallback must actually draw something, got \
                 {drawn:?}"
            );
            let file = format!("{order:02}-{kind}.txt");
            let path = text_dir.join(&file);
            std::fs::write(&path, format!("{}\n", drawn.join("\n")))
                .unwrap_or_else(|e| panic!("{lang}: write {path:?}: {e}"));
            texts.push(serde_json::json!({
                "order": order,
                "kind": kind,
                "file": format!("text/{file}"),
            }));
        }
        assert_eq!(
            texts.len(),
            2,
            "{lang}: the text block needs the first flowchart and the sequence diagram"
        );

        let manifest = serde_json::json!({
            "lang": lang,
            "sample": sample,
            "theme": "dark",
            "curve": "basis",
            // The device scale is **per image** (each render's own `scale` field): a diagram wide
            // enough that the page shrinks it is rastered at 1×. This records only the rule.
            "scale_2x_max_css_px": CATALOG_SCALE_2X_MAX_CSS_PX,
            "items": items,
            // Sample order, and within a sample each option's values in the order above — the page
            // renders both lists as it finds them, so this order is the order a reader sees:
            // konoma-orthogonal first, then each option's own default.
            "settings": settings,
            "text": { "columns": CATALOG_TEXT_COLUMNS, "items": texts },
        });
        let mut text = serde_json::to_string_pretty(&manifest).expect("serialise manifest");
        text.push('\n');
        let path = dir.join("manifest.json");
        std::fs::write(&path, text).unwrap_or_else(|e| panic!("{lang}: write {path:?}: {e}"));
    }
}

/// One sample's worth of the claim [`catalog_settings_values_really_change_the_picture`] makes.
///
/// Goes through [`crate::preview::markdown::mermaid_to_svg_flow`] — the dispatcher the dump and
/// production both call — rather than [`render_flow`], because this runs over state-diagram
/// sources too and the flowchart entry point cannot draw one.
///
/// `reads_curve` and `reads_routing` are the dispatcher's own divisions, not per-sample opinions:
///
/// * only a **flowchart**'s edges read `[ui] mermaid_curve`, so anything else would draw 13
///   identical pictures and "pairwise different" would be a false claim rather than a failing one;
/// * only a flowchart and a **state diagram** read `[ui] mermaid_routing`. Every other kind goes
///   through the shared `Draw` table (`fn(&str, &str)` — code and theme), which routing cannot
///   reach, so "the theme is inert under konoma-orthogonal" is not true of them: with no orthogonal
///   palette in play the theme still paints, exactly as it does under `"splines"`.
///
/// `theme` is checked for **every** sample, because it reaches every kind.
fn assert_catalog_settings_change_one_sample(
    name: &str,
    code: &str,
    reads_curve: bool,
    reads_routing: bool,
) {
    let render = |theme: &str, curve: &str, routing: &str| {
        crate::preview::markdown::mermaid_to_svg_flow(code, theme, curve, routing).unwrap_or_else(
            || panic!("{name}: must render (theme={theme} curve={curve} routing={routing})"),
        )
    };

    if reads_curve {
        let curves: Vec<(&str, String)> = CATALOG_CURVES
            .iter()
            .map(|c| (*c, render("dark", c, "splines")))
            .collect();
        for i in 0..curves.len() {
            for j in (i + 1)..curves.len() {
                assert_ne!(
                    curves[i].1, curves[j].1,
                    "{name}: mermaid_curve {} and {} must draw differently — the catalog shows \
                     them as two pictures",
                    curves[i].0, curves[j].0
                );
            }
        }
    }

    let themes: Vec<(&str, String)> = CATALOG_THEMES
        .iter()
        .map(|t| (*t, render(t, "basis", "splines")))
        .collect();
    for i in 0..themes.len() {
        for j in (i + 1)..themes.len() {
            assert_ne!(
                themes[i].1, themes[j].1,
                "{name}: mermaid_theme {} and {} must draw differently — the catalog shows them \
                 as two pictures",
                themes[i].0, themes[j].0
            );
        }
    }

    if !reads_routing {
        return;
    }
    let baseline = render("dark", "basis", "konoma-orthogonal");
    if reads_curve {
        for curve in CATALOG_CURVES {
            assert_eq!(
                render("dark", curve, "konoma-orthogonal"),
                baseline,
                "{name}: mermaid_curve {curve} must be inert under konoma-orthogonal — the page \
                 says so"
            );
        }
    }
    for theme in CATALOG_THEMES {
        assert_eq!(
            render(theme, "basis", "konoma-orthogonal"),
            baseline,
            "{name}: mermaid_theme {theme} must be inert under konoma-orthogonal — the page says so"
        );
    }
}

/// The catalog page's "What the settings change" section shows 65 pictures and claims each one
/// inside a grid is a *different* look. This states that claim as an assertion, permanently — the
/// dump above is `#[ignore]`d, so nothing there ever runs in CI, and a change that quietly
/// collapsed two curves (or made `mermaid_theme` inert under `splines`) would leave the page
/// shipping grids of identical pictures with different captions under them.
///
/// Three claims, one per sub-block of that section:
///
/// 1. All 13 `mermaid_curve` values draw a **pairwise different** SVG. Stronger than
///    `different_curves_draw_different_svg_path_data` (three of them) and than
///    `the_eight_new_curves_draw_different_paths_from_each_other` (eight, and at the free-function
///    level rather than through the dispatcher), and stated over exactly [`CATALOG_CURVES`] — the
///    same list the page's grid is built from, so the two cannot drift apart.
/// 2. All 5 `mermaid_theme` values draw a pairwise different SVG.
/// 3. Under `"konoma-orthogonal"`, changing either produces a **byte-identical** SVG. That is the
///    sentence both language versions of the page print ("ignored under konoma-orthogonal"), and
///    it is the converse of 1 and 2: an assertion that only says "these differ" would still pass
///    if the orthogonal mode had started reading the curve.
///
/// **Stated over the sources the page actually ships**, not only a lab specimen. The tiny inline
/// flowchart comes first and says what it needs on its own line — `A --> D` spans three ranks,
/// which is what gives dagre the intermediate waypoints a curve can differ *on* (on a straight
/// two-point edge several of these 13 agree, and `different_curves_draw_different_svg_path_data`'s
/// own doc records that trap being hit for real). Then every fence of `samples/mermaid.md` that
/// the dump writes a settings block for goes through the same three claims, so the assertion covers
/// the busy `03` diagram whose long rank-spanning edges are what actually separate the curves on
/// the page, the `02` diagram whose author-set `classDef` colours the themes have to survive, and
/// the state diagram (themes only). The sample is read through `CARGO_MANIFEST_DIR` so the test
/// does not depend on the working directory a runner happens to use.
#[test]
fn catalog_settings_values_really_change_the_picture() {
    if !text_metrics::fonts_available() {
        return;
    }
    assert_catalog_settings_change_one_sample(
        "inline three-rank flowchart",
        "flowchart TD\n  A[Tree] --> B{Kind}\n  B --> C[Image]\n  C --> D[Draw]\n  A --> D",
        true,
        true,
    );

    let sample = FsPath::new(env!("CARGO_MANIFEST_DIR")).join("samples/mermaid.md");
    let md = std::fs::read_to_string(&sample).unwrap_or_else(|e| panic!("read {sample:?}: {e}"));
    // **Every** fence, not only the ones a routing or a curve reaches: `mermaid_theme` is passed
    // to all 23 kinds, so the catalog now hangs a theme strip under every render in the kind
    // gallery, and this is the assertion that those strips are five pictures rather than five
    // copies.
    let mut covered = 0;
    for (i, code) in mermaid_fences_of(&md).iter().enumerate() {
        let is_flow = crate::preview::mermaid::flowchart::is_flowchart(code);
        let is_state = crate::preview::mermaid::state::is_state_diagram(code);
        assert_catalog_settings_change_one_sample(
            &format!("samples/mermaid.md fence #{:02}", i + 1),
            code,
            is_flow,
            is_flow || is_state,
        );
        covered += 1;
    }
    // The loop must actually have run over every sample the gallery draws — a scanner that
    // silently found nothing would leave every assertion above un-evaluated and still pass.
    assert!(
        covered >= 23,
        "samples/mermaid.md must still hold one fence per Mermaid kind the catalog draws: found \
         {covered}"
    );
}

/// Every direction the catalog's "Direction" block draws still obeys the orthogonal rules, and the
/// picture matches what the page's own sentence claims: `RL` is the exact mirror of `LR`, `BT` is
/// the exact mirror of `TB`, and `LR` genuinely differs from `TB` — turning the flow axis is the
/// half of `rankdir` the orthogonal path reads.
///
/// Stated with the very helpers the general corpus uses rather than a private re-derivation:
/// [`check_only_axis_parallel_segments`] (also used by
/// `orthogonal_routing_draws_only_axis_parallel_segments`) for the axis-parallel claim, and
/// [`assert_mirrored_diagrams`] — the same mirror check [`orthogonal_rl_is_the_exact_mirror_of_lr`]
/// and [`orthogonal_bt_is_the_exact_mirror_of_tb`] state over the general corpus — for the mirror
/// claim. `orthogonal_corpus` and that corpus already carry all four directions, but on *their own*
/// sources; this pins the same claims on the source the page actually prints them under.
#[test]
fn catalog_direction_renders_obey_the_orthogonal_rules() {
    if !text_metrics::fonts_available() {
        return;
    }
    let sample = FsPath::new(env!("CARGO_MANIFEST_DIR")).join("samples/mermaid.md");
    let md = std::fs::read_to_string(&sample).unwrap_or_else(|e| panic!("read {sample:?}: {e}"));
    let fences = mermaid_fences_of(&md);
    let code = fences
        .first()
        .expect("samples/mermaid.md must still open with a fence");
    assert!(
        crate::preview::mermaid::flowchart::is_flowchart(code),
        "the direction block is built on the first fence, which must still be a flowchart"
    );

    // `CATALOG_FLOW_DIRECTIONS` is `["LR", "TB", "RL", "BT"]` — the catalog's own printed order —
    // so index 0/2 is the LR/RL pair and 1/3 is the TB/BT pair.
    let mut laid_out: Vec<(&str, Diagram)> = Vec::new();
    let mut drawn: Vec<(&str, String)> = Vec::new();
    for direction in CATALOG_FLOW_DIRECTIONS {
        let src = with_flow_direction(code, direction);
        let diagram = laid_out_flow(&src, "basis", "konoma-orthogonal");
        check_only_axis_parallel_segments(&format!("catalog direction {direction}"), &diagram);
        let svg = crate::preview::markdown::mermaid_to_svg_flow(
            &src,
            "dark",
            "basis",
            "konoma-orthogonal",
        )
        .unwrap_or_else(|| panic!("direction={direction}: must render"));
        laid_out.push((direction, diagram));
        drawn.push((direction, svg));
    }
    // LR turns the flow axis relative to TB, which is the half of `rankdir` the orthogonal path
    // does read — the two are genuinely different pictures.
    assert_ne!(
        drawn[0].1, drawn[1].1,
        "LR and TB must draw differently under konoma-orthogonal"
    );
    // The reversal itself: `RL` is `LR` reflected along the flow axis, and `BT` is `TB` reflected —
    // the exact sentence the page prints under the grid.
    assert_mirrored_diagrams(
        "catalog direction LR/RL",
        &laid_out[0].1,
        &laid_out[2].1,
        false,
    );
    assert_mirrored_diagrams(
        "catalog direction TB/BT",
        &laid_out[1].1,
        &laid_out[3].1,
        true,
    );

    // The state diagram's own half: `direction LR` must move it off the default TB.
    let state = fences
        .iter()
        .find(|c| crate::preview::mermaid::state::is_state_diagram(c))
        .expect("samples/mermaid.md must still hold a state diagram");
    let by_dir: Vec<(&str, String)> = CATALOG_STATE_DIRECTIONS
        .iter()
        .map(|d| {
            let src = with_state_direction(state, d);
            let svg = crate::preview::markdown::mermaid_to_svg_flow(
                &src,
                "dark",
                "basis",
                "konoma-orthogonal",
            )
            .unwrap_or_else(|| panic!("state direction={d}: must render"));
            (*d, svg)
        })
        .collect();
    assert_ne!(
        by_dir[0].1, by_dir[1].1,
        "a state diagram's `direction LR` must draw differently from the default TB"
    );
}

/// The catalog's "Overrides written in the diagram" block claims two things that are easy to write
/// and easy to get wrong: that a `%%{init}%%` directive and a `linkStyle ... interpolate` really
/// do beat the config default (`"basis"` here, untouched), and that both are ignored under
/// `konoma-orthogonal` — the same precedence sentence the configuration reference prints.
///
/// Stated on the exact source the page shows, with the exact lines it shows being added, so the
/// captions and the pictures cannot drift apart from what actually happens.
#[test]
fn catalog_override_block_beats_the_default_curve_and_is_inert_under_orthogonal() {
    if !text_metrics::fonts_available() {
        return;
    }
    let sample = FsPath::new(env!("CARGO_MANIFEST_DIR")).join("samples/mermaid.md");
    let md = std::fs::read_to_string(&sample).unwrap_or_else(|e| panic!("read {sample:?}: {e}"));
    let code = mermaid_fences_of(&md)
        .first()
        .expect("samples/mermaid.md must still open with a fence")
        .clone();

    let plain = crate::preview::markdown::mermaid_to_svg_flow(&code, "dark", "basis", "splines")
        .expect("the plain sample must render");
    let orthogonal =
        crate::preview::markdown::mermaid_to_svg_flow(&code, "dark", "basis", "konoma-orthogonal")
            .expect("the plain sample must render under konoma-orthogonal");

    for (stem, line, prepend) in CATALOG_OVERRIDES {
        let src = with_override(&code, line, prepend);
        let splines =
            crate::preview::markdown::mermaid_to_svg_flow(&src, "dark", "basis", "splines")
                .unwrap_or_else(|| panic!("{stem}: must render"));
        assert_ne!(
            splines,
            plain,
            "{stem}: `{}` must beat the default mermaid_curve = \"basis\" — the catalog shows it \
             as a different picture",
            line.trim()
        );
        let ortho = crate::preview::markdown::mermaid_to_svg_flow(
            &src,
            "dark",
            "basis",
            "konoma-orthogonal",
        )
        .unwrap_or_else(|| panic!("{stem}: must render under konoma-orthogonal"));
        assert_eq!(
            ortho,
            orthogonal,
            "{stem}: `{}` must be inert under konoma-orthogonal — the page says so",
            line.trim()
        );
    }
}

/// Finding 1 (high): the cluster invariants stage 1b already states over `CORPUS` under
/// `"splines"` (`check_clusters_hold_their_members` and its three siblings, `pub(super)` above so
/// this section can reuse them rather than re-deriving the same geometry questions), run again
/// under `"konoma-orthogonal"` — routing an edge does not move a node or a frame, but §10-1 item 1's
/// own eviction growth *does* (a face too narrow for its ports grows the node, and `lay_out_spec`
/// re-lays the whole diagram out from the grown size), so nothing before this audit had actually
/// checked a frame still holds its members once that growth has happened.
///
/// The design-reference sources were **not** in this list until §10-5 round 4, and that gap cost a
/// real bug: `zz-design-2b`'s own `解析サンドボックス` (a member of `クラウド` that
/// `clear_foreign_cluster_overlaps` pushed clear of its sibling frame `保存層`) ended up outside its
/// own frame, and every test stayed green — the state-diagram sibling of this test
/// (`state_tests::orthogonal_state_nodes_and_clusters_stay_correct_after_growth`) had been running
/// its own half of the design corpus all along, so only the flowchart half was blind.
#[test]
fn invariant_orthogonal_clusters_hold_their_members() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain(orthogonal_design_reference_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let tree = tree_of_src(src);
        check_clusters_hold_their_members(name, &d, &tree);
    }
}

/// §10-5 part-3 item 1's own converse of the check just above — run over the same corpus, plus the
/// permanent design-reference sources (§10-5's own "恒久テスト対象" instruction), since `zz-
/// design-4a`'s state-diagram sibling was the case that actually exposed the gap this pins for the
/// flowchart side of the shared `orthogonal.rs` machinery too.
#[test]
fn invariant_orthogonal_foreign_nodes_stay_out_of_clusters() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain(orthogonal_design_reference_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let tree = tree_of_src(src);
        check_foreign_nodes_stay_out_of_clusters(name, &d, &tree);
    }
}

#[test]
fn invariant_orthogonal_nested_clusters_sit_inside_their_parent() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain(orthogonal_design_reference_corpus())
    {
        check_nested_clusters_sit_inside_their_parent(
            name,
            &laid_out_flow(src, "basis", "konoma-orthogonal"),
        );
    }
}

#[test]
fn invariant_orthogonal_unrelated_clusters_do_not_overlap() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain(orthogonal_design_reference_corpus())
    {
        check_unrelated_clusters_do_not_overlap(
            name,
            &laid_out_flow(src, "basis", "konoma-orthogonal"),
        );
    }
}

#[test]
fn invariant_orthogonal_cluster_titles_stay_inside_their_frame_and_off_every_node() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain(orthogonal_design_reference_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let tree = tree_of_src(src);
        check_cluster_titles(name, &d, &tree);
    }
}

/// Finding 1's own eviction-growth half, stated directly rather than only through the invariants
/// above: `orthogonal-subgraph-growth`'s `T` must actually grow past its label-only size (the
/// scenario those invariants are being run *for*), and its grown box must still fit inside its own
/// frame with the ordinary 16px cluster padding — not merely "the invariant above happened to pass
/// for unrelated reasons".
///
/// §10-3 item 3's own correction (`classify`'s `merge_target_side` doc) moved this fixture's five
/// merges (`W1`..`W5 --> T`) off `T`'s cross-axis face (Left/Right, for this `TD` diagram — a
/// height requirement) onto its flow-axis Top face instead (a WIDTH requirement) — the same axis
/// flip `orthogonal_growth_widens_a_node_whose_face_cannot_fit_its_ports`'s own doc explains for
/// its very similar `Z` fixture. Dumped and confirmed by hand, not assumed.
#[test]
fn orthogonal_eviction_growth_inside_a_subgraph_still_fits_the_frame() {
    if !text_metrics::fonts_available() {
        return;
    }
    let src = orthogonal_only_corpus()
        .into_iter()
        .find(|(name, _)| *name == "orthogonal-subgraph-growth")
        .unwrap()
        .1;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let t = d.node("T").expect("T must exist");
    // §10-8 N4's own label-derived half, since 2026-09-05 — `shapes::size(Flow(Rect), …)` before
    // that. The rule this test pins is "the ports grew it, and only along their own axis", which
    // is a statement about the *difference* from the label-derived box, so it is stated against
    // whatever that box currently is rather than against the numbers it once produced.
    let label_only = shapes::orthogonal_label_box(t.shape, &t.label);
    assert!(
        t.size.w > label_only.w + 1.0,
        "T must actually grow past its label-only width to fit its five merge ports on its Top \
         face: grown={} label_only={}",
        t.size.w,
        label_only.w
    );
    assert!(
        (t.size.h - label_only.h).abs() < 1e-6,
        "T's height must be untouched — nothing asked its Left/Right faces to grow any more: \
         grown={} label_only={}",
        t.size.h,
        label_only.h
    );
    let cluster = d.cluster("one").expect("cluster one must exist");
    let out = escapes(t.bounds(), cluster.bounds());
    assert!(
        out <= 0.01,
        "T's grown box must still sit fully inside its own frame: pokes {out:.2}px out"
    );
}

/// Finding 2 (high): a `classDef`/`style`-painted decision node under `"konoma-orthogonal"` draws
/// as a chamfered rectangle (`decision_node_is_chamfered_under_orthogonal_and_a_diamond_under_splines`
/// already pins the shape), but nothing before this audit ever rendered one *with* a resolved paint
/// — every existing orthogonal SVG test uses an unstyled node, and `CORPUS`'s own
/// `classdef-and-style-cascade` source (which does exercise the cascade) has no decision node.
/// `svg::emit_node`'s own `fill`/`stroke`/`sw` locals feed every `Outline` arm identically
/// (`Outline::Polygon` included, `svg.rs` line ~543), so this is really checking that a chamfered
/// node was not accidentally left on some *other* code path — the v0.28.0 regression's own shape
/// ("parses but nobody reads it").
#[test]
fn orthogonal_classdef_paints_a_chamfered_decision_node() {
    let src =
        "flowchart TD\n  classDef hot fill:#f9f,stroke:#a00\n  A --> B{cond}:::hot\n  B --> C";

    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let b = d.node("B").expect("B must exist");
    assert_eq!(
        b.shape,
        Glyph::ChamferedRect,
        "B must chamfer under orthogonal routing"
    );
    let style = b
        .style
        .as_ref()
        .expect("B must carry the resolved `:::hot` paint");
    assert_eq!(style.fill.as_deref(), Some("#f9f"));
    assert_eq!(style.stroke.as_deref(), Some("#a00"));

    let svg = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("must render");
    // `<polygon` also draws every arrowhead (a small 3-point triangle in the theme's own
    // arrowhead colour) — pick the *node's* polygon by its 8 vertices, `shapes::polygon`'s own
    // `Glyph::ChamferedRect` shape (already pinned by
    // `decision_node_is_chamfered_under_orthogonal_and_a_diamond_under_splines`), not the first
    // `<polygon` line in source order.
    let vertex_count = |l: &str| -> usize {
        l.split("points=\"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .map(|pts| pts.split_whitespace().count())
            .unwrap_or(0)
    };
    let polygon = svg
        .lines()
        .filter(|l| l.starts_with("<polygon"))
        .find(|l| vertex_count(l) == 8)
        .unwrap_or_else(|| panic!("no 8-vertex chamfered-rect <polygon> element in:\n{svg}"));
    assert!(
        polygon.contains("fill=\"#f9f\""),
        "the chamfered node's own polygon must carry the classDef fill: {polygon}"
    );
    assert!(
        polygon.contains("stroke=\"#a00\""),
        "the chamfered node's own polygon must carry the classDef stroke: {polygon}"
    );
}

// -------------------------------------------------------------------------------------------
// §10-3 item 6: an edge with no colour of its own takes a lightened version of the downstream
// (target) node's own resolved class colour, under `konoma-orthogonal` only
// -------------------------------------------------------------------------------------------

/// The plain, no-conflict case: `B` carries `:::hot` (`stroke:#1f6feb`, one of the three colours
/// `style::lighten`'s own reference set pins), `A->B` names neither `class` nor `linkStyle` of its
/// own, so it takes `style::lighten("#1f6feb")` — the exact value `style::tests::
/// lighten_approximates_the_three_reference_conversions_within_its_documented_error` already pins
/// for that input, reused here rather than re-derived so the two tests can never silently drift
/// apart about what `lighten` actually returns.
#[test]
fn orthogonal_edge_color_lightens_the_downstream_class_color() {
    let src = "flowchart LR\n  classDef hot stroke:#1f6feb\n  A --> B:::hot";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let ab = d
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "B")
        .expect("A->B must exist");
    let style = ab
        .style
        .as_ref()
        .expect("A->B must carry a derived style once B resolves a class stroke");
    assert_eq!(
        style.stroke.as_deref(),
        Some("#508eef"),
        "must match style::lighten(\"#1f6feb\") exactly"
    );
    // The label colour follows the line's own, same as the arrowhead already does via
    // `tip_matches_line` — `emit_edge`'s own doc on that field, extended to the label by this
    // rule.
    assert_eq!(style.text.as_deref(), Some("#508eef"));

    let svg = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("must render");
    assert!(
        svg.contains("stroke=\"#508eef\""),
        "the edge's own <path> must draw in the lightened colour:\n{svg}"
    );
    assert!(
        svg.contains("fill=\"#508eef\""),
        "the arrowhead (tip_matches_line) must draw in the same lightened colour:\n{svg}"
    );
}

/// Same rule, with a labelled edge: the label's own `<text>` must also carry the lightened colour
/// (`svg::emit_edge`'s `label_color`, wired from `edge.style.text` — previously never read for an
/// edge label at all, `theme.edge_label_text` hardcoded regardless of any `class`/`:::`/
/// `linkStyle` `color:` the source declared).
#[test]
fn orthogonal_edge_color_reaches_the_label_text_too() {
    let src = "flowchart LR\n  classDef hot stroke:#1f6feb\n  A -->|hi| B:::hot";
    let svg = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("must render");
    assert!(
        svg.contains("fill=\"#508eef\">") && svg.contains("hi"),
        "the edge label's own <text> must draw in the lightened colour:\n{svg}"
    );
}

/// An edge's own explicit paint — `linkStyle`, `class`, `:::`, or `style` naming *the edge itself*
/// — is the most specific instruction the source gave, and must win over the automatically
/// derived colour, exactly the priority order `docs/FEATURE-MERMAID-RENDERER.md` §10-3 item 6
/// states ("linkStyle 明示 > 自動導出 > テーマ既定"): a lightened downstream colour is a fallback
/// for an edge that asked for nothing, not an override for one that did.
#[test]
fn orthogonal_edge_color_prefers_an_explicit_link_style_over_the_derived_one() {
    let src = "flowchart LR\n  classDef hot stroke:#1f6feb\n  A --> B:::hot\n  linkStyle 0 stroke:#00ff00";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let ab = d
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "B")
        .expect("A->B must exist");
    assert_eq!(
        ab.style.as_ref().and_then(|s| s.stroke.as_deref()),
        Some("#00ff00"),
        "the edge's own linkStyle must win over B's lightened class colour"
    );
}

/// A downstream node with no resolved class colour at all leaves the edge exactly as it drew
/// before this rule existed: `[ui] mermaid_routing = "konoma-orthogonal"`'s own theme default
/// (`docs/FEATURE-MERMAID-RENDERER.md` §10-3 item 6's own "クラス無しの下流は従来のテーマ辺色").
#[test]
fn orthogonal_edge_color_leaves_an_unclassed_downstream_node_alone() {
    let src = "flowchart LR\n  A --> B";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let ab = d
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "B")
        .expect("A->B must exist");
    assert!(
        ab.style.is_none(),
        "an edge whose downstream node has no class must draw with no override at all: {:?}",
        ab.style
    );
}

/// §10-3 item 6 is `konoma-orthogonal` only ("konoma-orthogonal のみ", the rule's own opening
/// words) — the default `"splines"` routing must draw byte-for-byte what it always drew, the same
/// "既定は1バイトも変えない" invariant every other round-3 rule keeps.
#[test]
fn splines_routing_never_derives_an_edge_color_from_the_downstream_node() {
    let src = "flowchart LR\n  classDef hot stroke:#1f6feb\n  A --> B:::hot";
    let d = laid_out_flow(src, "basis", "splines");
    let ab = d
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "B")
        .expect("A->B must exist");
    assert!(
        ab.style.is_none(),
        "splines routing must never derive an edge colour from the target node: {:?}",
        ab.style
    );
}

// Finding 3's app-wiring pin lives in `e2e_tests.rs`
// (`e2e_ui_mermaid_routing_changes_rendered_pixels_standalone_mmd_fullscreen` and
// `..._mermaid_fence_fullscreen`) — the other two ways a flowchart's pixels reach the screen
// besides an inline fence, which is all `e2e_ui_mermaid_routing_changes_rendered_pixels` covers.

/// Finding 5 (medium): §10-1 item 4's 2026-09-01 clarification — a back edge's line style is
/// whatever the author wrote (`-->`/`-.->`/`==>`), never something `konoma-orthogonal` itself
/// decides — pinned directly against the emitted SVG's `stroke-dasharray`, the one place a reader
/// actually sees it. `strokes` (`CORPUS`) exercises every stroke spelling but not a *back* edge in
/// particular; these two sources are minimal 2-node cycles so the back edge is the only edge in the
/// diagram whose stroke matters.
#[test]
fn orthogonal_back_edge_keeps_the_authors_own_line_style() {
    // A solid back edge (the ordinary `-->`) must draw with no dash array at all.
    let solid = render_flow(
        "flowchart TD\n  A --> B\n  B --> A",
        "dark",
        "basis",
        "konoma-orthogonal",
    )
    .expect("must render");
    assert!(
        !solid.contains("stroke-dasharray"),
        "a solid back edge must not be drawn dashed just because it is routed on the perimeter \
         lane: {solid}"
    );

    // A dotted back edge (`-.->`) must keep its own dashes.
    let dotted = render_flow(
        "flowchart TD\n  A --> B\n  B -.-> A",
        "dark",
        "basis",
        "konoma-orthogonal",
    )
    .expect("must render");
    assert!(
        dotted.contains(&format!(
            "stroke-dasharray=\"{}\"",
            theme::Theme::for_routing("dark", Routing::Orthogonal)
                .tokens
                .map_or(super::svg::DOTTED_DASH, |t| t.dotted_dash)
        )),
        "an author-dashed back edge must keep drawing dashed: {dotted}"
    );
}

/// Finding 6 (medium): `[ui] mermaid_curve` / `%%{init}%%`'s `flowchart.curve` only mean anything
/// under `"splines"` (`docs/FEATURE-MERMAID-RENDERER.md` §10-2's own "orthogonal は折れ線なので
/// curve の概念が無い"); under `"konoma-orthogonal"` a curve name must be a complete no-op on the
/// emitted bytes. `orthogonal_splines_routing_is_deterministic_and_does_not_panic` states the
/// analogous fact for `"splines"` itself (curve resolution is decidable and non-panicking); this is
/// the missing byte-identity half for `"konoma-orthogonal"`.
#[test]
fn orthogonal_routing_ignores_mermaid_curve_and_the_init_directive() {
    for (name, src) in CORPUS {
        let basis = render_flow(src, "dark", "basis", "konoma-orthogonal")
            .unwrap_or_else(|e| panic!("{name}: basis must render: {e}"));
        for curve in ["linear", "step", "monotoneX", "bumpX"] {
            let other = render_flow(src, "dark", curve, "konoma-orthogonal")
                .unwrap_or_else(|e| panic!("{name}/{curve}: must render: {e}"));
            assert_eq!(
                basis, other,
                "{name}: konoma-orthogonal must ignore mermaid_curve={curve} entirely"
            );
        }
    }
    // The `%%{init}%%` directive's own `flowchart.curve` must be equally inert.
    let plain = render_flow(
        "flowchart TD\n  A --> B --> C",
        "dark",
        "basis",
        "konoma-orthogonal",
    )
    .expect("must render");
    let with_init = render_flow(
        "%%{init: {\"flowchart\": {\"curve\": \"stepBefore\"}}}%%\nflowchart TD\n  A --> B --> C",
        "dark",
        "basis",
        "konoma-orthogonal",
    )
    .expect("must render");
    assert_eq!(
        plain, with_init,
        "konoma-orthogonal must ignore an `%%{{init}}%%` flowchart.curve directive too"
    );
}

/// Finding 8a (medium): a self-loop is never a "detour" edge for §10-1 item 4's 12px crossing gap
/// (`orthogonal::insert_crossing_gaps`'s own `is_detour` excludes it via `source.id != target.id`)
/// — so when a self-loop and a genuine detour edge cross in real pixels (`orthogonal-self-loop-
/// crosses`, dumped and confirmed to cross), the self-loop must never be the side that gets cut, and
/// the crossing detour edge must be.
#[test]
fn orthogonal_self_loop_never_gets_cut_by_a_crossing_gap() {
    if !text_metrics::fonts_available() {
        return;
    }
    let src = orthogonal_only_corpus()
        .into_iter()
        .find(|(name, _)| *name == "orthogonal-self-loop-crosses")
        .unwrap()
        .1;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let loop_edge = d
        .edges
        .iter()
        .find(|e| e.from == "A" && e.to == "A")
        .expect("the self-loop must exist");
    assert!(
        loop_edge.gaps.is_empty(),
        "a self-loop must never be the spanning side of a crossing gap: {:?}",
        loop_edge.gaps
    );
    let detour = d
        .edges
        .iter()
        .find(|e| e.from == "C" && e.to == "B")
        .expect("C->B must exist");
    assert!(
        !detour.gaps.is_empty(),
        "the fixture must actually reproduce a real crossing against the self-loop, so C->B must \
         be the one carrying the gap: {:?}",
        detour.gaps
    );
    // And, directly: the fixture's own premise — the self-loop's bump and C->B's detour actually
    // occupy overlapping space in real pixels — confirmed by their bounding boxes overlapping on
    // both axes (the two polylines' own extents, not just "a gap happened to appear somewhere").
    let bbox = |pts: &[Point]| -> (f64, f64, f64, f64) {
        let (mut l, mut t, mut r, mut b) = (
            f64::INFINITY,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NEG_INFINITY,
        );
        for p in pts {
            l = l.min(p.x);
            t = t.min(p.y);
            r = r.max(p.x);
            b = b.max(p.y);
        }
        (l, t, r, b)
    };
    let (dx, dy) = rect_overlap(bbox(&loop_edge.points), bbox(&detour.points));
    assert!(
        dx > 0.0 && dy > 0.0,
        "fixture must reproduce a real overlap in space between the self-loop and C->B, not just \
         a coincidental gap: loop_bbox={:?} detour_bbox={:?}",
        bbox(&loop_edge.points),
        bbox(&detour.points)
    );
}

/// Finding 8b (medium): a self-loop never occupies a perimeter lane index
/// (`orthogonal::perimeter_lanes`'s own filter: `s.reverse && source.id != target.id`) — so adding
/// or removing a self-loop on a node that is *also* part of a genuine back-edge cycle must not shift
/// the back edge's own lane (and therefore its ring distance) at all. Pinned by comparing two
/// otherwise-identical sources, one with the self-loop and one without.
#[test]
fn orthogonal_self_loop_does_not_consume_a_perimeter_lane() {
    if !text_metrics::fonts_available() {
        return;
    }
    let with_loop = laid_out_flow(
        "flowchart TD\n  A --> A\n  A --> B\n  B --> C\n  C --> A",
        "basis",
        "konoma-orthogonal",
    );
    let without_loop = laid_out_flow(
        "flowchart TD\n  A --> B\n  B --> C\n  C --> A",
        "basis",
        "konoma-orthogonal",
    );
    let ca_with = with_loop
        .edges
        .iter()
        .find(|e| e.from == "C" && e.to == "A")
        .expect("C->A must exist");
    let ca_without = without_loop
        .edges
        .iter()
        .find(|e| e.from == "C" && e.to == "A")
        .expect("C->A must exist");
    // The rule is about the **lane**: `perimeter_lanes` hands out ring offsets, and a self-loop
    // must never take one, so the back edge's ring leg has to sit at exactly the same coordinate
    // either way. That is asserted directly.
    //
    // It used to be asserted through the whole route being byte-identical, which was a proxy and
    // stopped being a true one when §10-8's node sizes landed (2026-09-05): with `A` a full 96px
    // wide, `C -> A` can reach `A`'s Right face centre when nothing else is on it, and a flowchart
    // self-loop **is** something else on it (`route_flowchart`'s own `fixed_self_loops` is `false`
    // for a flowchart, so its two ports are ordinary claims on `evict`'s grid — only a state
    // diagram's self-transition gets the dedicated §10-5 S3 pair). So the back edge legitimately
    // enters a different *face* when the loop is there, while riding the identical ring lane. The
    // ring leg is the thing `perimeter_lanes` decides and the thing this test is named for.
    let ring_leg = |e: &super::PlacedEdge| {
        assert!(
            e.points.len() >= 3,
            "C->A rides the ring, so it has a leg between its two exits: {:?}",
            e.points
        );
        e.points[1].x
    };
    assert!(
        (ring_leg(ca_with) - ring_leg(ca_without)).abs() < 1e-6,
        "C->A's own ring lane must be the same whether or not A also carries a self-loop (the \
         self-loop must never consume a perimeter lane slot): with={:?} without={:?}",
        ca_with.points,
        ca_without.points
    );
    // And the lane is a real one on both sides — a ring leg that had collapsed onto the node's own
    // face would compare equal to itself and say nothing.
    let (_, _, a_right, _) = with_loop.node("A").expect("A must exist").bounds();
    assert!(
        ring_leg(ca_with) > a_right,
        "C->A's ring leg must run outside A, not along its face: {:?}",
        ca_with.points
    );
}

/// Finding 10 (low, investigated): `MAX_GROWTH_PASSES = 3` (`mod.rs`'s own `lay_out_spec`) is a
/// defensive cap over a process the code's own doc states is monotonic and therefore always
/// converges on its own — `apply_growth` only ever grows toward an exact, one-shot-computable
/// minimum (`Eviction::required_size`), not an iterative approximation, so there is no obvious
/// adversarial input that forces three full passes rather than converging in one or two. A stress
/// source combining heavy fan-in (12 merge edges onto one face, forcing node growth) with long
/// labels (forcing `label_boosts` growth at the same time, `mod.rs`'s own doc: "a pass can ask for
/// both at once") was tried; `lay_out_spec` has no public hook that reports how many passes a given
/// input actually took, so whether this specific source reaches the cap could not be confirmed
/// directly. What is confirmed: the combined stress case renders without panicking and comes out
/// axis-parallel and collision-free, i.e. self-consistent regardless of how many passes it took —
/// the property finding 10 asked to be pinned "if reachable", stated unconditionally instead since
/// reachability itself could not be established.
#[test]
fn orthogonal_heavy_growth_stress_renders_self_consistently() {
    if !text_metrics::fonts_available() {
        return;
    }
    let mut src = String::from("flowchart TD\n");
    for i in 1..=12 {
        src.push_str(&format!(
            "  W{i}[extremely long sibling label number {i} to force both node and label growth at once] --> T\n"
        ));
    }
    src.push_str("  T -- also a long label on the way out --> X\n");
    let d = laid_out_flow(&src, "basis", "konoma-orthogonal");
    // Self-consistency: every segment axis-parallel, no edge crosses a foreign node's box.
    for e in &d.edges {
        for w in e.points.windows(2) {
            let dx = (w[1].x - w[0].x).abs();
            let dy = (w[1].y - w[0].y).abs();
            assert!(
                dx < AXIS_EPS || dy < AXIS_EPS,
                "heavy-growth stress: {}->{} must stay axis-parallel: {w:?}",
                e.from,
                e.to
            );
        }
        for n in &d.nodes {
            if n.id == e.from || n.id == e.to {
                continue;
            }
            for w in e.points.windows(2) {
                assert!(
                    !orthogonal::segment_crosses_node(&w[0], &w[1], n),
                    "heavy-growth stress: {}->{} crosses foreign node {}",
                    e.from,
                    e.to,
                    n.id
                );
            }
        }
    }
    // And render_flow (the SVG-emitting entry point) must not panic on the same source either.
    render_flow(&src, "dark", "basis", "konoma-orthogonal").expect("must render");
}

/// Finding 11 (low): degenerate flowcharts under `"konoma-orthogonal"` must not panic. A single
/// node with no edges at all exercises `lay_out_spec`'s growth loop with an empty `eligible` list
/// (`spec.routing == Routing::Orthogonal` but nothing to route); a self-loop on a lone node
/// exercises the one-node/one-edge case of every pass (`evict`, `align_straight_lanes`,
/// `insert_crossing_gaps`) at once.
#[test]
fn orthogonal_degenerate_diagrams_do_not_panic() {
    if !text_metrics::fonts_available() {
        return;
    }
    for src in ["flowchart TD\n  A[only]", "flowchart TD\n  A --> A"] {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for e in &d.edges {
            for w in e.points.windows(2) {
                let dx = (w[1].x - w[0].x).abs();
                let dy = (w[1].y - w[0].y).abs();
                assert!(
                    dx < AXIS_EPS || dy < AXIS_EPS,
                    "{src:?}: {}->{} must stay axis-parallel: {w:?}",
                    e.from,
                    e.to
                );
            }
        }
        render_flow(src, "dark", "basis", "konoma-orthogonal")
            .unwrap_or_else(|e| panic!("{src:?} must render under konoma-orthogonal: {e}"));
    }
}

/// [`orthogonal_degenerate_diagrams_do_not_panic`]'s remaining case — two nodes placed at the exact
/// same centre — cannot be produced through a real mermaid source at all (dagre always separates
/// same-rank nodes by `nodesep`), so it is stated directly against [`orthogonal::route_edge`]
/// instead, the same private-access shortcut `orthogonal.rs`'s own unit tests use.
#[test]
fn orthogonal_route_edge_does_not_panic_on_coincident_centres() {
    let a = placed_node("A", 100.0, 100.0, 60.0, 40.0);
    let b = placed_node("B", 100.0, 100.0, 60.0, 40.0);
    // `route_edge` is `pub`; the coincident-centre case is exercised through it rather than the
    // private `route_flowchart`/`evict` pair this file has no direct access to.
    let pts = orthogonal::route_edge(
        crate::preview::mermaid::flowchart::Direction::TopToBottom,
        &a,
        &b,
        &[],
        Some(0),
        Some(1),
        1,
        1,
    );
    assert!(
        !pts.is_empty(),
        "must return a non-empty polyline, not panic"
    );
    for p in &pts {
        assert!(
            p.x.is_finite() && p.y.is_finite(),
            "must never emit a NaN/infinite point: {p:?}"
        );
    }
}

// ---------------------------------------------------------------------------------------------
// TEMP probe for docs/FEATURE-MERMAID-RENDERER.md §10-3 work — dumps a markdown file's own mermaid
// fences under `konoma-orthogonal` to `docs/render-check` for structural/visual comparison against
// hand-drawn reference SVGs. `#[ignore]`d so it never runs in the normal battery.

/// Dumps every mermaid fence in `md_path` to `docs/render-check/<stem>-NN-konoma-orthogonal.{svg,png}`
/// — `dump_mermaid_ja_corpus_under_orthogonal` and `dump_render_check_probes_under_orthogonal`'s
/// own shared body, factored out once a second source (`docs/render-check/zz-design-sources.md`,
/// `docs/render-check/zz-design-longedge-probe.md`) needed the identical treatment.
fn dump_fences_under_orthogonal(md_path: &str, stem: &str) {
    let md = std::fs::read_to_string(md_path).unwrap_or_else(|e| panic!("read {md_path}: {e}"));
    let mut fences: Vec<String> = Vec::new();
    let mut cur: Option<String> = None;
    for line in md.lines() {
        if let Some(buf) = &mut cur {
            if line.trim() == "```" {
                fences.push(std::mem::take(buf));
                cur = None;
            } else {
                buf.push_str(line);
                buf.push('\n');
            }
        } else if line.trim() == "```mermaid" {
            cur = Some(String::new());
        }
    }
    assert!(
        !fences.is_empty(),
        "{md_path}: must find at least one mermaid fence"
    );

    for (i, code) in fences.iter().enumerate() {
        let n = i + 1;
        let path = format!("docs/render-check/{stem}-{n:02}-konoma-orthogonal.svg");
        // `[ui] mermaid_routing` only ever means anything for a flowchart (`mod.rs`'s own doc) —
        // every other diagram kind renders through the ordinary `render`, unaffected by it.
        // `[ui] mermaid_routing` only ever means anything for a flowchart — this is the real
        // dispatcher every other diagram kind goes through in production
        // (`preview::markdown::mermaid_to_svg_reason_flow`), not `render_flow` alone (which only
        // ever knows how to parse a flowchart).
        let svg = crate::preview::markdown::mermaid_to_svg_flow(
            code,
            "dark",
            "basis",
            "konoma-orthogonal",
        );
        match svg {
            Some(svg) => {
                std::fs::write(&path, &svg).unwrap_or_else(|e| panic!("write {path}: {e}"));
                let png_path = format!("docs/render-check/{stem}-{n:02}-konoma-orthogonal.png");
                if let Some(img) = crate::preview::svg::rasterize_bytes(
                    svg.as_bytes(),
                    std::path::Path::new(&path),
                    2400,
                ) {
                    img.save(&png_path)
                        .unwrap_or_else(|e| panic!("save {png_path}: {e}"));
                }
            }
            None => eprintln!("{md_path} fence {n}: render failed"),
        }
    }
}

/// Dumps the "大きさ" flowchart (`samples/mermaid.ja.md` fence 3) to `docs/render-check` for
/// structural comparison against the round3 handoff's 3a SVG, and every other
/// `samples/mermaid.ja.md` fence for the same visual spot-check. Run explicitly with
/// `cargo test --features git dump_mermaid_ja_corpus_under_orthogonal -- --ignored --nocapture`.
#[test]
#[ignore]
fn dump_mermaid_ja_corpus_under_orthogonal() {
    dump_fences_under_orthogonal("samples/mermaid.ja.md", "mermaid.ja");
}

/// Dumps `docs/render-check/zz-design-sources.md` (2a/2b/2c-equivalent sources — a worker subgraph,
/// LR/TB nested-subgraph client/cloud/external graphs) and `docs/render-check/zz-design-longedge-
/// probe.md` (`CORPUS`'s own `long-edge` source, standalone, for the exact regression this session's
/// pass-through-reservation fix closes) to `docs/render-check`, for the general-corpus checks
/// `docs/FEATURE-MERMAID-RENDERER.md` §10-3's own implementation notes on this session's three
/// findings describe. Run explicitly with `cargo test --features git
/// dump_render_check_probes_under_orthogonal -- --ignored --nocapture`.
#[test]
#[ignore]
fn dump_render_check_probes_under_orthogonal() {
    dump_fences_under_orthogonal(
        "docs/render-check/zz-design-sources.md",
        "zz-design-sources",
    );
    dump_fences_under_orthogonal(
        "docs/render-check/zz-design-longedge-probe.md",
        "zz-design-longedge-probe",
    );
}

/// §10-3 item 13's own regression, found by generalising past `CORPUS` to real, larger sources
/// (`docs/render-check/zz-design-sources.md`'s `2b`): `API -> ID`, a cross-subgraph node-to-node
/// edge whose `classify`-decided shape is `staircase` (`raw` carries 13 dagre waypoints, several
/// collinear before ever reaching `ID`'s own port). `clear_local_route`'s own crossing search can
/// flag an *early* window of that collinear run, not the literal last one — an earlier draft of the
/// local-detour fix (§10-3 item 13) judged whether a port sat on the coordinate being moved by the
/// *literal window index* (`i + 2 == points.len()`) rather than by coordinate, so it never noticed
/// `ID`'s own port shared the exact coordinate an early window's fix slid out from under it: a
/// diagonal final segment, `orthogonal_routing_draws_only_axis_parallel_segments`'s own invariant
/// broken in a shape `CORPUS` had no fixture for. Pinned here directly, not only through the
/// corpus-wide invariant, because this is the exact real-world diagram the bug was found on
/// (`local_detour`'s own current implementation never slides a shared coordinate at all — it
/// detours only the interior span between two freshly-inserted boundary points either side of the
/// obstacle, so this specific failure mode cannot recur, but the fixture stays as a named regression
/// test for the general "port coordinate coincides with an obstacle boundary" shape).
#[test]
fn orthogonal_cross_subgraph_edge_never_draws_a_diagonal_segment() {
    let src = "flowchart LR\n  subgraph C[クライアント]\n    CLI[CLI]\n    UI[ブラウザ UI]\n    EX[エディタ拡張]\n  end\n  subgraph G[クラウド]\n    API[API ゲート]\n    Q[ジョブキュー]\n    W[ジョブ実行系]\n    SB[解析サンドボックス]:::exec\n    subgraph S[保存層]\n      DB[メタデータ DB]:::data\n      AR[成果物保管]:::data\n    end\n  end\n  subgraph E[外部]\n    ID[認証基盤]\n    LLM[モデル API]:::model\n    GIT[コード置き場]:::exec\n    PAY[決済ページ]\n  end\n  CLI --> API\n  UI -->|HTTPS| API\n  EX --> API\n  API --> ID\n  API -->|投入| Q\n  Q -->|取り出し| W\n  API --> DB\n  W --> DB\n  W --> AR\n  W --> LLM\n  W -->|ツール実行| SB\n  SB --> GIT\n  CLI -.->|リンク| PAY\n  classDef data fill:#161b22,stroke:#3fb950,color:#e6edf3\n  classDef model fill:#161b22,stroke:#a371f7,color:#e6edf3\n  classDef exec fill:#161b22,stroke:#f85149,color:#e6edf3\n  linkStyle 0,1,2 stroke:#58a6ff\n  linkStyle 4,5 stroke:#d29922\n";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let api_id = d
        .edges
        .iter()
        .find(|e| e.from == "API" && e.to == "ID")
        .expect("API->ID must exist");
    for w in api_id.points.windows(2) {
        let (a, b) = (&w[0], &w[1]);
        assert!(
            (a.x - b.x).abs() < AXIS_EPS || (a.y - b.y).abs() < AXIS_EPS,
            "API->ID must never draw a diagonal segment: {:?}-{:?} in {:?}",
            a,
            b,
            api_id.points
        );
    }
}

#[test]
fn zzdebug_fence3_structural_table() {
    let src = "flowchart LR\n  F[ファイル] --> C{設定のルール}\n  C -->|テキスト| T[窓読み]\n  C -->|コード| S[構文強調]\n  C -->|Markdown| MD[ブロックモデル]\n  C -->|CSV / TSV| TB[表]\n  C -->|画像| IM[デコード]\n  C -->|PDF| PD[ページ描画]\n  C -->|SVG| SV[usvg]\n  C -->|動画| VD[キーフレーム]\n  C -->|書庫| AR[一覧]\n  C -->|なし| NA[プレビュー不可]\n  MD --> MM[mermaid]\n  MD --> MA[数式]\n  MM --> RS[ラスタライズ]\n  MA --> RS\n  SV --> RS\n  PD --> RS\n  IM --> FIT[セルに合わせる]\n  RS --> FIT\n  VD --> FIT\n  FIT --> K{端末}\n  K -->|kitty| KT[圧縮転送]\n  K -->|sixel / iTerm2| RI[画像プロトコル]\n  K -->|それ以外| HB[ハーフブロック]\n  classDef pix fill:#132a3a,stroke:#1f6feb,color:#c9d1d9\n  classDef txt fill:#12291c,stroke:#2da44e,color:#c9d1d9\n  class IM,PD,SV,VD,MM,MA,RS,FIT,KT,RI,HB pix\n  class T,S,MD,TB,AR txt\n  style NA fill:#2d2418,stroke:#d4a017,color:#c9d1d9\n";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    for n in &d.nodes {
        eprintln!(
            "NODE {:>4}: center=({:.1},{:.1}) size=({:.1}x{:.1}) box=[{:.1}..{:.1}]x[{:.1}..{:.1}]",
            n.id,
            n.center.x,
            n.center.y,
            n.size.w,
            n.size.h,
            n.center.x - n.size.w / 2.0,
            n.center.x + n.size.w / 2.0,
            n.center.y - n.size.h / 2.0,
            n.center.y + n.size.h / 2.0,
        );
    }
    for e in &d.edges {
        let bends = e.points.len().saturating_sub(2);
        eprintln!(
            "{:>3} -> {:<3} bends={} start={:?} end={:?} color={:?} points={:?}",
            e.from,
            e.to,
            bends,
            e.points.first(),
            e.points.last(),
            e.style.as_ref().and_then(|s| s.stroke.clone()),
            e.points,
        );
    }
}

/// §10-3's "ファン列内の並び順" (`docs/FEATURE-MERMAID-RENDERER.md`, `mod.rs`'s own `regroup_fan_
/// lanes` doc) — the mechanical rule reverse-engineered from `3a`'s reference geometry, pinned on
/// a small, hand-built fan deliberately shaped to make every clause of the rule independently
/// checkable, rather than only on `samples/mermaid.ja.md`'s 20-node fence (the real-world source
/// the rule was derived from, covered separately by `orthogonal_settings_rules_sample_*`):
///
/// `S` fans out to six children, in declaration order `A`(red), `P`(blue), `B`(red), `T`(red,
/// *and* the sole one with its own further out-edge — `T -> D` — so it is the unambiguous trunk
/// regardless of any geometric tie-break), `Q`(blue), `Z`(no `class` at all, only `classDef`
/// members get one). The rule (trunk → group index `len/2`; group by resolved colour, group order
/// by first declared member; classless always last) predicts, and this test pins, the exact order
/// `A, B, P, T, Q, Z`: the two same-coloured groups (`red` first, since `A` is declared before
/// `P`) supply `regroup_fan_lanes`'s own `rest` list `[A, B, P, Q, Z]` (classless `Z` pushed to
/// the tail regardless of its own declaration position, third of six), and inserting `T` at
/// `6 / 2 = 3` splits it `[A, B, P]` / `[T]` / `[Q,Z]`.
///
/// Each assertion below is aimed at one clause a mutation of the rule would silently break:
/// swapping the group-order key (first-declared member) would put `P` ahead of `A`; dropping the
/// "同色内は安定" clause (or resorting a group by id instead of declaration order) would put `B`
/// ahead of `A` or `Q` ahead of `P`; treating the classless rule as "first" instead of "last"
/// would move `Z` to the front; using `len/2` rounded the other way, or not special-casing the
/// trunk's own slot at all, would misplace `T`; and dropping [`orthogonal::evict`]'s own anchor
/// fix (this module's own `orthogonal_branch_and_merge_edges_share_a_face_one_aligned_one_bends_
/// twice`, the general-purpose regression for the same fix) would leave `S -> T` bent instead of
/// the straight, exactly-centred line the last two assertions pin.
#[test]
fn regroup_fan_lanes_groups_by_colour_centres_the_trunk_and_pushes_classless_outermost() {
    let src = "flowchart LR\n  S --> A\n  S --> P\n  S --> B\n  S --> T\n  S --> Q\n  S --> Z\n  \
               T --> D\n  classDef red stroke:#ff0000\n  classDef blu stroke:#0000ff\n  \
               class A,B red\n  class P,Q blu\n";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    assert_no_edge_crosses_its_own_endpoint("regroup-minimal", &d);
    check_nodes_do_not_overlap("regroup-minimal", &d);

    let mut kids: Vec<(&str, f64)> = d
        .edges
        .iter()
        .filter(|e| e.from == "S")
        .map(|e| (e.to.as_str(), d.node(&e.to).unwrap().center.y))
        .collect();
    kids.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
    let order: Vec<&str> = kids.iter().map(|(id, _)| *id).collect();
    assert_eq!(
        order,
        vec!["A", "B", "P", "T", "Q", "Z"],
        "colour-grouped, trunk-centred, classless-outermost order: {order:?}"
    );

    // The trunk edge is `classify`'s `aligned` shape (a straight 2-point line), landing exactly
    // on S's own centre — `evict`'s anchor fix (§10-3's "幹7区間の曲げ0") is what makes this land
    // on 0 rather than `PORT_SPACING/2` off it despite six claims (an even count) on S's face.
    let st = d
        .edges
        .iter()
        .find(|e| e.from == "S" && e.to == "T")
        .expect("S->T must exist");
    let s_node = d.node("S").expect("S must exist");
    assert_eq!(
        st.points.len(),
        2,
        "S->T is the trunk — a straight 2-point line: {:?}",
        st.points
    );
    assert!(
        (st.points[0].y - s_node.center.y).abs() < 1e-6,
        "S->T exits exactly on S's own centre: {:?} vs {}",
        st.points[0],
        s_node.center.y
    );
}

/// §10-3 item 11 (`docs/FEATURE-MERMAID-RENDERER.md`) — `regroup_fan_lanes` widened from "at least
/// three members" to "at least two": `samples/mermaid.ja.md`'s own `ブロックモデル` (`MD`) fans out
/// to exactly two children, `mermaid`(`MM`, the trunk `MD->MM` selects — its own further edge
/// `MM->RS` is what makes it the unambiguous chain continuation) and `数式`(`MA`, the sole non-
/// trunk member), and `3a`'s own reference geometry puts `数式` *above* `mermaid`, not below —
/// pinned directly on the real corpus source rather than only inferred from the `SETTINGS_RULES_
/// SAMPLE` dump this fix was found against. Before this fix, a plain two-way fan was never
/// eligible for `regroup_fan_lanes` at all (`docs/STATUS.md`'s own ★未修正 entry — "`regroup_fan_
/// lanes` は要素3以上のファンのみ対象" — before this fix, `MA` fell wherever `align_straight_
/// lanes`'s own overlap sweep happened to leave it, landing *below* `MM` instead).
#[test]
fn orthogonal_settings_rules_sample_block_model_fan_puts_math_above_the_mermaid_trunk() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let mm = d.node("MM").expect("MM (mermaid) must exist");
    let ma = d.node("MA").expect("MA (数式) must exist");
    let mm_mm = d
        .edges
        .iter()
        .find(|e| e.from == "MD" && e.to == "MM")
        .expect("MD->MM must exist");
    assert_eq!(
        mm_mm.points.len(),
        2,
        "MD->MM is the trunk — a straight 2-point line: {:?}",
        mm_mm.points
    );
    assert!(
        ma.center.y < mm.center.y,
        "数式(MA) must sit above the mermaid(MM) trunk under LR (smaller y): MA.y={}, MM.y={}",
        ma.center.y,
        mm.center.y
    );
}

/// A minimal, hand-built counterpart to the corpus pin above, for the *other* half of
/// [`super::fan_split`]'s own one-branch rule: a two-way fan with no colour classes at all, whose
/// sole non-trunk branch is a **dead end** (`A` has no out-edge), goes *after* the trunk — the
/// positive cross side, `LR` down / `TB` right.
///
/// This test used to assert the opposite (`A` before `T`) and was named for it. That expectation
/// was the `before = len / 2` formula written down as if it were the rule, and
/// `docs/STATUS.md`'s own ★未修正 **G8** is what it cost: `zz-design-4b`'s own `休止` (a dead end
/// off `分岐`) came out *above* the `更新` trunk where every design reference puts it below. The
/// formula was reverse-engineered from `1b` and `3a`'s own `ブロックモデル`, and in **both** of those
/// the sole non-trunk branch happens to be one that continues (`1b`'s `画像 → デコード`, `3a`'s
/// `数式 → ラスタライズ`) — so "before" and "continues" were indistinguishable in the two examples
/// the formula came from. Run over all nine non-trunk branches of the design references at once,
/// only continuity explains them; this fixture is the case that separates the two readings, which
/// is why it is stated in both directions here.
#[test]
fn orthogonal_synthetic_two_way_fan_puts_a_dead_end_branch_after_the_trunk() {
    // `LR` (cross axis is y: "after" is down) and `TB` (cross axis is x: "after" is right). The
    // third case adds a self-loop on `A`: a branch that only loops back to itself is still a dead
    // end (`regroup_fan_lanes`'s own `continues` doc), so nothing about its side changes.
    for (direction, cross_of, extra) in [
        (
            "LR",
            (|n: &PlacedNode| n.center.y) as fn(&PlacedNode) -> f64,
            "",
        ),
        ("TB", |n: &PlacedNode| n.center.x, ""),
        ("LR", |n: &PlacedNode| n.center.y, "  A --> A\n"),
    ] {
        let src = format!("flowchart {direction}\n  S --> A\n  S --> T\n  T --> D\n{extra}");
        let d = laid_out_flow(&src, "basis", "konoma-orthogonal");
        let a = d.node("A").expect("A must exist");
        let t = d.node("T").expect("T must exist");
        let st = d
            .edges
            .iter()
            .find(|e| e.from == "S" && e.to == "T")
            .expect("S->T must exist");
        assert_eq!(
            st.points.len(),
            2,
            "{direction}: S->T is the trunk (T continues the chain via T->D) — a straight 2-point \
             line: {:?}",
            st.points
        );
        assert!(
            cross_of(a) > cross_of(t),
            "{direction}: the sole non-trunk branch (A) is a dead end, so it takes the positive \
             cross side — after the trunk (T): A={:.1}, T={:.1}",
            cross_of(a),
            cross_of(t)
        );
    }
}

/// [`super::fan_split`]'s own two-branch case, in 1b's regime: **both** cross-axis faces are spoken
/// for whatever the branches' continuity is, so the split stays at the centre and the trunk keeps
/// one branch on each side.
///
/// Stated twice, once for each way the two branches can agree. Both continuing (`A -> P`, `B -> Q`)
/// is the configuration where a naive "every continuing branch goes before the trunk" would stack
/// both on one side and leave the other face empty; both dead ends is `3a`'s own `端末` fan
/// (`圧縮転送` above, `ハーフブロック` below `画像プロトコル`), where the same naive reading would
/// stack both *after* it. 1b's basic shape can seat neither.
#[test]
fn orthogonal_three_way_fan_whose_branches_agree_keeps_one_on_each_side() {
    for (what, tail) in [
        ("both continue", "  A --> P\n  B --> Q\n"),
        ("both dead-end", ""),
    ] {
        let src = format!("flowchart LR\n  S --> A\n  S --> T\n  T --> D\n  S --> B\n{tail}");
        let d = laid_out_flow(&src, "basis", "konoma-orthogonal");
        let a = d.node("A").expect("A must exist");
        let b = d.node("B").expect("B must exist");
        let t = d.node("T").expect("T must exist");
        assert!(
            a.center.y < t.center.y && t.center.y < b.center.y,
            "{what}: the trunk (T) keeps the centre slot with one branch either side: A.y={}, \
             T.y={}, B.y={}",
            a.center.y,
            t.center.y,
            b.center.y
        );
    }
}

/// `zz-design-2b`/`2c`'s own spine: **`API ゲート → ジョブキュー → ジョブ実行系 → 解析サンドボックス
/// → コード置き場` is one straight run, and the two `保存層` stores fan off to one side of it** — the
/// composition both design references draw, stated once for each axis (`2b` is `LR`, `2c` the same
/// graph `TB`).
///
/// `ジョブ実行系` has four out-edges and only `解析サンドボックス` continues (into `コード置き場`,
/// a member of a *different* frame), so `align_straight_lanes` picks it as the chain's own
/// continuation — that part was never in doubt. What was wrong is where the rank then put it:
/// `メタデータ DB` and `成果物保管` are members of `保存層` inside the same `クラウド` frame
/// `ジョブ実行系` and `解析サンドボックス` sit in, and every pass that spaces a rank read each node's
/// **outermost** frame, so all four counted as one indivisible unit and none of them was ever spaced
/// against another. `解析サンドボックス` came out at *exactly* the same point as `成果物保管`, and
/// `clear_foreign_cluster_overlaps` — which runs much later and knows nothing about lanes — broke
/// the tie by shoving the one that was foreign to `保存層`, i.e. the lane's own member, out of the
/// frame and off the spine. `成果物保管` was then left sitting on the lane, which is what read as
/// "`成果物保管` is the straight continuation".
///
/// Which side the two stores end up on is dagre's own rank order, not a rule of §10-3's, so this
/// asserts only that they are together and on *a* side, never which.
/// §10-3 item 4's own branch half (`orthogonal::EdgeShape::cross_lane_bend`), stated on a
/// synthetic diagram built from the *shape* the rule is about rather than from any reference
/// picture: a branching source whose long edge has to reach a target whose own column is occupied
/// (`T3` sits directly above `Far`) and whose own flow-axis column carries a trunk (`T1`/`T2`), so
/// neither of `classify`'s two ordinary shapes nor any flow-face rank-lane bend can clear.
///
/// Before this rule existed that combination fell to `staircase` — dagre's dummy waypoints, laid
/// out before the cross-axis passes moved every node, so the chain pointed at columns that no
/// longer held anything and `clear_local_route` walked it out and back in a nine-point zig-zag.
/// What is asserted here is the rule, not that route's absence: the edge leaves through the face
/// already turned towards its target, runs one straight leg down a lane that keeps
/// [`orthogonal::PORT_CLEARANCE`] from every node, and turns into the target's own flow face —
/// three bends, the two the rule allows plus the hop onto the lane.
#[test]
fn orthogonal_blocked_multi_rank_branch_runs_a_free_lane_off_the_face_facing_its_target() {
    let src = "flowchart TB\n  S --> T1\n  T1 --> T2\n  T2 --> T3\n  T3 --> T4\n  \
               T2 --> Blk\n  Blk --> Far\n  S --> Far";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let e = d
        .edges
        .iter()
        .find(|e| e.from == "S" && e.to == "Far")
        .expect("S -> Far must be routed");
    let s = d.node("S").expect("S");
    let far = d.node("Far").expect("Far");
    assert!(
        far.center.x > s.center.x,
        "fixture assumption: Far must sit on S's right, not at {:?}",
        far.center
    );

    // Leaves through the cross-axis face already turned towards the target, not the flow face a
    // `staircase` fallback would use.
    let (_, _, s_right, _) = s.bounds();
    assert!(
        (e.points[0].x - (s_right + orthogonal::PORT_INSET)).abs() < AXIS_EPS
            && (e.points[0].y - s.center.y).abs() < AXIS_EPS,
        "S -> Far must leave S's own right face at its centre, not {:?}: {:?}",
        e.points[0],
        e.points
    );
    assert_eq!(
        e.points.len(),
        5,
        "S -> Far must be the rule's own four legs: {:?}",
        e.points
    );
    // …into the target's flow-axis face.
    let (far_l, far_t, far_r, _) = far.bounds();
    let end = e.points.last().expect("non-empty");
    assert!(
        (end.y - (far_t - orthogonal::PORT_INSET)).abs() < AXIS_EPS
            && end.x > far_l
            && end.x < far_r,
        "S -> Far must enter Far's own top face, not {end:?}: {:?}",
        e.points
    );

    // The lane itself: one straight run along the flow axis, clear of every node's column by at
    // least the module's own minimum port clearance on both sides.
    let lane = e.points[1].x;
    assert!(
        (e.points[2].x - lane).abs() < AXIS_EPS && (e.points[2].y - e.points[1].y).abs() > 100.0,
        "S -> Far's own second leg must be the long lane run: {:?}",
        e.points
    );
    for n in &d.nodes {
        if n.id == "S" || n.id == "Far" {
            continue;
        }
        let (l, t, r, b) = n.bounds();
        let spans_the_run = t < e.points[2].y && b > e.points[1].y;
        assert!(
            !spans_the_run
                || lane <= l - orthogonal::PORT_CLEARANCE
                || lane >= r + orthogonal::PORT_CLEARANCE,
            "S -> Far's lane at x={lane:.2} is closer than {}px to {} {:?}",
            orthogonal::PORT_CLEARANCE,
            n.id,
            n.bounds()
        );
    }
}

/// §10-5 round 4's own headline rule — "枠は 1 つの単位…ブロックは 1 つの body として動く"
/// ([`orthogonal::LaneUnits::unit_of`]) — stated where it actually has consequences, because
/// nothing stated it before: making that method the identity (every node its own unit) left the
/// whole suite green for a while, which means "a block moves as a body" was believed rather than
/// checked.
///
/// Two consequences, one per fixture, both of which the identity mutation breaks:
///
/// 1. **A lane that crosses a frame moves the block, it does not stretch it.** `A --> c2` reaches a
///    member in the middle of a block whose own spine is `c1 --> c2` with `c3` off to the side, so
///    aligning `A --> c2 --> B` has to move `c2`. Moving `c2` alone tears the block open — measured
///    at a 414.8px-wide frame for three 74.8px boxes. A block is only ever as wide as its own
///    members need, whatever a lane does to it.
/// 2. **A neighbour is spaced from the frame, not from a member.** `N` sits beside a block whose
///    nearest member (`c3`) stops well short of the frame's own border, so "spaced by
///    [`ORTHO_NODE_SEP`]" has two possible readings and only one of them leaves the drawn boxes
///    that far apart. Under the identity mutation the sweep never sees the frame at all and `N`
///    ends up wherever `clear_foreign_cluster_overlaps` shoves it — 16px out, not 24.
#[test]
fn orthogonal_a_block_moves_as_one_body_and_is_spaced_as_one() {
    // (1) an outside lane through the middle of a block.
    let d = laid_out_flow(
        "flowchart TB\n  A --> c2\n  subgraph C\n    c1 --> c2\n    c1 --> c3\n  end\n  c2 --> B",
        "basis",
        "konoma-orthogonal",
    );
    let frame = d.cluster("C").expect("C");
    let members: Vec<&PlacedNode> = ["c1", "c2", "c3"]
        .iter()
        .filter_map(|id| d.node(id))
        .collect();
    // The widest a rank inside this block can legitimately be: its own boxes, side by side, one
    // `ORTHO_NODE_SEP` apart — plus the frame's own padding on each side.
    let mut widest_rank = 0.0_f64;
    for m in &members {
        let row: Vec<&&PlacedNode> = members
            .iter()
            .filter(|o| (o.center.y - m.center.y).abs() < 1.0)
            .collect();
        let spread: f64 = row.iter().map(|o| o.size.w).sum::<f64>()
            + super::ORTHO_NODE_SEP * (row.len().saturating_sub(1)) as f64;
        widest_rank = widest_rank.max(spread);
    }
    let allowed = widest_rank + 2.0 * clusters::PAD;
    assert!(
        frame.size.w <= allowed + 0.01,
        "the lane through C stretched the block instead of moving it: frame is {:.2}px wide, \
         its own members need {allowed:.2}px",
        frame.size.w
    );

    // (2) a neighbour beside a block whose nearest member stops short of the frame.
    let d = laid_out_flow(
        "flowchart TB\n  A --> c1\n  A --> N\n  N --> M\n  subgraph C\n    c1 --> c2\n    \
         c1 --> c3\n  end\n  c2 --> M",
        "basis",
        "konoma-orthogonal",
    );
    let frame = d.cluster("C").expect("C");
    let n = d.node("N").expect("N");
    let (fl, _, fr, _) = frame.bounds();
    let (nl, _, nr, _) = n.bounds();
    let gap = if nl >= fr { nl - fr } else { fl - nr };
    assert!(
        (gap - super::ORTHO_NODE_SEP).abs() < 0.01,
        "N must sit {}px from C's own frame ({fl:.2}..{fr:.2}), not {gap:.2}px — it is at \
         {nl:.2}..{nr:.2}",
        super::ORTHO_NODE_SEP
    );
}

/// §10-3 item 8's own ASAP re-ranking, on the one graph shape that used to switch it off for the
/// **whole diagram**: an edge that leaves a block and comes straight back into it
/// (`subgraph C { c1 --> c2 }` plus `c1 --> X --> c2`). Counting only the levels `C`'s own members
/// occupy made `c1` and `c2` adjacent, and the unit graph then stated `X` after `C` and `C` after
/// `X` at once — unsatisfiable, so the bounded relaxation never settled and `pull_back_fan_ranks`
/// returned without re-ranking anything, fans included.
///
/// Two things are asserted, and the second is the point: the returning node keeps its own level
/// between the two members (which is where dagre already had it, and the only place a forward
/// route can reach it from), **and** the four-way fan further down still gets its ASAP layer —
/// every `d*` on one rank, immediately after `c2`, with nothing between.
#[test]
fn orthogonal_a_block_leaving_and_returning_edge_still_leaves_asap_running() {
    let src = "flowchart TB\n  subgraph C\n    c1 --> c2\n  end\n  c1 --> X\n  X --> c2\n  \
               c2 --> d1\n  c2 --> d2\n  c2 --> d3\n  c2 --> d4";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let y = |id: &str| d.node(id).unwrap_or_else(|| panic!("{id}")).center.y;
    assert!(
        y("c1") < y("X") && y("X") < y("c2"),
        "X must keep its own level between c1 ({:.2}) and c2 ({:.2}), not {:.2}",
        y("c1"),
        y("c2"),
        y("X")
    );
    // ASAP: the fan is one rank, and it is the rank immediately after `c2` — no empty column, and
    // no member left behind on a later one. Read as "every `d*` shares a row, and the gap from
    // `c2` to that row is the same as the gap `c1`'s own straight successor got".
    let fan: Vec<f64> = ["d1", "d2", "d3", "d4"].iter().map(|id| y(id)).collect();
    for w in fan.windows(2) {
        assert!(
            (w[0] - w[1]).abs() < 0.01,
            "the fan under c2 must be one rank: {fan:?}"
        );
    }
    let rows: std::collections::BTreeSet<i64> = d
        .nodes
        .iter()
        .map(|n| (n.center.y * 100.0) as i64)
        .collect();
    assert_eq!(
        rows.len(),
        4,
        "the diagram must re-rank to four rows (c1 / X / c2 / the fan), not {}: {:?}",
        rows.len(),
        d.nodes
            .iter()
            .map(|n| (n.id.as_str(), n.center.y))
            .collect::<Vec<_>>()
    );
}

/// Two sibling subgraphs on the same rank, with a title long enough on one of them that dagre's
/// own placement leaves the other's member inside it — the shape that exercises both halves of
/// "a frame is spaced and reserved like one body":
///
/// 1. §10-1 item 4's own "枠とノード・外周レーンの余白は最低16px" read for a frame *pair*:
///    `clear_foreign_cluster_overlaps` used to push the bare member box clear by
///    [`orthogonal::PERIMETER_MARGIN`], and `rebuild_frames` then wrapped that member in exactly
///    the same [`clusters::PAD`] — so `B`'s left edge landed precisely on `A`'s right edge and the
///    two frames shared a line. The push is by body now, and the gap is the rank's own
///    [`ORTHO_NODE_SEP`].
/// 2. `pull_back_fan_ranks`'s own column gaps: the room a frame's edge needs past its first member
///    column was *summed* over every block starting there, so two siblings reserved two heads' worth
///    of gap where the picture only ever shows one. Nesting sums (one frame really is beyond the
///    other); siblings take the maximum.
#[test]
fn orthogonal_sibling_frames_are_spaced_apart_and_reserve_one_column_gap() {
    let src = "flowchart TB\n  s --> a1\n  s --> b1\n                 subgraph A[A very very very very very very very very very long title]\n    a1\n                 end\n  subgraph B[B]\n    b1\n  end";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let (a, b) = (d.cluster("A").expect("A"), d.cluster("B").expect("B"));
    let (_, _, ar, _) = a.bounds();
    let (bl, _, _, _) = b.bounds();
    assert!(
        (bl - ar - super::ORTHO_NODE_SEP).abs() < 0.01,
        "two sibling frames must sit {}px apart, not {:.2}px (A ends at {ar:.2}, B starts at \
         {bl:.2})",
        super::ORTHO_NODE_SEP,
        bl - ar
    );

    // One column gap, not two: `s`'s own bottom to the frames' top is exactly `RANK_SEP`, and from
    // there to the member inside is that one frame's own head (its padding plus its title band).
    let s = d.node("s").expect("s");
    let (_, _, _, s_bottom) = s.bounds();
    for frame in [a, b] {
        let (_, ft, _, _) = frame.bounds();
        assert!(
            (ft - s_bottom - super::RANK_SEP).abs() < 0.01,
            "frame {} must start {}px below s (which ends at {s_bottom:.2}), not {:.2}px — a \
             sibling's own head must not be reserved twice",
            frame.id,
            super::RANK_SEP,
            ft - s_bottom
        );
    }
}

/// The same rule on the two design references it was found on: `zz-design-2b`/`2c`'s own
/// `API ゲート --> 認証基盤`, a four-rank branch whose direct column holds `メタデータ DB` and
/// whose flow column holds the `投入` trunk.
///
/// Two things are pinned, both of them the rule rather than the picture: the edge leaves through
/// whichever cross-axis face actually faces `認証基盤` (`2c`'s left, `2b`'s top — the axis flip is
/// why both are here), and its long lane keeps clear of every **frame** it does not itself belong
/// to. That second half is what makes `cross_lane_bends` read subgraph frames at all: without it
/// `2c`'s nearest free lane is the 24px gap *between* `メタデータ DB` and `成果物保管`, which draws
/// the line straight down the middle of `保存層`'s own rectangle.
#[test]
fn orthogonal_design_2b_2c_auth_edge_takes_a_free_lane_off_the_face_facing_it() {
    for name in ["zz-design-2b", "zz-design-2c"] {
        let (_, src) = orthogonal_design_reference_corpus()
            .into_iter()
            .find(|(n, _)| *n == name)
            .expect("design reference");
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let e = d
            .edges
            .iter()
            .find(|e| e.from == "API" && e.to == "ID")
            .expect("API -> ID must be routed");
        let api = d.node("API").expect("API");
        let id = d.node("ID").expect("ID");
        let (l, t, r, b) = api.bounds();
        let start = &e.points[0];
        // `2c` is TB, so the cross axis is horizontal and `ID` sits to the left; `2b` is LR, so it
        // is vertical and `ID` sits above. Either way: the face on the side the target is on.
        let leaves_towards = if name == "zz-design-2c" {
            (start.x - (l - orthogonal::PORT_INSET)).abs() < AXIS_EPS && id.center.x < api.center.x
        } else {
            (start.y - (t - orthogonal::PORT_INSET)).abs() < AXIS_EPS && id.center.y < api.center.y
        };
        assert!(
            leaves_towards,
            "{name}: API -> ID must leave the face facing 認証基盤, not {start:?} \
             (API {:?}, ID {:?}): {:?}",
            (l, t, r, b),
            id.bounds(),
            e.points
        );
        assert!(
            e.points.len() <= 5,
            "{name}: API -> ID must not need more than the rule's own four legs: {:?}",
            e.points
        );

        for c in &d.clusters {
            let (cl, ct, cr, cb) = c.bounds();
            let holds = |p: &crate::preview::mermaid::layout::Point| {
                p.x >= cl && p.x <= cr && p.y >= ct && p.y <= cb
            };
            if holds(&api.center) || holds(&id.center) {
                continue; // the frames this edge starts inside / ends inside are not obstacles
            }
            for w in e.points.windows(2) {
                let vertical = (w[0].x - w[1].x).abs() < AXIS_EPS;
                let (lane, lo, hi) = if vertical {
                    (w[0].x, cl, cr)
                } else {
                    (w[0].y, ct, cb)
                };
                let (run_lo, run_hi) = if vertical {
                    (w[0].y.min(w[1].y), w[0].y.max(w[1].y))
                } else {
                    (w[0].x.min(w[1].x), w[0].x.max(w[1].x))
                };
                let (frame_lo, frame_hi) = if vertical { (ct, cb) } else { (cl, cr) };
                if run_hi <= frame_lo || run_lo >= frame_hi {
                    continue; // this leg never reaches the frame's own extent along its own axis
                }
                assert!(
                    lane <= lo - orthogonal::PORT_CLEARANCE
                        || lane >= hi + orthogonal::PORT_CLEARANCE,
                    "{name}: API -> ID's leg at {lane:.2} runs inside the foreign frame {} \
                     {:?}: {:?}",
                    c.id,
                    c.bounds(),
                    e.points
                );
            }
        }
    }
}

/// The set of `(name, source, direction)` triples §10-5 round 5's own tier rule
/// (`orthogonal::place_dead_end_tiers`) is stated over: both design references, plus the same
/// shape reduced to a plain chain in each direction so nothing about the rule can be reading a
/// coincidence of those two particular pictures.
fn tier_cases() -> Vec<(
    &'static str,
    String,
    crate::preview::mermaid::flowchart::Direction,
)> {
    use crate::preview::mermaid::flowchart::Direction;
    let design = |name: &str| -> String {
        orthogonal_design_reference_corpus()
            .into_iter()
            .find(|(n, _)| *n == name)
            .unwrap_or_else(|| panic!("{name} is in the design-reference corpus"))
            .1
            .to_string()
    };
    // `A --> B --> C --> E` is the lane; `store` holds two dead ends fed from two *different*
    // nodes of it, which is `保存層`'s own shape with every incidental detail stripped out.
    let chain = |dir: &str| -> String {
        format!(
            "flowchart {dir}\n  A --> B\n  B --> C\n  C --> E\n  subgraph T[store]\n    t1\n    \
             t2\n  end\n  A --> t1\n  C --> t2"
        )
    };
    vec![
        (
            "zz-design-2b",
            design("zz-design-2b"),
            Direction::LeftToRight,
        ),
        (
            "zz-design-2c",
            design("zz-design-2c"),
            Direction::TopToBottom,
        ),
        ("chain-lr", chain("LR"), Direction::LeftToRight),
        ("chain-tb", chain("TB"), Direction::TopToBottom),
    ]
}

/// §10-5 round 5's own **tier** rule, stated on the finished picture
/// (`orthogonal::place_dead_end_tiers`'s own doc has the rule and the reference it comes from).
///
/// A block whose members are all dead ends, fed only from nodes of one straight lane, hangs off
/// that lane instead of taking a rank of its own: every member sits at its own first source's
/// **flow** coordinate, so that edge is a straight, zero-bend run across the flow, and the whole
/// shelf sits clear of the lane on one side of it.
///
/// `docs/render-check/zz-design-2b-browser.png` draws `メタデータ DB` directly under `API ゲート`
/// and `成果物保管` directly under `ジョブ実行系`; `2c` is the same rotated, the shelf to the
/// right. Before this rule the block took the rank after everything that fed it and all three of
/// its edges were long multi-bend runs back across the picture (measured: `API -> DB` 1 bend over
/// 714px of horizontal run, `W -> DB` 3 bends, `W -> AR` 2 bends).
///
/// Stated over the two design sources **and** the same shape reduced to a plain four-node chain in
/// both directions, so it cannot be passing by reading something particular to those pictures.
#[test]
fn orthogonal_a_dead_end_block_fed_from_one_lane_hangs_off_it_with_zero_bend_drops() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src, direction) in tier_cases() {
        let d = laid_out_flow(&src, "basis", "konoma-orthogonal");
        let node = |id: &str| -> &PlacedNode {
            d.nodes
                .iter()
                .find(|n| n.id == id)
                .unwrap_or_else(|| panic!("{name}: {id} is in the fixture"))
        };
        let (block, drops) = if name.starts_with("zz-design") {
            ("S", vec![("API", "DB"), ("W", "AR")])
        } else {
            ("T", vec![("A", "t1"), ("C", "t2")])
        };
        let lane_cross = super::cross_of(direction, node(drops[0].0));
        for (source, member) in &drops {
            let (s, m) = (node(source), node(member));
            assert!(
                (super::flow_of(direction, s) - super::flow_of(direction, m)).abs() < 0.5,
                "{name}: {member} must sit at {source}'s own flow coordinate, not {:.2} against \
                 {:.2}",
                super::flow_of(direction, m),
                super::flow_of(direction, s)
            );
            let e = d
                .edges
                .iter()
                .find(|e| e.from == *source && e.to == *member)
                .unwrap_or_else(|| panic!("{name}: {source} -> {member} must be routed"));
            assert_eq!(
                e.points.len(),
                2,
                "{name}: {source} -> {member} must be one straight drop, not {:?}",
                e.points
            );
        }
        // Every member on the same side of the lane, and every one of them clear of it.
        let side = (super::cross_of(direction, node(drops[0].1)) - lane_cross).signum();
        for (source, member) in &drops {
            let (s, m) = (node(source), node(member));
            let gap = side * (super::cross_of(direction, m) - lane_cross)
                - super::cross_extent_of(direction, m)
                - super::cross_extent_of(direction, s);
            assert!(
                gap >= super::ORTHO_NODE_SEP - 0.01,
                "{name}: {member} sits {gap:.2}px clear of the lane, less than one \
                 {}px separation",
                super::ORTHO_NODE_SEP
            );
        }
        // The shelf's own frame holds its members and nothing outside it overlaps them.
        let frame = d
            .cluster(block)
            .unwrap_or_else(|| panic!("{name}: {block} is drawn"));
        let (fl, ft, fr, fb) = frame.bounds();
        for (_, member) in &drops {
            let (ml, mt, mr, mb) = node(member).bounds();
            assert!(
                ml >= fl && mt >= ft && mr <= fr && mb <= fb,
                "{name}: {block}'s frame {:?} must hold {member} {:?}",
                frame.bounds(),
                node(member).bounds()
            );
        }
        let members: Vec<&str> = drops.iter().map(|(_, m)| *m).collect();
        for m in &members {
            let (ml, mt, mr, mb) = node(m).bounds();
            for other in &d.nodes {
                if members.contains(&other.id.as_str()) {
                    continue;
                }
                let (ol, ot, or, ob) = other.bounds();
                assert!(
                    ml >= or || or <= ol || mr <= ol || mb <= ot || mt >= ob,
                    "{name}: the tier member {m} {:?} overlaps {} {:?}",
                    node(m).bounds(),
                    other.id,
                    other.bounds()
                );
                let _ = (mt, ot, ob, ol, or);
            }
        }
    }
}

/// The tier rule's own scope, stated as the two things that stop it firing — both of them
/// consequences of what a tier *is* rather than extra conditions bolted on:
///
/// 1. **a member that is not a dead end**: the block is a stage of the flow, not a shelf beside
///    it, so it keeps its own rank;
/// 2. **only one source**: a block fed from a single lane node already has a natural column (the
///    rank after that node) and §10-3's own fan machinery already places it there with one bend.
///    The rule exists for a group fed from *several* points along the lane, which no single rank
///    can serve without long runs.
/// 3. **the lane runs through a member**: a shelf hangs *off* the spine and cannot also *be* part
///    of it — hanging the block off the side would take the trunk's own next node with it.
///    `zz-design-2b`/`2c`'s own `外部` is this case (`コード置き場` is the spine's last node), which
///    is why that block keeps a rank of its own while `保存層` does not.
/// 4. **a member whose only input is an aside**: an aside carries no ordering vote anywhere else
///    in this pipeline (`EdgeLabel::rank_only`, weight `0`) and is drawn on the perimeter rather
///    than as a drop, so it is not something a member can be placed under. `zz-design-2b`'s own
///    `決済ページ` is this case.
///
/// All four are stated the same way — the member does **not** end up at its source's own flow
/// coordinate, which is the one thing a tier would guarantee.
#[test]
fn orthogonal_a_block_that_is_not_a_shelf_is_never_made_a_tier() {
    if !text_metrics::fonts_available() {
        return;
    }
    let cases = [
        (
            "a member with an out-edge",
            "flowchart LR\n  A --> B\n  B --> C\n  C --> E\n  subgraph T[store]\n    t1\n    t2\n  \
             end\n  A --> t1\n  C --> t2\n  t2 --> E",
            "A",
            "t1",
        ),
        (
            "one source only",
            "flowchart LR\n  A --> B\n  B --> C\n  C --> E\n  subgraph T[store]\n    t1\n    t2\n  \
             end\n  A --> t1\n  A --> t2",
            "A",
            "t1",
        ),
        (
            // A back edge is still an out-edge, and it is the form that reaches this test on its
            // own merits: an ordinary forward out-edge usually makes the member a lane node too,
            // so condition 3 would have caught the block anyway and this one would never be read.
            "a member with a back edge out of it",
            "flowchart LR\n  A --> B\n  B --> C\n  C --> E\n  E --> F\n  subgraph T[store]\n    \
             t1\n    t2\n  end\n  A --> t1\n  C --> t2\n  t2 --> B",
            "A",
            "t1",
        ),
        (
            "the lane runs through a member",
            "flowchart LR\n  A --> B\n  B --> t1\n  subgraph T[store]\n    t1\n    t2\n  end\n  \
             A --> t2",
            "A",
            "t2",
        ),
        (
            "a member fed only by an aside",
            "flowchart LR\n  A --> B\n  B --> C\n  C --> E\n  subgraph T[store]\n    t1\n    t2\n  \
             end\n  A --> t1\n  C -.-> t2",
            "A",
            "t1",
        ),
    ];
    for (why, src, source, member) in cases {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let node = |id: &str| -> &PlacedNode {
            d.nodes
                .iter()
                .find(|n| n.id == id)
                .unwrap_or_else(|| panic!("{why}: {id} is in the fixture"))
        };
        assert!(
            (node(source).center.x - node(member).center.x).abs() > 0.5,
            "{why}: {member} must keep a column of its own, not sit in {source}'s at x={:.2}",
            node(member).center.x
        );
        if why == "the lane runs through a member" {
            assert!(
                (node("t1").center.y - node("A").center.y).abs() < 0.5,
                "{why}: the trunk's own next node must stay on the lane, not be hung off it at \
                 y={:.2} against the lane's {:.2}",
                node("t1").center.y,
                node("A").center.y
            );
        }
    }
}

/// Which side of the lane a tier takes: the one carrying **fewer other units** over the stretch of
/// lane it hangs off, positive (`LR` below / `TB` right) when the two tie —
/// `place_dead_end_tiers`'s own doc.
///
/// The design references are both the tie case (nothing else sits beside that stretch of their
/// spine at all), so the *other* branch needs a source of its own: one dead-end branch hanging
/// below the lane inside the tier's own span pushes the shelf to the other side.
#[test]
fn orthogonal_a_tier_takes_the_emptier_side_of_its_lane() {
    if !text_metrics::fonts_available() {
        return;
    }
    let src = "flowchart LR\n  A --> B\n  B --> C\n  C --> E\n  E --> F\n  B --> X\n  \
               subgraph T[store]\n    t1\n    t2\n  end\n  A --> t1\n  C --> t2";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let node = |id: &str| -> &PlacedNode {
        d.nodes
            .iter()
            .find(|n| n.id == id)
            .unwrap_or_else(|| panic!("{id} is in the fixture"))
    };
    let lane = node("A").center.y;
    assert!(
        node("X").center.y > lane,
        "the fixture only means anything with X below the lane: {:.2} vs {lane:.2}",
        node("X").center.y
    );
    for m in ["t1", "t2"] {
        assert!(
            node(m).center.y < lane,
            "{m} must take the side away from X, not sit at {:.2} beside it (lane {lane:.2})",
            node(m).center.y
        );
    }
    // …and it is still a tier: each member under its own source, zero bends.
    for (s, m) in [("A", "t1"), ("C", "t2")] {
        assert!(
            (node(s).center.x - node(m).center.x).abs() < 0.5,
            "{m} must still sit in {s}'s own column"
        );
    }
}

/// The tier's own "nothing on this side may overlap it" half, stated directly on
/// [`orthogonal::place_dead_end_tiers`] rather than through a whole diagram: an end-to-end fixture
/// cannot hold *both* sides of a lane occupied without also disturbing the lane itself (measured —
/// every attempt to give the lane a second branch either flipped the side or bent the lane, which
/// then correctly stops the rule firing at all), and the push is exactly the part those fixtures
/// therefore never reach.
///
/// One unit above the lane and one below, both inside the tier's own flow span: the sides tie, the
/// shelf takes the positive one, and it has to clear the occupant there by [`super::ORTHO_NODE_SEP`]
/// rather than landing on it.
#[test]
fn orthogonal_a_tier_is_pushed_past_whatever_already_occupies_its_band() {
    if !text_metrics::fonts_available() {
        return;
    }
    use crate::preview::mermaid::flowchart::Direction;
    let mut nodes = vec![
        placed_node("A", 100.0, 100.0, 60.0, 40.0),
        placed_node("B", 300.0, 100.0, 60.0, 40.0),
        placed_node("C", 500.0, 100.0, 60.0, 40.0),
        placed_node("X", 300.0, 200.0, 60.0, 40.0),
        placed_node("Y", 300.0, 20.0, 60.0, 40.0),
        placed_node("t1", 700.0, 100.0, 60.0, 40.0),
        placed_node("t2", 700.0, 160.0, 60.0, 40.0),
    ];
    let blocks = vec![super::SpecBlock {
        id: "T".to_string(),
        title: String::new(),
        members: vec!["t1".to_string(), "t2".to_string()],
        dashed: false,
    }];
    let ids: HashSet<String> = nodes.iter().map(|n| n.id.clone()).collect();
    let tree = clusters::Tree::from_blocks(&blocks, |id| ids.contains(id));
    let units = orthogonal::LaneUnits::build(&tree, &nodes);
    let chain_next: HashMap<String, String> = [("A", "B"), ("B", "C")]
        .into_iter()
        .map(|(a, b)| (a.to_string(), b.to_string()))
        .collect();
    let edges: Vec<(String, String, bool)> = [
        ("A", "B"),
        ("B", "C"),
        ("B", "X"),
        ("B", "Y"),
        ("A", "t1"),
        ("C", "t2"),
    ]
    .into_iter()
    .map(|(a, b)| (a.to_string(), b.to_string(), false))
    .collect();
    let tiers = orthogonal::place_dead_end_tiers(
        Direction::LeftToRight,
        &mut nodes,
        &tree,
        &units,
        &chain_next,
        &edges,
    );
    assert_eq!(
        tiers.len(),
        1,
        "the block must be recognised as one tier: {tiers:?}"
    );
    assert_eq!(tiers[0].side, 1.0, "the tie must take the positive side");
    let at = |id: &str| -> &PlacedNode { nodes.iter().find(|n| n.id == id).expect(id) };
    assert!(
        (at("t1").center.x - 100.0).abs() < 1e-6 && (at("t2").center.x - 500.0).abs() < 1e-6,
        "each member sits in its own first source's column: {:?}",
        nodes
            .iter()
            .map(|n| (n.id.as_str(), n.center.x, n.center.y))
            .collect::<Vec<_>>()
    );
    // X's own far edge is 220; a frame pad of `clusters::PAD` sits between the shelf's edge and
    // its members, so the nearest member's own top edge is 220 + ORTHO_NODE_SEP + PAD.
    let want = 220.0 + super::ORTHO_NODE_SEP + clusters::PAD + 20.0;
    for m in ["t1", "t2"] {
        assert!(
            (at(m).center.y - want).abs() < 1e-6,
            "{m} must clear X by one {}px separation plus the frame's own pad: {:.2}, want \
             {want:.2}",
            super::ORTHO_NODE_SEP,
            at(m).center.y
        );
    }
}

/// "One **straight** lane" is a geometric fact, not only a selection: the sources have to have
/// actually ended up on one shared cross coordinate. A chain member can be pushed off its own
/// chain average by `align_straight_lanes`'s own overlap sweep (that function's own doc on why its
/// selection and its geometry can disagree), and a shelf hung off a lane that is not straight has
/// no single coordinate to hang from — so the rule stands down and the block keeps its rank.
///
/// Stated directly on [`orthogonal::place_dead_end_tiers`], for the same reason the outward-push
/// test above is: an end-to-end source whose chain the sweep actually bends is not something a
/// fixture can ask for on demand.
#[test]
fn orthogonal_a_tier_needs_its_sources_on_one_straight_lane() {
    if !text_metrics::fonts_available() {
        return;
    }
    use crate::preview::mermaid::flowchart::Direction;
    let build = |c_cross: f64| -> Vec<PlacedNode> {
        vec![
            placed_node("A", 100.0, 100.0, 60.0, 40.0),
            placed_node("B", 300.0, 100.0, 60.0, 40.0),
            placed_node("C", 500.0, c_cross, 60.0, 40.0),
            placed_node("t1", 700.0, 100.0, 60.0, 40.0),
            placed_node("t2", 700.0, 160.0, 60.0, 40.0),
        ]
    };
    let blocks = vec![super::SpecBlock {
        id: "T".to_string(),
        title: String::new(),
        members: vec!["t1".to_string(), "t2".to_string()],
        dashed: false,
    }];
    let chain_next: HashMap<String, String> = [("A", "B"), ("B", "C")]
        .into_iter()
        .map(|(a, b)| (a.to_string(), b.to_string()))
        .collect();
    let edges: Vec<(String, String, bool)> = [("A", "B"), ("B", "C"), ("A", "t1"), ("C", "t2")]
        .into_iter()
        .map(|(a, b)| (a.to_string(), b.to_string(), false))
        .collect();
    for (why, c_cross, want) in [("straight", 100.0, 1), ("bent", 140.0, 0)] {
        let mut nodes = build(c_cross);
        let ids: HashSet<String> = nodes.iter().map(|n| n.id.clone()).collect();
        let tree = clusters::Tree::from_blocks(&blocks, |id| ids.contains(id));
        let units = orthogonal::LaneUnits::build(&tree, &nodes);
        let tiers = orthogonal::place_dead_end_tiers(
            Direction::LeftToRight,
            &mut nodes,
            &tree,
            &units,
            &chain_next,
            &edges,
        );
        assert_eq!(
            tiers.len(),
            want,
            "a {why} lane must yield {want} tier(s), not {tiers:?}"
        );
    }
}

/// §10-5 round 5's own label rule and §10-3 item 10's own merge mirror, both stated where they
/// were reported: the three-way merge into `API ゲート`.
///
/// The label half. `HTTPS` is a wide plate (~54px) on the middle sibling. Placed on that sibling's
/// *entry leg* — inside a corridor where §10-1 item 1 puts the three ports 16px apart — it covers
/// its two neighbours' legs, and `avoid_label_plates` then pushed their ports out from under it,
/// past each other, inverting item 1's own "もう一方の端点のcross座標順" and guaranteeing a crossing
/// (measured before the fix: `CLI`'s port stepped over *two* siblings). Two changes remove it —
/// the plate is chosen on a clear segment (`orthogonal::label_slot_clear`) and the nudge never
/// steps over a sibling (`orthogonal::push_outward`'s own doc).
///
/// The merge half (`docs/render-check/zz-design-2b-browser.png`, read against this output). The
/// three clients are a **pure merge** and none of them carries a through-lane, so
/// `orthogonal::merge_trunk_index`'s median clause picks the middle of the three *in declaration
/// order* — `UI`, exactly the source the design draws level with `API ゲート` — and `CLI` (above)
/// and `EX` (below) come in on the `±PORT_SPACING` ports either side of it. `align_straight_lanes`'s
/// own "タイは上・左優先" greedy used to hand the lane to `CLI`, the first-declared, which bent both
/// of the others in from the same side and grew `API ゲート` to 80px tall to fit three ports below
/// its own centre; `docs/STATUS.md`'s own ★未修正 entry reported it as the defect it is.
///
/// What this states, rather than either mechanism: three ports one `PORT_SPACING` apart in
/// **source order**, `UI`'s own edge dead straight while its two siblings each take the two bends
/// §10-1 item 1 allows a port-displaced edge ("退避則適用時は2回まで" — the design draws the same
/// out-across-in shape), and no two of the three crossing.
#[test]
fn orthogonal_design_2b_2c_the_merge_into_the_gate_keeps_its_port_order() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src, direction) in tier_cases()
        .into_iter()
        .filter(|(n, _, _)| n.starts_with("zz-design"))
    {
        let d = laid_out_flow(&src, "basis", "konoma-orthogonal");
        let legs: Vec<(&str, &PlacedEdge)> = ["CLI", "UI", "EX"]
            .iter()
            .map(|from| {
                (
                    *from,
                    d.edges
                        .iter()
                        .find(|e| e.from == *from && e.to == "API")
                        .unwrap_or_else(|| panic!("{name}: {from} -> API must be routed")),
                )
            })
            .collect();
        // The port coordinate on `API`'s own flow-axis face runs along the cross axis (`LR`'s
        // Left face varies in y, `TB`'s Top face in x), so this is the same reading in both.
        let ports: Vec<f64> = legs
            .iter()
            .map(|(_, e)| match direction {
                crate::preview::mermaid::flowchart::Direction::TopToBottom
                | crate::preview::mermaid::flowchart::Direction::BottomToTop => {
                    e.points[e.points.len() - 1].x
                }
                _ => e.points[e.points.len() - 1].y,
            })
            .collect();
        // Evenly spaced, ascending in source order, and a whole number of `PORT_SPACING` slots
        // apart — not necessarily *one* slot. §10-1 item 1 puts the grid at 16px, and §10-7's own
        // label rule is allowed to step a port one slot further out when a plate is in its way, so
        // long as it never steps over a sibling (`orthogonal::push_outward`). Both design
        // directions exercise one of those two cases: `2b`/`LR` takes one slot each side, while
        // `2c`/`TB` takes two, because there the `HTTPS` plate sits centred on the trunk's own
        // vertical line at exactly the `y` both siblings' cross legs run along (measured: plate
        // 360.7..414.6, the two legs stopping at 355.7 and 419.7). Pinning "exactly one slot"
        // would be pinning which direction the plate happens to land in, not the rule.
        let steps: Vec<f64> = ports.windows(2).map(|w| w[1] - w[0]).collect();
        for (i, &step) in steps.iter().enumerate() {
            let slots = (step / orthogonal::PORT_SPACING).round();
            assert!(
                slots >= 1.0 && (step - slots * orthogonal::PORT_SPACING).abs() < 0.01,
                "{name}: the merge's ports must be a whole ascending {}px step apart in source \
                 order (CLI, UI, EX), not {ports:?} — {} then {}",
                orthogonal::PORT_SPACING,
                legs[i].0,
                legs[i + 1].0
            );
        }
        assert!(
            (steps[0] - steps[1]).abs() < 0.01,
            "{name}: the two siblings straddle the trunk's own port symmetrically: {ports:?}"
        );
        let ui = legs[1].1;
        assert_eq!(
            ui.points.len(),
            2,
            "{name}: UI -> API is the merge's own trunk (the median source in declaration order) \
             and must be dead straight: {:?}",
            ui.points
        );
        let api = d.node("API").expect("API ゲート must exist");
        let api_cross = match direction {
            crate::preview::mermaid::flowchart::Direction::TopToBottom
            | crate::preview::mermaid::flowchart::Direction::BottomToTop => api.center.x,
            _ => api.center.y,
        };
        assert!(
            (ports[1] - api_cross).abs() < 0.01,
            "{name}: the trunk enters on API's own centre port, so its two siblings straddle it: \
             {ports:?} vs {api_cross}"
        );
        for (from, leg) in [legs[0], legs[2]] {
            assert_eq!(
                leg.points.len(),
                4,
                "{name}: {from} -> API is port-displaced, so §10-1 item 1 gives it two bends — out \
                 of its own face, across, and in: {:?}",
                leg.points
            );
        }
        for (i, (from_a, a)) in legs.iter().enumerate() {
            for (from_b, b) in legs.iter().skip(i + 1) {
                let crossing = a.points.windows(2).find_map(|wa| {
                    b.points
                        .windows(2)
                        .find_map(|wb| orthogonal::segment_crossing(wa, wb))
                });
                assert!(
                    crossing.is_none(),
                    "{name}: {from_a} -> API crosses {from_b} -> API at {crossing:?}: {:?} vs {:?}",
                    a.points,
                    b.points
                );
            }
        }
    }
}

#[test]
fn orthogonal_design_2b_2c_spine_runs_straight_through_the_sandbox() {
    if !text_metrics::fonts_available() {
        return;
    }
    // `2b`/`2c` by name: `2a` is a different graph, and `5b` (§10-8's own sizing artboard) is a
    // third — this test is about one specific spine in one specific pair of pictures.
    for (name, src) in orthogonal_design_reference_corpus()
        .into_iter()
        .filter(|(n, _)| *n == "zz-design-2b" || *n == "zz-design-2c")
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for (from, to) in [("API", "Q"), ("Q", "W"), ("W", "SB"), ("SB", "GIT")] {
            let e = d
                .edges
                .iter()
                .find(|e| e.from == from && e.to == to)
                .unwrap_or_else(|| panic!("{name}: {from}->{to} must exist"));
            assert_eq!(
                e.points.len(),
                2,
                "{name}: {from}->{to} is a spine segment — a straight 2-point line: {:?}",
                e.points
            );
        }
        // The two stores sit together, entirely to one side of the spine's own lane.
        let cross = |id: &str| {
            let n = d
                .node(id)
                .unwrap_or_else(|| panic!("{name}: {id} must exist"));
            match name {
                "zz-design-2b" => (n.center.y, n.size.h),
                _ => (n.center.x, n.size.w),
            }
        };
        let (lane, span) = cross("SB");
        for store in ["DB", "AR"] {
            let (c, store_span) = cross(store);
            assert!(
                (c - lane).abs() > (span + store_span) / 2.0,
                "{name}: {store} (at {c:.1}) must fan clear of the spine's own lane ({lane:.1})"
            );
        }
        let ((db, _), (ar, _)) = (cross("DB"), cross("AR"));
        assert_eq!(
            db < lane,
            ar < lane,
            "{name}: both 保存層 members belong on the same side of the spine — DB at {db:.1}, AR \
             at {ar:.1}, lane at {lane:.1}"
        );
    }
}

/// The same shape as the fixture above, hand-built and minimal: a branching node whose only
/// continuing branch leads *out of* the frame its dead-end siblings are in.
///
/// `C` continues (into `F`, which is a member of a *different* frame, so the branch that carries the
/// diagram on is one that crosses a cluster boundary — `zz-design-2c`'s own `解析サンドボックス →
/// コード置き場` in miniature), `D` and `E` do not and are the members of `store`. The trunk has to be
/// `C`, the trunk edge has to be straight, and `C` — which does not belong to `store` — must not be
/// laid out *between* `D` and `E`, because a frame is derived from wherever its members sit and `C`
/// would then be inside a frame it has nothing to do with.
#[test]
fn orthogonal_fan_keeps_a_frames_members_together_and_the_trunk_outside_it() {
    let src = "flowchart TB\n  A --> B\n  B --> C\n  B --> D\n  B --> E\n  C --> F\n  \
               subgraph S[store]\n    D\n    E\n  end\n  subgraph T[out]\n    F\n  end\n";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let bc = d
        .edges
        .iter()
        .find(|e| e.from == "B" && e.to == "C")
        .expect("B->C must exist");
    assert_eq!(
        bc.points.len(),
        2,
        "B->C is the trunk (C is the only branch that continues) — a straight line: {:?}",
        bc.points
    );
    let x = |id: &str| {
        d.node(id)
            .unwrap_or_else(|| panic!("{id} must exist"))
            .center
            .x
    };
    assert_eq!(
        x("D") < x("C"),
        x("E") < x("C"),
        "store's two members belong on the same side of C, which is not one of them: D={}, E={}, \
         C={}",
        x("D"),
        x("E"),
        x("C")
    );
    let frame = d.cluster("S").expect("the store frame must be placed");
    let (left, right) = (
        frame.center.x - frame.size.w / 2.0,
        frame.center.x + frame.size.w / 2.0,
    );
    let c = d.node("C").expect("C must exist");
    assert!(
        c.center.x + c.size.w / 2.0 < left || c.center.x - c.size.w / 2.0 > right,
        "C is not a member of store, so its box must sit clear of that frame ({left:.1}..{right:.1}): \
         C at {:.1} wide {:.1}",
        c.center.x,
        c.size.w
    );
}

/// [`super::fan_split`]'s own two-branch case again, this time with the branches *disagreeing*: the
/// dead end takes the positive cross side even when it was declared first, so the trunk still sits
/// on the continuity boundary rather than wherever declaration order left it.
///
/// `A` is written before `B` and neither carries a class, so the colour grouping hands `rest` over
/// as `[A, B]` — dead end first. Without the stable partition [`super::fan_split`] runs, the centre
/// split would put `A` *above* the trunk and the continuing `B` below it; with it, `A` is last. The
/// assertion is on `A` alone rather than on the whole order, because `T` and `B` both continue and
/// the trunk pick between two equally-continuing branches is `align_straight_lanes`'s own
/// coordinate tie-break, not this rule's — whichever of them wins, the dead end belongs after it.
#[test]
fn orthogonal_three_way_fan_orders_the_continuing_branch_ahead_of_the_dead_end() {
    let src = "flowchart LR\n  S --> A\n  S --> T\n  T --> D\n  S --> B\n  B --> Q\n";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let y = |id: &str| {
        d.node(id)
            .unwrap_or_else(|| panic!("{id} must exist"))
            .center
            .y
    };
    assert!(
        y("A") > y("T") && y("A") > y("B"),
        "A is the fan's only dead end, so it sits below both continuing branches however they were \
         declared: A.y={}, T.y={}, B.y={}",
        y("A"),
        y("T"),
        y("B")
    );
}

/// §10-3 item 2's own outside-in nesting (`3a`'s reference geometry, `orthogonal::route_fan_lane`'s
/// own doc), stated as the invariant it exists to buy: **no two fan-lane siblings on the same
/// source face ever cross each other's own segments** — not just "no node gets pierced" (the
/// pre-existing corpus invariants), a stronger, edge-vs-edge geometric claim only this fan region
/// can violate (an ordinary branch/merge pair never shares a face with more than one sibling).
///
/// Before the outside-in correction, the plain "step scales with distance from centre" formula drew
/// the *opposite* nesting: a sibling closer to the face's own centre got the *shallower* bend, so
/// its short stub sat inside a farther-out sibling's own bend lane and vice versa — on this exact
/// fixture (`設定のルール`'s ten-way fanout), `ページ描画`(`PD`, one step in from the centre on the
/// five-member half) and `一覧`(`AR`, two steps out) crossed: `AR`'s stub (`y=345.7`,
/// `x∈[319.75,359.75]`) sat inside the y-range of `PD`'s own vertical run (`y∈[308.3,361.7]`) at an
/// x (`327.75` under the old formula) still short of `PD`'s own bend depth — a real crossing, not a
/// hypothetical one, confirmed by hand against a dump of the pre-fix route before this test was
/// written. §10-3 item 5's "主辺どうしの交差は水平側が譲る" then fired on it, cutting a
/// [`orthogonal::CROSSING_GAP`]-px notch out of the horizontal stub — the "ファン根元のスタブが細切
/// れになる" symptom the user reported (`設定のルール` reads far busier than `3a`'s own reference).
/// The second half of this test (`gaps.is_empty()`) pins that the fix removes the crossing itself,
/// not just its visual symptom: once no two siblings cross, rule 5 never has anything to cut here.
#[test]
fn orthogonal_settings_rules_sample_fan_lane_siblings_never_cross() {
    let src = SETTINGS_RULES_SAMPLE;
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let fan: Vec<&PlacedEdge> = d.edges.iter().filter(|e| e.from == "C").collect();
    assert_eq!(
        fan.len(),
        10,
        "設定のルール's own ten-way fanout must still have all ten children: {:?}",
        fan.iter().map(|e| e.to.as_str()).collect::<Vec<_>>()
    );

    for e in &fan {
        assert!(
            e.gaps.is_empty(),
            "C->{}: a fan-lane sibling's own stub must never be cut by rule 5's crossing gap \
             (that only fires when two siblings actually cross) — gaps: {:?}, points: {:?}",
            e.to,
            e.gaps,
            e.points
        );
    }

    for i in 0..fan.len() {
        for j in (i + 1)..fan.len() {
            let (a, b) = (fan[i], fan[j]);
            for wa in a.points.windows(2) {
                for wb in b.points.windows(2) {
                    assert!(
                        orthogonal::segment_crossing(wa, wb).is_none(),
                        "C->{} crosses C->{}'s own segment ({:?}-{:?} vs {:?}-{:?}) — the two fan \
                         siblings' own routes must never cross: {} points={:?}, {} points={:?}",
                        a.to,
                        b.to,
                        wa[0],
                        wa[1],
                        wb[0],
                        wb[1],
                        a.to,
                        a.points,
                        b.to,
                        b.points
                    );
                }
            }
        }
    }
}

/// A minimal synthetic fixture with the same shape as [`orthogonal_settings_rules_sample_fan_lane_
/// siblings_never_cross`]'s own real-diagram pin, deliberately unbalanced (5 above the trunk, 4
/// below — `3a`'s own five-vs-four split, `MD` landing dead on `C`'s own centre line as the tenth,
/// aligned member) rather than a tidy symmetric fan, so this still exercises the "nest against the
/// *larger* half's own outer rank" rule (the per-face loop in `evict` builds this, `Eviction::
/// fan_step`'s own doc) a perfectly even fixture never would — the two closest-to-centre siblings on
/// *either* side of an unbalanced face (`MD` above, `B1` below) must bend to the identical depth,
/// the same "306 と 338 が同じ 348 を使う" behaviour `3a`'s own reference shows.
///
/// Every out-edge carries a label (`|ラベルA1|` etc): §10-1 item 3's own minimum-segment-length rule
/// is what gives real diagrams the flow-axis room a deep nested bend needs (`3a`'s own `設定のルー
/// ル`'s ten-way fanout has labels on every edge too) — without one, `C`'s ten unlabelled leaf
/// children all land at the bare `RANK_SEP` (50px) away, too close for the busiest half's deepest
/// bend (`PORT_CLEARANCE * (5 + 1)` = 48px) to clear before reaching the target, which trips
/// `route_fan_lane`'s own defensive "past the target" guard into its plain-midpoint fallback —
/// a real, if narrow, gap in that fallback's own no-crossing guarantee (`route_fan_lane`'s own doc:
/// the fallback is not built with §10-3's nesting in mind at all), but a different, already-
/// documented limitation from the one this test exists to pin, so the fixture is built to stay clear
/// of it rather than conflate the two.
#[test]
fn orthogonal_synthetic_ten_way_fan_lane_siblings_never_cross() {
    let src = "flowchart LR\n  Z --> C{cond}\n  \
               C -->|ラベルA1| A1\n  C -->|ラベルA2| A2\n  C -->|ラベルA3| A3\n  \
               C -->|ラベルA4| A4\n  C -->|ラベルA5| A5\n  \
               C -->|ラベルMD| MD\n  \
               C -->|ラベルB1| B1\n  C -->|ラベルB2| B2\n  C -->|ラベルB3| B3\n  C -->|ラベルB4| B4";
    let d = laid_out_flow(src, "basis", "konoma-orthogonal");
    let fan: Vec<&PlacedEdge> = d.edges.iter().filter(|e| e.from == "C").collect();
    assert_eq!(
        fan.len(),
        10,
        "C's own ten-way fanout: {:?}",
        fan.iter().map(|e| e.to.as_str()).collect::<Vec<_>>()
    );

    for e in &fan {
        assert!(
            e.gaps.is_empty(),
            "C->{}: no fan-lane sibling may carry a crossing gap: {:?}",
            e.to,
            e.gaps
        );
    }
    for i in 0..fan.len() {
        for j in (i + 1)..fan.len() {
            let (a, b) = (fan[i], fan[j]);
            for wa in a.points.windows(2) {
                for wb in b.points.windows(2) {
                    assert!(
                        orthogonal::segment_crossing(wa, wb).is_none(),
                        "C->{} crosses C->{}: {} points={:?}, {} points={:?}",
                        a.to,
                        b.to,
                        a.to,
                        a.points,
                        b.to,
                        b.points
                    );
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------------------------
// 15. `konoma-orthogonal`'s own palette (`docs/FEATURE-MERMAID-RENDERER.md` §10-1 item 5)
//
// The mode carries its own colours: `Theme::for_routing` answers `theme::KONOMA` for
// `Routing::Orthogonal` whatever `[ui] mermaid_theme` says, exactly the way `[ui] mermaid_curve`
// is already inert there. Three things have to hold, and each is stated separately below so a
// failure names which one broke:
//
//   1. the mode really does draw the reference's own tokens (`konoma_orthogonal_draws_…`);
//   2. `[ui] mermaid_theme` cannot change a byte of it (`…_theme_is_inert_…`);
//   3. none of it leaks into `"splines"`, which is every diagram konoma draws by default
//      (`…_palette_never_appears_under_splines`, plus the byte-exact hash sentinels below).
// ---------------------------------------------------------------------------------------------

/// FNV-1a over a string. A hand-rolled hash on purpose: `DefaultHasher` is explicitly not stable
/// across Rust releases, and a sentinel that changes when the toolchain does would be worse than
/// no sentinel at all.
pub(super) fn fnv1a(s: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in s.as_bytes() {
        h ^= *b as u64;
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// **The five `[ui] mermaid_theme` values still draw, byte for byte (once numbers are masked),
/// what they drew before this mode had a palette of its own** — under `"splines"`, over every
/// design-reference source. (`konoma_orthogonal_theme_is_inert` below is the `"konoma-orthogonal"`
/// counterpart; it asserts the five themes agree with each other rather than pinning a hash,
/// because that mode's own drawing is still meant to change on purpose.)
///
/// The golden corpus (`snapshots/`) already pins the splines byte stream for `CORPUS`, but it
/// pins one theme (`dark`); this is the other half — every theme, on the three sources the design
/// work actually moves.
///
/// **The hashes are over [`mask_numbers`]' output, not the raw SVG.** The raw-byte pins (taken at
/// `cb799eb`) broke on Linux CI in 2026-09 (`zz-design-2a/dark/splines` and its siblings): the SVG
/// embeds text-measured coordinates (label widths, wrap points), and Linux's font metrics differ
/// from macOS's, so the raw bytes legitimately differ per platform even though the renderer drew
/// the right thing — the same class of failure v0.28.3 hit in the size-fitting math. Masking
/// numbers keeps the sentinel's actual purpose (the orthogonal work must not touch the splines
/// path: structure, element order, colours, theme attributes) without depending on which platform
/// measured the text. Retaken on this machine 2026-09-06; must never move except for the source
/// itself changing, which is what happened on 2026-09-04: `2b`/`2c` had mistranscribed the design
/// SVG's own dashed aside as `CLI -.->|リンク| PAY` when the SVG (read again at
/// `docs/render-check/zz-design-2b-wrap.html`'s `M48,298 …` / `2c-wrap.html`'s `M482,96 …`, both
/// starting at `ブラウザ UI`'s own rect, not `CLI`'s) draws it from `UI`.
#[test]
fn design_reference_renders_are_byte_stable_per_theme() {
    if !text_metrics::fonts_available() {
        return;
    }
    // (source, theme, routing, FNV-1a of the *number-masked* SVG — see `mask_numbers` — taken on
    // this machine 2026-09-06). Masked, not raw: the raw-byte pins taken at `cb799eb` broke on
    // Linux CI (`zz-design-2a/dark/splines` and friends) because the SVG embeds text-measured
    // coordinates and Linux's font metrics differ from macOS's — the same class of failure v0.28.3
    // hit in the size-fitting math. Masking numbers keeps this sentinel's actual purpose (the
    // orthogonal work must not touch the splines path: structure, element order, colours, theme
    // attributes) without depending on which platform measured the text.
    let pinned: &[(&str, &str, &str, u64)] = &[
        ("zz-design-2a", "dark", "splines", 9110428218121198712),
        ("zz-design-2a", "light", "splines", 1747022079689348468),
        ("zz-design-2a", "classic", "splines", 17535052580463923218),
        ("zz-design-2a", "forest", "splines", 5950500633807246803),
        ("zz-design-2a", "neutral", "splines", 14524817129397963293),
        ("zz-design-2b", "dark", "splines", 6588218898948304090),
        ("zz-design-2b", "light", "splines", 14137538367644989869),
        ("zz-design-2b", "classic", "splines", 9166285881318630382),
        ("zz-design-2b", "forest", "splines", 14858083956717915971),
        ("zz-design-2b", "neutral", "splines", 12216959023177415803),
        ("zz-design-2c", "dark", "splines", 6588218898948304090),
        ("zz-design-2c", "light", "splines", 14137538367644989869),
        ("zz-design-2c", "classic", "splines", 9166285881318630382),
        ("zz-design-2c", "forest", "splines", 14858083956717915971),
        ("zz-design-2c", "neutral", "splines", 12216959023177415803),
    ];
    let corpus = orthogonal_design_reference_corpus();
    for (name, theme_name, routing, want) in pinned {
        let (_, src) = corpus
            .iter()
            .find(|(n, _)| n == name)
            .unwrap_or_else(|| panic!("{name} must still be in the design corpus"));
        let svg = render_flow(src, theme_name, "basis", routing).expect("renders");
        let masked = mask_numbers(&svg);
        assert_eq!(
            fnv1a(&masked),
            *want,
            "{name}/{theme_name}/{routing} is no longer byte-identical (number-masked) to its \
             pinned render"
        );
    }
}

/// `[ui] mermaid_theme` is **inert** under `konoma-orthogonal`: all five values draw the same
/// bytes, because the mode answers the palette question itself ([`Theme::for_routing`]).
///
/// Asserted as "all five agree" *and* as "that agreed drawing is not what any of them draws under
/// splines", so a bug that made the mode fall back to `dark` — which would also make all five
/// agree — cannot pass.
#[test]
fn konoma_orthogonal_theme_is_inert() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_design_reference_corpus() {
        let base = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("renders");
        for theme_name in ["light", "modern", "classic", "mermaid", "forest", "neutral"] {
            let other =
                render_flow(src, theme_name, "basis", "konoma-orthogonal").expect("renders");
            assert_eq!(
                base, other,
                "{name}: mermaid_theme={theme_name} changed a konoma-orthogonal render, which the \
                 mode is supposed to ignore entirely"
            );
        }
        // Not vacuous: the agreed drawing really is the orthogonal palette and not a fallback to
        // `dark`. `node_stroke` is the colour to ask about — every source here has at least one
        // uncoloured node, and none of them writes that hex in a `classDef` of its own (unlike
        // `node_fill`, which `2b`/`2c` do write).
        assert!(
            base.contains(theme::KONOMA.node_stroke),
            "{name}: an orthogonal render must draw the palette's own outline colour: {base}"
        );
        let dark_splines = render_flow(src, "dark", "basis", "splines").expect("renders");
        assert!(
            !dark_splines.contains(theme::KONOMA.node_stroke),
            "{name}: this comparison is only meaningful if the orthogonal palette is not simply \
             the dark theme"
        );
    }
}

/// Nothing of the orthogonal palette reaches `"splines"` — the default every diagram konoma draws
/// is untouched. The complement of [`konoma_orthogonal_draws_the_design_reference_look`]: that one
/// says the colours are all there under orthogonal, this one says not one of them is there
/// without it.
#[test]
fn konoma_palette_never_appears_under_splines() {
    if !text_metrics::fonts_available() {
        return;
    }
    let palette = [
        theme::KONOMA.background_ref,
        theme::KONOMA.node_fill,
        theme::KONOMA.node_stroke,
        theme::KONOMA.node_text,
        theme::KONOMA.cluster_stroke,
        theme::KONOMA.cluster_text,
        theme::KONOMA_TOKENS.composite_stroke,
        theme::KONOMA_TOKENS.composite_rule,
    ];
    for (name, src) in orthogonal_design_reference_corpus() {
        for theme_name in ["dark", "light", "classic", "forest", "neutral"] {
            let svg = render_flow(src, theme_name, "basis", "splines").expect("renders");
            for colour in palette {
                // `2a`/`2b`/`2c` write some of these hexes in their own `classDef`/`style`, and a
                // source's own declaration is drawn under every routing — so what is checked is
                // that the *palette* did not add one, not that the byte is absent.
                let from_source = src.contains(colour);
                assert!(
                    from_source || !svg.contains(colour),
                    "{name}/{theme_name} under splines drew {colour}, which only the orthogonal \
                     palette should ever produce"
                );
            }
        }
    }
}

/// **The design reference's own tokens, on the pictures the design drew** — every flowchart
/// design-reference source under `konoma-orthogonal`, checked against
/// `docs/render-check/zz-design-{2a,2b,2c}-wrap.html`.
///
/// One test rather than a dozen: each assertion below names its own token, and every one of them
/// is a property of the same render, so splitting them would mean re-rendering the corpus a dozen
/// times for no extra signal.
#[test]
fn konoma_orthogonal_draws_the_design_reference_look() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_design_reference_corpus() {
        let svg = render_flow(src, "dark", "basis", "konoma-orthogonal").expect("renders");

        // 1. No mermaid-palette colour survives anywhere: `dark`'s node fill, its outline, and its
        //    subgraph fill are the three that would show up first if the mode fell back.
        for stale in ["#2b2b38", "#1f2020", "#cccccc", "#d3d3d3", "#8a8a8a"] {
            assert!(
                !svg.contains(stale),
                "{name}: {stale} is a mermaid-theme colour and must not appear: {svg}"
            );
        }

        // 2. Frames: no fill, 1px `#484f58`, dashed 4,3 — `zz-design-2a-wrap.html`'s own
        //    `<rect … fill="none" stroke="#484f58" stroke-width="1" stroke-dasharray="4,3">`.
        for line in svg.lines() {
            if !line.starts_with("<rect") || !line.contains("stroke=") {
                continue;
            }
            if !line.contains("stroke=\"#484f58\"") {
                continue;
            }
            assert!(
                line.contains("fill=\"none\"")
                    && line.contains("stroke-width=\"1\"")
                    && line.contains("stroke-dasharray=\"4,3\"")
                    && line.contains("rx=\"3\""),
                "{name}: a subgraph frame must be an unfilled 1px 4,3-dashed rx=3 outline: {line}"
            );
        }
        let frames = svg
            .lines()
            .filter(|l| l.starts_with("<rect") && l.contains("stroke=\"#484f58\""))
            .count();
        assert_eq!(
            frames > 0,
            src.contains("subgraph"),
            "{name}: a source with a subgraph must draw a frame, and one without must not"
        );

        // 3. Nodes: `#161b22` (or a tint of the class colour), rx 3, 1.5px outline.
        let node_rects: Vec<&str> = svg
            .lines()
            .filter(|l| l.starts_with("<rect") && l.contains("stroke-width=\"1.5\""))
            .collect();
        assert!(!node_rects.is_empty(), "{name}: no node rectangles at all");
        for line in &node_rects {
            assert!(
                line.contains("rx=\"3\"") && line.contains("ry=\"3\""),
                "{name}: a node box must have the reference's 3px corner: {line}"
            );
            let fill = attr(line, "fill").expect("a node rect has a fill");
            assert!(
                fill == theme::KONOMA.node_fill || fill.starts_with('#'),
                "{name}: a node fill must be the palette's or a literal colour: {line}"
            );
        }

        // 4. Text: the body at 14, an edge label at the reference's 11, a subgraph title at 12.
        assert!(
            svg.contains("font-size=\"14\""),
            "{name}: body text must stay at the measured size: {svg}"
        );
        if svg.contains("<g class=\"edge-labels\">\n<") {
            assert!(
                svg.contains("font-size=\"11\""),
                "{name}: an edge label must be drawn at the reference's 11px: {svg}"
            );
        }
        assert_eq!(
            svg.contains("font-size=\"12\""),
            src.contains("subgraph"),
            "{name}: a subgraph title is drawn at 12px, and a source with no subgraph draws none: \
             {svg}"
        );

        // 5. "辺・矢尻・ラベル文字を同色で揃える": every edge's arrow head is filled with the
        //    line's own stroke, and its label is written in it too. Read straight out of the
        //    emitted markup, because that is where a mismatch would show.
        let mut last_stroke: Option<&str> = None;
        for line in svg.lines() {
            if line.starts_with("<path") && line.contains("stroke=") {
                last_stroke = attr(line, "stroke");
            } else if line.starts_with("<polygon") && line.contains("fill=") {
                let Some(stroke) = last_stroke else { continue };
                // A node's own outline is a polygon too (a chamfered decision box); those carry a
                // `stroke` of their own, an arrow head never does.
                if line.contains("stroke=") {
                    continue;
                }
                assert_eq!(
                    attr(line, "fill"),
                    Some(stroke),
                    "{name}: an arrow head must be filled with its own line's colour: {line}"
                );
            }
        }

        // 6. A class-coloured node's outline is the class colour the source wrote, and the edge
        //    flowing into it is that colour one step lighter (§10-3 item 6) — so the two are
        //    always the same hue, which is what the reference's colour coding depends on.
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let mut checked = 0;
        for e in &d.edges {
            let Some(target) = d.node(&e.to) else {
                continue;
            };
            let Some(target_stroke) = target.style.as_ref().and_then(|s| s.stroke.as_deref())
            else {
                continue;
            };
            let Some(line) = e.style.as_ref().and_then(|s| s.stroke.as_deref()) else {
                continue;
            };
            let Some(lightened) = super::style::lighten(target_stroke) else {
                continue;
            };
            // Only when the source did not colour this edge itself — a `linkStyle` is the more
            // specific instruction and wins over the derivation.
            if src.contains("linkStyle") {
                continue;
            }
            assert_eq!(
                line, lightened,
                "{name}: edge {}->{} must draw its target's own {target_stroke}, one step \
                 lighter",
                e.from, e.to
            );
            checked += 1;
        }
        // Only a source that actually declares a class can have a class-coloured edge — `5b` is
        // §10-8's sizing artboard and is deliberately monochrome, like the artboard it comes from.
        if !src.contains("linkStyle") && src.contains("classDef") {
            assert!(
                checked > 0,
                "{name}: no class-coloured edge was checked — the comparison is vacuous"
            );
        }
    }
}

/// [`super::aside_weight`]'s own truth table, stated directly rather than only through the two
/// layout tests below: the zero weight is for an **author-dotted** edge under **`konoma-
/// orthogonal`** and nothing else. Every other stroke, and every stroke at all under
/// `Routing::Splines`, keeps `EdgeLabel`'s own default — which is what makes the default rendering
/// of every diagram kind byte-identical (§10-2) rather than merely "probably unchanged".
#[test]
fn orthogonal_only_a_dotted_edge_is_an_aside_for_dagre() {
    let default = crate::preview::mermaid::layout::EdgeLabel::default().weight;
    assert_eq!(
        super::aside_weight(Routing::Orthogonal, Stroke::Dotted),
        0,
        "a dotted edge under konoma-orthogonal is the aside the perimeter lane is for"
    );
    for stroke in [
        Stroke::Normal,
        Stroke::Thick,
        Stroke::Invisible,
        Stroke::Invalid,
    ] {
        assert_eq!(
            super::aside_weight(Routing::Orthogonal, stroke),
            default,
            "{stroke:?} is not an aside — only the author's own dotted line marks one"
        );
    }
    for stroke in [
        Stroke::Normal,
        Stroke::Thick,
        Stroke::Dotted,
        Stroke::Invisible,
        Stroke::Invalid,
    ] {
        assert_eq!(
            super::aside_weight(Routing::Splines, stroke),
            default,
            "{stroke:?} under splines keeps dagre's own default weight"
        );
    }
}

/// The design rule [`super::aside_weight`] exists to state, checked on the finished layout rather
/// than on the weight it hands dagre: **an aside does not decide where the flow's own nodes go.**
///
/// Stated as "no two nodes that share a rank swap places when the aside is added" — the strongest
/// form that is actually true, and the one that names the user-visible defect. The defect was
/// found when `zz-design-2b`/`2c` were still mistranscribed as `CLI -.->|リンク| PAY` (`CLI` being
/// the client row's *first* declared sibling): with that aside weighted like a flow edge the three
/// clients came out `EX, UI, CLI` instead of `CLI, UI, EX`, so `CLI` ended up at the far side of
/// its own frame with its edge into `API ゲート` climbing back across `ブラウザ UI`'s. The corrected
/// source (`UI -.->|リンク| PAY` — `UI` is the *middle* sibling, verified against
/// `docs/render-check/zz-design-2b-wrap.html`'s own SVG) does not reproduce that reorder even
/// hypothetically weighted like a flow edge (re-measured after the fix: `CLI, UI, EX` either way,
/// on both `2b` and `2c`), which is exactly why the general shape still needs its own fixture —
/// see `orthogonal-dotted-aside-merge` below, kept independent of which sibling either design
/// reference happens to use. Nodes that do *not* share a rank are deliberately out of scope:
/// `zz-design-2c`'s own `ブラウザ UI` (rank 1) and `決済ページ` (rank 17) do trade places on the
/// cross axis, which is not a reordering of anything — they were never comparable.
///
/// The pair is built by deleting the one `-.->` line from each source, with the count asserted, so
/// the design-reference sources stay single-sourced and cannot drift away from the pictures in
/// `docs/render-check/`.
///
/// What this does **not** claim is that the two layouts are identical — only that no rank is
/// reordered. How *wide* a rank comes out is the second half of the same design rule and is stated
/// separately, by [`orthogonal_a_dotted_aside_leaves_its_source_stack_at_one_node_pitch`]: an aside
/// used to still span its ranks as a dummy chain, which `parentDummyChains` parents into the
/// source's own frame and which then has to sit outside every wider sibling frame, stretching the
/// frame until the position phase could spread its members (69.4px pitch without the aside,
/// 114.5/190.2px with it, measured on `2b` before `EdgeLabel::rank_only` existed).
#[test]
fn orthogonal_a_dotted_aside_does_not_reorder_a_rank() {
    use crate::preview::mermaid::flowchart::Direction;

    if !text_metrics::fonts_available() {
        return;
    }
    let design = orthogonal_design_reference_corpus();
    let named = |name: &str| -> &'static str {
        design
            .iter()
            .find(|(n, _)| *n == name)
            .unwrap_or_else(|| panic!("{name} is in the design-reference corpus"))
            .1
    };
    let cases: [(&str, &str, Direction); 3] = [
        (
            "orthogonal-dotted-aside-merge",
            dotted_aside_merge_source(),
            Direction::LeftToRight,
        ),
        (
            "zz-design-2b",
            named("zz-design-2b"),
            Direction::LeftToRight,
        ),
        (
            "zz-design-2c",
            named("zz-design-2c"),
            Direction::TopToBottom,
        ),
    ];
    for (name, src, direction) in cases {
        let kept: Vec<&str> = src.lines().filter(|l| !l.contains("-.->")).collect();
        assert_eq!(
            src.lines().count() - kept.len(),
            1,
            "{name}: the pair is built by deleting exactly one dotted line"
        );
        let without = laid_out_flow(&kept.join("\n"), "basis", "konoma-orthogonal");
        let with = laid_out_flow(src, "basis", "konoma-orthogonal");
        let cross: HashMap<&str, f64> = with
            .nodes
            .iter()
            .map(|n| (n.id.as_str(), super::cross_of(direction, n)))
            .collect();
        let mut ranks: HashMap<i64, Vec<&PlacedNode>> = HashMap::new();
        for n in &without.nodes {
            // A rank is a shared flow-axis centre. Keyed off the aside-free layout, which is the
            // one this rule measures the other against; both layouts agree on every flow-axis
            // coordinate, so the grouping is the same either way.
            ranks
                .entry((super::flow_of(direction, n) * 100.0).round() as i64)
                .or_default()
                .push(n);
        }
        let mut checked = 0usize;
        for members in ranks.values() {
            if members.len() < 2 {
                continue;
            }
            let mut order: Vec<&PlacedNode> = members.clone();
            order.sort_by(|a, b| {
                super::cross_of(direction, a)
                    .partial_cmp(&super::cross_of(direction, b))
                    .expect("a placed centre is never NaN")
            });
            for pair in order.windows(2) {
                let (lo, hi) = (pair[0].id.as_str(), pair[1].id.as_str());
                let (Some(&a), Some(&b)) = (cross.get(lo), cross.get(hi)) else {
                    continue;
                };
                assert!(
                    a < b,
                    "{name}: adding the aside swapped {lo} and {hi}, which share a rank — \
                     without it {lo} comes first, with it {lo} is at {a:.2} and {hi} at {b:.2}"
                );
                checked += 1;
            }
        }
        assert!(
            checked >= 2,
            "{name}: no same-rank pair was compared — the check is vacuous"
        );
    }
}

/// The picture the rule above buys, on the cluster-free fixture where nothing else is in play
/// (`orthogonal-dotted-aside-merge`): the three merge siblings stay stacked one node pitch apart
/// in declaration order, and their three edges land on three distinct, evenly spaced ports of the
/// target's own entry face in that same order, none crossing another.
///
/// The pitch bound is the layout's own — the tallest of the three plus [`super::ORTHO_NODE_SEP`],
/// which is exactly what dagre's position phase leaves between two neighbours on one rank when
/// nothing pulls them apart. With the aside weighted like a flow edge `A` is dragged past `B`
/// instead (`orthogonal_a_dotted_aside_does_not_reorder_a_rank` states that half), so the port
/// order below is the half that says the *merge* still reads correctly afterwards.
#[test]
fn orthogonal_dotted_aside_leaves_its_merge_siblings_evenly_stacked() {
    use crate::preview::mermaid::flowchart::Direction;

    if !text_metrics::fonts_available() {
        return;
    }
    let d = laid_out_flow(dotted_aside_merge_source(), "basis", "konoma-orthogonal");
    let node = |id: &str| -> &PlacedNode {
        d.nodes
            .iter()
            .find(|n| n.id == id)
            .unwrap_or_else(|| panic!("{id} is in the fixture"))
    };
    let sources = ["A", "B", "C"].map(node);
    let pitch = sources.iter().map(|n| n.size.h).fold(0.0_f64, f64::max) + super::ORTHO_NODE_SEP;
    for pair in sources.windows(2) {
        let gap = super::cross_of(Direction::LeftToRight, pair[1])
            - super::cross_of(Direction::LeftToRight, pair[0]);
        assert!(
            gap > 0.0 && gap <= pitch + 0.01,
            "{} and {} are {gap:.2}px apart on the cross axis, more than one {pitch:.2}px \
             node pitch — the merge siblings are no longer a stack",
            pair[0].id,
            pair[1].id
        );
    }

    let merge = node("M");
    let face = merge.center.x - merge.size.w / 2.0;
    let mut ports: Vec<(&str, f64)> = Vec::new();
    for from in ["A", "B", "C"] {
        let e = d
            .edges
            .iter()
            .find(|e| e.from == from && e.to == "M")
            .unwrap_or_else(|| panic!("{from} -> M is in the fixture"));
        let end = e.points.last().expect("a routed edge has points");
        assert!(
            (end.x - face).abs() <= orthogonal::PORT_INSET + 0.01,
            "{from} -> M ends at x={:.2}, not on M's own left face at x={face:.2}",
            end.x
        );
        ports.push((from, end.y));
    }
    for (i, (from, y)) in ports.iter().enumerate() {
        for (other, other_y) in ports.iter().skip(i + 1) {
            assert!(
                (y - other_y).abs() >= orthogonal::PORT_SPACING - 0.01,
                "{from} and {other} share a port on M's left face ({y:.2} vs {other_y:.2})"
            );
        }
    }
    assert!(
        ports.windows(2).all(|p| p[0].1 < p[1].1),
        "the ports on M's left face are not in the sources' own cross-axis order: {ports:?}"
    );
    let routed = |from: &str| -> &PlacedEdge {
        d.edges
            .iter()
            .find(|e| e.from == from && e.to == "M")
            .expect("checked above")
    };
    for (i, from) in ["A", "B", "C"].iter().enumerate() {
        for other in ["A", "B", "C"].iter().skip(i + 1) {
            assert!(
                !orthogonal::polylines_cross(&routed(from).points, &routed(other).points),
                "{from} -> M crosses {other} -> M"
            );
        }
    }
}

/// §10-3 item 10's own hop nesting, stated as the ordering rule rather than only as "nothing
/// crossed" (`orthogonal_merge_sibling_hops_never_cross_or_coincide_across_corpus` states that
/// half): among merge siblings whose sources **share a rank**, the hop row nearest the target
/// belongs to the sibling whose hop leg has to travel furthest along the cross axis.
///
/// This is what `orthogonal::nest_merge_target_hops`'s own `Candidate::span` tie-break decides,
/// and it only ever has to decide it for a shared rank — siblings at different ranks are already
/// separated by `max_reach`, which the widest leg has no claim over (a nearer source with a wide
/// leg must still not be pushed past its own facing wall, `Candidate::max_reach`'s own doc). So
/// the invariant is scoped exactly the way the tie-break is, and reads the finished polylines
/// rather than any of that pass's internal numbers.
#[test]
fn orthogonal_merge_hops_from_one_rank_nest_widest_leg_first() {
    use crate::preview::mermaid::flowchart::Direction;

    if !text_metrics::fonts_available() {
        return;
    }
    let mut checked = 0usize;
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let direction = if src.contains("LR") || src.contains("RL") {
            Direction::LeftToRight
        } else {
            Direction::TopToBottom
        };
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let by_id: HashMap<&str, &PlacedNode> =
            d.nodes.iter().map(|n| (n.id.as_str(), n)).collect();
        let mut out_degree: HashMap<&str, usize> = HashMap::new();
        for e in &d.edges {
            *out_degree.entry(e.from.as_str()).or_insert(0) += 1;
        }
        let mut by_target: HashMap<&str, Vec<&PlacedEdge>> = HashMap::new();
        for e in &d.edges {
            // The same scope `orthogonal::is_merge_hop_candidate` itself has: a genuine merge
            // sibling, drawn as the four-point "out, across, in" hop this rule is about.
            if e.stroke == Stroke::Invisible
                || out_degree.get(e.from.as_str()).copied().unwrap_or(0) > 1
                || e.points.len() != 4
            {
                continue;
            }
            by_target.entry(e.to.as_str()).or_default().push(e);
        }
        for (target, merge) in by_target {
            let Some(&target_node) = by_id.get(target) else {
                continue;
            };
            // Flow-axis distance from the target's own centre out to the hop row, and cross-axis
            // width of the leg that runs along it — both read straight off the polyline.
            let leg = |e: &PlacedEdge| -> Option<(f64, f64, f64)> {
                let src_flow = super::flow_of(direction, by_id.get(e.from.as_str())?);
                let hop = &e.points[1];
                let (hop_flow, hop_cross) = match direction {
                    Direction::TopToBottom | Direction::BottomToTop => (hop.y, hop.x),
                    Direction::LeftToRight | Direction::RightToLeft => (hop.x, hop.y),
                };
                let tgt_flow = super::flow_of(direction, target_node);
                let span = (hop_cross
                    - match direction {
                        Direction::TopToBottom | Direction::BottomToTop => e.points[2].x,
                        Direction::LeftToRight | Direction::RightToLeft => e.points[2].y,
                    })
                .abs();
                Some((src_flow, (tgt_flow - hop_flow).abs(), span))
            };
            for i in 0..merge.len() {
                for j in (i + 1)..merge.len() {
                    let (Some(a), Some(b)) = (leg(merge[i]), leg(merge[j])) else {
                        continue;
                    };
                    // Same rank only, and only when the two legs are genuinely different widths —
                    // two siblings whose legs match have nothing to nest.
                    if (a.0 - b.0).abs() > 0.01 || (a.2 - b.2).abs() <= 0.01 {
                        continue;
                    }
                    let (wide, narrow) = if a.2 > b.2 { (a, b) } else { (b, a) };
                    assert!(
                        wide.1 <= narrow.1 + 0.01,
                        "{name}: into {target}, the {:.2}px-wide hop leg sits {:.2}px from the \
                         target while the narrower {:.2}px leg sits {:.2}px — the wide leg has to \
                         be the one nearest the target or the two cross",
                        wide.2,
                        wide.1,
                        narrow.2,
                        narrow.1
                    );
                    checked += 1;
                }
            }
        }
    }
    assert!(
        checked > 0,
        "no same-rank merge siblings with differing leg widths were compared — the check is vacuous"
    );
}

// ---------------------------------------------------------------------------------------------
// §10-1 item 4, both halves: an aside constrains ranks and nothing else (`super::is_aside` /
// `EdgeLabel::rank_only`), and it is drawn on the outer perimeter lane whichever way it points
// (`orthogonal::classify`'s own `aside` branch).
// ---------------------------------------------------------------------------------------------

/// The four sources that carry an author-dotted aside, paired with the direction they are laid out
/// in and the merge stack the aside leaves from — the two synthetic fixtures
/// ([`orthogonal_only_corpus`]'s own `orthogonal-dotted-aside-merge` and its framed `TB` sibling)
/// and the two design references that produced the rule.
fn dotted_aside_cases() -> Vec<(
    &'static str,
    &'static str,
    crate::preview::mermaid::flowchart::Direction,
    [&'static str; 3],
)> {
    use crate::preview::mermaid::flowchart::Direction;
    let named = |list: Vec<(&'static str, &'static str)>, name: &str| -> &'static str {
        list.iter()
            .find(|(n, _)| *n == name)
            .unwrap_or_else(|| panic!("{name} is in the corpus"))
            .1
    };
    vec![
        (
            "orthogonal-dotted-aside-merge",
            named(orthogonal_only_corpus(), "orthogonal-dotted-aside-merge"),
            Direction::LeftToRight,
            ["A", "B", "C"],
        ),
        (
            "orthogonal-dotted-aside-merge-tb",
            named(orthogonal_only_corpus(), "orthogonal-dotted-aside-merge-tb"),
            Direction::TopToBottom,
            ["A", "B", "C"],
        ),
        (
            "zz-design-2b",
            named(orthogonal_design_reference_corpus(), "zz-design-2b"),
            Direction::LeftToRight,
            ["CLI", "UI", "EX"],
        ),
        (
            "zz-design-2c",
            named(orthogonal_design_reference_corpus(), "zz-design-2c"),
            Direction::TopToBottom,
            ["CLI", "UI", "EX"],
        ),
        // A stack of three siblings all feeding one hub, with the aside leaving the **middle**
        // one, so its way out of the row has to pass a sibling's leg on whichever side it takes.
        // Added 2026-09-04 to keep the crossing-gap machinery covered by a two-line diagram of its
        // own rather than by whichever design direction happened to reproduce a crossing that
        // week; renamed 2026-09-05 (it used to be `…-crosses-a-sibling-leg-…`) because it no
        // longer crosses one: with nothing feeding the row from the other side, the aside now
        // leaves the row the *free* way and goes round, which is §10-0's own preference and what
        // the crossing term added that day is for. It stays in the list as the case that states
        // exactly that — a middle sibling's aside gets out without cutting anything — while
        // `orthogonal-aside-must-cross-a-leg-lr` (`orthogonal_only_corpus`, the same shape with the
        // row fed from both sides) carries the crossing the gap rule needs.
        (
            "orthogonal-aside-off-a-middle-sibling-lr",
            "flowchart LR\n  subgraph S[row]\n    A\n    B\n    D\n  end\n  A --> H\n  B --> H\n  D --> H\n  H --> Z\n  B -.-> Z",
            Direction::LeftToRight,
            ["A", "B", "D"],
        ),
        (
            "orthogonal-aside-off-a-middle-sibling-tb",
            "flowchart TB\n  subgraph S[row]\n    A\n    B\n    D\n  end\n  A --> H\n  B --> H\n  D --> H\n  H --> Z\n  B -.-> Z",
            Direction::TopToBottom,
            ["A", "B", "D"],
        ),
        (
            "orthogonal-aside-must-cross-a-leg-lr",
            named(orthogonal_only_corpus(), "orthogonal-aside-must-cross-a-leg-lr"),
            Direction::LeftToRight,
            ["A", "B", "D"],
        ),
    ]
}

/// §10-1 item 4's **layout** half, stated on the finished picture: a rank an aside leaves from is
/// no wider for the aside being there.
///
/// `super::aside_weight` (weight `0`) alone was not enough, and the gap it left is what this
/// states. An aside still spans its ranks, so — until `EdgeLabel::rank_only` — `normalize` built it
/// a dummy chain that occupied a lane in every rank in between; `parent_dummy_chains` parents a
/// dummy whose rank falls inside a cluster's own span into that cluster, that lane then has to sit
/// outside every wider sibling frame, and the frame it was parented into stretches to hold it,
/// which gives `position::bk` room to spread the members. Measured on `zz-design-2b`: the three
/// clients came out **114.5 and 190.2px** apart where one node pitch is 69.4.
///
/// The bound is the layout's own — the widest member's own cross-axis size plus
/// [`super::ORTHO_NODE_SEP`], which is what dagre's position phase leaves between two neighbours on
/// one rank when nothing pulls them apart — never a recorded coordinate, so this cannot pass by
/// being re-recorded. Runs over the framed fixtures as well as the plain one: the cluster-free
/// `orthogonal-dotted-aside-merge` already stacked correctly under weight `0` alone, so a test that
/// only saw it would have said the defect was fixed when it was not.
#[test]
fn orthogonal_a_dotted_aside_leaves_its_source_stack_at_one_node_pitch() {
    use crate::preview::mermaid::flowchart::Direction;
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src, direction, stack) in dotted_aside_cases() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let node = |id: &str| -> &PlacedNode {
            d.nodes
                .iter()
                .find(|n| n.id == id)
                .unwrap_or_else(|| panic!("{name}: {id} is in the fixture"))
        };
        let members = stack.map(node);
        let cross_size = |n: &PlacedNode| match direction {
            Direction::TopToBottom | Direction::BottomToTop => n.size.w,
            Direction::LeftToRight | Direction::RightToLeft => n.size.h,
        };
        for pair in members.windows(2) {
            // One pitch is the two neighbours' own half-sizes plus the separation dagre keeps
            // between them; the widest member's full size is the same quantity rounded up, which
            // is the form the pre-existing sibling test already uses.
            let pitch = cross_size(pair[0]).max(cross_size(pair[1])) + super::ORTHO_NODE_SEP;
            let gap = super::cross_of(direction, pair[1]) - super::cross_of(direction, pair[0]);
            assert!(
                gap > 0.0 && gap <= pitch + 0.01,
                "{name}: {} and {} sit {gap:.2}px apart on the cross axis, more than one \
                 {pitch:.2}px node pitch — the aside is still spreading the rank it leaves",
                pair[0].id,
                pair[1].id
            );
        }
    }
}

/// The half of §10-1 item 4's layout rule that says why the aside is lifted out **after** ranking
/// rather than never handed to dagre at all: a target nothing else reaches would otherwise have no
/// in-edge, and dagre's own ranking would put it at rank 0 — *upstream* of the source that links
/// to it (`super::aside_weight`'s own doc records the same measurement for the rejected "drop it
/// entirely" variant).
///
/// Stated on the flow axis of the finished picture rather than on a rank number, so it holds
/// whatever `pull_back_fan_ranks` afterwards does with the ranks: an aside's target is never
/// upstream of its source. `zz-design-2b`/`2c`'s own `決済ページ` is reached by the dotted
/// `UI -.->|リンク| PAY` and by nothing else at all, which is exactly the shape at issue; the
/// third case states it on a two-line diagram where nothing else could possibly be holding the
/// target in place.
#[test]
fn orthogonal_an_aside_only_target_still_ranks_after_its_source() {
    use crate::preview::mermaid::flowchart::Direction;
    if !text_metrics::fonts_available() {
        return;
    }
    let design = orthogonal_design_reference_corpus();
    let named = |name: &str| -> &'static str {
        design
            .iter()
            .find(|(n, _)| *n == name)
            .unwrap_or_else(|| panic!("{name} is in the design-reference corpus"))
            .1
    };
    let cases: [(&str, &str, Direction, &str, &str); 4] = [
        (
            "bare-lr",
            "flowchart LR\n  A --> B\n  A -.-> D",
            Direction::LeftToRight,
            "A",
            "D",
        ),
        (
            "bare-tb",
            "flowchart TB\n  A --> B\n  A -.-> D",
            Direction::TopToBottom,
            "A",
            "D",
        ),
        (
            "zz-design-2b",
            named("zz-design-2b"),
            Direction::LeftToRight,
            "UI",
            "PAY",
        ),
        (
            "zz-design-2c",
            named("zz-design-2c"),
            Direction::TopToBottom,
            "UI",
            "PAY",
        ),
    ];
    for (name, src, direction, source, target) in cases {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let node = |id: &str| -> &PlacedNode {
            d.nodes
                .iter()
                .find(|n| n.id == id)
                .unwrap_or_else(|| panic!("{name}: {id} is in the fixture"))
        };
        let (s, t) = (
            super::flow_of(direction, node(source)),
            super::flow_of(direction, node(target)),
        );
        assert!(
            t > s + 0.01,
            "{name}: the aside's target {target} sits at flow {t:.2}, not downstream of its \
             source {source} at {s:.2} — the aside stopped being a ranking constraint"
        );
    }
}

/// The content box every node and every frame of `d` fits in — what [`orthogonal::PERIMETER_MARGIN`]
/// is measured out from, recomputed here from the finished picture rather than asked of the router.
fn diagram_content_box(d: &Diagram) -> (f64, f64, f64, f64) {
    let (mut l, mut t, mut r, mut b) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
    for (nl, nt, nr, nb) in d
        .nodes
        .iter()
        .map(|n| n.bounds())
        .chain(d.clusters.iter().map(|c| c.bounds()))
    {
        l = l.min(nl);
        t = t.min(nt);
        r = r.max(nr);
        b = b.max(nb);
    }
    (l, t, r, b)
}

/// Whether `e` is one of the lines drawn **on the perimeter ring** — read off the finished picture:
/// the ring is [`orthogonal::PERIMETER_MARGIN`] px outside the content box, so a rider is exactly a
/// line with a vertex out there. A self-loop is excluded, the same way `orthogonal::routes_last`
/// excludes it: it is `reverse` but is drawn locally, and is main flow as far as anything crossing
/// it is concerned.
fn rides_the_ring(e: &PlacedEdge, (l, t, r, b): (f64, f64, f64, f64)) -> bool {
    e.from != e.to
        && e.points.iter().any(|p| {
            p.x <= l - orthogonal::PERIMETER_MARGIN + 0.01
                || p.y <= t - orthogonal::PERIMETER_MARGIN + 0.01
                || p.x >= r + orthogonal::PERIMETER_MARGIN - 0.01
                || p.y >= b + orthogonal::PERIMETER_MARGIN - 0.01
        })
}

/// How many segments of `polylines` the line `pts` crosses, through the same
/// [`orthogonal::segment_crossing`] the router itself counts with (so a shared port or a
/// T-junction — a touch, not a crossing — is not one here either).
fn crossings_against(pts: &[Point], polylines: &[Vec<Point>]) -> usize {
    pts.windows(2)
        .map(|a| {
            polylines
                .iter()
                .flat_map(|o| o.windows(2))
                .filter(|b| orthogonal::segment_crossing(a, b).is_some())
                .count()
        })
        .sum()
}

/// §10-1 item 4's **routing** half: "戻り辺・補助辺は破線で外周レーンを回す…外周レーンは最も外側の枠
/// から16px以上外に置く", as §10-5 round 5 narrowed it — an author-dotted edge whose direct route
/// would **cut through the picture** leaves the content box by at least
/// [`orthogonal::PERIMETER_MARGIN`] px somewhere along its run, and gets there in no more corners
/// than the design's own drawing of it uses; one with nothing at all between its two ends stays a
/// plain, local line instead.
///
/// Before item 4's routing half existed, [`orthogonal::route_perimeter`] was reached only by a
/// *reverse* edge, so a forward aside stayed on dagre's own waypoint chain and was drawn straight
/// through the middle of the picture the design takes round the outside — `zz-design-2b`'s own
/// `UI -.->|リンク| PAY` ran the full 1301px width of the diagram between two frames. The
/// narrowing is the opposite error, found on `CORPUS`'s own `strokes`: `B -.-> C`, two adjacent
/// boxes on one row with nothing between them, was sent round the outside and came back a two-bend
/// hop where a straight two-point line reaches (§10-0 — a rule is adopted if it makes lines
/// simpler).
///
/// Which of the two an aside is, is decided here from the finished picture — *is anything at all
/// inside the rectangle its two ends span* — rather than by asking the implementation
/// (`orthogonal::aside_route_stays_local`), so the two are independent statements of the same rule
/// rather than the implementation agreeing with itself. The content box is recomputed here from the
/// diagram's own nodes and frames for the same reason. Four bends is the design's own worst case
/// (`zz-design-2c`: down, along, down, in) — `2a` draws two and `2b` three.
#[test]
fn orthogonal_every_aside_rides_the_outer_perimeter_lane() {
    if !text_metrics::fonts_available() {
        return;
    }
    let mut checked = 0usize;
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let (l, t, r, b) = diagram_content_box(&d);
        for e in &d.edges {
            if e.stroke != Stroke::Dotted || e.from == e.to {
                continue;
            }
            checked += 1;
            let outside = rides_the_ring(e, (l, t, r, b));
            // Is there anything at all between the two ends? Restated here from the finished
            // picture: the rectangle the two boxes span, against every other node box and every
            // frame that does not hold both of them.
            let node_of = |id: &str| {
                d.nodes
                    .iter()
                    .find(|n| n.id == id)
                    .unwrap_or_else(|| panic!("{name}: {id} is a node"))
            };
            let (sl, st, sr, sb) = node_of(&e.from).bounds();
            let (tl, tt, tr, tb) = node_of(&e.to).bounds();
            let span = (sl.min(tl), st.min(tt), sr.max(tr), sb.max(tb));
            let clear = |(nl, nt, nr, nb): (f64, f64, f64, f64)| {
                nl >= span.2 || nr <= span.0 || nt >= span.3 || nb <= span.1
            };
            let holds = |(fl, ft, fr, fb): (f64, f64, f64, f64), n: &PlacedNode| {
                n.center.x >= fl && n.center.x <= fr && n.center.y >= ft && n.center.y <= fb
            };
            let nothing_between = d
                .nodes
                .iter()
                .all(|n| n.id == e.from || n.id == e.to || clear(n.bounds()))
                && d.clusters.iter().all(|c| {
                    let bounds = c.bounds();
                    (holds(bounds, node_of(&e.from)) && holds(bounds, node_of(&e.to)))
                        || clear(bounds)
                });
            if nothing_between {
                assert!(
                    !outside && e.points.len() <= 3,
                    "{name}: the aside {}->{} has nothing between its two ends and must stay a \
                     plain local line, not take the perimeter: {:?}",
                    e.from,
                    e.to,
                    e.points
                );
                continue;
            }
            assert!(
                outside,
                "{name}: the aside {}->{} never reaches the perimeter lane — no vertex sits \
                 {}px outside the content box ({l:.2},{t:.2})-({r:.2},{b:.2}): {:?}",
                e.from,
                e.to,
                orthogonal::PERIMETER_MARGIN,
                e.points
            );
            let bends = e.points.len().saturating_sub(2);
            assert!(
                bends <= 4,
                "{name}: the aside {}->{} takes {bends} corners to get round the outside, more \
                 than the design's own worst case of 4: {:?}",
                e.from,
                e.to,
                e.points
            );
        }
    }
    assert!(
        checked >= 5,
        "only {checked} asides were checked — the corpus lost its dotted edges and the check is \
         vacuous"
    );
}

/// §10-1 item 4's own "跨ぐ側の線に12pxの隙間を開ける", for the newest member of the perimeter
/// family: where a **forward** aside crosses another edge, the aside is the side that is cut, and
/// exactly [`orthogonal::CROSSING_GAP`] px of its own arc length is left undrawn.
///
/// By arc length along the whole polyline, never straight-line distance between the gap's two
/// endpoints — `orthogonal_crossing_gaps_cut_the_horizontal_side_of_each_crossing`'s own doc has
/// the Linux-CI regression that distinction exists to catch.
#[test]
fn orthogonal_a_forward_aside_carries_the_crossing_gaps() {
    if !text_metrics::fonts_available() {
        return;
    }
    let mut checked = 0usize;
    for (name, src, _, _) in dotted_aside_cases() {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for e in &d.edges {
            if e.stroke != Stroke::Dotted || e.from == e.to {
                continue;
            }
            // Every crossing this aside actually makes against another edge, counted from the
            // finished geometry — the aside must carry at least that many gaps of its own.
            let crossings = d
                .edges
                .iter()
                .filter(|o| !std::ptr::eq(*o, e))
                .flat_map(|o| {
                    e.points.windows(2).flat_map(move |a| {
                        o.points
                            .windows(2)
                            .filter_map(move |b| orthogonal::segment_crossing(a, b))
                    })
                })
                .count();
            assert_eq!(
                e.gaps.len(),
                crossings,
                "{name}: the aside {}->{} crosses {crossings} other edge segments but carries \
                 {} gaps — the perimeter side is the one that has to be cut: {:?}",
                e.from,
                e.to,
                e.gaps.len(),
                e.points
            );
            for (g0, g1) in &e.gaps {
                let arc = edges::arc_length_between(&e.points, g0, g1).unwrap_or_else(|| {
                    panic!(
                        "{name}: the aside {}->{}'s gap {g0:?}-{g1:?} is not on its own \
                         segments {:?}",
                        e.from, e.to, e.points
                    )
                });
                assert!(
                    (arc - orthogonal::CROSSING_GAP).abs() < 1e-6,
                    "{name}: the aside {}->{}'s gap removes {arc:.3}px of arc length, not \
                     {}px",
                    e.from,
                    e.to,
                    orthogonal::CROSSING_GAP
                );
                checked += 1;
            }
        }
    }
    assert!(
        checked > 0,
        "no forward aside crossed anything — the check is vacuous"
    );
}

/// §10-0 ("線が複雑にならないこと — 交差は遠回りより悪い"), stated over the whole orthogonal corpus
/// for the lines [`orthogonal::perimeter_faces`] decides: **an aside on the perimeter ring never
/// crosses more main-flow lines than the best of its sixteen candidate face pairs would have.**
///
/// The two halves are measured differently on purpose. The left-hand side is the *drawn* line — the
/// polyline in the finished diagram, crossings counted against every line that is not itself on the
/// ring — so a route that picked the right faces and then lost them to eviction, a local detour or a
/// label plate is still caught. The right-hand side is `orthogonal::fewest_perimeter_crossings`, the
/// router's own candidate table, so "could it have done better" is answered by scoring the fifteen
/// pairs it did not take rather than by a second, hand-rolled idea of what the alternatives were.
///
/// Scoped to asides, which is exactly the set of riders `perimeter_faces` chooses faces for: a
/// genuine **back edge** on the same ring takes its two faces from dagre's own waypoint chain
/// (`classify`'s `is_reverse` branch calls `dominant_face`, never `perimeter_faces`), so there is no
/// candidate table to hold it to and this says nothing about it.
#[test]
fn invariant_orthogonal_aside_crosses_no_more_than_the_best_face_pair_could() {
    if !text_metrics::fonts_available() {
        return;
    }
    let mut checked = 0usize;
    let mut with_a_crossing = 0usize;
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let content = diagram_content_box(&d);
        let main_flow: Vec<Vec<Point>> = d
            .edges
            .iter()
            .filter(|e| !rides_the_ring(e, content))
            .map(|e| e.points.clone())
            .collect();
        for e in &d.edges {
            if e.stroke != Stroke::Dotted || !rides_the_ring(e, content) {
                continue;
            }
            let node_of = |id: &str| {
                d.nodes
                    .iter()
                    .find(|n| n.id == id)
                    .unwrap_or_else(|| panic!("{name}: {id} is a node"))
            };
            let drawn = crossings_against(&e.points, &main_flow);
            let best = orthogonal::fewest_perimeter_crossings(
                node_of(&e.from),
                node_of(&e.to),
                &d.nodes,
                &d.clusters,
                &main_flow,
            );
            assert!(
                drawn <= best,
                "{name}: the aside {}->{} crosses {drawn} main-flow segments, but a face pair \
                 crossing only {best} was available — §10-0 makes a crossing worse than any \
                 detour: {:?}",
                e.from,
                e.to,
                e.points
            );
            checked += 1;
            with_a_crossing += usize::from(drawn > 0);
        }
    }
    assert!(
        checked >= 6,
        "only {checked} perimeter-riding asides were checked — the corpus lost its dotted edges \
         and the check is vacuous"
    );
    // Without a fixture whose every face pair crosses something, `drawn <= best` would hold for the
    // trivial reason that both sides are always 0, and the ranking could be deleted without this
    // test noticing (`orthogonal-aside-must-cross-a-leg-lr` is that fixture, and its own comment
    // says why it exists).
    assert!(
        with_a_crossing > 0,
        "no corpus aside crosses anything at all — `drawn <= best` is then vacuously true whatever \
         `perimeter_faces` ranks by"
    );
}

/// The defect the crossing term was added for (2026-09-05), pinned on the two design references
/// that showed it: `zz-design-2b`/`2c`'s own `UI -.->|リンク| PAY` leaves ブラウザ UI, goes round,
/// and **crosses nothing at all**.
///
/// Before the term, `2b`'s aside left ブラウザ UI's Right face — the short way, two corners — and
/// cut straight through `エディタ拡張 --> API` (one gapped crossing); `2c`'s cut a sibling's leg the
/// same way. The design draws neither: it takes the aside out of the picture's own body, which is
/// §10-1 item 4's whole reason for the perimeter lane.
///
/// Stated as "zero crossings against the whole rest of the diagram", not as a face name or a
/// coordinate: which face is free depends on where dagre puts the row, and pinning `Left` here
/// would fail for a layout that is just as correct. The corpus-wide sibling of this test
/// (`invariant_orthogonal_aside_crosses_no_more_than_the_best_face_pair_could`) is what states the
/// general rule; this one states that these two particular pictures actually reach zero.
#[test]
fn orthogonal_the_design_reference_asides_cross_nothing() {
    if !text_metrics::fonts_available() {
        return;
    }
    for name in ["zz-design-2a", "zz-design-2b", "zz-design-2c"] {
        let src = orthogonal_design_reference_corpus()
            .into_iter()
            .find(|(n, _)| *n == name)
            .unwrap_or_else(|| panic!("{name} is in the design-reference corpus"))
            .1;
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let others: Vec<Vec<Point>> = d
            .edges
            .iter()
            .filter(|e| e.stroke != Stroke::Dotted)
            .map(|e| e.points.clone())
            .collect();
        let mut asides = 0usize;
        for e in &d.edges {
            if e.stroke != Stroke::Dotted || e.from == e.to {
                continue;
            }
            asides += 1;
            assert_eq!(
                crossings_against(&e.points, &others),
                0,
                "{name}: the aside {}->{} must reach {} without crossing a single main-flow \
                 line — §10-0's own 交差は遠回りより悪い: {:?}",
                e.from,
                e.to,
                e.to,
                e.points
            );
        }
        assert_eq!(asides, 1, "{name} carries exactly one author-dotted aside");
    }
}

/// §10-3's own 8px nested-lane pitch, stated over the whole corpus for the shape
/// [`orthogonal::nest_merge_target_hops`] owns: two merge siblings' own hop legs never run
/// alongside each other closer than [`orthogonal::PORT_CLEARANCE`] px.
///
/// The sibling invariant next to this one
/// (`orthogonal_merge_sibling_hops_never_cross_or_coincide_across_corpus`) asks whether two routes
/// ever *meet*; this asks whether they ever fail to separate, which is a different question and
/// the one `zz-design-2b` failed: `ブラウザ UI`'s and `エディタ拡張`'s hops into `API ゲート` came
/// out **2.53px** apart and ran alongside each other for 37.4px, reading as one thick line. They
/// never touch, so nothing that asks about meeting could see it.
///
/// Scoped to the four-point "out, across, in" hop — `points.len() == 4` — which is exactly the
/// shape whose middle segment `nest_merge_target_hops` is free to move, and therefore exactly the
/// crowding it can be asked to fix. Two legs that do not overlap along the cross axis are not
/// running alongside each other at all and are out of scope by construction.
#[test]
fn orthogonal_merge_hop_legs_stay_eight_px_apart_across_the_corpus() {
    use crate::preview::mermaid::flowchart::Direction;
    if !text_metrics::fonts_available() {
        return;
    }
    let mut checked = 0usize;
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
        .chain([("settings-rules-sample", SETTINGS_RULES_SAMPLE)])
    {
        let direction = if src.contains("LR") || src.contains("RL") {
            Direction::LeftToRight
        } else {
            Direction::TopToBottom
        };
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        let mut by_target: HashMap<&str, Vec<&PlacedEdge>> = HashMap::new();
        for e in &d.edges {
            if e.stroke == Stroke::Invisible || e.points.len() != 4 {
                continue;
            }
            by_target.entry(e.to.as_str()).or_default().push(e);
        }
        // The hop leg is the middle segment: its flow coordinate is the lane, its cross span is
        // how much of the corridor it occupies.
        let leg = |e: &PlacedEdge| -> (f64, f64, f64) {
            let (a, b) = (&e.points[1], &e.points[2]);
            let (lo, hi) = match direction {
                Direction::TopToBottom | Direction::BottomToTop => (a.x.min(b.x), a.x.max(b.x)),
                Direction::LeftToRight | Direction::RightToLeft => (a.y.min(b.y), a.y.max(b.y)),
            };
            let lane = match direction {
                Direction::TopToBottom | Direction::BottomToTop => a.y,
                Direction::LeftToRight | Direction::RightToLeft => a.x,
            };
            (lane, lo, hi)
        };
        for (target, merge) in by_target {
            for i in 0..merge.len() {
                for j in (i + 1)..merge.len() {
                    let (a, b) = (leg(merge[i]), leg(merge[j]));
                    // Only legs that genuinely run alongside each other.
                    if a.1.max(b.1) >= a.2.min(b.2) - 1e-6 {
                        continue;
                    }
                    checked += 1;
                    assert!(
                        (a.0 - b.0).abs() >= orthogonal::PORT_CLEARANCE - 1e-6,
                        "{name}: {}->{target} and {}->{target} run their hop legs {:.2}px apart \
                         over an overlapping stretch — §10-3's nested lanes are {}px: {:?} / {:?}",
                        merge[i].from,
                        merge[j].from,
                        (a.0 - b.0).abs(),
                        orthogonal::PORT_CLEARANCE,
                        merge[i].points,
                        merge[j].points
                    );
                }
            }
        }
    }
    assert!(
        checked > 0,
        "no two merge hop legs overlapped anywhere in the corpus — the check is vacuous"
    );
}

/// The vendored engine's own half of §10-1 item 4, tested against `layout()` directly rather than
/// through a diagram: an [`crate::preview::mermaid::layout::EdgeLabel::rank_only`] edge holds its
/// `minlen` through the rank phase and then leaves the graph before `normalize`, so it builds no
/// dummy chain, occupies no lane in the ranks it spans, and comes back as the plain two-point
/// border-to-border line an edge with no waypoints always gets.
///
/// `dummy_chains` is the graph label field `normalize::run` writes and `normalize::undo` reads —
/// one entry per long edge it split — so "did this edge become a chain" is answerable directly
/// rather than inferred from geometry. `A -> D` spans three ranks, which is exactly the shape that
/// produces one.
///
/// The second half is why the lift happens *after* ranking rather than instead of it: `Z` has no
/// in-edge but the rank-only one, and still ranks below `A`. Drop the edge before `rank::rank` and
/// `Z` falls to rank 0, above the node that links to it.
#[test]
fn rank_only_edges_hold_their_ranks_and_build_no_dummy_chain() {
    use crate::preview::mermaid::layout::graph::{Graph, GraphOptions};
    use crate::preview::mermaid::layout::{
        layout, EdgeLabel, GraphLabel, LayoutOptions, NodeLabel,
    };

    let build = |rank_only: bool| -> Graph<NodeLabel, EdgeLabel> {
        let mut g: Graph<NodeLabel, EdgeLabel> = Graph::with_options(GraphOptions {
            directed: true,
            multigraph: true,
            compound: false,
        });
        for id in ["A", "B", "C", "D", "Z"] {
            g.set_node(
                id.to_string(),
                Some(NodeLabel {
                    width: 40.0,
                    height: 20.0,
                    ..NodeLabel::default()
                }),
            );
        }
        for (v, w) in [("A", "B"), ("B", "C"), ("C", "D")] {
            g.set_edge(v, w, Some(EdgeLabel::default()), None);
        }
        // The long edge, and the one whose target nothing else reaches.
        for (v, w, minlen) in [("A", "D", 3), ("A", "Z", 2)] {
            g.set_edge(
                v,
                w,
                Some(EdgeLabel {
                    minlen,
                    rank_only,
                    ..EdgeLabel::default()
                }),
                None,
            );
        }
        layout(&mut g, Some(LayoutOptions::default()));
        g
    };

    let plain = build(false);
    let lifted = build(true);

    let chains = |g: &Graph<NodeLabel, EdgeLabel>| {
        g.graph_label::<GraphLabel>()
            .map(|gl| gl.dummy_chains.len())
            .unwrap_or(0)
    };
    // Every edge here spans more than one rank once `make_space_for_edge_labels` has doubled every
    // `minlen`, so the three `A-B-C-D` chain edges each produce a chain of their own either way;
    // what the flag has to remove is exactly the two long edges' chains, no more and no fewer.
    assert_eq!(
        chains(&plain),
        5,
        "the fixture must produce one chain per edge without the flag, or it proves nothing"
    );
    assert_eq!(
        chains(&lifted),
        3,
        "a rank-only edge must never be normalised into a dummy chain, and must not stop any          other edge from being"
    );

    // Every edge handed in comes back, and the lifted ones carry exactly the two border points
    // `assign_node_intersects` gives an edge with no waypoints of its own.
    // `Graph::edges()`, not `edge_count()`: the cached counter drifts through `normalize`'s own
    // add/remove churn in the vendored engine (measured: 3 for the unflagged graph, 6 for the
    // flagged one, both of which really hold the same five edges), and nothing in the pipeline
    // reads it — the descriptor list is the honest answer.
    assert_eq!(
        lifted.edges(),
        plain.edges(),
        "a rank-only edge must come back under the exact key it was handed in under"
    );
    for (v, w) in [("A", "D"), ("A", "Z")] {
        let points = &lifted.edge(v, w, None).expect("the edge comes back").points;
        assert_eq!(
            points.len(),
            2,
            "{v}->{w} must be a plain two-point line for konoma to route itself: {points:?}"
        );
    }

    // The ranking constraint is still in force, both for a node the flow also reaches (`D`, held
    // three ranks below `A` by the long edge alongside the `A-B-C-D` chain) and for one only the
    // rank-only edge reaches at all (`Z`).
    let rank = |g: &Graph<NodeLabel, EdgeLabel>, id: &str| {
        g.node(id)
            .and_then(|n| n.rank)
            .expect("every node is ranked")
    };
    // Ranks are counted in dagre's own doubled units — `make_space_for_edge_labels` doubles every
    // `minlen` so a labelled edge has a rank of its own to put its label in — so `minlen: 3` holds
    // `D` six ranks below `A`, and `minlen: 2` holds `Z` four.
    assert_eq!(rank(&lifted, "D"), rank(&lifted, "A") + 6);
    assert_eq!(
        rank(&lifted, "Z"),
        rank(&lifted, "A") + 4,
        "Z ranks at {} against A's {} — a rank-only edge must still hold its own minlen, and it          is the only thing ranking Z at all",
        rank(&lifted, "Z"),
        rank(&lifted, "A")
    );
}

// =============================================================================================
// §10-8: node sizing under `konoma-orthogonal`
// =============================================================================================
//
// `docs/FEATURE-MERMAID-RENDERER.md` §10-8 (original: `docs/mermaid-theme/handoff/round5-Konoma-
// Flowchart-Routing.dc.html`, sections 5a and 5b). The 5b artboard is a set of worked examples
// drawn at 100%, which is exactly a set of assertions, so it is transcribed as one below and the
// rules it is drawn from are stated separately over the corpus.

/// The four worked examples 5b draws at 100%, each to the exact pixel.
///
/// These are the acceptance test for N1 and N2 and are written from the artboard's own numbers,
/// not from what the implementation produces: 「表」's box is `<rect width="96" height="36">`,
/// 「ブロックモデル」's is `144x36` (annotated "7 字 = 98px+40px = 138px → 144"), and the decision
/// node's polygon spans `x=24..168` by `y=330..366` — 144x36 again, chamfer included.
///
/// The fourth (a left face with four ports, `max(36, 3x16+16) = 64`) is N4 rather than N1/N2, so
/// it is asserted through a real routed diagram in
/// [`orthogonal_five_b_merge_target_grows_to_its_four_ports`] instead of through `orthogonal_node`,
/// which only ever answers the label-derived half.
#[test]
fn orthogonal_node_reproduces_the_five_b_worked_examples() {
    if !text_metrics::fonts_available() {
        return;
    }
    let box_of = |glyph, text: &str| {
        shapes::orthogonal_node(glyph, text)
            .unwrap_or_else(|| panic!("{text}: {glyph:?} is in §10-8 N3's scope"))
            .1
    };

    // 「表」: one CJK character, 14px of text. 14 + 40 = 54, floored at the 96px minimum.
    assert_eq!(
        box_of(Glyph::Flow(Shape::Rect), "表"),
        Size::new(96.0, 36.0)
    );

    // 「ブロックモデル」: seven CJK characters, 98px of text. 98 + 40 = 138, rounded up to 144.
    assert_eq!(
        text_metrics::measure("ブロックモデル", 14.0) as f64,
        98.0,
        "5b's own annotation — the artboard's arithmetic starts from this measurement"
    );
    assert_eq!(
        box_of(Glyph::Flow(Shape::Rect), "ブロックモデル"),
        Size::new(144.0, 36.0)
    );

    // 「ルールに一致?」 as a decision node: 91.79px of text, +40 padding, +12 for the two 6px
    // chamfers = 143.79, rounded up to 144 — the polygon 5b draws spans exactly that.
    assert_eq!(
        box_of(Glyph::ChamferedRect, "ルールに一致?"),
        Size::new(144.0, 36.0)
    );
}

/// 5b's third example, which is N4 rather than N1/N2 and therefore only observable on a routed
/// diagram: a merge target whose face carries four ports grows along **that face's axis only**,
/// by `(n-1) * PORT_SPACING + 2 * PORT_CLEARANCE`, and stays centred on its own middle.
///
/// **Where konoma and 5b's drawing differ, and why the difference is not this rule breaking.** 5b
/// draws the four ports centred on the face — `±8`, `±24` — which makes the box `3*16 + 16 = 64`
/// tall. konoma puts one of the four *on* the centre line, because §10-3 item 12 anchors a merge's
/// own trunk claim at its natural sort position and §10-3 item 10 promotes a median source to be
/// that trunk: `合流先` is reached by a straight, zero-bend edge, which is only possible if that
/// edge's port is the face's own centre. The remaining three then sit at `-16`, `+16`, `+32`, and
/// N4's own arithmetic — the outermost port plus its 8px corner clearance, doubled for symmetry —
/// gives 80 rather than 64. The formula is the same formula; 5b's *64* is the value it takes on a
/// face with no trunk on it, which this test pins separately just below. Straightening the spine
/// is what §10-0 ranks first, so the centred trunk port stays and 5b's centred four is recorded
/// here as the arithmetic it is rather than forced onto a diagram that would then bend.
///
/// `LR` so the four merges land on the target's **left** face, which is the face 5b draws them on
/// — under §10-3 item 3 a merge always rides the flow-axis face, so the direction is what puts
/// them there rather than a special case.
#[test]
fn orthogonal_five_b_merge_target_grows_to_its_four_ports() {
    if !text_metrics::fonts_available() {
        return;
    }
    // 5b's own arithmetic, on the centred four-port face it draws: "16px×3+両端 8px = 64px".
    assert_eq!(
        3.0 * orthogonal::PORT_SPACING + 2.0 * orthogonal::PORT_CLEARANCE,
        64.0
    );
    let d = laid_out_flow(
        "flowchart LR\n  A[あ] --> Z[合流先]\n  B[い] --> Z\n  C[う] --> Z\n  D[え] --> Z",
        "basis",
        "konoma-orthogonal",
    );
    let z = d.node("Z").expect("Z must exist");
    let (left, top, _, bottom) = z.bounds();
    let mut ys: Vec<f64> = d
        .edges
        .iter()
        .filter(|e| e.to == "Z")
        .map(|e| {
            let p = e.points.last().expect("routed");
            assert!(
                (p.x - (left - orthogonal::PORT_INSET)).abs() < 1e-6,
                "5b puts all four ports on Z's own left face: {p:?} vs left {left}"
            );
            p.y
        })
        .collect();
    assert_eq!(ys.len(), 4, "all four sources must reach Z");
    ys.sort_by(|a, b| a.partial_cmp(b).expect("finite"));

    // 16px pitch, and 8px of corner clearance at each end — N4's two terms, read off the picture.
    for w in ys.windows(2) {
        assert_eq!(
            w[1] - w[0],
            orthogonal::PORT_SPACING,
            "the four ports sit on the 16px grid: {ys:?}"
        );
    }
    let reach = (ys[3] - z.center.y).abs().max((ys[0] - z.center.y).abs());
    assert_eq!(
        z.size.h,
        2.0 * (reach + orthogonal::PORT_CLEARANCE),
        "N4: the face is the outermost port plus its 8px clearance, doubled — {ys:?}"
    );
    assert!(
        ys[0] - top >= orthogonal::PORT_CLEARANCE - 1e-6
            && bottom - ys[3] >= orthogonal::PORT_CLEARANCE - 1e-6,
        "no port may sit closer than 8px to its face's own corner: {ys:?} in {top}..{bottom}"
    );

    let (_, label_box) =
        shapes::orthogonal_node(z.shape, "合流先").expect("a plain rectangle is in scope");
    assert!(
        z.size.h > label_box.h,
        "the ports are what grew it: {:?} vs {label_box:?}",
        z.size
    );
    assert_eq!(
        z.size.w, label_box.w,
        "N4: growth is along the ports' own axis only — the width stays label-derived"
    );
    assert!(
        ((top + bottom) / 2.0 - z.center.y).abs() < 1e-6,
        "N4: the grown box stays symmetric about its own centre line"
    );
}

/// N2's 96px floor, and the exact width the floor gives way at.
///
/// Both sides of the boundary, so neither "always 96" nor "never 96" can pass: 56px of text pads
/// to exactly 96 and is the widest label the minimum still covers, and a hair more rounds up to
/// the next 8px step.
#[test]
fn orthogonal_width_floors_at_ninety_six_then_follows_the_text() {
    let w = |t: f64| shapes::ortho_width(Glyph::Flow(Shape::Rect), t);
    assert_eq!(w(0.0), 96.0, "an empty label still gets N2's minimum");
    assert_eq!(w(20.0), 96.0);
    assert_eq!(w(56.0), 96.0, "56 + 40 = 96 exactly — still the minimum");
    assert_eq!(w(56.5), 104.0, "past the minimum, the 8px grid takes over");
    assert_eq!(w(58.0), 104.0, "58 + 40 = 98 -> 104");
}

/// N2's "8px 単位に切り上げ", at every residue class — a rounding that only worked for multiples of
/// 8 would pass a single-value check.
#[test]
fn orthogonal_width_rounds_up_onto_the_eight_pixel_grid() {
    for text in [
        58.0, 60.0, 63.9, 64.0, 64.1, 71.9, 72.0, 100.0, 137.5, 160.0,
    ] {
        let w = shapes::ortho_width(Glyph::Flow(Shape::Rect), text);
        assert_eq!(
            w % shapes::ORTHO_WIDTH_STEP,
            0.0,
            "text {text} -> {w} must land on the 8px grid"
        );
        assert!(
            w >= text + 2.0 * shapes::ORTHO_PAD_X,
            "text {text} -> {w} must still hold the words plus 20px a side"
        );
        assert!(
            w < text + 2.0 * shapes::ORTHO_PAD_X + shapes::ORTHO_WIDTH_STEP
                || w == shapes::ORTHO_MIN_WIDTH,
            "text {text} -> {w} must round UP, not up-and-then-some"
        );
    }
    // Exactly on the grid already: rounding up must be the identity, not one more step.
    assert_eq!(
        shapes::ortho_width(Glyph::Flow(Shape::Rect), 104.0 - 40.0),
        104.0
    );
}

/// N3's chamfer allowance: the same words in a decision node get 6px more padding a side than in
/// a plain rectangle — 12px in all, before the 8px rounding.
#[test]
fn orthogonal_decision_node_pays_six_more_pixels_a_side_for_its_chamfer() {
    // Chosen so neither value is on the 96px floor and the 12px difference cannot be swallowed by
    // the 8px rounding (both land on their own step).
    let text = 108.0;
    let rect = shapes::ortho_width(Glyph::Flow(Shape::Rect), text);
    let decision = shapes::ortho_width(Glyph::ChamferedRect, text);
    assert_eq!(rect, 152.0, "108 + 40 = 148 -> 152");
    assert_eq!(
        decision, 160.0,
        "108 + 40 + 12 = 160, already on the grid — 8px more box for the two 6px chamfers"
    );
    assert_eq!(
        decision - rect,
        8.0,
        "the chamfer allowance survives the rounding rather than being rounded away"
    );
}

/// N1's height for k lines, `14k + 6(k-1) + 22`, and the identity the drawing path depends on: the
/// box is exactly the label block [`super::svg::emit_text`] centres inside it plus 2 x
/// [`shapes::ORTHO_PAD_Y`]. The doc on [`shapes::ortho_height`] names this test for that reason —
/// if the two spellings ever disagree, the words drift off centre in every multi-line node.
#[test]
fn orthogonal_box_height_is_the_label_block_plus_padding() {
    for (k, expected) in [(1, 36.0), (2, 56.0), (3, 76.0), (4, 96.0)] {
        assert_eq!(shapes::ortho_height(k), expected, "{k} lines");
        let block = k as f64 * super::labels::ortho_line_pitch();
        assert_eq!(
            shapes::ortho_height(k),
            block + 2.0 * shapes::ORTHO_PAD_Y - super::labels::ORTHO_LINE_GAP,
            "{k} lines: the box must be the drawn block plus N1's own padding"
        );
    }
    assert_eq!(
        super::labels::ortho_line_pitch(),
        20.0,
        "N1: 14px of text and a 6px gap"
    );
}

/// N2's cap: a label too wide for 240px wraps at a word boundary and the box grows *down* instead
/// of out — two lines, `14*2 + 6 + 22 = 56` tall.
#[test]
fn orthogonal_label_wider_than_the_cap_wraps_instead_of_widening() {
    if !text_metrics::fonts_available() {
        return;
    }
    let text = "resolve the preview kind and hand it to the right renderer";
    let one_line = text_metrics::measure(text, 14.0) as f64;
    assert!(
        one_line + 2.0 * shapes::ORTHO_PAD_X > shapes::ORTHO_MAX_WIDTH,
        "the fixture must actually be over the cap: {one_line}px of text"
    );
    let (label, size) =
        shapes::orthogonal_node(Glyph::Flow(Shape::Rect), text).expect("a rectangle is in scope");
    assert!(
        label.lines.len() >= 2,
        "it must wrap, not overflow: {:?}",
        label.lines
    );
    assert_eq!(
        size.h,
        shapes::ortho_height(label.lines.len()),
        "N1's height for however many lines it took"
    );
    assert!(
        size.w <= shapes::ORTHO_MAX_WIDTH,
        "wrapping must bring it back under the cap: {size:?}"
    );
    // Nothing is thrown away and nothing is invented — the words come back in order, whole.
    assert_eq!(
        label.lines.join(" "),
        text,
        "N2 forbids truncation and an ellipsis alike"
    );
    for line in &label.lines {
        assert!(
            !line.contains('…') && !line.ends_with("..."),
            "no ellipsis: {line:?}"
        );
    }
}

/// N2's exact wrap: a label that is *just* over the cap comes back as two lines and 56px tall,
/// pinning the height formula for `k = 2` on a real label rather than on `ortho_height` alone.
#[test]
fn orthogonal_two_line_wrap_is_fifty_six_pixels_tall() {
    if !text_metrics::fonts_available() {
        return;
    }
    // 16 CJK characters = 224px of text; 224 + 40 = 264 > 240, and any 15 of them (210 + 40 = 250)
    // would still be over, so this genuinely exercises the per-character CJK rule.
    let text = "設定のルールに従って描画方法を決める";
    let (label, size) =
        shapes::orthogonal_node(Glyph::Flow(Shape::Rect), text).expect("a rectangle is in scope");
    assert_eq!(label.lines.len(), 2, "two lines: {:?}", label.lines);
    assert_eq!(size.h, 56.0, "14*2 + 6 + 22 = 56");
    assert_eq!(
        label.lines.concat(),
        text,
        "CJK wraps between characters, and no character is lost or added"
    );
    assert!(
        label.lines.iter().all(|l| l.chars().count() > 1),
        "per character does not mean one character per line: {:?}",
        label.lines
    );
}

/// N2's own escape hatch: a single unbreakable run wider than the cap keeps its box rather than
/// being cut. "折り返し後も超える場合のみ上限を撤廃(切らない・省略記号なし)".
#[test]
fn orthogonal_unbreakable_run_widens_past_the_cap_rather_than_being_truncated() {
    if !text_metrics::fonts_available() {
        return;
    }
    let text = "A".repeat(30);
    let (label, size) =
        shapes::orthogonal_node(Glyph::Flow(Shape::Rect), &text).expect("a rectangle is in scope");
    assert_eq!(
        label.lines,
        vec![text.clone()],
        "there is nowhere to break, so it stays one line"
    );
    assert!(
        size.w > shapes::ORTHO_MAX_WIDTH,
        "the cap gives way, the text does not: {size:?}"
    );
    assert_eq!(
        size.w,
        shapes::ortho_width(Glyph::Flow(Shape::Rect), label.width),
        "still padded and still on the 8px grid — only the cap is lifted"
    );
    assert_eq!(size.h, 36.0, "one line is still one line");
}

/// The mixed case the two rules above meet in: a long unbreakable token *and* ordinary words. The
/// words wrap around the token, the token keeps its own line whole, and the box is as wide as the
/// token needs.
#[test]
fn orthogonal_wrapping_keeps_a_long_token_whole_and_wraps_the_words_around_it() {
    if !text_metrics::fonts_available() {
        return;
    }
    let token = "A".repeat(30);
    let text = format!("open {token} now please and then some more words");
    let (label, _) =
        shapes::orthogonal_node(Glyph::Flow(Shape::Rect), &text).expect("a rectangle is in scope");
    assert!(
        label.lines.iter().any(|l| l.contains(&token)),
        "the token is never split: {:?}",
        label.lines
    );
    assert_eq!(label.lines.join(" "), text, "every word survives, in order");
    assert!(
        label.lines.len() >= 3,
        "the words either side of it wrap: {:?}",
        label.lines
    );
}

/// N3's exclusions, stated where they are decided. A glyph out of scope must come back `None` so
/// that `spec_of` falls through to mermaid's own [`shapes::size`] — the state markers, a choice, a
/// fork/join bar (all of which §10-5 S1/S4 size), and every shape with geometry of its own.
#[test]
fn orthogonal_node_sizing_leaves_n3s_exclusions_to_mermaids_own_sizes() {
    for glyph in [
        Glyph::StateStart,
        Glyph::StateEnd,
        Glyph::Choice,
        Glyph::Bar { horizontal: true },
        Glyph::Bar { horizontal: false },
        Glyph::Note,
        Glyph::Flow(Shape::Circle),
        Glyph::Flow(Shape::DoubleCircle),
        Glyph::Flow(Shape::Stadium),
        Glyph::Flow(Shape::Hexagon),
        Glyph::Flow(Shape::Cylinder),
        Glyph::Flow(Shape::Subroutine),
        Glyph::Flow(Shape::Diamond),
        Glyph::Flow(Shape::Trapezoid),
    ] {
        assert!(
            shapes::orthogonal_node(glyph, "text").is_none(),
            "{glyph:?} is outside §10-8 N3 and must keep mermaid's own size"
        );
        assert!(!shapes::orthogonal_covers(glyph), "{glyph:?}");
    }
    for glyph in [
        Glyph::Flow(Shape::Rect),
        Glyph::Flow(Shape::RoundedRect),
        Glyph::ChamferedRect,
        Glyph::TitledBox,
    ] {
        assert!(
            shapes::orthogonal_covers(glyph),
            "{glyph:?} is a box §10-8 sizes"
        );
    }
}

/// §10-8 applies **only** to `konoma-orthogonal`. Every splines box comes back exactly as
/// [`shapes::size`] alone would have made it — the same claim `splines_routing_signature_is_pinned`
/// and the goldens make about the whole byte stream, stated here on the one thing this change
/// touched, in a form that fails loudly rather than through a snapshot diff.
#[test]
fn splines_node_sizes_are_untouched_by_the_orthogonal_rules() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_full_corpus() {
        let d = laid_out_curve(src, "basis");
        for n in &d.nodes {
            let expected = shapes::size(n.shape, Size::new(n.label.width, n.label.height));
            assert_eq!(
                (n.size.w, n.size.h),
                (expected.w, expected.h),
                "{name}: {} must keep mermaid's own size under splines",
                n.id
            );
            assert_eq!(
                n.label.line_pitch,
                super::labels::line_height(),
                "{name}: {} must keep mermaid's own 1.1em line pitch under splines",
                n.id
            );
        }
    }
}

/// N1-N4 as a corpus-wide invariant, over every source the orthogonal mode is checked against.
///
/// Four separate claims, because each can fail on its own:
///
/// 1. no box is ever **smaller** than its own label asks for (N4's `max`, from the label side);
/// 2. a width is either exactly the label-derived one — on the 8px grid, at least 96 — or a
///    port-derived one, which is `2*(k*8 + PORT_CLEARANCE)` plus a chamfered node's own allowance;
/// 3. a height is either N1's `14k + 6(k-1) + 22` or, again, a port-derived value on that grid;
/// 4. the box is symmetric about its own centre, so growth never slid a node sideways.
///
/// "Or port-derived" is not a loophole: `apply_growth` never shrinks (`mod.rs`'s own doc on why
/// that is what makes the retry loop converge), so a face that needed room in an early pass keeps
/// it even if a later pass reroutes the edge that asked. What must stay true is that any box
/// bigger than its label is bigger by exactly what some face's port grid asks for — never by an
/// arbitrary amount.
#[test]
fn orthogonal_every_box_is_label_derived_or_on_the_port_grid() {
    if !text_metrics::fonts_available() {
        return;
    }
    let on_port_grid = |v: f64, glyph: Glyph| {
        let chamfer = if glyph == Glyph::ChamferedRect {
            2.0 * shapes::CHAMFER
        } else {
            0.0
        };
        let reach = (v - chamfer) / 2.0 - orthogonal::PORT_CLEARANCE;
        reach >= -1e-6 && (reach / (orthogonal::PORT_SPACING / 2.0)).fract().abs() < 1e-6
    };
    let mut checked = 0usize;
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for n in &d.nodes {
            if !shapes::orthogonal_covers(n.shape) {
                continue;
            }
            checked += 1;
            let label_box = shapes::orthogonal_label_box(n.shape, &n.label);
            assert!(
                n.size.w >= label_box.w - 1e-6 && n.size.h >= label_box.h - 1e-6,
                "{name}: {} is smaller than its own label needs: {:?} vs {label_box:?}",
                n.id,
                n.size
            );
            assert_eq!(
                label_box.w % shapes::ORTHO_WIDTH_STEP,
                0.0,
                "{name}: {}'s label-derived width must be on the 8px grid",
                n.id
            );
            assert!(
                label_box.w >= shapes::ORTHO_MIN_WIDTH,
                "{name}: {}'s label-derived width must be at least 96",
                n.id
            );
            assert_eq!(
                label_box.h,
                shapes::ortho_height(n.label.lines.len()),
                "{name}: {}'s label-derived height must be N1's own",
                n.id
            );
            if (n.size.w - label_box.w).abs() > 1e-6 {
                assert!(
                    on_port_grid(n.size.w, n.shape),
                    "{name}: {} is wider than its label by something that is not a port grid: \
                     {:?} vs {label_box:?}",
                    n.id,
                    n.size
                );
            }
            if (n.size.h - label_box.h).abs() > 1e-6 {
                assert!(
                    on_port_grid(n.size.h, n.shape),
                    "{name}: {} is taller than its label by something that is not a port grid: \
                     {:?} vs {label_box:?}",
                    n.id,
                    n.size
                );
            }
            let (l, t, r, b) = n.bounds();
            assert!(
                ((l + r) / 2.0 - n.center.x).abs() < 1e-6
                    && ((t + b) / 2.0 - n.center.y).abs() < 1e-6,
                "{name}: {}'s box must stay symmetric about its own centre",
                n.id
            );
        }
    }
    assert!(
        checked > 100,
        "the corpus must actually reach the boxes §10-8 sizes: only {checked} seen"
    );
}

/// N1/N2's padding, checked as the thing padding is *for*: no node's words touch its box.
///
/// Measured against the drawn label block ([`super::labels::Label`]'s own width and the pitch
/// [`super::svg::emit_text`] steps by), not against a second guess at the text extent, and stated
/// with a 1px slack because a rounded-up width can leave a hair more room than the padding alone.
#[test]
fn orthogonal_no_node_text_overflows_its_own_box() {
    if !text_metrics::fonts_available() {
        return;
    }
    for (name, src) in orthogonal_full_corpus()
        .into_iter()
        .chain(orthogonal_only_corpus())
    {
        let d = laid_out_flow(src, "basis", "konoma-orthogonal");
        for n in &d.nodes {
            if !shapes::orthogonal_covers(n.shape) || n.label.is_blank() {
                continue;
            }
            let pad_x = shapes::ORTHO_PAD_X
                + if n.shape == Glyph::ChamferedRect {
                    shapes::CHAMFER
                } else {
                    0.0
                };
            assert!(
                n.label.width <= n.size.w - 2.0 * pad_x + 1.0,
                "{name}: {}'s words ({:.2}px) run into its own {:.2}px box",
                n.id,
                n.label.width,
                n.size.w
            );
            // The ink is `14k + 6(k-1)`; the label block carries half a line gap above the first
            // line and below the last, which is what centres it — so the comparison subtracts one
            // gap rather than pretending the block and the ink are the same number.
            let ink = n.label.height - super::labels::ORTHO_LINE_GAP;
            assert!(
                ink <= n.size.h - 2.0 * shapes::ORTHO_PAD_Y + 1e-6,
                "{name}: {}'s {} line(s) run past its own {:.2}px box",
                n.id,
                n.label.lines.len(),
                n.size.h
            );
        }
    }
}

// =============================================================================================
// `direction`'s **sign** — `RL` is `LR` mirrored, `BT` is `TB` mirrored
// (`docs/FEATURE-MERMAID-RENDERER.md` §10; `super::canonicalise_flow_axis`/`super::
// mirror_flow_axis`)
//
// Under `konoma-orthogonal` all four directions used to come out of the same two layouts: every
// post-dagre pass keys on the flow *axis* without its *sign*, and `pull_back_fan_ranks` rewrote
// every node's flow coordinate as "ascending with rank" for all four — so `RL` rendered
// byte-identical to `LR` and `BT` to `TB` (measured on the sample flowchart: `Key press` at x=50.4
// and `Redraw` at x=636.6 under both `LR` and `RL`, where splines puts them at 50.4/645.9 and
// 657.6/62.1 — a real mirror). dagre's own edge waypoints were *not* rewritten, so the eight corpus
// sources with a self-loop or a staircase fallback came out worse than identical: `self-loop`'s own
// `A --> A` under `BT` was drawn around `B`'s box (y 88-130) while `A` sat at y 26.
// =============================================================================================

/// `samples/mermaid.md`'s **first** flowchart, byte-for-byte — the diagram the direction bug was
/// found on, kept here as a source rather than read off disk for the same reason
/// [`SETTINGS_RULES_SAMPLE`] is: several tests below need this exact string, and a fixture nobody
/// can diff against the sample is worse than one copy of it.
const SAMPLE_FIRST_FLOWCHART: &str = "flowchart LR\n  K([Key press]) --> S{Which surface?}\n  \
     S -->|Tree| M[Move or open]\n  S -->|Preview| P[Scroll or search]\n  M --> R[Redraw]\n  \
     P --> R";

/// One source carrying every shape whose §10 rule is stated **flow-relative** and therefore has to
/// mirror, so that a mirror test over it is not just a test of ordinary boxes and straight lines:
///
/// * a **fan** wide enough for §10-3 item 1's own multi-branch regime (five branches, past
///   `orthogonal::FAN_ELIGIBLE_MIN_BRANCHES`), whose ports go on the source's *flow-direction* face;
/// * the **merge** back onto one target, whose ports go on that target's own *upstream* flow face
///   (§10-3 item 10) — the face that is the left one under `LR` and the right one under `RL`;
/// * an **aside** (`-.->`, `render::is_aside`) that is also a **back edge**, so the outer perimeter
///   lane (§10-1 item 4) is in the picture;
/// * a **self-loop**, the one shape still drawn from dagre's own waypoints
///   (`orthogonal::route_staircase_with_ports`) and so the one that catches a waypoint set left
///   behind in the un-mirrored space;
/// * a **dead-end tier** — a block whose members are all dead ends fed from the trunk and which the
///   trunk does not itself run through (`orthogonal::place_dead_end_tiers`), whose side is chosen on
///   the *cross* axis and must therefore come out on the **same** side under both directions;
/// * **edge labels**, so the label plates and their §10-1 item 3 minimum segment lengths are in it.
const FAN_MERGE_ASIDE_TIER: &str = "flowchart LR\n  A[入力] --> D{振り分け}\n  \
     D -->|1| B1[枝一]\n  D -->|2| B2[枝二]\n  D -->|3| B3[枝三]\n  D -->|4| B4[枝四]\n  \
     D -->|5| B5[枝五]\n  B1 --> M[合流]\n  B2 --> M\n  B3 --> M\n  B4 --> M\n  B5 --> M\n  \
     M --> Z[出力]\n  subgraph T[控え]\n    T1[記録]\n    T2[計測]\n  end\n  M --> T1\n  \
     M --> T2\n  Z -.->|再試行| A\n  Z --> Z";

/// The sources [`orthogonal_rl_is_the_exact_mirror_of_lr`] and its `BT` sibling state the mirror
/// over — the two above plus [`SETTINGS_RULES_SAMPLE`], the twenty-node sample §10-3 was written
/// against, because a source this size is where a pass that silently drops the sign shows up.
fn direction_fixture_sources() -> Vec<(&'static str, &'static str)> {
    vec![
        ("sample-first-flowchart", SAMPLE_FIRST_FLOWCHART),
        ("fan-merge-aside-tier", FAN_MERGE_ASIDE_TIER),
        ("settings-rules-sample", SETTINGS_RULES_SAMPLE),
    ]
}

/// [`direction_fixture_sources`], minus the ones whose **`TB` form** trips a corpus-wide invariant
/// for a reason that has nothing to do with `direction`.
///
/// [`SETTINGS_RULES_SAMPLE`] is the one: it is authored `LR` (and is drawn `LR` everywhere it is
/// used), and laying the same graph out `TB` puts `設定のルール`'s own `Markdown` label plate over
/// the neighbouring `画像` edge, and orders two of `ラスタライズ`'s merge hop legs widest-last.
/// Both reproduce with the flow-axis mirror disabled — they are pre-existing `TB` layout faults
/// this task did not introduce and is not scoped to fix (recorded rather than papered over; the
/// mirror tests above still run this source in all four directions, and it mirrors exactly).
fn direction_corpus_sources() -> Vec<(&'static str, &'static str)> {
    direction_fixture_sources()
        .into_iter()
        .filter(|(name, _)| *name != "settings-rules-sample")
        .collect()
}

/// The same source with its header's `direction` keyword replaced — `flowchart LR` into
/// `flowchart RL`, and so on. Panics rather than returning an `Option`: every caller is a test with
/// a source it wrote itself, so a header this cannot read is a mistake in the test, not a case to
/// skip silently.
pub(super) fn flowchart_with_direction(src: &str, direction: &str) -> String {
    let (head, rest) = src.split_once('\n').unwrap_or((src, ""));
    let mut words = head.split_whitespace();
    let kind = words
        .next()
        .filter(|w| matches!(*w, "flowchart" | "graph"))
        .unwrap_or_else(|| {
            panic!("a flowchart fixture starts with `flowchart` or `graph`: {head}")
        });
    assert!(
        words
            .next()
            .is_none_or(|w| matches!(w, "TB" | "TD" | "BT" | "LR" | "RL")),
        "a flowchart fixture's header carries nothing but a direction: {head}"
    );
    format!("{kind} {direction}\n{rest}")
}

/// [`direction_corpus_sources`] in all four directions, plus every
/// [`orthogonal_design_reference_corpus`] source in the direction that reverses its own — chained
/// into [`orthogonal_full_corpus`], so every corpus-wide invariant (axis-parallel segments,
/// perpendicular entry, no puncture, no crossing, frames holding their members…) runs over the
/// reversed half of each axis too, which before the mirror existed nothing did.
///
/// **Derived, not copied.** Writing `flowchart RL` variants out by hand would be four more
/// near-duplicates of sources that already have one near-duplicate each (`2b`/`2c` are the same
/// graph in `LR` and `TB`), and a hand copy drifts from the source it mirrors the first time either
/// is edited. Built once into a [`OnceLock`] so the borrowed `&'static str`s outlive every caller.
///
/// [`OnceLock`]: std::sync::OnceLock
fn orthogonal_reversed_direction_corpus() -> &'static [(String, String)] {
    static CACHE: std::sync::OnceLock<Vec<(String, String)>> = std::sync::OnceLock::new();
    CACHE.get_or_init(|| {
        let mut out: Vec<(String, String)> = Vec::new();
        for (name, src) in direction_corpus_sources() {
            for direction in ["LR", "RL", "TB", "BT"] {
                out.push((
                    format!("{name}-{direction}"),
                    flowchart_with_direction(src, direction),
                ));
            }
        }
        for (name, src) in orthogonal_design_reference_corpus() {
            let reversed = match src
                .lines()
                .next()
                .unwrap_or_default()
                .split_whitespace()
                .nth(1)
            {
                Some("LR") => "RL",
                Some("RL") => "LR",
                Some("BT") => "TB",
                // `flowchart` with nothing after it is `TB`, the parser's own default.
                Some("TB") | Some("TD") | None => "BT",
                Some(other) => panic!("{name}: unknown direction {other}"),
            };
            out.push((
                format!("{name}-{reversed}"),
                flowchart_with_direction(src, reversed),
            ));
        }
        out
    })
}

/// How far two coordinates may differ and still be the same point. The mirror is a reflection of
/// finished geometry — one negation and one translation, both exact in binary floating point for
/// the magnitudes a diagram uses — so this is a guard against a stray rounding, not a tolerance
/// the implementation is expected to need.
pub(super) const MIRROR_EPS: f64 = 1e-6;

/// Asserts `b` is `a` reflected along the flow axis: every coordinate on that axis at `span - v`
/// (`span` being the diagram's own extent along it), every coordinate across it unchanged, and
/// every size, id and ordering identical.
///
/// Shared with [`super::state_tests`], which states the same property over a state diagram's own
/// design references.
pub(super) fn assert_mirrored_diagrams(label: &str, a: &Diagram, b: &Diagram, vertical: bool) {
    assert!(
        (a.width - b.width).abs() < MIRROR_EPS && (a.height - b.height).abs() < MIRROR_EPS,
        "{label}: a mirror keeps the diagram's own size — {}x{} became {}x{}",
        a.width,
        a.height,
        b.width,
        b.height
    );
    let span = if vertical { a.height } else { a.width };
    // `(flow, cross)` of a point, with the flow coordinate already reflected on `b`'s side, so the
    // two sides below are compared with one `assert` rather than two mirrored ones.
    let split = |p: &Point, mirrored: bool| -> (f64, f64) {
        let (flow, cross) = if vertical { (p.y, p.x) } else { (p.x, p.y) };
        (if mirrored { span - flow } else { flow }, cross)
    };
    let same = |what: &str, id: &str, pa: &Point, pb: &Point| {
        let ((fa, ca), (fb, cb)) = (split(pa, false), split(pb, true));
        assert!(
            (fa - fb).abs() < MIRROR_EPS && (ca - cb).abs() < MIRROR_EPS,
            "{label}: {what} {id} sits at {pa:?}, whose mirror is flow {fa} cross {ca} — \
             the reversed direction drew it at {pb:?} (flow {fb} cross {cb})"
        );
    };

    assert_eq!(
        a.nodes.iter().map(|n| &n.id).collect::<Vec<_>>(),
        b.nodes.iter().map(|n| &n.id).collect::<Vec<_>>(),
        "{label}: a mirror keeps every node, in order"
    );
    for (na, nb) in a.nodes.iter().zip(&b.nodes) {
        assert_eq!(
            (na.size.w, na.size.h),
            (nb.size.w, nb.size.h),
            "{label}: node {}'s own box is reflected, not resized",
            na.id
        );
        assert_eq!(
            na.shape, nb.shape,
            "{label}: node {}'s own glyph is unchanged by the direction",
            na.id
        );
        same("node", &na.id, &na.center, &nb.center);
    }

    assert_eq!(
        a.clusters.iter().map(|c| &c.id).collect::<Vec<_>>(),
        b.clusters.iter().map(|c| &c.id).collect::<Vec<_>>(),
        "{label}: a mirror keeps every frame, in order"
    );
    for (ca, cb) in a.clusters.iter().zip(&b.clusters) {
        assert_eq!(
            (ca.size.w, ca.size.h),
            (cb.size.w, cb.size.h),
            "{label}: frame {}'s own rectangle is reflected, not resized",
            ca.id
        );
        same("frame", &ca.id, &ca.center, &cb.center);
    }

    assert_eq!(
        a.edges.iter().map(|e| (&e.from, &e.to)).collect::<Vec<_>>(),
        b.edges.iter().map(|e| (&e.from, &e.to)).collect::<Vec<_>>(),
        "{label}: a mirror keeps every edge, in order"
    );
    for (ea, eb) in a.edges.iter().zip(&b.edges) {
        let id = format!("{}->{}", ea.from, ea.to);
        assert_eq!(
            ea.points.len(),
            eb.points.len(),
            "{label}: edge {id} is the same route reflected, so it has the same number of \
             corners — {:?} against {:?}",
            ea.points,
            eb.points
        );
        for (pa, pb) in ea.points.iter().zip(&eb.points) {
            same("edge", &id, pa, pb);
        }
        assert_eq!(
            ea.gaps.len(),
            eb.gaps.len(),
            "{label}: edge {id} keeps its own §10-1 item 4 crossing gaps"
        );
        for ((a0, a1), (b0, b1)) in ea.gaps.iter().zip(&eb.gaps) {
            same("gap start", &id, a0, b0);
            same("gap end", &id, a1, b1);
        }
        for (what, la, lb) in [
            ("label", &ea.label, &eb.label),
            ("start label", &ea.start_label, &eb.start_label),
            ("end label", &ea.end_label, &eb.end_label),
            ("badge", &ea.badge, &eb.badge),
        ] {
            match (la, lb) {
                (Some(la), Some(lb)) => {
                    assert_eq!(
                        (la.size.w, la.size.h),
                        (lb.size.w, lb.size.h),
                        "{label}: edge {id}'s {what} is moved, not re-measured"
                    );
                    same(what, &id, &la.center, &lb.center);
                }
                (None, None) => {}
                _ => panic!("{label}: edge {id} has a {what} in one direction and not the other"),
            }
        }
    }
}

/// §10 under `RL`: the same drawing as `LR`, reflected along x.
///
/// The **whole** drawing, not a sample of it — node centres, frame rectangles, every polyline
/// vertex (which is where the ports are: a route's first and last point *is* its port, pulled
/// `PORT_INSET` outside the face), every crossing gap and every label plate. Stated as an exact
/// reflection rather than as "looks different from `LR`" because that is what the direction
/// actually means, and because a weaker statement passes on a drawing that is merely translated.
#[test]
fn orthogonal_rl_is_the_exact_mirror_of_lr() {
    for (name, src) in direction_fixture_sources()
        .into_iter()
        .chain(orthogonal_design_reference_corpus())
    {
        let lr = laid_out_flow(
            &flowchart_with_direction(src, "LR"),
            "basis",
            "konoma-orthogonal",
        );
        let rl = laid_out_flow(
            &flowchart_with_direction(src, "RL"),
            "basis",
            "konoma-orthogonal",
        );
        assert_mirrored_diagrams(&format!("{name} LR/RL"), &lr, &rl, false);
    }
}

/// §10 under `BT`: the same drawing as `TB`, reflected along y. [`orthogonal_rl_is_the_exact_
/// mirror_of_lr`]'s own doc has the reasoning; this is the other axis.
#[test]
fn orthogonal_bt_is_the_exact_mirror_of_tb() {
    for (name, src) in direction_fixture_sources()
        .into_iter()
        .chain(orthogonal_design_reference_corpus())
    {
        let tb = laid_out_flow(
            &flowchart_with_direction(src, "TB"),
            "basis",
            "konoma-orthogonal",
        );
        let bt = laid_out_flow(
            &flowchart_with_direction(src, "BT"),
            "basis",
            "konoma-orthogonal",
        );
        assert_mirrored_diagrams(&format!("{name} TB/BT"), &tb, &bt, true);
    }
}

/// The mirror is a **reflection**, not a relabelling: `RL` must not simply come out as `LR` again.
///
/// The bug this pins was exactly that — every one of the four directions produced one of two
/// layouts — so a mirror suite alone could be satisfied by a diagram whose flow axis happens to be
/// symmetric. This states the thing that cannot be true of one: the reversed direction moves the
/// **first** node past the middle of the diagram and the last one back before it.
#[test]
fn orthogonal_reversing_the_direction_actually_moves_the_flow() {
    for (name, src) in direction_fixture_sources() {
        for (forward, reverse, vertical) in [("LR", "RL", false), ("TB", "BT", true)] {
            let a = laid_out_flow(
                &flowchart_with_direction(src, forward),
                "basis",
                "konoma-orthogonal",
            );
            let b = laid_out_flow(
                &flowchart_with_direction(src, reverse),
                "basis",
                "konoma-orthogonal",
            );
            let head = &a.nodes[0].id;
            let flow = |d: &Diagram, id: &str| {
                let n = d.nodes.iter().find(|n| n.id == id).expect("node exists");
                if vertical {
                    n.center.y
                } else {
                    n.center.x
                }
            };
            let span = if vertical { a.height } else { a.width };
            assert!(
                flow(&a, head) < span / 2.0 && flow(&b, head) > span / 2.0,
                "{name}: {head} is the source's own first node — {forward} puts it in the near \
                 half of a {span}px diagram (at {}) and {reverse} must put it in the far half, \
                 not at {}",
                flow(&a, head),
                flow(&b, head)
            );
        }
    }
}

/// A rule §10 states about the **cross** axis is stated in absolute screen terms and must
/// therefore *not* mirror: §10-5 S3's own self-transition face ("`LR`: 上辺"), §10-3 item 11's own
/// "非幹の枝は上から宣言順", and `orthogonal::place_dead_end_tiers`' own "the emptier side".
///
/// [`assert_mirrored_diagrams`] already implies this (a flow-axis reflection leaves the cross axis
/// alone, and it checks every cross coordinate), but only as a consequence. Saying it directly is
/// what would fail loudly if the mirror were ever widened into a point reflection or a rotation —
/// which is the shape a "just flip both axes" reading of `RL` would take, and which would silently
/// put the tier on the wrong side and reverse the fan's own declaration order.
#[test]
fn orthogonal_mirroring_the_flow_axis_leaves_the_cross_axis_alone() {
    let lr = laid_out_flow(
        &flowchart_with_direction(FAN_MERGE_ASIDE_TIER, "LR"),
        "basis",
        "konoma-orthogonal",
    );
    let rl = laid_out_flow(
        &flowchart_with_direction(FAN_MERGE_ASIDE_TIER, "RL"),
        "basis",
        "konoma-orthogonal",
    );
    let cross = |d: &Diagram, id: &str| {
        d.nodes
            .iter()
            .find(|n| n.id == id)
            .unwrap_or_else(|| panic!("{id} is a node of the fixture"))
            .center
            .y
    };
    // The fan's own five branches, in declaration order, and the tier's own two members: both
    // groups' cross-axis order is a rule about the screen, not about the flow.
    for id in ["B1", "B2", "B3", "B4", "B5", "T1", "T2"] {
        assert!(
            (cross(&lr, id) - cross(&rl, id)).abs() < MIRROR_EPS,
            "{id} sits at y {} under LR and y {} under RL — the cross axis is not mirrored",
            cross(&lr, id),
            cross(&rl, id)
        );
    }
    let tier_side = |d: &Diagram| cross(d, "T1") > cross(d, "M");
    assert_eq!(
        tier_side(&lr),
        tier_side(&rl),
        "the dead-end tier hangs off the same side of the trunk in both directions"
    );
}

/// [`super::mirror_flow_axis`] on its own, over a hand-built diagram — no font, no layout, and one
/// of every piece of geometry the function has to carry.
///
/// The corpus tests above state the *property*; this states the **coverage**. A mirror that forgot
/// `PlacedEdge::gaps`, or an edge's `start_label`/`end_label`/`badge`, would still pass every
/// mirror assertion over a flowchart source — no flowchart edge carries the last three, and a
/// crossing gap only appears in a diagram busy enough to have one. `super::normalise` already had
/// exactly this hole once (its own doc records `gaps` being left pointing at the pre-translation
/// location), and it is the same list, so it is the same hole.
#[test]
fn mirror_flow_axis_reflects_every_piece_of_geometry_and_only_for_bt_and_rl() {
    let built = || {
        let mut edge = bent_edge(
            vec![Point::new(10.0, 20.0), Point::new(30.0, 40.0)],
            Curve::Basis,
        );
        edge.gaps = vec![(Point::new(12.0, 22.0), Point::new(18.0, 28.0))];
        let plate = |x: f64, y: f64| PlacedEdgeLabel {
            center: Point::new(x, y),
            size: Size::new(8.0, 4.0),
            label: Label::measure(""),
        };
        edge.label = Some(plate(50.0, 60.0));
        edge.start_label = Some(plate(52.0, 62.0));
        edge.end_label = Some(plate(54.0, 64.0));
        edge.badge = Some(plate(56.0, 66.0));
        Diagram {
            width: 0.0,
            height: 0.0,
            nodes: vec![placed_node("n", 100.0, 200.0, 40.0, 20.0)],
            clusters: vec![PlacedCluster {
                id: "c".to_string(),
                title: Label::measure(""),
                center: Point::new(300.0, 400.0),
                size: Size::new(60.0, 30.0),
                parent: None,
                depth: 0,
                dashed: false,
                filled: true,
                sections: Vec::new(),
                title_strip: false,
            }],
            edges: vec![edge],
            lifelines: Vec::new(),
        }
    };

    for direction in [Direction::LeftToRight, Direction::TopToBottom] {
        let mut d = built();
        super::mirror_flow_axis(&mut d, direction);
        assert_eq!(
            d,
            built(),
            "{direction:?} is already the canonical orientation: the mirror must not touch it"
        );
    }

    // Every coordinate on the flow axis negated, every coordinate across it left alone. Listed as
    // whole points rather than checked with a loop, so a piece of geometry the function forgets is
    // a failing assertion and not a silently shorter list.
    let mut rl = built();
    super::mirror_flow_axis(&mut rl, Direction::RightToLeft);
    assert_eq!(rl.nodes[0].center, Point::new(-100.0, 200.0));
    assert_eq!(
        rl.nodes[0].size,
        Size::new(40.0, 20.0),
        "sizes do not reflect"
    );
    assert_eq!(rl.clusters[0].center, Point::new(-300.0, 400.0));
    assert_eq!(
        rl.edges[0].points,
        vec![Point::new(-10.0, 20.0), Point::new(-30.0, 40.0)]
    );
    assert_eq!(
        rl.edges[0].gaps,
        vec![(Point::new(-12.0, 22.0), Point::new(-18.0, 28.0))]
    );
    for (what, plate) in [
        ("label", &rl.edges[0].label),
        ("start_label", &rl.edges[0].start_label),
        ("end_label", &rl.edges[0].end_label),
        ("badge", &rl.edges[0].badge),
    ] {
        let plate = plate.as_ref().unwrap_or_else(|| panic!("{what} survives"));
        assert!(
            plate.center.x < 0.0 && plate.center.y > 0.0,
            "{what} sits at {:?}: its flow coordinate is reflected and its cross one is not",
            plate.center
        );
    }

    let mut bt = built();
    super::mirror_flow_axis(&mut bt, Direction::BottomToTop);
    assert_eq!(bt.nodes[0].center, Point::new(100.0, -200.0));
    assert_eq!(bt.clusters[0].center, Point::new(300.0, -400.0));
    assert_eq!(
        bt.edges[0].points,
        vec![Point::new(10.0, -20.0), Point::new(30.0, -40.0)]
    );
    assert_eq!(
        bt.edges[0].gaps,
        vec![(Point::new(12.0, -22.0), Point::new(18.0, -28.0))]
    );
}

/// A self-loop stays on its **own** node's box in every one of the four directions — the half of
/// the direction bug that was not a plain mirror.
///
/// `pull_back_fan_ranks` rewrites every *node*'s flow coordinate, so the nodes came out canonical
/// under `BT`/`RL` all along; dagre's own edge waypoints did not, and a self-loop is the one shape
/// still drawn from them (`orthogonal::route_staircase_with_ports`). The two therefore disagreed by
/// the whole diagram's flow extent: on the `self-loop` corpus source laid out `BT`, `A --> A` was
/// drawn spanning y 88-130 while `A` sat at y 26 — a loop around `B`. Stated with a bound tight
/// enough that a loop attached to the *next* node along the flow cannot pass, which is what the
/// corpus-wide "no dangling fragment" check catches only incidentally.
#[test]
fn orthogonal_a_self_loop_hugs_its_own_node_in_every_direction() {
    // The loop bumps `SELF_LOOP_BUMP` px clear of the face plus its own label room; one rank gap
    // (`RANK_SEP`, 50px) is the distance to the next node, and anything under it is unambiguously
    // "on its own box".
    const BUMP_MARGIN: f64 = 45.0;
    let src = "flowchart LR\n  A --> A\n  A --> B\n  B --> C";
    for direction in ["LR", "RL", "TB", "BT"] {
        let d = laid_out_flow(
            &flowchart_with_direction(src, direction),
            "basis",
            "konoma-orthogonal",
        );
        let loop_edge = d
            .edges
            .iter()
            .find(|e| e.from == "A" && e.to == "A")
            .unwrap_or_else(|| panic!("{direction}: the self-loop must still be drawn"));
        let (l, t, r, b) = d
            .nodes
            .iter()
            .find(|n| n.id == "A")
            .expect("A is a node")
            .bounds();
        for p in &loop_edge.points {
            assert!(
                p.x >= l - BUMP_MARGIN
                    && p.x <= r + BUMP_MARGIN
                    && p.y >= t - BUMP_MARGIN
                    && p.y <= b + BUMP_MARGIN,
                "{direction}: A's self-loop runs through {p:?}, which is more than {BUMP_MARGIN}px \
                 outside A's own box ({l},{t})-({r},{b}) — the loop is drawn from dagre's own \
                 waypoints, so this is what a waypoint left in the un-canonicalised space looks like"
            );
        }
    }
}