merman-render 0.8.0

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

/// Stable identity for a built-in typed render family.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RenderFamilyKind {
    Error,
    Mindmap,
    State,
    Sequence,
    Zenuml,
    Flowchart,
    Swimlane,
    Architecture,
    Class,
    C4,
    Cynefin,
    Wardley,
    Railroad,
    Kanban,
    Gantt,
    Pie,
    Packet,
    Timeline,
    Journey,
    Requirement,
    Sankey,
    Radar,
    Info,
    Treemap,
    Block,
    Er,
    QuadrantChart,
    XyChart,
    GitGraph,
    TreeView,
    Ishikawa,
    EventModeling,
    Venn,
    Usecase,
    Agentflow,
}

impl RenderFamilyKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Mindmap => "mindmap",
            Self::State => "state",
            Self::Sequence => "sequence",
            Self::Zenuml => "zenuml",
            Self::Flowchart => "flowchart",
            Self::Swimlane => "swimlane",
            Self::Architecture => "architecture",
            Self::Class => "class",
            Self::C4 => "c4",
            Self::Cynefin => "cynefin",
            Self::Wardley => "wardley",
            Self::Railroad => "railroad",
            Self::Kanban => "kanban",
            Self::Gantt => "gantt",
            Self::Pie => "pie",
            Self::Packet => "packet",
            Self::Timeline => "timeline",
            Self::Journey => "journey",
            Self::Requirement => "requirement",
            Self::Sankey => "sankey",
            Self::Radar => "radar",
            Self::Info => "info",
            Self::Treemap => "treemap",
            Self::Block => "block",
            Self::Er => "er",
            Self::QuadrantChart => "quadrantChart",
            Self::XyChart => "xychart",
            Self::GitGraph => "gitGraph",
            Self::TreeView => "treeView",
            Self::Ishikawa => "ishikawa",
            Self::EventModeling => "eventmodeling",
            Self::Venn => "venn",
            Self::Usecase => "usecase",
            Self::Agentflow => "agentflow",
        }
    }
}

/// Capabilities required by one parsed typed render operation before layout starts.
///
/// Requirements come from the canonically paired semantic model and effective Mermaid config;
/// availability comes from the compiled layout backends and the operation's render session.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderCapabilityPlan {
    diagram_type: String,
    required: Vec<RenderCapability>,
    missing: Vec<RenderCapability>,
    presentation_profile: Option<PresentationProfile>,
    presentation_aspects: Vec<PresentationAspectResolution>,
}

impl RenderCapabilityPlan {
    /// Returns the detected Mermaid diagram type used by render dispatch.
    pub fn diagram_type(&self) -> &str {
        &self.diagram_type
    }

    /// Returns every optional capability this operation requires.
    pub fn required_capabilities(&self) -> &[RenderCapability] {
        &self.required
    }

    /// Returns the required capabilities unavailable in the planned render session.
    pub fn missing_capabilities(&self) -> &[RenderCapability] {
        &self.missing
    }

    /// Returns the selected first-party presentation profile, if any.
    pub const fn presentation_profile(&self) -> Option<PresentationProfile> {
        self.presentation_profile
    }

    /// Returns the selected presentation profile's stable ID, if any.
    pub const fn presentation_profile_id(&self) -> Option<&'static str> {
        match self.presentation_profile {
            Some(profile) => Some(profile.id()),
            None => None,
        }
    }

    /// Returns per-aspect resolution for the selected presentation profile.
    pub fn presentation_aspects(&self) -> &[PresentationAspectResolution] {
        &self.presentation_aspects
    }

    /// Iterates over stable semantic IDs for every required capability.
    pub fn required_capability_ids(&self) -> impl ExactSizeIterator<Item = &'static str> + '_ {
        self.required.iter().copied().map(RenderCapability::id)
    }

    /// Iterates over stable semantic IDs for every missing capability.
    pub fn missing_capability_ids(&self) -> impl ExactSizeIterator<Item = &'static str> + '_ {
        self.missing.iter().copied().map(RenderCapability::id)
    }

    /// Reports whether the planned render session satisfies every requirement.
    pub fn is_ready(&self) -> bool {
        self.missing.is_empty()
    }

    fn ensure_available(&self) -> Result<()> {
        let Some(capability) = self.missing.first().copied() else {
            return Ok(());
        };
        Err(Error::MissingCapability {
            capability,
            diagram_type: self.diagram_type.clone(),
        })
    }
}

impl fmt::Display for RenderFamilyKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug)]
pub(crate) struct FamilyPair<S, L> {
    semantic: S,
    layout: L,
}

impl<S, L> FamilyPair<S, L> {
    fn new(semantic: S, layout: L) -> Self {
        Self { semantic, layout }
    }

    pub(crate) fn semantic(&self) -> &S {
        &self.semantic
    }

    pub(crate) fn layout(&self) -> &L {
        &self.layout
    }
}

impl<S: BuiltinRenderSemantic, L> FamilyPair<S, L> {
    fn compatibility_json(
        &self,
        metadata: &ParseMetadata,
    ) -> merman_core::Result<serde_json::Value> {
        self.semantic.compatibility_json(metadata)
    }
}

#[derive(Debug)]
#[cfg(any(
    feature = "diagram-flowchart",
    feature = "diagram-swimlane",
    feature = "diagram-agentflow"
))]
pub(crate) struct FlowchartFamilyArtifact<L> {
    pair: FamilyPair<diagrams::flowchart::FlowchartModel, L>,
    render_context: diagrams::flowchart::FlowchartRenderContext,
    svg_label_sidecar: crate::flowchart::FlowchartSvgLabelSidecar,
    policy: Option<FlowchartPresentationPolicy>,
}

#[cfg(any(
    feature = "diagram-flowchart",
    feature = "diagram-swimlane",
    feature = "diagram-agentflow"
))]
impl<L> FlowchartFamilyArtifact<L> {
    pub(crate) fn pair(&self) -> &FamilyPair<diagrams::flowchart::FlowchartModel, L> {
        &self.pair
    }

    pub(crate) fn render_context(&self) -> &diagrams::flowchart::FlowchartRenderContext {
        &self.render_context
    }

    pub(crate) fn svg_label_sidecar(&self) -> &crate::flowchart::FlowchartSvgLabelSidecar {
        &self.svg_label_sidecar
    }

    pub(crate) const fn policy(&self) -> Option<FlowchartPresentationPolicy> {
        self.policy
    }
}

#[derive(Debug)]
pub(crate) enum BuiltinFamilyArtifact {
    #[cfg(feature = "diagram-agentflow")]
    Agentflow {
        semantic: Box<diagrams::agentflow::AgentflowDiagramRenderModel>,
        flow: Box<FlowchartFamilyArtifact<FlowchartLayout>>,
    },
    Error(Box<FamilyPair<diagrams::error_diagram::ErrorDiagramRenderModel, ErrorDiagramLayout>>),
    #[cfg(feature = "diagram-mindmap")]
    Mindmap(Box<FamilyPair<diagrams::mindmap::MindmapDiagramRenderModel, MindmapDiagramLayout>>),
    #[cfg(feature = "diagram-state")]
    State(Box<FamilyPair<diagrams::state::StateDiagramRenderModel, StateDiagramLayout>>),
    #[cfg(feature = "diagram-sequence")]
    Sequence(
        Box<
            FamilyPair<
                diagrams::sequence::SequenceDiagramRenderModel,
                crate::sequence::SequencePreparedArtifact,
            >,
        >,
    ),
    #[cfg(feature = "diagram-zenuml")]
    Zenuml(
        Box<
            FamilyPair<
                diagrams::zenuml::ZenumlDiagramRenderModel,
                crate::zenuml::ZenumlDiagramLayout,
            >,
        >,
    ),
    #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
    Flowchart(Box<FlowchartFamilyArtifact<FlowchartLayout>>),
    #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
    Swimlane(Box<FlowchartFamilyArtifact<SwimlaneLayout>>),
    #[cfg(feature = "layout-cytoscape")]
    #[cfg(feature = "diagram-architecture")]
    Architecture(
        Box<
            FamilyPair<
                diagrams::architecture::ArchitectureDiagramRenderModel,
                ArchitectureDiagramLayout,
            >,
        >,
    ),
    #[cfg(feature = "diagram-class")]
    Class(Box<FamilyPair<ClassDiagram, ClassDiagramLayout>>),
    #[cfg(feature = "diagram-c4")]
    C4(Box<FamilyPair<diagrams::c4::C4DiagramRenderModel, C4DiagramLayout>>),
    #[cfg(feature = "diagram-cynefin")]
    Cynefin(Box<FamilyPair<diagrams::cynefin::CynefinDiagramRenderModel, CynefinDiagramLayout>>),
    #[cfg(feature = "diagram-wardley")]
    Wardley(Box<FamilyPair<diagrams::wardley::WardleyDiagramRenderModel, WardleyDiagramLayout>>),
    #[cfg(feature = "diagram-railroad")]
    Railroad(
        Box<FamilyPair<diagrams::railroad::RailroadDiagramRenderModel, RailroadDiagramLayout>>,
    ),
    #[cfg(feature = "diagram-kanban")]
    Kanban(
        Box<
            FamilyPair<
                diagrams::kanban::KanbanDiagramRenderModel,
                crate::kanban::KanbanPreparedArtifact,
            >,
        >,
    ),
    #[cfg(feature = "diagram-gantt")]
    Gantt(Box<FamilyPair<diagrams::gantt::GanttDiagramRenderModel, GanttDiagramLayout>>),
    #[cfg(feature = "diagram-pie")]
    Pie(Box<FamilyPair<diagrams::pie::PieDiagramRenderModel, PieDiagramLayout>>),
    #[cfg(feature = "diagram-packet")]
    Packet(Box<FamilyPair<diagrams::packet::PacketDiagramRenderModel, PacketDiagramLayout>>),
    #[cfg(feature = "diagram-timeline")]
    Timeline(
        Box<FamilyPair<diagrams::timeline::TimelineDiagramRenderModel, TimelineDiagramLayout>>,
    ),
    #[cfg(feature = "diagram-journey")]
    Journey(Box<FamilyPair<diagrams::journey::JourneyDiagramRenderModel, JourneyDiagramLayout>>),
    #[cfg(feature = "diagram-requirement")]
    Requirement(
        Box<
            FamilyPair<
                diagrams::requirement::RequirementDiagramRenderModel,
                crate::requirement::RequirementPreparedArtifact,
            >,
        >,
    ),
    #[cfg(feature = "diagram-sankey")]
    Sankey(Box<FamilyPair<diagrams::sankey::SankeyDiagramRenderModel, SankeyDiagramLayout>>),
    #[cfg(feature = "diagram-radar")]
    Radar(Box<FamilyPair<diagrams::radar::RadarDiagramRenderModel, RadarDiagramLayout>>),
    #[cfg(feature = "diagram-info")]
    Info(Box<FamilyPair<diagrams::info::InfoDiagramRenderModel, InfoDiagramLayout>>),
    #[cfg(feature = "diagram-treemap")]
    Treemap(Box<FamilyPair<diagrams::treemap::TreemapDiagramRenderModel, TreemapDiagramLayout>>),
    #[cfg(feature = "diagram-block")]
    Block(Box<FamilyPair<diagrams::block::BlockDiagramRenderModel, BlockDiagramLayout>>),
    #[cfg(feature = "diagram-er")]
    Er(Box<FamilyPair<diagrams::er::ErDiagramRenderModel, ErDiagramLayout>>),
    #[cfg(feature = "diagram-quadrant-chart")]
    QuadrantChart(
        Box<
            FamilyPair<
                diagrams::quadrant_chart::QuadrantChartRenderModel,
                QuadrantChartDiagramLayout,
            >,
        >,
    ),
    #[cfg(feature = "diagram-xychart")]
    XyChart(Box<FamilyPair<diagrams::xychart::XyChartDiagramRenderModel, XyChartDiagramLayout>>),
    #[cfg(feature = "diagram-git-graph")]
    GitGraph(Box<FamilyPair<diagrams::git_graph::GitGraphRenderModel, GitGraphDiagramLayout>>),
    #[cfg(feature = "diagram-tree-view")]
    TreeView(
        Box<FamilyPair<diagrams::tree_view::TreeViewDiagramRenderModel, TreeViewDiagramLayout>>,
    ),
    #[cfg(feature = "diagram-ishikawa")]
    Ishikawa(
        Box<FamilyPair<diagrams::ishikawa::IshikawaDiagramRenderModel, IshikawaDiagramLayout>>,
    ),
    #[cfg(feature = "diagram-event-modeling")]
    EventModeling(
        Box<
            FamilyPair<
                diagrams::eventmodeling::EventModelingDiagramRenderModel,
                EventModelingDiagramLayout,
            >,
        >,
    ),
    #[cfg(feature = "diagram-venn")]
    Venn(Box<FamilyPair<diagrams::venn::VennDiagramRenderModel, VennDiagramLayout>>),
    #[cfg(feature = "diagram-usecase")]
    Usecase(
        Box<
            FamilyPair<
                diagrams::usecase::UsecaseDiagramRenderModel,
                crate::usecase::UsecasePreparedArtifact,
            >,
        >,
    ),
}

#[derive(serde::Serialize)]
enum LayoutProjection<'a> {
    #[cfg(feature = "diagram-agentflow")]
    AgentflowDiagram(&'a FlowchartLayout),
    #[cfg(feature = "diagram-block")]
    BlockDiagram(&'a BlockDiagramLayout),
    #[cfg(feature = "diagram-requirement")]
    RequirementDiagram(&'a RequirementDiagramLayout),
    #[cfg(feature = "layout-cytoscape")]
    #[cfg(feature = "diagram-architecture")]
    ArchitectureDiagram(&'a ArchitectureDiagramLayout),
    #[cfg(feature = "diagram-mindmap")]
    MindmapDiagram(&'a MindmapDiagramLayout),
    #[cfg(feature = "diagram-sankey")]
    SankeyDiagram(&'a SankeyDiagramLayout),
    #[cfg(feature = "diagram-radar")]
    RadarDiagram(&'a RadarDiagramLayout),
    #[cfg(feature = "diagram-treemap")]
    TreemapDiagram(&'a TreemapDiagramLayout),
    #[cfg(feature = "diagram-venn")]
    VennDiagram(&'a VennDiagramLayout),
    #[cfg(feature = "diagram-usecase")]
    UsecaseDiagram(&'a crate::usecase::UsecaseDiagramLayout),
    #[cfg(feature = "diagram-xychart")]
    XyChartDiagram(&'a XyChartDiagramLayout),
    #[cfg(feature = "diagram-quadrant-chart")]
    QuadrantChartDiagram(&'a QuadrantChartDiagramLayout),
    #[serde(rename = "FlowchartV2")]
    #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
    Flowchart(&'a FlowchartLayout),
    #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
    SwimlaneDiagram(&'a SwimlaneLayout),
    #[serde(rename = "StateDiagramV2")]
    #[cfg(feature = "diagram-state")]
    StateDiagram(&'a StateDiagramLayout),
    #[serde(rename = "ClassDiagramV2")]
    #[cfg(feature = "diagram-class")]
    ClassDiagram(&'a ClassDiagramLayout),
    #[cfg(feature = "diagram-er")]
    ErDiagram(&'a ErDiagramLayout),
    #[cfg(feature = "diagram-sequence")]
    SequenceDiagram(&'a SequenceDiagramLayout),
    #[cfg(feature = "diagram-zenuml")]
    ZenumlDiagram(&'a crate::zenuml::ZenumlDiagramLayout),
    #[cfg(feature = "diagram-info")]
    InfoDiagram(&'a InfoDiagramLayout),
    #[cfg(feature = "diagram-packet")]
    PacketDiagram(&'a PacketDiagramLayout),
    #[cfg(feature = "diagram-timeline")]
    TimelineDiagram(&'a TimelineDiagramLayout),
    #[cfg(feature = "diagram-pie")]
    PieDiagram(&'a PieDiagramLayout),
    #[cfg(feature = "diagram-journey")]
    JourneyDiagram(&'a JourneyDiagramLayout),
    #[cfg(feature = "diagram-kanban")]
    KanbanDiagram(&'a KanbanDiagramLayout),
    #[cfg(feature = "diagram-git-graph")]
    GitGraphDiagram(&'a GitGraphDiagramLayout),
    #[cfg(feature = "diagram-tree-view")]
    TreeViewDiagram(&'a TreeViewDiagramLayout),
    #[cfg(feature = "diagram-ishikawa")]
    IshikawaDiagram(&'a IshikawaDiagramLayout),
    #[cfg(feature = "diagram-event-modeling")]
    EventModelingDiagram(&'a EventModelingDiagramLayout),
    #[cfg(feature = "diagram-cynefin")]
    CynefinDiagram(&'a CynefinDiagramLayout),
    #[cfg(feature = "diagram-wardley")]
    WardleyDiagram(&'a WardleyDiagramLayout),
    #[cfg(feature = "diagram-railroad")]
    RailroadDiagram(&'a RailroadDiagramLayout),
    #[cfg(feature = "diagram-gantt")]
    GanttDiagram(&'a GanttDiagramLayout),
    #[cfg(feature = "diagram-c4")]
    C4Diagram(&'a C4DiagramLayout),
    ErrorDiagram(&'a ErrorDiagramLayout),
}

fn clone_json_value_nonrecursive(value: &serde_json::Value) -> serde_json::Value {
    let mut cloned = rustc_hash::FxHashMap::default();
    let mut stack = vec![(value, false)];

    while let Some((current, visited)) = stack.pop() {
        let current_ptr = std::ptr::from_ref(current);
        if visited {
            let value = match current {
                serde_json::Value::Null => serde_json::Value::Null,
                serde_json::Value::Bool(value) => serde_json::Value::Bool(*value),
                serde_json::Value::Number(value) => serde_json::Value::Number(value.clone()),
                serde_json::Value::String(value) => serde_json::Value::String(value.clone()),
                serde_json::Value::Array(items) => serde_json::Value::Array(
                    items
                        .iter()
                        .filter_map(|item| cloned.remove(&std::ptr::from_ref(item)))
                        .collect(),
                ),
                serde_json::Value::Object(entries) => {
                    let mut object = serde_json::Map::new();
                    for (key, child) in entries {
                        if let Some(value) = cloned.remove(&std::ptr::from_ref(child)) {
                            object.insert(key.clone(), value);
                        }
                    }
                    serde_json::Value::Object(object)
                }
            };
            cloned.insert(current_ptr, value);
            continue;
        }

        stack.push((current, true));
        match current {
            serde_json::Value::Array(items) => {
                for item in items.iter().rev() {
                    stack.push((item, false));
                }
            }
            serde_json::Value::Object(entries) => {
                for child in entries.values().rev() {
                    stack.push((child, false));
                }
            }
            serde_json::Value::Null
            | serde_json::Value::Bool(_)
            | serde_json::Value::Number(_)
            | serde_json::Value::String(_) => {}
        }
    }

    cloned
        .remove(&std::ptr::from_ref(value))
        .unwrap_or(serde_json::Value::Null)
}

impl BuiltinFamilyArtifact {
    pub fn kind(&self) -> RenderFamilyKind {
        match self {
            #[cfg(feature = "diagram-agentflow")]
            Self::Agentflow { .. } => RenderFamilyKind::Agentflow,
            Self::Error(_) => RenderFamilyKind::Error,
            #[cfg(feature = "diagram-mindmap")]
            Self::Mindmap(_) => RenderFamilyKind::Mindmap,
            #[cfg(feature = "diagram-state")]
            Self::State(_) => RenderFamilyKind::State,
            #[cfg(feature = "diagram-sequence")]
            Self::Sequence(_) => RenderFamilyKind::Sequence,
            #[cfg(feature = "diagram-zenuml")]
            Self::Zenuml(_) => RenderFamilyKind::Zenuml,
            #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
            Self::Flowchart(_) => RenderFamilyKind::Flowchart,
            #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
            Self::Swimlane(_) => RenderFamilyKind::Swimlane,
            #[cfg(feature = "layout-cytoscape")]
            #[cfg(feature = "diagram-architecture")]
            Self::Architecture(_) => RenderFamilyKind::Architecture,
            #[cfg(feature = "diagram-class")]
            Self::Class(_) => RenderFamilyKind::Class,
            #[cfg(feature = "diagram-c4")]
            Self::C4(_) => RenderFamilyKind::C4,
            #[cfg(feature = "diagram-cynefin")]
            Self::Cynefin(_) => RenderFamilyKind::Cynefin,
            #[cfg(feature = "diagram-wardley")]
            Self::Wardley(_) => RenderFamilyKind::Wardley,
            #[cfg(feature = "diagram-railroad")]
            Self::Railroad(_) => RenderFamilyKind::Railroad,
            #[cfg(feature = "diagram-kanban")]
            Self::Kanban(_) => RenderFamilyKind::Kanban,
            #[cfg(feature = "diagram-gantt")]
            Self::Gantt(_) => RenderFamilyKind::Gantt,
            #[cfg(feature = "diagram-pie")]
            Self::Pie(_) => RenderFamilyKind::Pie,
            #[cfg(feature = "diagram-packet")]
            Self::Packet(_) => RenderFamilyKind::Packet,
            #[cfg(feature = "diagram-timeline")]
            Self::Timeline(_) => RenderFamilyKind::Timeline,
            #[cfg(feature = "diagram-journey")]
            Self::Journey(_) => RenderFamilyKind::Journey,
            #[cfg(feature = "diagram-requirement")]
            Self::Requirement(_) => RenderFamilyKind::Requirement,
            #[cfg(feature = "diagram-sankey")]
            Self::Sankey(_) => RenderFamilyKind::Sankey,
            #[cfg(feature = "diagram-radar")]
            Self::Radar(_) => RenderFamilyKind::Radar,
            #[cfg(feature = "diagram-info")]
            Self::Info(_) => RenderFamilyKind::Info,
            #[cfg(feature = "diagram-treemap")]
            Self::Treemap(_) => RenderFamilyKind::Treemap,
            #[cfg(feature = "diagram-block")]
            Self::Block(_) => RenderFamilyKind::Block,
            #[cfg(feature = "diagram-er")]
            Self::Er(_) => RenderFamilyKind::Er,
            #[cfg(feature = "diagram-quadrant-chart")]
            Self::QuadrantChart(_) => RenderFamilyKind::QuadrantChart,
            #[cfg(feature = "diagram-xychart")]
            Self::XyChart(_) => RenderFamilyKind::XyChart,
            #[cfg(feature = "diagram-git-graph")]
            Self::GitGraph(_) => RenderFamilyKind::GitGraph,
            #[cfg(feature = "diagram-tree-view")]
            Self::TreeView(_) => RenderFamilyKind::TreeView,
            #[cfg(feature = "diagram-ishikawa")]
            Self::Ishikawa(_) => RenderFamilyKind::Ishikawa,
            #[cfg(feature = "diagram-event-modeling")]
            Self::EventModeling(_) => RenderFamilyKind::EventModeling,
            #[cfg(feature = "diagram-venn")]
            Self::Venn(_) => RenderFamilyKind::Venn,
            #[cfg(feature = "diagram-usecase")]
            Self::Usecase(_) => RenderFamilyKind::Usecase,
        }
    }

    fn compatibility_json(
        &self,
        metadata: &ParseMetadata,
    ) -> merman_core::Result<serde_json::Value> {
        match self {
            #[cfg(feature = "diagram-agentflow")]
            Self::Agentflow { semantic, .. } => semantic.compatibility_json(metadata),
            Self::Error(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-mindmap")]
            Self::Mindmap(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-state")]
            Self::State(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-sequence")]
            Self::Sequence(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-zenuml")]
            Self::Zenuml(pair) => pair.compatibility_json(metadata),
            #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
            Self::Flowchart(artifact) => artifact.pair.compatibility_json(metadata),
            #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
            Self::Swimlane(artifact) => artifact.pair.compatibility_json(metadata),
            #[cfg(feature = "layout-cytoscape")]
            #[cfg(feature = "diagram-architecture")]
            Self::Architecture(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-class")]
            Self::Class(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-c4")]
            Self::C4(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-cynefin")]
            Self::Cynefin(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-wardley")]
            Self::Wardley(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-railroad")]
            Self::Railroad(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-kanban")]
            Self::Kanban(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-gantt")]
            Self::Gantt(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-pie")]
            Self::Pie(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-packet")]
            Self::Packet(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-timeline")]
            Self::Timeline(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-journey")]
            Self::Journey(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-requirement")]
            Self::Requirement(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-sankey")]
            Self::Sankey(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-radar")]
            Self::Radar(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-info")]
            Self::Info(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-treemap")]
            Self::Treemap(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-block")]
            Self::Block(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-er")]
            Self::Er(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-quadrant-chart")]
            Self::QuadrantChart(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-xychart")]
            Self::XyChart(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-git-graph")]
            Self::GitGraph(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-tree-view")]
            Self::TreeView(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-ishikawa")]
            Self::Ishikawa(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-event-modeling")]
            Self::EventModeling(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-venn")]
            Self::Venn(pair) => pair.compatibility_json(metadata),
            #[cfg(feature = "diagram-usecase")]
            Self::Usecase(pair) => pair.compatibility_json(metadata),
        }
    }

    fn layout_projection(&self) -> LayoutProjection<'_> {
        match self {
            #[cfg(feature = "diagram-agentflow")]
            Self::Agentflow { flow, .. } => LayoutProjection::AgentflowDiagram(flow.pair.layout()),
            Self::Error(pair) => LayoutProjection::ErrorDiagram(pair.layout()),
            #[cfg(feature = "diagram-mindmap")]
            Self::Mindmap(pair) => LayoutProjection::MindmapDiagram(pair.layout()),
            #[cfg(feature = "diagram-state")]
            Self::State(pair) => LayoutProjection::StateDiagram(pair.layout()),
            #[cfg(feature = "diagram-sequence")]
            Self::Sequence(pair) => LayoutProjection::SequenceDiagram(pair.layout().layout()),
            #[cfg(feature = "diagram-zenuml")]
            Self::Zenuml(pair) => LayoutProjection::ZenumlDiagram(pair.layout()),
            #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
            Self::Flowchart(artifact) => LayoutProjection::Flowchart(artifact.pair.layout()),
            #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
            Self::Swimlane(artifact) => LayoutProjection::SwimlaneDiagram(artifact.pair.layout()),
            #[cfg(feature = "layout-cytoscape")]
            #[cfg(feature = "diagram-architecture")]
            Self::Architecture(pair) => LayoutProjection::ArchitectureDiagram(pair.layout()),
            #[cfg(feature = "diagram-class")]
            Self::Class(pair) => LayoutProjection::ClassDiagram(pair.layout()),
            #[cfg(feature = "diagram-c4")]
            Self::C4(pair) => LayoutProjection::C4Diagram(pair.layout()),
            #[cfg(feature = "diagram-cynefin")]
            Self::Cynefin(pair) => LayoutProjection::CynefinDiagram(pair.layout()),
            #[cfg(feature = "diagram-wardley")]
            Self::Wardley(pair) => LayoutProjection::WardleyDiagram(pair.layout()),
            #[cfg(feature = "diagram-railroad")]
            Self::Railroad(pair) => LayoutProjection::RailroadDiagram(pair.layout()),
            #[cfg(feature = "diagram-kanban")]
            Self::Kanban(pair) => LayoutProjection::KanbanDiagram(pair.layout().layout()),
            #[cfg(feature = "diagram-gantt")]
            Self::Gantt(pair) => LayoutProjection::GanttDiagram(pair.layout()),
            #[cfg(feature = "diagram-pie")]
            Self::Pie(pair) => LayoutProjection::PieDiagram(pair.layout()),
            #[cfg(feature = "diagram-packet")]
            Self::Packet(pair) => LayoutProjection::PacketDiagram(pair.layout()),
            #[cfg(feature = "diagram-timeline")]
            Self::Timeline(pair) => LayoutProjection::TimelineDiagram(pair.layout()),
            #[cfg(feature = "diagram-journey")]
            Self::Journey(pair) => LayoutProjection::JourneyDiagram(pair.layout()),
            #[cfg(feature = "diagram-requirement")]
            Self::Requirement(pair) => LayoutProjection::RequirementDiagram(pair.layout().layout()),
            #[cfg(feature = "diagram-sankey")]
            Self::Sankey(pair) => LayoutProjection::SankeyDiagram(pair.layout()),
            #[cfg(feature = "diagram-radar")]
            Self::Radar(pair) => LayoutProjection::RadarDiagram(pair.layout()),
            #[cfg(feature = "diagram-info")]
            Self::Info(pair) => LayoutProjection::InfoDiagram(pair.layout()),
            #[cfg(feature = "diagram-treemap")]
            Self::Treemap(pair) => LayoutProjection::TreemapDiagram(pair.layout()),
            #[cfg(feature = "diagram-block")]
            Self::Block(pair) => LayoutProjection::BlockDiagram(pair.layout()),
            #[cfg(feature = "diagram-er")]
            Self::Er(pair) => LayoutProjection::ErDiagram(pair.layout()),
            #[cfg(feature = "diagram-quadrant-chart")]
            Self::QuadrantChart(pair) => LayoutProjection::QuadrantChartDiagram(pair.layout()),
            #[cfg(feature = "diagram-xychart")]
            Self::XyChart(pair) => LayoutProjection::XyChartDiagram(pair.layout()),
            #[cfg(feature = "diagram-git-graph")]
            Self::GitGraph(pair) => LayoutProjection::GitGraphDiagram(pair.layout()),
            #[cfg(feature = "diagram-tree-view")]
            Self::TreeView(pair) => LayoutProjection::TreeViewDiagram(pair.layout()),
            #[cfg(feature = "diagram-ishikawa")]
            Self::Ishikawa(pair) => LayoutProjection::IshikawaDiagram(pair.layout()),
            #[cfg(feature = "diagram-event-modeling")]
            Self::EventModeling(pair) => LayoutProjection::EventModelingDiagram(pair.layout()),
            #[cfg(feature = "diagram-venn")]
            Self::Venn(pair) => LayoutProjection::VennDiagram(pair.layout()),
            #[cfg(feature = "diagram-usecase")]
            Self::Usecase(pair) => LayoutProjection::UsecaseDiagram(pair.layout().layout()),
        }
    }
}

pub struct FamilyRenderArtifact {
    metadata: ParseMetadata,
    compatibility_projection: OnceLock<std::result::Result<serde_json::Value, String>>,
    family: BuiltinFamilyArtifact,
    required_capabilities: Vec<RenderCapability>,
    session: RenderSession,
}

/// Owned projection of the Gantt time scale used by comparison tooling.
///
/// The projection deliberately hides the full family layout. Its inverse uses the same rounded
/// pixel mapping as the renderer, so coordinates that fall between representable task times return
/// `None` instead of inventing a timestamp.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GanttTimeAxisDiagnostics {
    min_ms: i64,
    max_ms: i64,
    left_x: f64,
    drawable_width: f64,
}

impl GanttTimeAxisDiagnostics {
    #[cfg(feature = "diagram-gantt")]
    fn from_layout(layout: &GanttDiagramLayout) -> Option<Self> {
        let min_ms = layout.tasks.iter().map(|task| task.start_ms).min()?;
        let max_ms = layout.tasks.iter().map(|task| task.end_ms).max()?;
        if max_ms <= min_ms {
            return None;
        }

        let left_x = layout.left_padding;
        let drawable_width = (layout.width - layout.left_padding - layout.right_padding).max(1.0);
        if !left_x.is_finite() || !drawable_width.is_finite() {
            return None;
        }

        Some(Self {
            min_ms,
            max_ms,
            left_x,
            drawable_width,
        })
    }

    /// Resolves an exact rendered x coordinate back to a Unix timestamp in milliseconds.
    pub fn unix_millis_at_rendered_x(&self, target_x: f64) -> Option<i64> {
        if !target_x.is_finite() {
            return None;
        }

        let span_ms = (i128::from(self.max_ms) - i128::from(self.min_ms)) as f64;
        let scaled_x = target_x - self.left_x;
        if !span_ms.is_finite() || !scaled_x.is_finite() {
            return None;
        }

        let estimate = self.min_ms as f64 + span_ms * (scaled_x / self.drawable_width);
        if !estimate.is_finite() {
            return None;
        }

        let mut lo = estimate.round() as i64;
        let mut hi = lo;
        let mut step = 1_i64;
        for _ in 0..80 {
            if self.rendered_x(lo)? <= target_x {
                break;
            }
            hi = lo;
            lo = lo.saturating_sub(step);
            step = step.saturating_mul(2);
        }

        step = 1;
        for _ in 0..80 {
            if self.rendered_x(hi)? >= target_x {
                break;
            }
            lo = hi;
            hi = hi.saturating_add(step);
            step = step.saturating_mul(2);
        }

        let lo_x = self.rendered_x(lo)?;
        let hi_x = self.rendered_x(hi)?;
        if !(lo_x <= target_x && target_x <= hi_x) {
            return None;
        }

        while lo < hi {
            let half_distance = ((i128::from(hi) - i128::from(lo)) / 2) as i64;
            let mid = lo + half_distance;
            if self.rendered_x(mid)? < target_x {
                lo = mid.saturating_add(1);
            } else {
                hi = mid;
            }
        }

        (self.rendered_x(lo)? == target_x).then_some(lo)
    }

    fn rendered_x(&self, unix_millis: i64) -> Option<f64> {
        let offset_ms = (i128::from(unix_millis) - i128::from(self.min_ms)) as f64;
        let span_ms = (i128::from(self.max_ms) - i128::from(self.min_ms)) as f64;
        let x = self.left_x + (offset_ms / span_ms * self.drawable_width).round();
        x.is_finite().then_some(x)
    }
}

/// A completed family SVG produced by the canonical typed render operation.
///
/// Root completion evidence is private to the renderer and cannot be named by callers:
///
/// ```compile_fail
/// use merman_render::svg::RootedSvg;
/// ```
///
/// A raw string cannot be substituted for a completed family SVG:
///
/// ```compile_fail
/// use merman_render::family::RenderedFamilySvg;
///
/// let forged: RenderedFamilySvg = String::from("<svg xmlns=\"http://www.w3.org/2000/svg\"/>");
/// ```
pub struct RenderedFamilySvg {
    svg: String,
    family_kind: RenderFamilyKind,
    metadata: ParseMetadata,
    required_capabilities: Vec<RenderCapability>,
    session: RenderSession,
}

impl RenderedFamilySvg {
    pub fn svg(&self) -> &str {
        &self.svg
    }

    pub fn metadata(&self) -> &ParseMetadata {
        &self.metadata
    }

    pub fn family_kind(&self) -> RenderFamilyKind {
        self.family_kind
    }

    /// Returns the optional capabilities admitted during this artifact's preparation.
    pub fn required_capabilities(&self) -> &[RenderCapability] {
        &self.required_capabilities
    }

    /// Applies an output pipeline while retaining the renderer-owned family capability.
    pub fn apply_pipeline(mut self, pipeline: &SvgPipeline) -> Result<Self> {
        self.session.checkpoint(OperationPhase::Postprocess)?;
        let output_metadata = self.output_metadata()?;
        self.svg = pipeline.process_owned_to_string_with_metadata(
            self.svg,
            &output_metadata,
            &self.session,
        )?;
        self.session.work_meter().preflight_svg_byte_count(
            self.svg.len(),
            ResourceLimitPhase::SvgPostprocess,
            OperationPhase::Postprocess,
        )?;
        self.session.checkpoint(OperationPhase::Postprocess)?;
        Ok(self)
    }

    /// Finalizes the typed family output for resvg/raster consumption.
    pub fn finalize_resvg(self, pipeline: &SvgPipeline) -> Result<RenderedResvgCompatibleSvg> {
        self.session.checkpoint(OperationPhase::Export)?;
        let output_metadata = self.output_metadata()?;
        let svg = pipeline.process_owned_resvg_compatible_with_metadata(
            self.svg,
            &output_metadata,
            &self.session,
        )?;
        self.session.work_meter().preflight_svg_byte_count(
            svg.as_str().len(),
            ResourceLimitPhase::SvgPostprocess,
            OperationPhase::Export,
        )?;
        self.session.checkpoint(OperationPhase::Export)?;
        Ok(RenderedResvgCompatibleSvg {
            svg,
            family_kind: self.family_kind,
            metadata: self.metadata,
            session: self.session,
        })
    }

    fn output_metadata(&self) -> Result<SvgPostprocessMetadata> {
        let metadata = SvgPostprocessMetadata::from_svg_with_execution(
            &self.svg,
            SvgPostprocessExecution::new(&self.session),
        )?;
        Ok(metadata
            .with_family_kind(self.family_kind)
            .with_diagram_type(self.metadata.diagram_type.clone())
            .with_optional_diagram_title(self.metadata.title.clone()))
    }

    pub fn into_parts(self) -> (String, RenderFamilyKind, ParseMetadata, RenderSession) {
        (self.svg, self.family_kind, self.metadata, self.session)
    }
}

/// Renderer-owned family output after the terminal resvg compatibility finalizer.
pub struct RenderedResvgCompatibleSvg {
    svg: ResvgCompatibleSvg,
    family_kind: RenderFamilyKind,
    metadata: ParseMetadata,
    session: RenderSession,
}

impl RenderedResvgCompatibleSvg {
    pub fn svg(&self) -> &ResvgCompatibleSvg {
        &self.svg
    }

    pub fn into_parts(
        self,
    ) -> (
        ResvgCompatibleSvg,
        RenderFamilyKind,
        ParseMetadata,
        RenderSession,
    ) {
        (self.svg, self.family_kind, self.metadata, self.session)
    }
}

impl FamilyRenderArtifact {
    pub fn metadata(&self) -> &ParseMetadata {
        &self.metadata
    }

    pub fn family_kind(&self) -> RenderFamilyKind {
        self.family.kind()
    }

    pub fn gantt_time_axis_diagnostics(&self) -> Option<GanttTimeAxisDiagnostics> {
        match &self.family {
            #[cfg(feature = "diagram-gantt")]
            BuiltinFamilyArtifact::Gantt(pair) => {
                GanttTimeAxisDiagnostics::from_layout(pair.layout())
            }
            _ => None,
        }
    }

    pub fn layout_json(&self) -> Result<serde_json::Value> {
        self.session.checkpoint(OperationPhase::Emit)?;
        let semantic = self
            .compatibility_projection
            .get_or_init(|| {
                self.family
                    .compatibility_json(&self.metadata)
                    .map_err(|error| {
                        format!(
                            "failed to project {} compatibility JSON: {error}",
                            self.family.kind()
                        )
                    })
            })
            .as_ref()
            .map_err(|message| Error::InvalidModel {
                message: message.clone(),
            })?;
        let layout = serde_json::to_value(self.family.layout_projection())?;

        let mut metadata = serde_json::Map::new();
        metadata.insert(
            "diagram_type".to_string(),
            serde_json::Value::String(self.metadata.diagram_type.clone()),
        );
        metadata.insert(
            "title".to_string(),
            self.metadata
                .title
                .as_ref()
                .map_or(serde_json::Value::Null, |title| {
                    serde_json::Value::String(title.clone())
                }),
        );
        metadata.insert(
            "config".to_string(),
            clone_json_value_nonrecursive(self.metadata.config.as_value()),
        );
        metadata.insert(
            "effective_config".to_string(),
            clone_json_value_nonrecursive(self.metadata.effective_config.as_value()),
        );

        let mut projection = serde_json::Map::new();
        projection.insert("meta".to_string(), serde_json::Value::Object(metadata));
        projection.insert(
            "semantic".to_string(),
            clone_json_value_nonrecursive(semantic),
        );
        projection.insert("layout".to_string(), layout);
        self.session.checkpoint(OperationPhase::Emit)?;
        Ok(serde_json::Value::Object(projection))
    }

    pub fn render_svg(
        self,
        options: &SvgRenderOptions,
        debug: &SvgDebugOptions,
    ) -> Result<RenderedFamilySvg> {
        self.session.checkpoint(OperationPhase::Emit)?;
        let trace_stage = debug.flowchart_edge_trace().map(|(edge_id, destination)| {
            let staging = FlowchartEdgeTraceCollector::default();
            let staged_debug = debug
                .clone()
                .with_flowchart_edge_trace(edge_id.to_owned(), staging.clone());
            (destination.clone(), staging, staged_debug)
        });
        let render_debug = trace_stage
            .as_ref()
            .map_or(debug, |(_, _, staged_debug)| staged_debug);
        let svg = render_family_artifact_svg(&self, options, render_debug)?;
        admit_rendered_svg_output(&self.session, &svg)?;
        self.session.checkpoint(OperationPhase::Emit)?;
        if let Some((destination, staging, _)) = trace_stage {
            for trace in staging.drain() {
                destination.record(trace);
            }
        }
        let family_kind = self.family.kind();
        let Self {
            metadata,
            compatibility_projection: _,
            family: _,
            required_capabilities,
            session,
        } = self;

        Ok(RenderedFamilySvg {
            svg,
            family_kind,
            metadata,
            required_capabilities,
            session,
        })
    }
}

fn admit_rendered_svg_output(session: &RenderSession, svg: &str) -> Result<()> {
    // Termination wins over the final output ceiling when both become observable during emit.
    session.checkpoint(OperationPhase::Emit)?;
    session.work_meter().preflight_svg_byte_count(
        svg.len(),
        ResourceLimitPhase::SvgOutput,
        OperationPhase::Emit,
    )?;
    Ok(())
}

#[inline(never)]
fn render_family_artifact_svg(
    artifact: &FamilyRenderArtifact,
    request: &SvgRenderOptions,
    debug: &SvgDebugOptions,
) -> Result<String> {
    let options = crate::svg::normalize_svg_render_options(request, &artifact.session)?;
    #[cfg(feature = "diagram-agentflow")]
    // Agentflow is adapted to the Flowchart renderer, while Mermaid's config namespace remains
    // `agentflow`. Keep the public metadata untouched and project only the renderer input.
    let projected_metadata = if matches!(&artifact.family, BuiltinFamilyArtifact::Agentflow { .. })
    {
        let mut metadata = artifact.metadata.clone();
        metadata.effective_config = project_agentflow_flowchart_config(&metadata.effective_config);
        Some(metadata)
    } else {
        None
    };
    #[cfg(feature = "diagram-agentflow")]
    let metadata = projected_metadata.as_ref().unwrap_or(&artifact.metadata);
    #[cfg(not(feature = "diagram-agentflow"))]
    let metadata = &artifact.metadata;
    #[cfg(all(feature = "layout-cytoscape", feature = "diagram-architecture"))]
    if let BuiltinFamilyArtifact::Architecture(pair) = &artifact.family {
        return crate::svg::render_architecture_family_artifact(
            pair,
            &metadata.effective_config,
            &artifact.session,
            &options,
            debug,
        );
    }
    crate::svg::render_builtin_family_artifact(
        &artifact.family,
        metadata,
        &artifact.session,
        &options,
        debug,
    )
}

#[inline(never)]
fn prepare_pair<S, L>(
    semantic: S,
    layout: impl FnOnce(&S) -> Result<L>,
) -> Result<Box<FamilyPair<S, L>>> {
    let layout = layout(&semantic)?;
    Ok(Box::new(FamilyPair::new(semantic, layout)))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FlowchartSvgLabelPreparation(bool);

impl FlowchartSvgLabelPreparation {
    #[cfg(any(
        feature = "diagram-flowchart",
        feature = "diagram-swimlane",
        feature = "diagram-agentflow"
    ))]
    const fn enabled(self) -> bool {
        self.0
    }
}

const DEFAULT_FLOWCHART_SVG_LABEL_PREPARATION: FlowchartSvgLabelPreparation =
    FlowchartSvgLabelPreparation(true);

#[cfg(any(
    feature = "diagram-flowchart",
    feature = "diagram-swimlane",
    feature = "diagram-agentflow"
))]
fn prepare_flowchart_artifact<L>(
    semantic: diagrams::flowchart::FlowchartModel,
    render_context: diagrams::flowchart::FlowchartRenderContext,
    policy: Option<FlowchartPresentationPolicy>,
    svg_label_preparation: FlowchartSvgLabelPreparation,
    layout: impl FnOnce(
        &diagrams::flowchart::FlowchartModel,
        &diagrams::flowchart::FlowchartRenderContext,
        Option<&crate::flowchart::FlowchartSvgLabelSidecarBuilder>,
    ) -> Result<L>,
) -> Result<Box<FlowchartFamilyArtifact<L>>> {
    let svg_label_sidecar = svg_label_preparation
        .enabled()
        .then(crate::flowchart::FlowchartSvgLabelSidecarBuilder::default);
    let layout = layout(&semantic, &render_context, svg_label_sidecar.as_ref())?;
    let svg_label_sidecar = svg_label_sidecar
        .map(crate::flowchart::FlowchartSvgLabelSidecarBuilder::finish)
        .unwrap_or_default();
    Ok(Box::new(FlowchartFamilyArtifact {
        pair: FamilyPair::new(semantic, layout),
        render_context,
        svg_label_sidecar,
        policy,
    }))
}

#[cfg(feature = "diagram-agentflow")]
fn project_agentflow_flowchart_config(
    config: &merman_core::MermaidConfig,
) -> merman_core::MermaidConfig {
    let mut projected = config.clone();
    let root = config.as_value();
    let agentflow = root.get("agentflow").unwrap_or(&serde_json::Value::Null);
    // Agentflow's renderer owns the root viewport. Defaults here mirror its `??`
    // expressions; normal Engine configuration already includes schema defaults.
    // Overwrite even absent family values so unrelated Flowchart settings cannot leak in.
    for (key, fallback) in [
        ("diagramPadding", serde_json::json!(8)),
        ("useMaxWidth", serde_json::json!(true)),
        ("titleTopMargin", serde_json::json!(0)),
    ] {
        let value = agentflow.get(key).filter(|value| !value.is_null());
        projected.set_value(
            &format!("flowchart.{key}"),
            value.cloned().unwrap_or(fallback),
        );
    }
    // Dagre takes a truthy root override before the renderer's family spacing.
    // Mermaid's ELK adapter ignores all three configuration namespaces for spacing.
    // Our shared adapter reads Flowchart settings, so keep its default spacing for ELK.
    // Resolve registration first: an unavailable ELK loader executes Dagre instead.
    let uses_dagre = crate::layout_backend::resolve_graph_layout(root).backend
        == crate::layout_backend::GraphLayoutBackend::Dagre;
    for key in ["nodeSpacing", "rankSpacing"] {
        let value = uses_dagre
            .then(|| {
                root.get(key)
                    .filter(|value| crate::config::json_value_is_truthy(value))
                    .or_else(|| {
                        agentflow
                            .get(key)
                            .filter(|value| crate::config::json_value_is_truthy(value))
                    })
            })
            .flatten();
        projected.set_value(
            &format!("flowchart.{key}"),
            value.cloned().unwrap_or_else(|| serde_json::json!(50)),
        );
    }
    // AgentflowDB assigns these values to each node before the shared shape helpers
    // read them. Node-specific values precede Flowchart configuration; only a falsy
    // wrappingWidth falls through via labelHelper's JavaScript `||` expression.
    for key in ["minNodeWidth", "wrappingWidth"] {
        if let Some(value) = agentflow.get(key) {
            if key == "wrappingWidth" && !crate::config::json_value_is_truthy(value) {
                continue;
            }
            projected.set_value(&format!("flowchart.{key}"), value.clone());
        }
    }
    projected
}

#[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
fn semantic_flowchart_requires_math(model: &diagrams::flowchart::FlowchartModel) -> bool {
    model
        .nodes
        .iter()
        .filter_map(|node| node.label.as_deref())
        .chain(model.edges.iter().filter_map(|edge| edge.label.as_deref()))
        .chain(
            model
                .subgraphs
                .iter()
                .map(|subgraph| subgraph.title.as_str()),
        )
        .any(crate::math::contains_delimited_math)
}

#[cfg(feature = "diagram-sequence")]
fn sequence_requires_math(model: &diagrams::sequence::SequenceDiagramRenderModel) -> bool {
    model
        .actors
        .values()
        .map(|actor| actor.description.as_str())
        .chain(model.messages.iter().map(|message| message.message_text()))
        .chain(model.notes.iter().map(|note| note.message.as_str()))
        .any(crate::math::contains_delimited_math)
}

#[cfg(feature = "diagram-mindmap")]
fn mindmap_requires_math(model: &diagrams::mindmap::MindmapDiagramRenderModel) -> bool {
    model
        .nodes
        .iter()
        .map(|node| node.label.as_str())
        .any(crate::math::contains_delimited_math)
}

fn parsed_render_requires_math(parsed: &ParsedDiagramRender) -> bool {
    match parsed.model() {
        #[cfg(feature = "diagram-usecase")]
        RenderSemanticModel::Usecase(model) => {
            crate::usecase::requires_math(model, &parsed.metadata().effective_config)
        }
        #[cfg(feature = "diagram-agentflow")]
        RenderSemanticModel::Agentflow(model) => model
            .vertices
            .iter()
            .filter_map(|node| node.label.as_deref())
            .chain(model.edges.iter().filter_map(|edge| edge.label.as_deref()))
            .chain(
                model
                    .sub_graphs
                    .iter()
                    .filter_map(|graph| graph.title.as_deref()),
            )
            .chain(
                model
                    .connectors
                    .iter()
                    .filter_map(|connector| connector.title.as_deref()),
            )
            .any(crate::math::contains_delimited_math),
        #[cfg(feature = "diagram-class")]
        RenderSemanticModel::Class(model) => crate::class::class_requires_math(model),
        #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
        RenderSemanticModel::Flowchart(model) => parsed.flowchart_render_context().map_or_else(
            || semantic_flowchart_requires_math(model),
            |render_context| {
                crate::flowchart::FlowchartRenderModelRef::new(model, render_context)
                    .requires_math()
            },
        ),
        #[cfg(feature = "diagram-mindmap")]
        RenderSemanticModel::Mindmap(model) => mindmap_requires_math(model),
        #[cfg(feature = "diagram-sequence")]
        RenderSemanticModel::Sequence(model) => sequence_requires_math(model),
        _ => false,
    }
}

fn capability_is_available(capability: RenderCapability, session: &RenderSession) -> bool {
    session.supports_capability(capability)
}

#[allow(
    unused_variables,
    reason = "Dispatch inputs depend on the selected diagram families."
)]
fn required_capabilities(parsed: &ParsedDiagramRender) -> Vec<RenderCapability> {
    let mut required = Vec::with_capacity(2);
    let meta = parsed.metadata();
    let model = parsed.model();
    let effective_config = &meta.effective_config;
    match model {
        #[cfg(feature = "diagram-architecture")]
        RenderSemanticModel::Architecture(_) => {
            required.push(RenderCapability::LayoutCytoscape);
        }
        #[cfg(feature = "diagram-mindmap")]
        RenderSemanticModel::Mindmap(_) => {
            if let Some(capability) = crate::mindmap::required_layout_capability(effective_config) {
                required.push(capability);
            }
        }
        #[cfg(feature = "diagram-agentflow")]
        RenderSemanticModel::Agentflow(_) => {
            required.extend(
                crate::layout_backend::resolve_graph_layout(effective_config.as_value())
                    .required_capability(),
            );
        }
        #[cfg(feature = "diagram-usecase")]
        RenderSemanticModel::Usecase(_) => {
            required.extend(
                crate::layout_backend::resolve_graph_layout(effective_config.as_value())
                    .required_capability(),
            );
        }
        #[cfg(feature = "diagram-state")]
        RenderSemanticModel::State(_) => {
            required.extend(
                crate::layout_backend::resolve_graph_layout(effective_config.as_value())
                    .required_capability(),
            );
        }
        #[cfg(feature = "diagram-requirement")]
        RenderSemanticModel::Requirement(_) => {
            required.extend(
                crate::layout_backend::resolve_graph_layout(effective_config.as_value())
                    .required_capability(),
            );
        }
        #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
        RenderSemanticModel::Flowchart(_) => {
            required.extend(
                crate::layout_backend::resolve_graph_layout(effective_config.as_value())
                    .required_capability(),
            );
        }
        #[cfg(feature = "diagram-class")]
        RenderSemanticModel::Class(_) => {
            required.extend(
                crate::layout_backend::resolve_graph_layout(effective_config.as_value())
                    .required_capability(),
            );
        }
        #[cfg(feature = "diagram-er")]
        RenderSemanticModel::Er(_) => {
            required.extend(
                crate::layout_backend::resolve_graph_layout(effective_config.as_value())
                    .required_capability(),
            );
        }
        _ => {}
    }

    if parsed_render_requires_math(parsed) {
        required.push(RenderCapability::Math);
    }
    required
}

/// Reports whether this renderer contains the logical family handler for a known diagram type.
/// Optional layout and math capabilities are admitted separately during planning.
#[allow(
    clippy::match_like_matches_macro,
    reason = "Each arm has a distinct feature condition that only coincides in all-family builds."
)]
pub fn supports_diagram_type(diagram_type: &str) -> bool {
    match merman_core::diagram_type_family_kind(diagram_type) {
        Some("error") => true,
        Some("agentflow") => cfg!(feature = "diagram-agentflow"),
        Some("usecase") => cfg!(feature = "diagram-usecase"),
        Some("flowchart") => cfg!(feature = "diagram-flowchart"),
        Some("swimlane") => cfg!(feature = "diagram-swimlane"),
        Some("mindmap") => cfg!(feature = "diagram-mindmap"),
        Some("architecture") => cfg!(feature = "diagram-architecture"),
        Some("zenuml") => cfg!(feature = "diagram-zenuml"),
        Some("sequence") => cfg!(feature = "diagram-sequence"),
        Some("c4") => cfg!(feature = "diagram-c4"),
        Some("kanban") => cfg!(feature = "diagram-kanban"),
        Some("class") => cfg!(feature = "diagram-class"),
        Some("er") => cfg!(feature = "diagram-er"),
        Some("gantt") => cfg!(feature = "diagram-gantt"),
        Some("info") => cfg!(feature = "diagram-info"),
        Some("pie") => cfg!(feature = "diagram-pie"),
        Some("requirement") => cfg!(feature = "diagram-requirement"),
        Some("timeline") => cfg!(feature = "diagram-timeline"),
        Some("gitGraph") => cfg!(feature = "diagram-git-graph"),
        Some("state") => cfg!(feature = "diagram-state"),
        Some("journey") => cfg!(feature = "diagram-journey"),
        Some("quadrantChart") => cfg!(feature = "diagram-quadrant-chart"),
        Some("sankey") => cfg!(feature = "diagram-sankey"),
        Some("packet") => cfg!(feature = "diagram-packet"),
        Some("xychart") => cfg!(feature = "diagram-xychart"),
        Some("block") => cfg!(feature = "diagram-block"),
        Some("eventmodeling") => cfg!(feature = "diagram-event-modeling"),
        Some("treeView") => cfg!(feature = "diagram-tree-view"),
        Some("radar") => cfg!(feature = "diagram-radar"),
        Some("ishikawa") => cfg!(feature = "diagram-ishikawa"),
        Some("treemap") => cfg!(feature = "diagram-treemap"),
        Some("railroad") => cfg!(feature = "diagram-railroad"),
        Some("venn") => cfg!(feature = "diagram-venn"),
        Some("wardley") => cfg!(feature = "diagram-wardley"),
        Some("cynefin") => cfg!(feature = "diagram-cynefin"),
        _ => false,
    }
}

fn validate_render_input(parsed: &ParsedDiagramRender, session: &RenderSession) -> Result<()> {
    session.checkpoint(OperationPhase::Layout)?;
    let meta = parsed.metadata();
    let model = parsed.model();
    let diagram_type = meta.diagram_type.as_str();
    if let RenderSemanticModel::CustomJson(custom) = model {
        return Err(Error::NonRenderableCustomModel {
            diagram_type: meta.diagram_type.clone(),
            model_name: custom.model_name().to_string(),
            provenance: custom.provenance(),
        });
    }

    if !model.supports_diagram_type(diagram_type) {
        return Err(Error::InvalidModel {
            message: format!(
                "unexpected render model variant {} for diagram type: {diagram_type}",
                model.kind()
            ),
        });
    }

    if !supports_diagram_type(diagram_type) {
        return Err(Error::UnsupportedDiagram {
            diagram_type: diagram_type.to_owned(),
        });
    }
    session
        .work_meter()
        .preflight_parsed_render(parsed, OperationPhase::Layout)?;
    Ok(())
}

/// Plans capability admission for a canonically paired typed render model without running layout.
pub fn plan_render(
    parsed: &ParsedDiagramRender,
    session: &RenderSession,
) -> Result<RenderCapabilityPlan> {
    plan_render_with_policy(parsed, session, PresentationRenderPolicy::default())
}

/// Plans capability admission and selected presentation aspects without running layout.
pub fn plan_render_with_policy(
    parsed: &ParsedDiagramRender,
    session: &RenderSession,
    render_policy: PresentationRenderPolicy,
) -> Result<RenderCapabilityPlan> {
    let meta = parsed.metadata();
    let model = parsed.model();
    validate_render_input(parsed, session)?;
    let required = required_capabilities(parsed);
    let missing = required
        .iter()
        .copied()
        .filter(|capability| !capability_is_available(*capability, session))
        .collect();
    let flowchart_svg_applicable = match model {
        #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
        RenderSemanticModel::Flowchart(_) => {
            meta.effective_config.get_str("layout") != Some("swimlane")
        }
        #[cfg(feature = "diagram-agentflow")]
        RenderSemanticModel::Agentflow(_) => {
            meta.effective_config.get_str("layout") != Some("swimlane")
        }
        _ => false,
    };
    let presentation_aspects = render_policy.resolve_aspects(
        flowchart_svg_applicable,
        crate::layout_backend::ElkRootAlgorithm::from_name(
            crate::layout_backend::resolve_graph_layout(meta.effective_config.as_value()).requested,
        )
        .is_some(),
        capability_is_available(RenderCapability::LayoutElk, session),
    );

    Ok(RenderCapabilityPlan {
        diagram_type: meta.diagram_type.clone(),
        required,
        missing,
        presentation_profile: render_policy.profile(),
        presentation_aspects,
    })
}

#[inline(never)]
#[cfg(feature = "diagram-class")]
fn prepare_class_family(
    model: ClassDiagram,
    meta: &ParseMetadata,
    execution: &LayoutExecution<'_>,
) -> Result<BuiltinFamilyArtifact> {
    Ok(BuiltinFamilyArtifact::Class(prepare_pair(
        model,
        |model| crate::layout_class_typed_by_engine(model, &meta.effective_config, execution),
    )?))
}

#[inline(never)]
#[cfg(feature = "diagram-class")]
fn prepare_class_render(
    parsed: ParsedDiagramRender,
    options: &LayoutOptions,
    required_capabilities: Vec<RenderCapability>,
    session: RenderSession,
) -> Result<FamilyRenderArtifact> {
    let (meta, model) = parsed.into_parts();
    let RenderSemanticModel::Class(model) = model else {
        unreachable!("Class render dispatch requires a Class semantic model")
    };
    let execution = LayoutExecution::new(options, &session);
    let family = prepare_class_family(model, &meta, &execution)?;

    Ok(FamilyRenderArtifact {
        metadata: meta,
        compatibility_projection: OnceLock::new(),
        family,
        required_capabilities,
        session,
    })
}

/// Prepares one family-owned typed semantic model for layout and SVG rendering.
///
/// Compatibility JSON is deliberately not accepted by this interface:
///
/// ```compile_fail
/// use merman_render::{LayoutOptions, environment::RenderEnvironment};
///
/// let session = RenderEnvironment::deterministic().begin_session().unwrap();
/// let raw_json = serde_json::json!({ "type": "flowchart-v2" });
/// let _ = merman_render::family::prepare(raw_json, &LayoutOptions::default(), session);
/// ```
///
/// Family semantic/layout pairing is private and therefore cannot be assembled independently:
///
/// ```compile_fail
/// use merman_render::family::FamilyPair;
/// ```
pub fn prepare(
    parsed: ParsedDiagramRender,
    options: &LayoutOptions,
    session: RenderSession,
) -> Result<FamilyRenderArtifact> {
    prepare_with_render_policy(
        parsed,
        options,
        session,
        PresentationRenderPolicy::default(),
    )
}

/// Prepares one family artifact with renderer policy derived from a resolved presentation.
pub fn prepare_with_render_policy(
    parsed: ParsedDiagramRender,
    options: &LayoutOptions,
    session: RenderSession,
    render_policy: PresentationRenderPolicy,
) -> Result<FamilyRenderArtifact> {
    prepare_with_render_policy_impl(
        parsed,
        options,
        session,
        render_policy,
        DEFAULT_FLOWCHART_SVG_LABEL_PREPARATION,
    )
}

fn prepare_with_render_policy_impl(
    parsed: ParsedDiagramRender,
    options: &LayoutOptions,
    session: RenderSession,
    render_policy: PresentationRenderPolicy,
    flowchart_svg_label_preparation: FlowchartSvgLabelPreparation,
) -> Result<FamilyRenderArtifact> {
    session.checkpoint(OperationPhase::Layout)?;
    let capability_plan = plan_render_with_policy(&parsed, &session, render_policy)?;
    capability_plan.ensure_available()?;
    let required_capabilities = capability_plan.required_capabilities().to_vec();
    // The heterogeneous router has one generic layout call per family. Keep its debug-build
    // caller slots out of the Class Dagre call chain, whose own phase frames are already deep.
    #[cfg(feature = "diagram-class")]
    if matches!(parsed.model(), RenderSemanticModel::Class(_)) {
        let artifact = prepare_class_render(parsed, options, required_capabilities, session)?;
        artifact.session.checkpoint(OperationPhase::Layout)?;
        return Ok(artifact);
    }
    let artifact = prepare_non_class_render(
        parsed,
        options,
        session,
        render_policy,
        required_capabilities,
        flowchart_svg_label_preparation,
    )?;
    artifact.session.checkpoint(OperationPhase::Layout)?;
    Ok(artifact)
}

#[inline(never)]
#[allow(
    unused_variables,
    reason = "Dispatch inputs depend on the selected diagram families."
)]
fn prepare_non_class_render(
    parsed: ParsedDiagramRender,
    options: &LayoutOptions,
    session: RenderSession,
    render_policy: PresentationRenderPolicy,
    required_capabilities: Vec<RenderCapability>,
    flowchart_svg_label_preparation: FlowchartSvgLabelPreparation,
) -> Result<FamilyRenderArtifact> {
    let (meta, model, render_context) = parsed.into_render_parts();
    #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
    let flowchart_label_sources = render_context.into_flowchart_render_context();
    let diagram_type = meta.diagram_type.as_str();
    let execution = LayoutExecution::new(options, &session);
    let effective_config = meta.effective_config.as_value();
    let title = meta.title.as_deref();
    let family = match model {
        RenderSemanticModel::Error(model) => {
            BuiltinFamilyArtifact::Error(prepare_pair(model, |model| {
                crate::error::layout_error_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-mindmap")]
        RenderSemanticModel::Mindmap(model) => {
            BuiltinFamilyArtifact::Mindmap(prepare_pair(model, |model| {
                crate::mindmap::layout_mindmap_diagram_typed_with_work_meter(
                    model,
                    &meta.effective_config,
                    execution.text_measurer(),
                    execution.math_renderer(),
                    execution.work_meter(),
                    #[cfg(feature = "layout-elk")]
                    execution.elk_operation_seed(),
                )
            })?)
        }
        #[cfg(feature = "diagram-state")]
        RenderSemanticModel::State(model) => {
            BuiltinFamilyArtifact::State(prepare_pair(model, |model| {
                crate::state::layout_state_diagram_typed_with_work_meter(
                    model,
                    effective_config,
                    &execution,
                )
            })?)
        }
        #[cfg(feature = "diagram-sequence")]
        RenderSemanticModel::Sequence(model) => {
            let text_measurer = session
                .controlled_text_measurer(TextMeasurementPhase::Layout, OperationPhase::Layout);
            BuiltinFamilyArtifact::Sequence(prepare_pair(model, |model| {
                crate::sequence::prepare_sequence_diagram_typed_with_title_and_work_meter(
                    model,
                    title,
                    effective_config,
                    &text_measurer,
                    execution.math_renderer(),
                    execution.work_meter_ref(),
                )
            })?)
        }
        #[cfg(feature = "diagram-zenuml")]
        RenderSemanticModel::Zenuml(model) => {
            BuiltinFamilyArtifact::Zenuml(prepare_pair(model, |model| {
                crate::zenuml::layout_zenuml_diagram_typed(model, execution.text_measurer())
            })?)
        }
        #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
        RenderSemanticModel::Flowchart(model)
            if meta.effective_config.get_str("layout") == Some("swimlane") =>
        {
            BuiltinFamilyArtifact::Swimlane(prepare_flowchart_artifact(
                model,
                flowchart_label_sources,
                None,
                flowchart_svg_label_preparation,
                |model, label_sources, svg_label_sidecar| {
                    crate::swimlane::layout_swimlane_typed_with_work_meter_and_svg_label_sidecar(
                        model,
                        label_sources,
                        &meta.effective_config,
                        execution.text_measurer(),
                        execution.math_renderer(),
                        svg_label_sidecar,
                        execution.work_meter(),
                    )
                },
            )?)
        }
        #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
        RenderSemanticModel::Flowchart(model) => {
            BuiltinFamilyArtifact::Flowchart(prepare_flowchart_artifact(
                model,
                flowchart_label_sources,
                render_policy.flowchart(),
                flowchart_svg_label_preparation,
                |model, label_sources, svg_label_sidecar| {
                    crate::layout_flowchart_typed_with_render_labels_by_engine(
                        model,
                        label_sources,
                        &meta.effective_config,
                        &execution,
                        svg_label_sidecar,
                    )
                },
            )?)
        }
        #[cfg(feature = "layout-cytoscape")]
        #[cfg(feature = "diagram-architecture")]
        RenderSemanticModel::Architecture(model) => {
            BuiltinFamilyArtifact::Architecture(prepare_pair(model, |model| {
                crate::architecture::layout_architecture_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                    execution.operation_seed(),
                    execution.work_meter().as_ref(),
                )
            })?)
        }
        #[cfg(not(feature = "layout-cytoscape"))]
        #[cfg(feature = "diagram-architecture")]
        RenderSemanticModel::Architecture(_) => {
            return Err(Error::MissingCapability {
                capability: RenderCapability::LayoutCytoscape,
                diagram_type: diagram_type.to_string(),
            });
        }
        #[cfg(feature = "diagram-class")]
        RenderSemanticModel::Class(_) => {
            unreachable!("Class models use the stack-bounded family dispatch path")
        }
        #[cfg(feature = "diagram-c4")]
        RenderSemanticModel::C4(model) => {
            BuiltinFamilyArtifact::C4(prepare_pair(model, |model| {
                crate::c4::layout_c4_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                    execution.container_width,
                    execution.container_height,
                    execution.screen_available_width,
                )
            })?)
        }
        #[cfg(feature = "diagram-cynefin")]
        RenderSemanticModel::Cynefin(model) => {
            BuiltinFamilyArtifact::Cynefin(prepare_pair(model, |model| {
                crate::cynefin::layout_cynefin_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-wardley")]
        RenderSemanticModel::Wardley(model) => {
            BuiltinFamilyArtifact::Wardley(prepare_pair(model, |model| {
                crate::wardley::layout_wardley_diagram_typed(
                    model,
                    title,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-railroad")]
        RenderSemanticModel::Railroad(model) => {
            BuiltinFamilyArtifact::Railroad(prepare_pair(model, |model| {
                crate::railroad::layout_railroad_diagram_typed_for_type(
                    model,
                    diagram_type,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-kanban")]
        RenderSemanticModel::Kanban(model) => {
            BuiltinFamilyArtifact::Kanban(prepare_pair(model, |model| {
                crate::kanban::prepare_kanban_diagram_typed_with_work_meter(
                    model,
                    &meta.effective_config,
                    execution.text_measurer(),
                    execution.work_meter_ref(),
                )
            })?)
        }
        #[cfg(feature = "diagram-gantt")]
        RenderSemanticModel::Gantt(model) => {
            BuiltinFamilyArtifact::Gantt(prepare_pair(model, |model| {
                crate::gantt::layout_gantt_diagram_typed(
                    model,
                    title,
                    effective_config,
                    execution.text_measurer(),
                    execution.container_width,
                    execution.local_time_zone(),
                )
            })?)
        }
        #[cfg(feature = "diagram-pie")]
        RenderSemanticModel::Pie(model) => {
            BuiltinFamilyArtifact::Pie(prepare_pair(model, |model| {
                crate::pie::layout_pie_diagram_typed(
                    model,
                    title,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-packet")]
        RenderSemanticModel::Packet(model) => {
            BuiltinFamilyArtifact::Packet(prepare_pair(model, |model| {
                crate::packet::layout_packet_diagram_typed(
                    model,
                    title,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-timeline")]
        RenderSemanticModel::Timeline(model) => {
            BuiltinFamilyArtifact::Timeline(prepare_pair(model, |model| {
                crate::timeline::layout_timeline_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-journey")]
        RenderSemanticModel::Journey(model) => {
            BuiltinFamilyArtifact::Journey(prepare_pair(model, |model| {
                crate::journey::layout_journey_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-requirement")]
        RenderSemanticModel::Requirement(model) => {
            BuiltinFamilyArtifact::Requirement(prepare_pair(model, |model| {
                crate::requirement::layout_requirement_diagram_typed_with_work_meter(
                    model,
                    effective_config,
                    execution.text_measurer(),
                    execution.work_meter(),
                    #[cfg(feature = "layout-elk")]
                    execution.elk_operation_seed(),
                )
            })?)
        }
        #[cfg(feature = "diagram-sankey")]
        RenderSemanticModel::Sankey(model) => {
            BuiltinFamilyArtifact::Sankey(prepare_pair(model, |model| {
                crate::sankey::layout_sankey_diagram_typed_with_work_meter(
                    model,
                    effective_config,
                    execution.text_measurer(),
                    execution.work_meter_ref(),
                )
            })?)
        }
        #[cfg(feature = "diagram-radar")]
        RenderSemanticModel::Radar(model) => {
            BuiltinFamilyArtifact::Radar(prepare_pair(model, |model| {
                crate::radar::layout_radar_diagram_typed_with_work_meter(
                    model,
                    effective_config,
                    execution.text_measurer(),
                    execution.work_meter_ref(),
                )
            })?)
        }
        #[cfg(feature = "diagram-info")]
        RenderSemanticModel::Info(model) => {
            BuiltinFamilyArtifact::Info(prepare_pair(model, |model| {
                crate::info::layout_info_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-treemap")]
        RenderSemanticModel::Treemap(model) => {
            BuiltinFamilyArtifact::Treemap(prepare_pair(model, |model| {
                crate::treemap::layout_treemap_diagram_typed(
                    model,
                    title,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-block")]
        RenderSemanticModel::Block(model) => {
            BuiltinFamilyArtifact::Block(prepare_pair(model, |model| {
                crate::block::layout_block_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-er")]
        RenderSemanticModel::Er(model) => {
            #[cfg(feature = "layout-elk")]
            {
                BuiltinFamilyArtifact::Er(prepare_pair(model, |model| {
                    crate::er::layout_er_diagram_typed_with_elk_operation_seed(
                        model,
                        effective_config,
                        execution.text_measurer(),
                        execution.elk_operation_seed(),
                        execution.work_meter(),
                    )
                })?)
            }
            #[cfg(not(feature = "layout-elk"))]
            BuiltinFamilyArtifact::Er(prepare_pair(model, |model| {
                crate::er::layout_er_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                    execution.work_meter(),
                )
            })?)
        }
        #[cfg(feature = "diagram-quadrant-chart")]
        RenderSemanticModel::QuadrantChart(model) => {
            BuiltinFamilyArtifact::QuadrantChart(prepare_pair(model, |model| {
                crate::quadrantchart::layout_quadrantchart_diagram_typed(
                    model,
                    title,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-xychart")]
        RenderSemanticModel::XyChart(model) => {
            BuiltinFamilyArtifact::XyChart(prepare_pair(model, |model| {
                crate::xychart::layout_xychart_diagram_typed(
                    model,
                    title,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-git-graph")]
        RenderSemanticModel::GitGraph(model) => {
            BuiltinFamilyArtifact::GitGraph(prepare_pair(model, |model| {
                crate::gitgraph::layout_gitgraph_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-tree-view")]
        RenderSemanticModel::TreeView(model) => {
            BuiltinFamilyArtifact::TreeView(prepare_pair(model, |model| {
                crate::tree_view::layout_tree_view_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-ishikawa")]
        RenderSemanticModel::Ishikawa(model) => {
            BuiltinFamilyArtifact::Ishikawa(prepare_pair(model, |model| {
                crate::ishikawa::layout_ishikawa_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-event-modeling")]
        RenderSemanticModel::EventModeling(model) => {
            BuiltinFamilyArtifact::EventModeling(prepare_pair(model, |model| {
                crate::eventmodeling::layout_eventmodeling_diagram_typed(
                    model,
                    effective_config,
                    execution.text_measurer(),
                )
            })?)
        }
        #[cfg(feature = "diagram-venn")]
        RenderSemanticModel::Venn(model) => {
            BuiltinFamilyArtifact::Venn(prepare_pair(model, |model| {
                crate::venn::layout_venn_diagram_typed_with_work_meter(
                    model,
                    title,
                    effective_config,
                    execution.work_meter_ref(),
                )
            })?)
        }
        #[cfg(feature = "diagram-usecase")]
        RenderSemanticModel::Usecase(model) => {
            BuiltinFamilyArtifact::Usecase(prepare_pair(model, |model| {
                crate::usecase::prepare_usecase_diagram(
                    model,
                    effective_config,
                    execution.text_measurer(),
                    execution.math_renderer(),
                    execution.work_meter(),
                    #[cfg(feature = "layout-elk")]
                    execution.elk_operation_seed(),
                )
            })?)
        }
        #[cfg(feature = "diagram-agentflow")]
        RenderSemanticModel::Agentflow(model) => {
            let (flowchart, render_context) = model.to_flowchart_model();
            let agentflow_config = project_agentflow_flowchart_config(&meta.effective_config);
            let flow = prepare_flowchart_artifact(
                flowchart,
                render_context,
                render_policy.flowchart(),
                flowchart_svg_label_preparation,
                |model, label_sources, svg_label_sidecar| {
                    crate::layout_flowchart_typed_with_render_labels_by_engine(
                        model,
                        label_sources,
                        &agentflow_config,
                        &execution,
                        svg_label_sidecar,
                    )
                },
            )?;
            BuiltinFamilyArtifact::Agentflow {
                semantic: Box::new(model),
                flow,
            }
        }
        RenderSemanticModel::CustomJson(_) => {
            unreachable!("custom JSON models return before built-in family dispatch")
        }
        // Another dependency can widen core without widening this renderer.
        #[allow(unreachable_patterns)]
        _ => {
            return Err(Error::UnsupportedDiagram {
                diagram_type: diagram_type.to_owned(),
            });
        }
    };
    Ok(FamilyRenderArtifact {
        metadata: meta,
        compatibility_projection: OnceLock::new(),
        family,
        required_capabilities,
        session,
    })
}

#[cfg(all(test, feature = "all-diagrams"))]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

    use crate::environment::{
        HostMeasurementResult, HostTextMeasurement, HostTextMeasurementRequest, HostTextMeasurer,
        MeasurementProfileId, TextMeasurementOperation, TextMeasurementPhase,
        TextMeasurementPolicy, TextMeasurementProfileIdentity, TextMeasurementReport,
        TextMeasurementResultKind,
    };
    use crate::text::{TextMetrics, WrapMode};
    use merman_core::{
        CustomJsonProvenance, CustomJsonRenderModel, Engine, OperationControl, ParseOptions,
    };
    use serde_json::{Value, json};

    fn custom_semantic_parser(
        _code: &str,
        meta: &ParseMetadata,
        control: &merman_core::OperationControl,
    ) -> merman_core::OperationControlResult<merman_core::Result<Value>> {
        control.checkpoint()?;
        Ok(Ok(
            json!({ "type": meta.diagram_type, "owner": "semantic" }),
        ))
    }

    fn custom_render_parser(
        _code: &str,
        _meta: &ParseMetadata,
        control: &merman_core::OperationControl,
    ) -> merman_core::OperationControlResult<merman_core::Result<CustomJsonRenderModel>> {
        control.checkpoint()?;
        Ok(Ok(CustomJsonRenderModel::new(
            "custom-flowchart",
            json!({ "owner": "render" }),
        )))
    }

    fn session() -> RenderSession {
        crate::environment::RenderEnvironment::deterministic()
            .begin_session()
            .unwrap()
    }

    #[test]
    fn agentflow_layout_config_prioritizes_family_measurement_keys() {
        let config = merman_core::MermaidConfig::from_value(json!({
            "agentflow": { "minNodeWidth": 180, "wrappingWidth": 240 },
            "flowchart": { "minNodeWidth": 90 }
        }));
        let projected = project_agentflow_flowchart_config(&config);
        let number = |config: &merman_core::MermaidConfig, path: &str| {
            config
                .as_value()
                .pointer(path)
                .and_then(serde_json::Value::as_f64)
        };
        assert_eq!(number(&projected, "/flowchart/minNodeWidth"), Some(180.0));
        assert_eq!(number(&projected, "/flowchart/wrappingWidth"), Some(240.0));
        assert_eq!(number(&config, "/flowchart/wrappingWidth"), None);
        assert_eq!(number(&config, "/agentflow/minNodeWidth"), Some(180.0));
    }

    #[test]
    fn agentflow_layout_config_keeps_flowchart_wrapping_fallback() {
        for wrapping in [json!(0), json!(null), json!(false), json!("")] {
            let config = merman_core::MermaidConfig::from_value(json!({
                "agentflow": { "minNodeWidth": 0, "wrappingWidth": wrapping },
                "flowchart": { "minNodeWidth": 90, "wrappingWidth": 240 }
            }));
            let projected = project_agentflow_flowchart_config(&config);
            assert_eq!(projected.as_value()["flowchart"]["minNodeWidth"], 0);
            assert_eq!(projected.as_value()["flowchart"]["wrappingWidth"], 240);
        }
    }

    #[test]
    fn agentflow_projection_separates_renderer_ownership_from_shared_shape_settings() {
        for family in [json!({}), json!(null)] {
            let config = merman_core::MermaidConfig::from_value(json!({
                "agentflow": family,
                "flowchart": {
                    "diagramPadding": 99, "titleTopMargin": 99, "useMaxWidth": false,
                    "nodeSpacing": 99, "rankSpacing": 99,
                    "padding": 17, "curve": "linear", "htmlLabels": false,
                    "inheritDir": true, "subGraphTitleMargin": {"top": 7}
                }
            }));
            let projected = project_agentflow_flowchart_config(&config);
            let flow = &projected.as_value()["flowchart"];
            assert_eq!(flow["diagramPadding"], 8);
            assert_eq!(flow["titleTopMargin"], 0);
            assert_eq!(flow["useMaxWidth"], true);
            assert_eq!(flow["nodeSpacing"], 50);
            assert_eq!(flow["rankSpacing"], 50);
            for key in [
                "padding",
                "curve",
                "htmlLabels",
                "inheritDir",
                "subGraphTitleMargin",
            ] {
                assert_eq!(flow[key], config.as_value()["flowchart"][key]);
            }
        }
        for value in [json!(null), json!(0)] {
            let config = merman_core::MermaidConfig::from_value(json!({
                "nodeSpacing": 90, "rankSpacing": 0,
                "agentflow": {
                    "diagramPadding": value, "titleTopMargin": value, "useMaxWidth": false,
                    "nodeSpacing": 200, "rankSpacing": value
                }
            }));
            let projected = project_agentflow_flowchart_config(&config);
            let flow = &projected.as_value()["flowchart"];
            assert_eq!(flow["diagramPadding"], if value.is_null() { 8 } else { 0 });
            assert_eq!(flow["titleTopMargin"], 0);
            assert_eq!(flow["useMaxWidth"], false);
            assert_eq!(flow["nodeSpacing"], 90);
            assert_eq!(flow["rankSpacing"], 50);
        }
    }

    #[test]
    fn agentflow_spacing_projection_follows_registered_backend_selection() {
        for layout in [
            "dagre",
            "unknown",
            "elk.layered",
            "elk",
            "elk.stress",
            "elk.force",
            "elk.mrtree",
            "elk.sporeOverlap",
            "elk.box",
            "elk.rectpacking",
        ] {
            let config = merman_core::MermaidConfig::from_value(json!({
                "layout": layout,
                "nodeSpacing": 90, "rankSpacing": 110,
                "agentflow": {"nodeSpacing": 200, "rankSpacing": 210},
                "flowchart": {"nodeSpacing": 300, "rankSpacing": 310}
            }));
            let selected = crate::layout_backend::resolve_graph_layout(config.as_value());
            let projected = project_agentflow_flowchart_config(&config);
            let flow = &projected.as_value()["flowchart"];
            let elk_registered = cfg!(feature = "layout-elk")
                && crate::layout_backend::ElkRootAlgorithm::from_name(layout).is_some();
            assert_eq!(
                selected.backend == crate::layout_backend::GraphLayoutBackend::Elk,
                elk_registered,
                "{layout}"
            );
            assert_eq!(
                flow["nodeSpacing"],
                if elk_registered { 50 } else { 90 },
                "{layout}"
            );
            assert_eq!(
                flow["rankSpacing"],
                if elk_registered { 50 } else { 110 },
                "{layout}"
            );
        }
    }

    #[test]
    fn final_svg_admission_prefers_emit_cancellation_to_byte_limit() {
        let policy = crate::resources::RenderResourcePolicy::unbounded_for_trusted_input()
            .with_limit(crate::resources::ResourceLimitId::MaxSvgBytes, 1)
            .unwrap();
        let control = OperationControl::new();
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_resource_policy(policy)
            .begin_session_with_control(control.clone())
            .unwrap();
        let svg = "<svg/>";

        let limit = session
            .resource_policy()
            .check_svg_bytes(svg, ResourceLimitPhase::SvgOutput)
            .unwrap_err();
        assert_eq!(limit.limit, "max_svg_bytes");

        control.cancel();
        let error = admit_rendered_svg_output(&session, svg).unwrap_err();
        let Error::Cancelled(error) = error else {
            panic!("expected final SVG admission cancellation");
        };
        assert_eq!(error.phase, OperationPhase::Emit);
    }

    #[test]
    fn final_svg_resource_terminal_replays_before_later_cancellation() {
        let policy = crate::resources::RenderResourcePolicy::unbounded_for_trusted_input()
            .with_limit(crate::resources::ResourceLimitId::MaxSvgBytes, 1)
            .unwrap();
        let control = OperationControl::new();
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_resource_policy(policy)
            .begin_session_with_control(control.clone())
            .unwrap();
        let svg = "<svg/>";

        let first = admit_rendered_svg_output(&session, svg)
            .expect_err("the formal SVG output admission must reject");
        let Error::ResourceLimitExceeded(first_limit) = first else {
            panic!("expected a resource rejection");
        };
        assert_eq!(first_limit.limit, "max_svg_bytes");
        assert_eq!(first_limit.actual, svg.len());
        assert_eq!(first_limit.max, 1);

        control.cancel();
        let replayed = admit_rendered_svg_output(&session, svg)
            .expect_err("the first SVG output terminal must remain sticky");
        let Error::ResourceLimitExceeded(replayed_limit) = replayed else {
            panic!("expected the resource terminal to replay");
        };
        assert_eq!(replayed_limit, first_limit);
    }

    #[test]
    fn requested_diagram_id_fanout_is_admitted_per_output_occurrence() {
        let diagram_id = "d".repeat(256);
        let maximum = diagram_id.len() * 4;
        let policy = crate::resources::RenderResourcePolicy::unbounded_for_trusted_input()
            .with_limit(crate::resources::ResourceLimitId::MaxSvgBytes, maximum)
            .unwrap();
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync("info", ParseOptions::strict())
            .expect("parse info diagram")
            .expect("detect info diagram");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_resource_policy(policy)
            .begin_session()
            .expect("begin render session");
        let artifact =
            prepare(parsed, &LayoutOptions::default(), session).expect("prepare info diagram");
        let error = match artifact.render_svg(
            &SvgRenderOptions {
                diagram_id: Some(diagram_id.clone()),
                ..SvgRenderOptions::default()
            },
            &SvgDebugOptions::default(),
        ) {
            Ok(_) => panic!("the diagram ID fanout must exceed the SVG byte ceiling"),
            Err(error) => error,
        };

        let Error::ResourceLimitExceeded(details) = error else {
            panic!("expected the family fanout preflight to reject");
        };
        assert_eq!(details.limit, "max_svg_bytes");
        assert_eq!(details.max, maximum);
        assert_eq!(details.actual, maximum + diagram_id.len());
    }

    #[test]
    fn renderer_owned_metadata_scan_observes_the_artifact_session_control() {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync("info", ParseOptions::strict())
            .expect("parse info diagram")
            .expect("detect info diagram");
        let control = OperationControl::new();
        let session = crate::environment::RenderEnvironment::deterministic()
            .begin_session_with_control(control.clone())
            .expect("begin render session");
        let rendered = prepare(parsed, &LayoutOptions::default(), session)
            .expect("prepare info diagram")
            .render_svg(&SvgRenderOptions::default(), &SvgDebugOptions::default())
            .expect("render info diagram");

        control.cancel();
        let error = rendered
            .output_metadata()
            .expect_err("metadata extraction must observe the artifact session control");

        let Error::Cancelled(cancelled) = error else {
            panic!("expected structured postprocess cancellation");
        };
        assert_eq!(cancelled.phase, OperationPhase::Postprocess);
    }

    fn text_measurement_call_count(session: &RenderSession) -> u64 {
        session
            .text_measurement_report()
            .entries()
            .iter()
            .map(crate::environment::TextMeasurementSummary::count)
            .sum()
    }

    #[derive(Debug, Clone, Copy)]
    enum SidecarHostOutcome {
        Success,
        Missing,
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct SidecarHostRequest {
        ordinal: usize,
        phase: TextMeasurementPhase,
        operation: TextMeasurementOperation,
        result_kind: TextMeasurementResultKind,
        text: String,
        font_size_bits: u64,
        max_width_bits: Option<u64>,
        wrap_mode: WrapMode,
    }

    struct SidecarRecordingHost {
        outcome: SidecarHostOutcome,
        requests: Mutex<Vec<SidecarHostRequest>>,
    }

    impl SidecarRecordingHost {
        fn new(outcome: SidecarHostOutcome) -> Self {
            Self {
                outcome,
                requests: Mutex::new(Vec::new()),
            }
        }

        fn snapshot(&self) -> Vec<SidecarHostRequest> {
            self.requests.lock().expect("host request trace").clone()
        }
    }

    impl HostTextMeasurer for SidecarRecordingHost {
        fn measure(&self, request: HostTextMeasurementRequest<'_>) -> HostMeasurementResult {
            let ordinal = {
                let mut requests = self.requests.lock().expect("host request trace");
                let ordinal = requests.len();
                requests.push(SidecarHostRequest {
                    ordinal,
                    phase: request.phase,
                    operation: request.operation,
                    result_kind: request.operation.required_result_kind(),
                    text: request.text.to_string(),
                    font_size_bits: request.style.font_size.to_bits(),
                    max_width_bits: request.max_width.map(f64::to_bits),
                    wrap_mode: request.wrap_mode,
                });
                ordinal
            };

            match self.outcome {
                SidecarHostOutcome::Success => Ok(Some(sidecar_host_measurement(request, ordinal))),
                SidecarHostOutcome::Missing => Ok(None),
            }
        }
    }

    struct CancellingSuccessfulHost {
        calls: AtomicUsize,
        control: OperationControl,
    }

    impl HostTextMeasurer for CancellingSuccessfulHost {
        fn measure(&self, request: HostTextMeasurementRequest<'_>) -> HostMeasurementResult {
            self.calls.fetch_add(1, Ordering::Relaxed);
            self.control.cancel();
            Ok(Some(sidecar_host_measurement(request, 0)))
        }
    }

    fn sidecar_host_measurement(
        request: HostTextMeasurementRequest<'_>,
        ordinal: usize,
    ) -> HostTextMeasurement {
        let state_delta = (ordinal % 7) as f64 / 32.0;
        let raw_width = request
            .text
            .lines()
            .map(|line| line.chars().count() as f64 * 8.0)
            .fold(0.0_f64, f64::max)
            + state_delta;
        let max_width = request
            .max_width
            .filter(|width| width.is_finite() && *width > 0.0);
        let line_count = max_width
            .map(|width| (raw_width / width).ceil() as usize)
            .unwrap_or(1)
            .max(request.text.lines().count())
            .max(1)
            .min(request.text.len().saturating_add(1));
        let metrics = TextMetrics {
            width: max_width.map_or(raw_width, |width| raw_width.min(width)),
            height: line_count as f64 * 20.0 + state_delta,
            line_count,
        };

        match request.operation.required_result_kind() {
            TextMeasurementResultKind::Metrics => HostTextMeasurement::Metrics(metrics),
            TextMeasurementResultKind::Length => {
                let length = match request.operation {
                    TextMeasurementOperation::RawBBoxHeight
                    | TextMeasurementOperation::SimpleBBoxHeight
                    | TextMeasurementOperation::TspanBBoxHeight => metrics.height,
                    TextMeasurementOperation::CreateTextBBoxYOffset
                    | TextMeasurementOperation::CreateTextMiddleBBoxYOffset => 0.0,
                    _ => raw_width,
                };
                HostTextMeasurement::Length(length)
            }
            TextMeasurementResultKind::HorizontalExtents => {
                HostTextMeasurement::HorizontalExtents {
                    left: raw_width / 2.0,
                    right: raw_width / 2.0,
                }
            }
            TextMeasurementResultKind::WrappedWithRawWidth => {
                HostTextMeasurement::WrappedWithRawWidth {
                    metrics,
                    raw_width: Some(raw_width),
                }
            }
        }
    }

    #[test]
    fn family_layout_stops_host_measurement_after_callback_cancellation() {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(
                "---\nconfig:\n  layout: tidy-tree\n---\nmindmap\n  Root\n    First child\n    Second child\n",
                ParseOptions::strict(),
            )
            .expect("parse mindmap")
            .expect("detect mindmap");
        let control = OperationControl::new();
        let host = Arc::new(CancellingSuccessfulHost {
            calls: AtomicUsize::new(0),
            control: control.clone(),
        });
        let identity = TextMeasurementProfileIdentity::new(
            MeasurementProfileId::new("test.family-cancelling-host").expect("profile id"),
            "1",
        )
        .expect("profile identity");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_text_measurement_policy(TextMeasurementPolicy::host_display(
                identity,
                host.clone(),
                TextMeasurementPhase::ALL,
            ))
            .begin_session_with_control(control)
            .expect("begin render session");

        let result = prepare(parsed, &LayoutOptions::default(), session);
        let Err(Error::Cancelled(cancelled)) = result else {
            panic!("family preparation must surface callback cancellation");
        };
        assert_eq!(cancelled.phase, OperationPhase::Layout);
        assert_eq!(host.calls.load(Ordering::Relaxed), 1);
    }

    fn render_with_sidecar_host_control(
        preparation: FlowchartSvgLabelPreparation,
        outcome: SidecarHostOutcome,
    ) -> (bool, Vec<SidecarHostRequest>, TextMeasurementReport, String) {
        let source = r#"---
config:
  htmlLabels: false
  flowchart:
    htmlLabels: false
    wrappingWidth: 96
---
flowchart LR
subgraph S["service words"]
  A["alpha beta<br/>gamma"]
end
A traced-edge@-->|edge label words| B["delta epsilon"]
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .expect("parse flowchart")
            .expect("detect flowchart");
        let identity = TextMeasurementProfileIdentity::new(
            MeasurementProfileId::new("test.flowchart-sidecar-control").expect("profile id"),
            "1",
        )
        .expect("profile identity");
        let host = Arc::new(SidecarRecordingHost::new(outcome));
        let environment = crate::environment::RenderEnvironment::deterministic()
            .with_text_measurement_policy(TextMeasurementPolicy::host_display(
                identity,
                host.clone(),
                TextMeasurementPhase::ALL,
            ));
        let session = environment.begin_session().expect("render session");
        let artifact = prepare_with_render_policy_impl(
            parsed,
            &LayoutOptions::default(),
            session,
            PresentationRenderPolicy::default(),
            preparation,
        )
        .expect("prepare flowchart artifact");
        let indexed_sidecar = match &artifact.family {
            #[cfg(any(feature = "diagram-flowchart", feature = "diagram-swimlane"))]
            BuiltinFamilyArtifact::Flowchart(flowchart) => {
                flowchart
                    .svg_label_sidecar()
                    .node_owner("A", false)
                    .is_some()
                    && flowchart
                        .svg_label_sidecar()
                        .edge_owner("traced-edge", false)
                        .is_some()
            }
            _ => panic!("expected Flowchart family artifact"),
        };
        let rendered = artifact
            .render_svg(&SvgRenderOptions::default(), &SvgDebugOptions::default())
            .expect("render Flowchart SVG");
        let trace = host.snapshot();
        let (svg, _, _, session) = rendered.into_parts();
        (
            indexed_sidecar,
            trace,
            session.text_measurement_report(),
            svg,
        )
    }

    #[cfg(feature = "layout-cytoscape")]
    fn prepare_mindmap_with_host_limit(
        max_layout_work_units: Option<usize>,
    ) -> (Result<FamilyRenderArtifact>, Arc<SidecarRecordingHost>) {
        let source = "mindmap\n  Root\n    First child\n    Second child\n";
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .expect("parse mindmap")
            .expect("detect mindmap");
        let identity = TextMeasurementProfileIdentity::new(
            MeasurementProfileId::new("test.mindmap-cose-budget").expect("profile id"),
            "1",
        )
        .expect("profile identity");
        let host = Arc::new(SidecarRecordingHost::new(SidecarHostOutcome::Success));
        let mut environment = crate::environment::RenderEnvironment::deterministic()
            .with_text_measurement_policy(TextMeasurementPolicy::host_display(
                identity,
                host.clone(),
                TextMeasurementPhase::ALL,
            ));
        if let Some(limit) = max_layout_work_units {
            let policy = crate::resources::RenderResourcePolicy::unbounded_for_trusted_input()
                .with_limit(crate::resources::ResourceLimitId::MaxLayoutWorkUnits, limit)
                .expect("layout work limit");
            environment = environment.with_resource_policy(policy);
        }
        let session = environment.begin_session().expect("render session");
        (prepare(parsed, &LayoutOptions::default(), session), host)
    }

    #[test]
    fn public_flowchart_preparation_enables_prepared_svg_label_reuse() {
        let source = r#"---
config:
  htmlLabels: false
  flowchart:
    htmlLabels: false
---
flowchart LR
A -->|control label| B
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .expect("parse flowchart")
            .expect("detect flowchart");
        let artifact = prepare_with_render_policy(
            parsed,
            &LayoutOptions::default(),
            session(),
            PresentationRenderPolicy::default(),
        )
        .expect("prepare public flowchart artifact");
        let BuiltinFamilyArtifact::Flowchart(flowchart) = &artifact.family else {
            panic!("expected Flowchart family artifact");
        };

        assert!(
            flowchart
                .svg_label_sidecar()
                .node_owner("A", false)
                .is_some(),
            "the public Flowchart preparation path must build the label sidecar"
        );
    }

    #[test]
    fn routed_host_and_fallback_traces_match_a_no_sidecar_family_control() {
        for outcome in [SidecarHostOutcome::Success, SidecarHostOutcome::Missing] {
            let (control_indexed, control_trace, control_report, control_svg) =
                render_with_sidecar_host_control(FlowchartSvgLabelPreparation(false), outcome);
            let (sidecar_indexed, sidecar_trace, sidecar_report, sidecar_svg) =
                render_with_sidecar_host_control(FlowchartSvgLabelPreparation(true), outcome);

            assert!(
                !control_indexed,
                "the control must bypass sidecar preparation"
            );
            assert!(
                sidecar_indexed,
                "the candidate must prepare semantic owners"
            );
            assert!(!control_trace.is_empty());
            assert_eq!(sidecar_trace, control_trace);
            assert_eq!(sidecar_report, control_report);
            assert_eq!(sidecar_svg, control_svg);
        }
    }

    #[test]
    fn prepared_self_loop_edge_label_keeps_its_semantic_owner_through_family_dispatch() {
        let source = r#"---
config:
  htmlLabels: false
  flowchart:
    htmlLabels: false
---
flowchart LR
A ordinary-edge@-->|ordinary owner sentinel| B
A self-loop-edge@-->|self loop semantic owner keeps wrapped label rows through the logical render id alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron| A
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .expect("parse flowchart")
            .expect("detect flowchart");
        let artifact = prepare_with_render_policy_impl(
            parsed,
            &LayoutOptions::default(),
            session(),
            PresentationRenderPolicy::default(),
            FlowchartSvgLabelPreparation(true),
        )
        .expect("prepare flowchart family artifact");

        let rendered_svg = {
            let BuiltinFamilyArtifact::Flowchart(flowchart) = &artifact.family else {
                panic!("expected Flowchart family artifact");
            };
            let model = crate::flowchart::FlowchartRenderModelRef::new(
                flowchart.pair().semantic(),
                flowchart.render_context(),
            );
            let edge = model.edges.get(1).expect("self-loop edge");
            assert_eq!(edge.id, "self-loop-edge");
            let label = model
                .edge_label_for_render(edge)
                .expect("self-loop edge label");
            let owner = flowchart
                .svg_label_sidecar()
                .edge_owner(edge.id.as_str(), false)
                .expect("semantic self-loop owner");
            assert_eq!(owner, crate::flowchart::FlowchartSvgLabelOwner::Edge(1));
            assert_eq!(
                flowchart
                    .svg_label_sidecar()
                    .edge_owner("A-cyclic-special-mid", false),
                None
            );
            assert!(
                flowchart
                    .pair()
                    .layout()
                    .edges
                    .iter()
                    .any(|edge| edge.id == "self-loop-edge")
            );

            let config = crate::flowchart::FlowchartConfigView::new(
                artifact.metadata.effective_config.as_value(),
            );
            let font_family = config.font_family();
            let render_style = config.render_text_style(&font_family, config.render_font_size());
            let edge_width = config.layout_settings().edge_label_wrapping_width;
            let render_measurer = artifact
                .session
                .text_measurer(crate::environment::TextMeasurementPhase::SvgBBox);
            let calls_before = text_measurement_call_count(&artifact.session);
            let plan = crate::flowchart::FlowchartSvgLabelRenderPlan::new(
                Some(flowchart.svg_label_sidecar()),
                Some(owner),
                label,
                &render_measurer,
                &render_style,
                Some(edge_width),
                true,
                crate::flowchart::FlowchartSvgWidthMode::Bbox,
            );
            assert!(matches!(
                &plan,
                crate::flowchart::FlowchartSvgLabelRenderPlan::Prepared { .. }
            ));
            let wrapped = plan.wrapped_lines();
            assert!(matches!(&wrapped, std::borrow::Cow::Borrowed(_)));
            assert!(wrapped.len() >= 2, "{wrapped:?}");
            assert_eq!(
                text_measurement_call_count(&artifact.session),
                calls_before,
                "a prepared self-loop label must not invoke the SVG measurer again"
            );
            drop(wrapped);
            drop(plan);

            let hits_before_render = flowchart.svg_label_sidecar().prepared_hit_count(owner);
            let svg = render_family_artifact_svg(
                &artifact,
                &SvgRenderOptions::default(),
                &SvgDebugOptions::default(),
            )
            .expect("render self-loop SVG");
            assert!(
                flowchart.svg_label_sidecar().prepared_hit_count(owner) > hits_before_render,
                "the real Flowchart SVG renderer must consume the prepared self-loop label"
            );
            svg
        };

        assert!(!rendered_svg.contains("cyclic-special"), "{}", rendered_svg);
        let document = roxmltree::Document::parse(&rendered_svg).expect("valid self-loop SVG");
        let logical_path = document.descendants().any(|node| {
            node.has_tag_name("path") && node.attribute("data-id") == Some("self-loop-edge")
        });
        assert!(logical_path, "{rendered_svg}");
        let label_group = document
            .descendants()
            .find(|node| {
                node.has_tag_name("g") && node.attribute("data-id") == Some("self-loop-edge")
            })
            .expect("logical self-loop label group");
        let text = label_group
            .descendants()
            .filter_map(|node| node.text().filter(|_| node.is_text()))
            .collect::<String>();
        assert!(text.contains("self loop semantic owner"), "{text:?}");
        let row_count = label_group
            .descendants()
            .filter(|node| {
                node.has_tag_name("tspan")
                    && node.attribute("class").is_some_and(|class| {
                        class
                            .split_ascii_whitespace()
                            .any(|part| part == "text-outer-tspan")
                    })
            })
            .count();
        assert!(row_count >= 2, "rows={row_count}: {rendered_svg}");
    }

    #[test]
    fn prepared_swimlane_edge_label_is_consumed_by_the_real_svg_renderer() {
        let source = r#"---
config:
  htmlLabels: false
  flowchart:
    htmlLabels: false
    wrappingWidth: 96
---
swimlane-beta LR
A styled@-->|swimlane semantic owner keeps wrapped label rows through the generated labelRect| B
linkStyle default font-size:24px,font-weight:bold
linkStyle 0 font-size:12px,font-style:italic
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .expect("parse Swimlane")
            .expect("detect Swimlane");
        let artifact = prepare_with_render_policy_impl(
            parsed,
            &LayoutOptions::default(),
            session(),
            PresentationRenderPolicy::default(),
            FlowchartSvgLabelPreparation(true),
        )
        .expect("prepare Swimlane family artifact");

        let rendered_svg = {
            let BuiltinFamilyArtifact::Swimlane(swimlane) = &artifact.family else {
                panic!("expected Swimlane family artifact");
            };
            let model = crate::flowchart::FlowchartRenderModelRef::new(
                swimlane.pair().semantic(),
                swimlane.render_context(),
            );
            let edge = model.edges.first().expect("styled Swimlane edge");
            assert_eq!(edge.id, "styled");
            let label = model
                .edge_label_for_render(edge)
                .expect("Swimlane edge label");
            let owner = swimlane
                .svg_label_sidecar()
                .edge_owner(edge.id.as_str(), true)
                .expect("semantic Swimlane edge owner");
            assert_eq!(
                owner,
                crate::flowchart::FlowchartSvgLabelOwner::SwimlaneEdgeLabel(0)
            );
            assert_eq!(
                swimlane.pair().layout().edges[0].label_node_id.as_deref(),
                Some("edge-label-A-B-styled")
            );

            let config = crate::flowchart::FlowchartConfigView::new(
                artifact.metadata.effective_config.as_value(),
            );
            let font_family = config.font_family();
            let base_style = config.render_text_style(&font_family, config.render_font_size());
            let default_edge_styles = model
                .edge_defaults
                .as_ref()
                .map_or(&[][..], |defaults| defaults.style.as_slice());
            let label_style = crate::flowchart::flowchart_swimlane_label_rect_text_style(
                &base_style,
                default_edge_styles,
                &edge.style,
            );
            let render_measurer = artifact
                .session
                .text_measurer(crate::environment::TextMeasurementPhase::SvgBBox);
            let plan = crate::flowchart::FlowchartSvgLabelRenderPlan::new(
                Some(swimlane.svg_label_sidecar()),
                Some(owner),
                label,
                &render_measurer,
                label_style.as_ref(),
                Some(config.render_wrapping_width()),
                true,
                crate::flowchart::FlowchartSvgWidthMode::Bbox,
            );
            assert!(matches!(
                &plan,
                crate::flowchart::FlowchartSvgLabelRenderPlan::Prepared { .. }
            ));
            let wrapped = plan.wrapped_lines();
            assert!(matches!(&wrapped, std::borrow::Cow::Borrowed(_)));
            assert!(wrapped.len() >= 2, "{wrapped:?}");
            drop(wrapped);
            drop(plan);

            let hits_before_render = swimlane.svg_label_sidecar().prepared_hit_count(owner);
            let svg = render_family_artifact_svg(
                &artifact,
                &SvgRenderOptions::default(),
                &SvgDebugOptions::default(),
            )
            .expect("render Swimlane SVG");
            assert!(
                swimlane.svg_label_sidecar().prepared_hit_count(owner) > hits_before_render,
                "the real Swimlane SVG renderer must consume the prepared labelRect"
            );
            svg
        };

        let document = roxmltree::Document::parse(&rendered_svg).expect("valid Swimlane SVG");
        let label_group = document
            .descendants()
            .find(|node| {
                node.has_tag_name("g") && node.attribute("id") == Some("edge-label-A-B-styled")
            })
            .expect("generated labelRect group");
        let visible = label_group
            .descendants()
            .filter_map(|node| node.text().filter(|_| node.is_text()))
            .flat_map(str::chars)
            .filter(|ch| !ch.is_whitespace())
            .collect::<String>();
        assert_eq!(
            visible,
            "swimlanesemanticownerkeepswrappedlabelrowsthroughthegeneratedlabelRect"
        );
    }

    fn prepare_with_model_item_limit(
        source: &str,
        max_model_items: usize,
    ) -> Result<FamilyRenderArtifact> {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("flowchart source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_resource_policy(
                crate::resources::RenderResourcePolicy::unbounded_for_trusted_input()
                    .with_limit(
                        crate::resources::ResourceLimitId::MaxModelItems,
                        max_model_items,
                    )
                    .unwrap(),
            )
            .begin_session()
            .unwrap();
        prepare(parsed, &LayoutOptions::default(), session)
    }

    fn prepare_with_layout_work_limit(
        source: &str,
        max_layout_work_units: usize,
    ) -> Result<FamilyRenderArtifact> {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("flowchart source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_resource_policy(
                crate::resources::RenderResourcePolicy::unbounded_for_trusted_input()
                    .with_limit(
                        crate::resources::ResourceLimitId::MaxLayoutWorkUnits,
                        max_layout_work_units,
                    )
                    .unwrap(),
            )
            .begin_session()
            .unwrap();
        prepare(parsed, &LayoutOptions::default(), session)
    }

    fn prepare_with_unbounded_layout_work(source: &str) -> Result<FamilyRenderArtifact> {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_resource_policy(
                crate::resources::RenderResourcePolicy::unbounded_for_trusted_input(),
            )
            .begin_session()
            .unwrap();
        prepare(parsed, &LayoutOptions::default(), session)
    }

    fn assert_model_item_limit(error: Error, actual: usize, max: usize) {
        let Error::ResourceLimitExceeded(limit) = error else {
            panic!("expected max_model_items resource limit error")
        };
        assert_eq!(limit.phase, ResourceLimitPhase::LayoutModel);
        assert_eq!(limit.limit, "max_model_items");
        assert_eq!(limit.actual, actual);
        assert_eq!(limit.max, max);
    }

    #[test]
    fn session_report_accounts_for_every_metered_layout_family() {
        let cases = vec![
            (
                "classDiagram\nclass A\nclass B\nA --> B\n",
                RenderFamilyKind::Class,
            ),
            (
                "stateDiagram-v2\n[*] --> Idle\nIdle --> Active\n",
                RenderFamilyKind::State,
            ),
            (
                "erDiagram\nCUSTOMER ||--o{ ORDER : places\n",
                RenderFamilyKind::Er,
            ),
            (
                "---\nconfig:\n  layout: tidy-tree\n---\nmindmap\n  Root\n    First child\n    Second child\n",
                RenderFamilyKind::Mindmap,
            ),
            (
                "sequenceDiagram\nparticipant A\nparticipant B\nA->>B: hello\n",
                RenderFamilyKind::Sequence,
            ),
            (
                "kanban\n  todo[Todo]\n    task[Task]\n",
                RenderFamilyKind::Kanban,
            ),
            (
                "requirementDiagram\nrequirement req1 {\n  id: 1\n  text: Login\n  risk: high\n}\n",
                RenderFamilyKind::Requirement,
            ),
            ("sankey-beta\nA,B,10\n", RenderFamilyKind::Sankey),
            (
                "radar-beta\naxis A,B,C\ncurve score{1,2,3}\n",
                RenderFamilyKind::Radar,
            ),
            (
                "venn-beta\nset A[\"Core\"]:20\nset B[\"Editor\"]:14\nunion A,B[\"Shared\"]:4\n",
                RenderFamilyKind::Venn,
            ),
        ];

        #[cfg(feature = "layout-cytoscape")]
        let cases = {
            let mut cases = cases;
            cases.push((
                "mindmap\n  Root\n    First child\n    Second child\n",
                RenderFamilyKind::Mindmap,
            ));
            cases
        };

        for (source, expected_family) in cases {
            let parsed = Engine::new()
                .parse_diagram_for_render_model_sync(source, ParseOptions::default())
                .unwrap()
                .expect("the layout-work fixture should produce a render model");
            let artifact = prepare(parsed, &LayoutOptions::default(), session()).unwrap();

            assert_eq!(artifact.family_kind(), expected_family);
            assert!(
                artifact.session.report().layout_work_units() > 0,
                "{expected_family} must contribute layout work to the session report"
            );
        }
    }

    #[test]
    fn dagre_family_work_budgets_are_exact_and_preserve_layout_output() {
        let cases = [
            (
                "classDiagram\nnamespace Outer {\n  class A\n  class B\n}\nA --> B\n",
                RenderFamilyKind::Class,
            ),
            (
                "stateDiagram-v2\nstate Parent {\n  [*] --> Idle\n  Idle --> Active\n}\nParent --> Outside\n",
                RenderFamilyKind::State,
            ),
            (
                "erDiagram\nNODE {\n  string id\n}\nNODE ||--o{ NODE : leads\n",
                RenderFamilyKind::Er,
            ),
        ];

        for (source, expected_family) in cases {
            let unbounded = prepare_with_unbounded_layout_work(source).unwrap();
            assert_eq!(unbounded.family_kind(), expected_family);
            let exact = unbounded.session.report().layout_work_units();
            assert!(exact > 0, "{expected_family} must report layout work");
            let expected_layout = unbounded.layout_json().unwrap();

            let bounded = prepare_with_layout_work_limit(source, exact).unwrap();
            assert_eq!(bounded.session.report().layout_work_units(), exact);
            assert_eq!(bounded.layout_json().unwrap(), expected_layout);

            let error = match prepare_with_layout_work_limit(source, exact - 1) {
                Ok(_) => panic!("{expected_family} exact minus one unexpectedly succeeded"),
                Err(error) => error,
            };
            let Error::ResourceLimitExceeded(limit) = error else {
                panic!("expected {expected_family} layout work rejection")
            };
            assert_eq!(limit.limit, "max_layout_work_units");
            assert_eq!(limit.max, exact - 1);
        }
    }

    #[cfg(feature = "layout-cytoscape")]
    #[test]
    fn default_mindmap_cose_reports_kernel_work_and_has_an_exact_resource_boundary() {
        let (unbounded_result, unbounded_host) = prepare_mindmap_with_host_limit(None);
        let unbounded = unbounded_result.expect("unbounded COSE mindmap");
        let exact = unbounded.session.report().layout_work_units();
        assert!(
            exact > 78,
            "kernel work must exceed the 3-node adapter estimate"
        );
        let unbounded_layout = unbounded.layout_json().expect("unbounded layout json");
        let unbounded_trace = unbounded_host.snapshot();
        assert!(!unbounded_trace.is_empty());

        let (exact_result, exact_host) = prepare_mindmap_with_host_limit(Some(exact));
        let exact_artifact = exact_result.expect("exact COSE budget");
        assert_eq!(exact_artifact.session.report().layout_work_units(), exact);
        assert_eq!(
            exact_artifact.layout_json().expect("exact layout json"),
            unbounded_layout
        );
        assert_eq!(exact_host.snapshot(), unbounded_trace);

        let (short_result, _short_host) = prepare_mindmap_with_host_limit(Some(exact - 1));
        let error = match short_result {
            Ok(_) => panic!("exact minus one must reject COSE work"),
            Err(error) => error,
        };
        let Error::ResourceLimitExceeded(limit) = error else {
            panic!("expected max_layout_work_units rejection")
        };
        assert_eq!(limit.limit, "max_layout_work_units");
        assert_eq!(limit.max, exact - 1);

        let (early_result, early_host) = prepare_mindmap_with_host_limit(Some(1));
        assert!(matches!(early_result, Err(Error::ResourceLimitExceeded(_))));
        assert!(
            early_host.snapshot().is_empty(),
            "adapter admission must reject before the first host measurement"
        );
    }

    #[test]
    fn requirement_layout_projection_excludes_operation_prepared_labels() {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(
                r#"requirementDiagram
requirement req1 {
  id: 1
  text: User logs in
  risk: high
}
element system {
  type: service
}
system - satisfies -> req1
"#,
                ParseOptions::strict(),
            )
            .unwrap()
            .expect("Requirement source should produce a render model");
        let artifact = prepare(parsed, &LayoutOptions::default(), session()).unwrap();
        let projection = artifact.layout_json().unwrap();
        let layout = &projection["layout"]["RequirementDiagram"];
        let fields = layout
            .as_object()
            .expect("Requirement layout projection should remain an object");

        assert_eq!(artifact.family_kind(), RenderFamilyKind::Requirement);
        assert!(fields.contains_key("nodes"));
        assert!(fields.contains_key("edges"));
        assert!(fields.contains_key("bounds"));
        assert!(!fields.contains_key("labels"));
        assert!(!layout.to_string().contains("display_text"));
        let serialized_projection = projection.to_string();
        assert!(!serialized_projection.contains("max_width_px"));
        assert!(!serialized_projection.contains("keep_centered"));
        assert!(!serialized_projection.contains("divider_y_offset"));
        assert!(
            serde_json::from_value::<RequirementDiagramLayout>(layout.clone()).is_ok(),
            "prepared labels must not alter the public Requirement layout schema"
        );
    }

    #[test]
    fn dagre_flowchart_node_limit_accepts_boundary_and_rejects_one_beyond() {
        let source = "flowchart TD\nA --> B";
        let artifact = prepare_with_model_item_limit(source, 3).unwrap();
        assert_eq!(artifact.family_kind(), RenderFamilyKind::Flowchart);

        let error = match prepare_with_model_item_limit(source, 2) {
            Err(error) => error,
            Ok(_) => panic!("flowchart above the node limit unexpectedly rendered"),
        };
        assert_model_item_limit(error, 3, 2);
    }

    #[test]
    fn swimlane_node_limit_accepts_boundary_and_rejects_one_beyond() {
        let source = "swimlane-beta LR\nA --> B";
        let artifact = prepare_with_model_item_limit(source, 3).unwrap();
        assert_eq!(artifact.family_kind(), RenderFamilyKind::Swimlane);

        let error = match prepare_with_model_item_limit(source, 2) {
            Err(error) => error,
            Ok(_) => panic!("swimlane above the node limit unexpectedly rendered"),
        };
        assert_model_item_limit(error, 3, 2);
    }

    #[test]
    fn swimlane_rejects_pairwise_routing_work_before_layout() {
        let source = "swimlane-beta LR\nA --> B\nB --> C";
        let artifact = prepare_with_layout_work_limit(source, 1_000).unwrap();
        assert_eq!(artifact.family_kind(), RenderFamilyKind::Swimlane);

        let error = match prepare_with_layout_work_limit(source, 1) {
            Err(error) => error,
            Ok(_) => panic!("swimlane above the layout work limit unexpectedly rendered"),
        };
        let Error::ResourceLimitExceeded(limit) = error else {
            panic!("expected max_layout_work_units resource limit error");
        };
        assert_eq!(limit.phase, ResourceLimitPhase::LayoutModel);
        assert_eq!(limit.limit, "max_layout_work_units");
        assert!(limit.actual > limit.max);
        assert_eq!(limit.max, 1);
    }

    #[test]
    fn mindmap_node_limit_is_checked_before_layout_allocation_or_backend_dispatch() {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(
                "mindmap\n  Root\n    First child\n    Second child\n",
                ParseOptions::strict(),
            )
            .unwrap()
            .expect("mindmap source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_resource_policy(
                crate::resources::RenderResourcePolicy::unbounded_for_trusted_input()
                    .with_limit(crate::resources::ResourceLimitId::MaxModelItems, 4)
                    .unwrap(),
            )
            .begin_session()
            .unwrap();

        let error = match prepare(parsed, &LayoutOptions::default(), session) {
            Err(error) => error,
            Ok(_) => panic!("mindmap above the node limit unexpectedly reached layout"),
        };
        let Error::ResourceLimitExceeded(limit) = error else {
            panic!("expected max_model_items resource limit error");
        };
        assert_eq!(limit.phase, ResourceLimitPhase::LayoutModel);
        assert_eq!(limit.limit, "max_model_items");
        assert_eq!(limit.actual, 5);
        assert_eq!(limit.max, 4);
    }

    #[test]
    fn flowchart_math_capability_uses_parser_owned_render_spelling() {
        for source in [
            "flowchart TD\nA[\"#36;#36;node#36;#36;\"]\n",
            "flowchart TD\nA -->|#36;#36;edge#36;#36;| B\n",
            "flowchart TD\nsubgraph S[\"#36;#36;group#36;#36;\"]\nA\nend\n",
        ] {
            let parsed = Engine::new()
                .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
                .unwrap()
                .expect("Flowchart source should produce a render model");
            let session = crate::environment::RenderEnvironment::deterministic()
                .without_math_renderer()
                .begin_session()
                .unwrap();

            let plan = plan_render(&parsed, &session).unwrap();
            assert!(
                !plan
                    .required_capabilities()
                    .contains(&RenderCapability::Math),
                "encoded dollar entities remain ordinary createText input: {source}"
            );
            prepare(parsed, &LayoutOptions::default(), session)
                .expect("encoded dollar entities must not require a Math renderer");
        }

        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(
                "flowchart TD\nA[\"$$x$$\"]\n",
                ParseOptions::strict(),
            )
            .unwrap()
            .expect("Flowchart source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .without_math_renderer()
            .begin_session()
            .unwrap();
        let plan = plan_render(&parsed, &session).unwrap();
        assert_eq!(
            plan.required_capabilities(),
            if cfg!(feature = "layout-elk") {
                &[RenderCapability::LayoutElk, RenderCapability::Math][..]
            } else {
                &[RenderCapability::Math][..]
            }
        );
        assert_eq!(plan.missing_capabilities(), &[RenderCapability::Math]);
    }

    #[test]
    fn mindmap_math_label_requires_the_math_capability() {
        let source = r#"---
config:
  layout: tidy-tree
---
mindmap
  root[Root]
    formula["$$x^2$$"]
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("mindmap source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .without_math_renderer()
            .begin_session()
            .unwrap();

        let plan = plan_render(&parsed, &session).unwrap();
        assert_eq!(plan.required_capabilities(), &[RenderCapability::Math]);
        assert_eq!(plan.missing_capabilities(), &[RenderCapability::Math]);
        assert!(!plan.is_ready());

        let error = match prepare(parsed, &LayoutOptions::default(), session) {
            Err(error) => error,
            Ok(_) => panic!("mindmap math label unexpectedly rendered without a math backend"),
        };
        assert!(matches!(
            error,
            Error::MissingCapability {
                capability: RenderCapability::Math,
                ref diagram_type,
            } if diagram_type == "mindmap"
        ));
    }

    #[derive(Debug)]
    struct MindmapMathRenderer;

    impl crate::math::MathRenderer for MindmapMathRenderer {
        fn render_html_label(
            &self,
            text: &str,
            _config: &merman_core::MermaidConfig,
        ) -> Option<String> {
            text.contains("$$")
                .then(|| "<strong>rendered-mindmap-math</strong>".to_string())
        }

        fn measure_html_label(
            &self,
            text: &str,
            _config: &merman_core::MermaidConfig,
            _style: &crate::text::TextStyle,
            _max_width_px: Option<f64>,
            _wrap_mode: crate::text::WrapMode,
        ) -> Option<crate::text::TextMetrics> {
            text.contains("$$").then_some(crate::text::TextMetrics {
                width: 96.0,
                height: 24.0,
                line_count: 1,
            })
        }
    }

    #[test]
    fn mindmap_math_label_is_consumed_by_the_math_renderer() {
        let source = r#"---
config:
  layout: tidy-tree
---
mindmap
  root[Root]
    formula["$$x^2$$"]
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("mindmap source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_math_renderer(std::sync::Arc::new(MindmapMathRenderer))
            .begin_session()
            .unwrap();

        let plan = plan_render(&parsed, &session).unwrap();
        assert_eq!(plan.required_capabilities(), &[RenderCapability::Math]);
        assert!(plan.missing_capabilities().is_empty());
        assert!(plan.is_ready());

        let artifact = prepare(parsed, &LayoutOptions::default(), session).unwrap();
        let rendered = artifact
            .render_svg(&SvgRenderOptions::default(), &SvgDebugOptions::default())
            .unwrap();
        assert_eq!(rendered.required_capabilities(), &[RenderCapability::Math]);
        assert!(rendered.svg().contains("rendered-mindmap-math"));
        assert!(!rendered.svg().contains("$$x^2$$"));
    }

    #[test]
    fn class_math_label_requires_the_math_capability() {
        let source = r#"classDiagram
class Formula["$$x^2$$"]
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("Class source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .without_math_renderer()
            .begin_session()
            .unwrap();

        let plan = plan_render(&parsed, &session).unwrap();
        assert_eq!(
            plan.required_capabilities(),
            if cfg!(feature = "layout-elk") {
                &[RenderCapability::LayoutElk, RenderCapability::Math][..]
            } else {
                &[RenderCapability::Math][..]
            }
        );
        assert_eq!(plan.missing_capabilities(), &[RenderCapability::Math]);
        assert!(!plan.is_ready());

        let error = match prepare(parsed, &LayoutOptions::default(), session) {
            Err(error) => error,
            Ok(_) => panic!("Class math label unexpectedly rendered without a math backend"),
        };
        assert!(matches!(
            error,
            Error::MissingCapability {
                capability: RenderCapability::Math,
                ref diagram_type,
            } if diagram_type == "classDiagram"
        ));
    }

    #[derive(Debug)]
    struct ClassMathRenderer;

    impl crate::math::MathRenderer for ClassMathRenderer {
        fn render_html_label(
            &self,
            text: &str,
            _config: &merman_core::MermaidConfig,
        ) -> Option<String> {
            text.contains("$$")
                .then(|| "<div>rendered-class-math</div>".to_string())
        }

        fn measure_html_label(
            &self,
            text: &str,
            _config: &merman_core::MermaidConfig,
            _style: &crate::text::TextStyle,
            _max_width_px: Option<f64>,
            _wrap_mode: crate::text::WrapMode,
        ) -> Option<crate::text::TextMetrics> {
            text.contains("$$").then_some(crate::text::TextMetrics {
                width: 96.0,
                height: 24.0,
                line_count: 1,
            })
        }
    }

    #[test]
    fn class_math_label_is_consumed_by_the_math_renderer() {
        let source = r#"classDiagram
class Formula["$$x^2$$"]
"#;
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("Class source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_math_renderer(std::sync::Arc::new(ClassMathRenderer))
            .begin_session()
            .unwrap();

        let plan = plan_render(&parsed, &session).unwrap();
        assert_eq!(
            plan.required_capabilities(),
            if cfg!(feature = "layout-elk") {
                &[RenderCapability::LayoutElk, RenderCapability::Math][..]
            } else {
                &[RenderCapability::Math][..]
            }
        );
        assert!(plan.missing_capabilities().is_empty());
        assert!(plan.is_ready());

        let rendered = prepare(parsed, &LayoutOptions::default(), session)
            .unwrap()
            .render_svg(&SvgRenderOptions::default(), &SvgDebugOptions::default())
            .unwrap();
        assert!(rendered.svg().contains("rendered-class-math"));
        assert!(!rendered.svg().contains("$$x^2$$"));
    }

    fn render_class_math(source: &str) -> String {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
            .unwrap()
            .expect("Class source should produce a render model");
        let session = crate::environment::RenderEnvironment::deterministic()
            .with_math_renderer(std::sync::Arc::new(ClassMathRenderer))
            .begin_session()
            .unwrap();
        prepare(parsed, &LayoutOptions::default(), session)
            .unwrap()
            .render_svg(&SvgRenderOptions::default(), &SvgDebugOptions::default())
            .unwrap()
            .svg()
            .to_string()
    }

    #[test]
    fn class_math_label_forces_html_rendering_when_html_labels_are_disabled() {
        let svg = render_class_math(
            r#"---
config:
  htmlLabels: false
---
classDiagram
class Formula["$$x^2$$"]
"#,
        );

        assert!(svg.contains("rendered-class-math"));
        assert!(!svg.contains("$$x^2$$"));
    }

    #[test]
    fn class_relation_terminal_and_note_math_labels_use_the_math_renderer() {
        let svg = render_class_math(
            r#"classDiagram
class Formula
class Result
Formula "$$one$$" --> "$$many$$" Result : $$edge$$
note for Formula "$$note$$"
"#,
        );

        assert_eq!(svg.matches("rendered-class-math").count(), 4);
        assert!(!svg.contains("$$"));
        assert!(!svg.contains("<p><div>"));
    }

    #[test]
    fn class_annotation_and_interface_math_labels_require_and_use_math() {
        for source in [
            r#"classDiagram
class Formula <<$$annotation$$>>
"#,
            r#"classDiagram
class Formula
$$interface$$ ()-- Formula
"#,
        ] {
            let parsed = Engine::new()
                .parse_diagram_for_render_model_sync(source, ParseOptions::strict())
                .unwrap()
                .expect("Class source should produce a render model");
            let session = crate::environment::RenderEnvironment::deterministic()
                .without_math_renderer()
                .begin_session()
                .unwrap();

            let plan = plan_render(&parsed, &session).unwrap();
            assert_eq!(
                plan.required_capabilities(),
                if cfg!(feature = "layout-elk") {
                    &[RenderCapability::LayoutElk, RenderCapability::Math][..]
                } else {
                    &[RenderCapability::Math][..]
                }
            );
            assert_eq!(plan.missing_capabilities(), &[RenderCapability::Math]);

            let svg = render_class_math(source);
            assert!(svg.contains("rendered-class-math"));
            assert!(!svg.contains("$$"));
            assert!(!svg.contains("<p><div>"));
        }
    }

    #[cfg(feature = "layout-elk")]
    #[test]
    fn elk_flowchart_node_limit_accepts_boundary_and_rejects_one_beyond() {
        let source = "flowchart-elk TD\nA --> B";
        let artifact = prepare_with_model_item_limit(source, 3).unwrap();
        assert_eq!(artifact.family_kind(), RenderFamilyKind::Flowchart);

        let error = match prepare_with_model_item_limit(source, 2) {
            Err(error) => error,
            Ok(_) => panic!("ELK flowchart above the node limit unexpectedly rendered"),
        };
        assert_model_item_limit(error, 3, 2);
    }

    #[test]
    fn custom_semantic_json_is_explicitly_non_renderable() {
        let mut engine = Engine::new();
        engine
            .diagram_registry_mut()
            .insert("customDiagram", custom_semantic_parser);
        let parsed = engine
            .parse_diagram_for_render_model_with_type_sync(
                "customDiagram",
                "customDiagram\npayload",
                ParseOptions::strict(),
            )
            .unwrap()
            .unwrap();

        let error = match prepare(parsed, &LayoutOptions::default(), session()) {
            Err(error) => error,
            Ok(_) => panic!("custom JSON unexpectedly produced a built-in artifact"),
        };
        let Error::NonRenderableCustomModel {
            diagram_type,
            model_name,
            provenance,
        } = error
        else {
            panic!("expected explicit custom-model capability error")
        };
        assert_eq!(diagram_type, "customDiagram");
        assert_eq!(model_name, "customDiagram");
        assert_eq!(provenance, CustomJsonProvenance::SemanticRegistryOverlay);
    }

    #[test]
    fn custom_render_overlay_cannot_masquerade_as_a_builtin_family() {
        let mut engine = Engine::new();
        engine
            .render_diagram_registry_mut()
            .insert("flowchart-v2", custom_render_parser);
        let parsed = engine
            .parse_diagram_for_render_model_with_type_sync(
                "flowchart-v2",
                "flowchart TD\nA --> B",
                ParseOptions::strict(),
            )
            .unwrap()
            .unwrap();

        let error = match prepare(parsed, &LayoutOptions::default(), session()) {
            Err(error) => error,
            Ok(_) => panic!("custom JSON unexpectedly produced a built-in artifact"),
        };
        let Error::NonRenderableCustomModel {
            diagram_type,
            model_name,
            provenance,
        } = error
        else {
            panic!("expected explicit custom-model capability error")
        };
        assert_eq!(diagram_type, "flowchart-v2");
        assert_eq!(model_name, "custom-flowchart");
        assert_eq!(provenance, CustomJsonProvenance::RenderRegistryOverlay);
    }

    #[test]
    fn gantt_time_axis_diagnostics_invert_rendered_x_without_exposing_layout() {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync(
                r#"---
config:
  gantt:
    useWidth: 130
    leftPadding: 10
    rightPadding: 20
---
gantt
dateFormat x
section Delivery
First: first,-1,1ms
Second: second,after first,2ms
"#,
                ParseOptions::strict(),
            )
            .unwrap()
            .unwrap();
        let artifact = prepare(parsed, &LayoutOptions::default(), session()).unwrap();

        assert_eq!(artifact.family_kind(), RenderFamilyKind::Gantt);
        let diagnostics = artifact
            .gantt_time_axis_diagnostics()
            .expect("Gantt tasks should expose time-axis diagnostics");
        assert_eq!(diagnostics.unix_millis_at_rendered_x(10.0), Some(-1));
        assert_eq!(diagnostics.unix_millis_at_rendered_x(43.0), Some(0));
        assert_eq!(diagnostics.unix_millis_at_rendered_x(77.0), Some(1));
        assert_eq!(diagnostics.unix_millis_at_rendered_x(110.0), Some(2));
        assert_eq!(diagnostics.unix_millis_at_rendered_x(44.0), None);
        assert_eq!(diagnostics.unix_millis_at_rendered_x(f64::NAN), None);

        artifact
            .render_svg(&SvgRenderOptions::default(), &SvgDebugOptions::default())
            .unwrap();
        assert_eq!(diagnostics.unix_millis_at_rendered_x(77.0), Some(1));
    }

    #[test]
    fn suppressed_parse_failure_uses_the_typed_error_artifact_and_renderer() {
        let parsed = Engine::new()
            .parse_diagram_for_render_model_sync("flowchart TD\nA -->", ParseOptions::lenient())
            .unwrap()
            .unwrap();
        let artifact = prepare(parsed, &LayoutOptions::default(), session()).unwrap();

        assert_eq!(artifact.family_kind(), RenderFamilyKind::Error);
        let rendered = artifact
            .render_svg(&SvgRenderOptions::default(), &SvgDebugOptions::default())
            .unwrap();
        assert!(rendered.svg().contains("Syntax error in text"));
    }
}