nucleation 0.10.14

A high-performance Minecraft schematic parser and utility library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
//! Design: the composition document over cells, loose blocks and buses.
//!
//! See `redstone-eda/DESIGN_SPEC.md` for the co-designed model. A `Design`
//! is a Photoshop-style layer stack over a shared coordinate space:
//!
//! - a **loose block layer** (the base schematic — endpoint hardware placed
//!   with plain `set_block`),
//! - **instance layers** referencing typed cells (schematic + embedded
//!   [`CellContract`]) through a transform,
//! - **bus layers** owning their routed voxel fragments, with per-bus state
//!   `intended | routed | FAILED(reason)` — unroutability is a *state*, not
//!   an exception.
//!
//! `flatten()` collapses the stack into ONE self-describing
//! [`UniversalSchematic`] with a named region per layer and the merged
//! contract embedded — the artifact is itself placeable as a cell.
//!
//! Buses realize the verified vertical 2y-pitch form
//! (`redstone-eda/bus8_*.py`): axis-aligned runs (with one implicit L
//! corner per waypoint pair) between the driver, optional gates and the
//! primary sink, implicit dip-under crossings ported from `bus8_cross.py`
//! v2 as template data, fanout branches for extra sinks and explicit
//! wired-OR merges for extra drivers (`route_bus_or`).
//!
//! Phase 2 Lane A adds the INTERFERENCE model and drag APIs: a spatial
//! [`OccupancyIndex`] (loose blocks + instance footprints + influence
//! halos + routed fragments), [`Design::move_instance`] /
//! [`Design::move_gate`] computing the affected bus set and co-rerouting
//! it deterministically in bounded rounds, and [`Design::check`] gaining
//! STA/skew plus per-bus net-class rule enforcement. Moves always succeed
//! (they are the document's truth); buses fail into a visible
//! `BusState::Failed`, never a half-routed fragment.

use crate::design_decay::{tile_dust_debt, Carrier, DecayLedger, CROSSING_ALLOWANCE, DUST_BUDGET};
use crate::io_contract::{CellContract, IoType, LayoutFunction, NetClassRule, PortDirection};
use crate::routing::engine::blocks as rblocks;
use crate::UniversalSchematic;
use std::collections::{BTreeMap, BTreeSet};

/// Position triple, kept plain so the module stays wasm-safe and
/// serde-friendly.
pub type P3 = (i32, i32, i32);

fn add(a: P3, b: P3) -> P3 {
    (a.0 + b.0, a.1 + b.1, a.2 + b.2)
}

fn scale(a: P3, k: i32) -> P3 {
    (a.0 * k, a.1 * k, a.2 * k)
}

/// A cell's TRUE block extent, min and max corner inclusive.
pub struct CellBounds {
    pub min: P3,
    pub max: P3,
}

/// The cell's real occupied extent — NOT `UniversalSchematic::get_bounding_box`.
///
/// `get_bounding_box()` reports the region's allocated envelope, which for a
/// programmatically built schematic is its growth capacity, not its contents: a
/// 10x18x6 cell built with `set_block_from_string` reports
/// `(0,0,0)..(10,65,65)`. [`transform_pos`] derives the rotation's footprint
/// size from that box, so an over-reported extent flings every ROTATED
/// instance — its blocks, its ports, its halo — tens of blocks away from where
/// the user placed it, while rot_y=0 (where only `min` matters) looks fine.
/// That asymmetry is exactly what "the bus fails as soon as I rotate a cell"
/// looks like from the studio.
///
/// Air is excluded so a padded schematic does not inflate the footprint.
fn cell_bounds(sch: &UniversalSchematic) -> CellBounds {
    let mut min: Option<P3> = None;
    let mut max: Option<P3> = None;
    for (bp, bs) in sch.iter_blocks() {
        if bs.to_string().contains("minecraft:air") {
            continue;
        }
        let p = (bp.x, bp.y, bp.z);
        min = Some(match min {
            None => p,
            Some(m) => (m.0.min(p.0), m.1.min(p.1), m.2.min(p.2)),
        });
        max = Some(match max {
            None => p,
            Some(m) => (m.0.max(p.0), m.1.max(p.1), m.2.max(p.2)),
        });
    }
    match (min, max) {
        (Some(min), Some(max)) => CellBounds { min, max },
        _ => {
            // An empty cell: fall back to the declared envelope.
            let bb = sch.get_bounding_box();
            CellBounds {
                min: bb.min,
                max: bb.max,
            }
        }
    }
}

/// The single straight run realizing an axis-aligned anchor pair, or `None`
/// when the pair needs a corner (differs on both horizontal axes, or on y).
fn axis_run(a: P3, b: P3, width: u8) -> Option<RunInfo> {
    if a.1 != b.1 {
        return None;
    }
    if a.2 == b.2 && a.0 != b.0 {
        return Some(RunInfo {
            along_x: true,
            fixed: a.2,
            y0: a.1,
            from: a.0,
            to: b.0,
            width,
        });
    }
    if a.0 == b.0 && a.2 != b.2 {
        return Some(RunInfo {
            along_x: false,
            fixed: a.0,
            y0: a.1,
            from: a.2,
            to: b.2,
            width,
        });
    }
    None
}

/// Dust cells a mid-bus segment must assume were already spent when the count
/// entering it is genuinely unknown (a port patch splicing into the middle of
/// somebody else's route). This is the ONLY place a blanket constant is still
/// right: there is no upstream geometry to measure.
///
/// Refresh spacing everywhere else is decided by
/// [`crate::design_decay::DecayLedger`] from the strength actually spent — see
/// that module for why a single constant was both too dense on a straight run
/// and too optimistic through a form conversion.
const UNKNOWN_ARRIVAL: u32 = DUST_BUDGET / 2;

/// Dust cells tolerated between refresh stations INSIDE a level shift. A
/// staircase cell cannot host a repeater (a repeater does not power
/// diagonally), so a slope spends the signal 2 cells per level; leaving 2 in
/// hand keeps the exit cell plus a joint column inside dust's reach.
const SHIFT_DUST_CAP: u32 = DUST_BUDGET - 2;

/// One column of the verified BUS LEVEL-SHIFT tile ([`shift_plan`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ShiftCell {
    /// The dust the stack steps OFF toward the next level.
    Step,
    /// The dust the stack LANDS on, one level away.
    Land,
    /// Flat dust resuming the bus form at the shifted level.
    Flat,
    /// Refresh station entry block (weak-powered by the dust pointing in).
    Entry,
    /// Refresh station repeater, on a conducting floor.
    Rep,
    /// Refresh station exit block (strongly powered: a fresh 15 out).
    Exit,
}

/// The column plan of a `k`-level shift of a dense 2y-pitch stack:
/// `(offset along the axis, level RELATIVE to the entry level, cell)`, plus
/// the dust-since-refresh count on the way out.
///
/// A level costs TWO columns — step off, land — so the slope is 1 y per 2
/// cells. A continuous 1y-per-1x staircase is IMPOSSIBLE for a dense stack:
/// every cell would be both the step-UPPER of the next diagonal (its support
/// must CONDUCT, the diode law) and the cap over bit n-1's in-use lower
/// diagonal (its support must INSULATE, the cut law) — an over-constrained
/// cell, i.e. the geometry itself is wrong. Landing flat for one cell splits
/// those two roles across two columns: THE ALTERNATION.
///
/// Because stairs cannot host repeaters, a station is inserted before any
/// level whose two dust cells would blow [`SHIFT_DUST_CAP`] — which also
/// refreshes a stale arrival on entry. `k` is therefore unbounded.
///
/// Verified in mc-tick by `redstone-eda/bus_levelshift.py`: 8-bit stack,
/// k in {1,2,3,5,8} x {down,up} x {fresh,stale} arrival, walking-ones /
/// all-on / alternating / 8 random patterns, 3040 output checks, zero
/// crosstalk. All-solid, all-glass and swapped-parity variants all FAIL,
/// so the alternation below is load-bearing in both directions.
/// `exit_reserve` is the strength the geometry PAST the tile's exit spends and
/// cannot refresh — a sink's form adapter. A shift placed hard against the sink
/// end exits onto that anchor with nothing between, so without this the tile's
/// stale-exit case (`SHIFT_DUST_CAP` spent, plus the exit cell) and the
/// adapter's own debt add up past dust's reach. One trailing station buys it
/// back; it is the same Entry/Rep/Exit triple the tile already inserts mid-slope
/// and `bus_levelshift.py` already verifies against a stale arrival.
fn shift_plan(
    k: u32,
    down: bool,
    since0: u32,
    exit_reserve: u32,
) -> (Vec<(i32, i32, ShiftCell)>, u32) {
    let sgn = if down { -1 } else { 1 };
    let mut cols = Vec::new();
    let (mut o, mut dy, mut since) = (0i32, 0i32, since0);
    let station = |cols: &mut Vec<(i32, i32, ShiftCell)>, o: &mut i32, dy: i32| {
        for kind in [ShiftCell::Entry, ShiftCell::Rep, ShiftCell::Exit] {
            cols.push((*o, dy, kind));
            *o += 1;
        }
    };
    for _ in 0..k {
        if since + 2 > SHIFT_DUST_CAP {
            station(&mut cols, &mut o, dy);
            since = 0;
        }
        cols.push((o, dy, ShiftCell::Step));
        o += 1;
        dy += sgn;
        cols.push((o, dy, ShiftCell::Land));
        o += 1;
        since += 2;
    }
    // The exit cell is one more dust cell, and whatever waits past it spends
    // `exit_reserve` more with nothing to refresh in between.
    if since + 1 + exit_reserve > DUST_BUDGET {
        station(&mut cols, &mut o, dy);
        since = 0;
    }
    cols.push((o, dy, ShiftCell::Flat));
    (cols, since + 1)
}

/// Cells of straight run a `k`-level shift consumes (entry cell included).
fn shift_len(k: u32, down: bool, since0: u32, exit_reserve: u32) -> i32 {
    shift_plan(k, down, since0, exit_reserve)
        .0
        .last()
        .map_or(0, |c| c.0 + 1)
}

/// The MOST cells a `k`-level shift can ever consume when what follows its exit
/// spends `exit_reserve`.
///
/// The tile's real length depends on how much of the dust budget the leg into
/// it already spent — a stale arrival buys a leading refresh station, three
/// cells the caller cannot know about before planning that leg. Placement is
/// therefore checked against the worst case, so a tile can never grow past the
/// room reserved for it and leave a gap at its exit.
fn shift_len_max(k: u32, down: bool, exit_reserve: u32) -> i32 {
    shift_len(k, down, SHIFT_DUST_CAP, exit_reserve)
}

/// A library cell: schematic + resolved contract, stored once and shared by
/// every instance that references it.
#[derive(Clone, Debug)]
pub struct CellDef {
    /// The cell body.
    pub schematic: UniversalSchematic,
    /// The resolved contract (embedded metadata or Insign, see
    /// [`UniversalSchematic::resolve_cell_contract`]).
    pub contract: CellContract,
}

/// One placed instance layer: a cell REFERENCE plus a transform.
#[derive(Clone, Debug)]
pub struct Instance {
    /// Layer name (region `inst:{name}` on flatten).
    pub name: String,
    /// Key into the design's cell library.
    pub cell: String,
    /// Translation applied after rotation.
    pub at: P3,
    /// Y rotation in degrees (0/90/180/270), about the cell's min corner.
    pub rot_y: i32,
    /// Per-port mode overrides. A port absent here is in
    /// [`PortMode::Executor`]; see [`Design::set_port_mode`].
    pub port_modes: BTreeMap<String, PortOverride>,
}

/// How a port presents itself. The two modes are mutually exclusive by
/// physics, not by policy: a lever cannot be driven by redstone, and dust
/// cannot be flipped by a player.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PortMode {
    /// The shipped hardware (levers/buttons in, lamps out). Drivable by
    /// `CellExecutor`; NOT routable.
    Executor,
    /// Promoted: the hardware is replaced by a driver stub ending in dust.
    /// Routable; no longer hand-drivable.
    Bus,
}

impl PortMode {
    /// `"executor"` / `"bus"`.
    pub fn as_str(self) -> &'static str {
        match self {
            PortMode::Executor => "executor",
            PortMode::Bus => "bus",
        }
    }

    /// Parse `"executor"` / `"bus"`.
    pub fn parse(s: &str) -> Option<PortMode> {
        match s {
            "executor" => Some(PortMode::Executor),
            "bus" => Some(PortMode::Bus),
            _ => None,
        }
    }
}

/// A port's remembered BOTH-FORMS state: the current mode plus the reversible
/// patch that realizes [`PortMode::Bus`].
///
/// The patch is kept even in `Executor` mode so toggling is instant and a UI
/// can say in advance what promoting would change. The cell library itself is
/// never mutated, which is what makes Bus -> Executor a byte-exact undo.
#[derive(Clone, Debug)]
pub struct PortOverride {
    pub mode: PortMode,
    pub patch: crate::design_promote::PortPatch,
}

/// Scanned per-bit hardware capabilities of a port (derived, not declared).
#[derive(Clone, Debug, Default)]
pub struct BitHardware {
    /// The connection cell holds dust: a router may land here.
    pub connectable: bool,
    /// An adjacent lever: the executor can drive this bit (lever position).
    pub lever: Option<P3>,
    /// A lamp supports/neighbours the cell: the bit is human-readable.
    pub lamp: Option<P3>,
}

/// A design port: named typed geometry. The anchor is the bit-0
/// CONNECTION CELL; capabilities are derived by hardware scan and validated
/// loudly at declaration.
#[derive(Clone, Debug)]
pub struct DesignPort {
    pub name: String,
    /// Bit-0 connection cell.
    pub anchor: P3,
    /// Step from bit k to bit k+1.
    pub step: P3,
    /// Logical width in bits (Binary1PerWire in Phase 1: one wire per bit).
    pub width: u8,
    /// Semantic word type (bit order: position order, LSB first).
    pub ty: IoType,
    /// Signal direction as seen from the design.
    pub direction: PortDirection,
    /// Scanned hardware per bit, in bit order.
    pub bits: Vec<BitHardware>,
}

impl DesignPort {
    /// Connection cell of bit `k`.
    pub fn wire(&self, k: u8) -> P3 {
        add(self.anchor, scale(self.step, k as i32))
    }

    /// All connection cells in bit order.
    pub fn wires(&self) -> Vec<P3> {
        (0..self.width).map(|k| self.wire(k)).collect()
    }
}

/// Neighbour scan order of a connection cell (deterministic: the first dust
/// found in this order is the cell's tap).
const AROUND: [P3; 6] = [
    (1, 0, 0),
    (-1, 0, 0),
    (0, 0, 1),
    (0, 0, -1),
    (0, 1, 0),
    (0, -1, 0),
];

/// A routing endpoint contributed by a placed instance, named
/// `{instance}.{port}`.
///
/// Instance ports are DERIVED, never declared: the cell's contract port
/// transformed by the instance transform, plus the dust CONNECTION CELLS a
/// bus can actually land on. A cell contract stores *executor-facing*
/// hardware (levers/buttons for its inputs, lamps for its outputs) while a
/// bus terminates on *dust*, so each bit's connection cell is found by
/// hardware scan: the contract position itself when it already holds dust,
/// else the first dust neighbour in [`AROUND`] order.
///
/// A port with no dust tap on every bit is reported `blocked` rather than
/// silently mis-routed — a lever input, for instance, can only ever be
/// driven by the executor, never by a bus.
#[derive(Clone, Debug)]
pub struct InstancePort {
    /// `{instance}.{port}` — the name [`Design::route_bus`] accepts.
    pub name: String,
    pub instance: String,
    pub port: String,
    /// Direction as the CELL sees it: an `Output` drives the fabric, an
    /// `Input` receives from it (the design-facing direction is the flip,
    /// see [`Design::resolve_port`]).
    pub cell_direction: PortDirection,
    pub ty: IoType,
    pub width: u8,
    /// Executor-facing hardware in bit order, transformed.
    pub hardware: Vec<P3>,
    /// Dust connection cells in bit order, when every bit has one.
    pub wires: Option<Vec<P3>>,
    /// Step between consecutive connection cells, when uniform.
    pub step: Option<P3>,
    /// Why a bus cannot terminate here; `None` when it can.
    pub blocked: Option<String>,
}

impl InstancePort {
    /// A bus may terminate on this port.
    pub fn routable(&self) -> bool {
        self.blocked.is_none()
    }

    /// `{"name","instance","port","role","ty","width","hardware","wires",
    ///   "step","routable","blocked"}` — `role` is the CELL-facing
    /// direction (`"output"` drives a bus, `"input"` receives one).
    pub fn to_json(&self) -> String {
        let pos = |ps: &[P3]| {
            let items: Vec<String> = ps
                .iter()
                .map(|p| format!("[{},{},{}]", p.0, p.1, p.2))
                .collect();
            format!("[{}]", items.join(","))
        };
        format!(
            "{{\"name\":{:?},\"instance\":{:?},\"port\":{:?},\"role\":{:?},\"ty\":{},\
             \"width\":{},\"hardware\":{},\"wires\":{},\"step\":{},\"routable\":{},\
             \"blocked\":{}}}",
            self.name,
            self.instance,
            self.port,
            match self.cell_direction {
                PortDirection::Input => "input",
                PortDirection::Output => "output",
            },
            serde_json::to_string(&self.ty).unwrap_or_else(|_| "null".to_string()),
            self.width,
            pos(&self.hardware),
            self.wires.as_ref().map(|w| pos(w)).unwrap_or("null".into()),
            self.step
                .map(|s| format!("[{},{},{}]", s.0, s.1, s.2))
                .unwrap_or("null".into()),
            self.routable(),
            self.blocked
                .as_ref()
                .map(|b| format!("{b:?}"))
                .unwrap_or("null".into()),
        )
    }
}

/// Per-bus material style. The transparent block is used ONLY where a
/// diagonal must survive (the `materials.py` predicate model).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BusStyle {
    /// Solid conductor used for supports, separators and station blocks.
    pub bus_block: String,
    /// Non-conducting sturdy support for in-use diagonals (default glass).
    pub transparent_block: String,
}

impl Default for BusStyle {
    fn default() -> Self {
        BusStyle {
            bus_block: "minecraft:gray_concrete".to_string(),
            transparent_block: "minecraft:glass".to_string(),
        }
    }
}

impl BusStyle {
    /// Loud style validation: the bus block must be a sturdy conductor, the
    /// transparent block a sturdy NON-conductor (the dip's diode law and
    /// diagonal-survival both depend on it).
    pub fn validate(&self) -> Result<(), String> {
        if !rblocks::is_solid_block(&self.bus_block) {
            return Err(format!(
                "bus_block `{}` is not a solid conductor (stone/concrete/lamp family)",
                self.bus_block
            ));
        }
        if !rblocks::is_sturdy_support(&self.transparent_block)
            || rblocks::is_solid_block(&self.transparent_block)
        {
            return Err(format!(
                "transparent_block `{}` must be a sturdy non-conductor (glass family / top slab)",
                self.transparent_block
            ));
        }
        Ok(())
    }
}

/// How a narrower word is placed inside a wider one.
///
/// A width mismatch is a LAYOUT question, not an error: 3 BCD-hundreds bits
/// genuinely fit inside a 4-bit `bcd` input, and which 3 of the 4 they drive is
/// the only thing anyone has to decide.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum BusAlign {
    /// Bit 0 to bit 0 — the arithmetic default (a narrow value keeps its
    /// magnitude; the destination's high bits read 0).
    #[default]
    Lsb,
    /// Top bit to top bit: the source is shifted up by the width difference.
    /// This is a MULTIPLY BY 2^(ws-wd), not a reinterpretation — it is what you
    /// want when the two words are fixed-point fields, not integers.
    Msb,
    /// Place the source word `n` positions toward the MSB. Negative shifts
    /// down (and drops the bits that fall off, which needs `truncate`).
    Shift(i32),
}

/// The width-adaptation policy for one bus.
#[derive(Clone, Copy, Debug, Default)]
pub struct WidthAdapt {
    /// Where the source word sits in the destination.
    pub align: BusAlign,
    /// Permit DROPPING source bits that fall outside the destination.
    /// Refused by default: silently losing the high bits of a word is the kind
    /// of thing a router must make you ask for.
    pub truncate: bool,
}

impl WidthAdapt {
    /// LSB-aligned, no truncation — what [`Design::route_bus`] uses.
    pub fn lsb() -> Self {
        Self::default()
    }

    /// MSB-aligned.
    pub fn msb() -> Self {
        WidthAdapt {
            align: BusAlign::Msb,
            truncate: false,
        }
    }

    /// Shifted `n` toward the MSB.
    pub fn shift(n: i32) -> Self {
        WidthAdapt {
            align: BusAlign::Shift(n),
            truncate: false,
        }
    }

    /// The same policy, allowed to drop source bits.
    pub fn truncating(mut self) -> Self {
        self.truncate = true;
        self
    }
}

/// What a bus actually did about a width mismatch: the resolved bit mapping,
/// recorded so LVS pairs the right bits and a UI can show the wiring.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WidthMap {
    /// Driver word width.
    pub driver_width: u8,
    /// Sink word width.
    pub sink_width: u8,
    /// Positions the source is moved toward the MSB: driver bit `i` drives sink
    /// bit `i + shift`.
    pub shift: i32,
    /// First driver bit that is actually connected.
    pub from_bit: u8,
    /// How many bits are connected (the routed stack's width).
    pub bits: u8,
    /// Sink bits nothing drives. Undriven dust IS logical 0 — no hardware is
    /// needed to tie them, which is verified in
    /// `tests/design_width_adapt.rs::an_undriven_promoted_input_reads_zero`.
    pub tied_zero: Vec<u8>,
    /// Driver bits DROPPED (only ever non-empty with `truncate`).
    pub dropped: Vec<u8>,
}

impl WidthMap {
    /// Whether this is the trivial identity (equal widths, nothing to say).
    pub fn is_identity(&self) -> bool {
        self.driver_width == self.sink_width && self.shift == 0 && self.dropped.is_empty()
    }

    /// The sentence to show the user.
    pub fn note(&self, driver: &str, sink: &str) -> String {
        let mut s = format!(
            "{driver}[{}] -> {sink}[{}], {}",
            self.driver_width,
            self.sink_width,
            match self.shift {
                0 => "lsb-aligned".to_string(),
                n if n > 0 => format!("shifted {n} toward the msb"),
                n => format!("shifted {} toward the lsb", -n),
            }
        );
        if !self.tied_zero.is_empty() {
            s.push_str(&format!(
                "; sink bit(s) {} left undriven, which reads 0",
                ranges(&self.tied_zero)
            ));
        }
        if !self.dropped.is_empty() {
            s.push_str(&format!(
                "; driver bit(s) {} TRUNCATED away",
                ranges(&self.dropped)
            ));
        }
        s
    }

    /// `{"driver_width":n,"sink_width":n,"shift":n,"from_bit":n,"bits":n,
    ///   "tied_zero":[..],"dropped":[..],"pairs":[[dbit,sbit],..]}`
    pub fn to_json(&self) -> String {
        let list = |v: &[u8]| -> String {
            v.iter()
                .map(|b| b.to_string())
                .collect::<Vec<_>>()
                .join(",")
        };
        let pairs: Vec<String> = (0..self.bits)
            .map(|k| {
                let d = self.from_bit + k;
                format!("[{},{}]", d, d as i32 + self.shift)
            })
            .collect();
        format!(
            "{{\"driver_width\":{},\"sink_width\":{},\"shift\":{},\"from_bit\":{},\
             \"bits\":{},\"tied_zero\":[{}],\"dropped\":[{}],\"pairs\":[{}]}}",
            self.driver_width,
            self.sink_width,
            self.shift,
            self.from_bit,
            self.bits,
            list(&self.tied_zero),
            list(&self.dropped),
            pairs.join(",")
        )
    }
}

/// Whether two types differ ONLY in width, so a resolved width adaptation makes
/// them compatible. Two integer words of different widths are different
/// `IoType`s by construction, which is exactly the case adaptation exists for;
/// an int and a float, or an int and a string, are not.
fn same_type_family(a: &IoType, b: &IoType) -> bool {
    matches!(
        (a, b),
        (IoType::UnsignedInt { .. }, IoType::UnsignedInt { .. })
            | (IoType::SignedInt { .. }, IoType::SignedInt { .. })
            | (IoType::UnsignedInt { .. }, IoType::Boolean)
            | (IoType::Boolean, IoType::UnsignedInt { .. })
    )
}

/// `[0,1,2,5]` as `"0..2, 5"` — a bit list a human can read.
fn ranges(bits: &[u8]) -> String {
    let mut out: Vec<String> = Vec::new();
    let mut i = 0;
    while i < bits.len() {
        let start = bits[i];
        let mut end = start;
        while i + 1 < bits.len() && bits[i + 1] == end + 1 {
            i += 1;
            end = bits[i];
        }
        out.push(if start == end {
            format!("{start}")
        } else {
            format!("{start}..{end}")
        });
        i += 1;
    }
    out.join(", ")
}

/// Resolve a width mismatch into a bit mapping, or say why it cannot be.
fn plan_width_map(driver_width: u8, sink_width: u8, adapt: WidthAdapt) -> Result<WidthMap, String> {
    let (wd, ws) = (driver_width as i32, sink_width as i32);
    let shift = match adapt.align {
        BusAlign::Lsb => 0,
        BusAlign::Msb => ws - wd,
        BusAlign::Shift(n) => n,
    };
    // Driver bits whose destination exists.
    let from = 0.max(-shift);
    let to = wd.min(ws - shift);
    if to <= from {
        return Err(format!(
            "a {wd}-bit word shifted {shift} lands entirely outside a {ws}-bit destination, so              there is nothing to connect"
        ));
    }
    let dropped: Vec<u8> = (0..wd)
        .filter(|i| *i < from || *i >= to)
        .map(|i| i as u8)
        .collect();
    if !dropped.is_empty() && !adapt.truncate {
        return Err(format!(
            "connecting a {wd}-bit driver to a {ws}-bit sink shifted {shift} would drop bits {} of the driver word — losing the high bits silently is not something a router should decide, so pass truncate to accept it (or align/shift so it fits)",
            ranges(&dropped)
        ));
    }
    let tied_zero: Vec<u8> = (0..ws)
        .filter(|j| *j < from + shift || *j >= to + shift)
        .map(|j| j as u8)
        .collect();
    Ok(WidthMap {
        driver_width,
        sink_width,
        shift,
        from_bit: from as u8,
        bits: (to - from) as u8,
        tied_zero,
        dropped,
    })
}

/// Per-bus WEIGHTS over the cost vector. A scalar cost is how we ended up
/// benchmarking cell counts on straight runs and declaring victory while the
/// actual route gathered into a bar and fanned out eight lanes: identical
/// length, wildly different quality.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BusCost {
    /// Realized cells.
    pub length: f64,
    /// Worst-bit arrival, in redstone ticks.
    pub delay: f64,
    /// max-min arrival across bits. Matched skew is a real requirement, not a
    /// nicety, so it is its own term rather than folded into delay.
    pub skew: f64,
    /// BUNDLE DISPERSION: how far the N bits stray from travelling together in
    /// their canonical relative arrangement, plus form conversions. This is the
    /// term that catches "gather bar plus eight lanes" at equal length.
    pub coherence: f64,
    /// Occupied volume including clearance — how much of the workspace this
    /// route denies to everything else.
    pub footprint: f64,
}

impl Default for BusCost {
    /// Balanced: length still dominates, but coherence is heavy enough to
    /// reject a sprawling route that happens to tie on cells.
    fn default() -> Self {
        BusCost {
            length: 1.0,
            delay: 4.0,
            skew: 8.0,
            coherence: 6.0,
            footprint: 0.5,
        }
    }
}

impl BusCost {
    /// Minimise cells and volume; tolerate delay.
    pub fn compact() -> Self {
        BusCost {
            length: 2.0,
            delay: 1.0,
            skew: 4.0,
            coherence: 6.0,
            footprint: 2.0,
        }
    }

    /// Minimise arrival and skew; tolerate sprawl.
    pub fn fast() -> Self {
        BusCost {
            length: 0.5,
            delay: 16.0,
            skew: 24.0,
            coherence: 3.0,
            footprint: 0.25,
        }
    }

    /// Weighted total of a measured vector.
    pub fn total(&self, v: &BusCostVector) -> f64 {
        self.length * v.length as f64
            + self.delay * v.delay_rt as f64
            + self.skew * v.skew_rt as f64
            + self.coherence * v.coherence as f64
            + self.footprint * v.footprint as f64
    }
}

/// The MEASURED cost of a realized bus, reported as a vector so a human can see
/// WHY a route was chosen — and so no single dimension can be optimised in
/// isolation again.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BusCostVector {
    /// Realized cells.
    pub length: u32,
    /// Worst-bit arrival in redstone ticks.
    pub delay_rt: u32,
    /// max-min arrival across bits.
    pub skew_rt: u32,
    /// Bundle dispersion: summed cross-section area ABOVE the canonical form's,
    /// per slice along the route's principal axis, plus a fixed charge per form
    /// conversion. Zero means the bits travelled together the whole way in
    /// their canonical arrangement — a bus that reads as ONE object.
    pub coherence: u32,
    /// Occupied volume including a one-cell clearance shell.
    pub footprint: u32,
}

impl BusCostVector {
    /// `{"length":n,"delay_rt":n,"skew_rt":n,"coherence":n,"footprint":n}`
    pub fn to_json(&self) -> String {
        format!(
            "{{\"length\":{},\"delay_rt\":{},\"skew_rt\":{},\"coherence\":{},\"footprint\":{}}}",
            self.length, self.delay_rt, self.skew_rt, self.coherence, self.footprint
        )
    }
}

/// A bus-shaped waypoint splitting the bus into independently-routed
/// segments.
#[derive(Clone, Debug)]
pub struct Gate {
    pub name: String,
    /// Bit-0 cell of the gate column.
    pub anchor: P3,
    /// Step between bits (must match the bus form).
    pub step: P3,
}

/// Lifecycle state of a bus layer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BusState {
    /// Declared, not yet realized.
    Intended,
    /// Realized; the fragment is committed.
    Routed,
    /// Realization failed; the reason is user-facing. The workspace was
    /// left untouched (atomic realization).
    Failed(String),
}

/// One straight realized run of a bus (crossing detection input for buses
/// routed later).
#[derive(Clone, Debug)]
pub struct RunInfo {
    /// `true`: the run varies along X (fixed z). `false`: along Z (fixed x).
    pub along_x: bool,
    /// The fixed cross-axis coordinate.
    pub fixed: i32,
    /// Bit-0 canonical dust level.
    pub y0: i32,
    /// Start coordinate along the axis (the driver-side anchor).
    pub from: i32,
    /// End coordinate along the axis (the sink-side anchor).
    pub to: i32,
    /// Bus width.
    pub width: u8,
}

impl RunInfo {
    fn sign(&self) -> i32 {
        if self.to >= self.from {
            1
        } else {
            -1
        }
    }

    /// Whether `c` lies strictly between the run's anchors with `margin`
    /// cells of slack on each side.
    fn strictly_inside(&self, c: i32, margin: i32) -> bool {
        let (lo, hi) = if self.from <= self.to {
            (self.from, self.to)
        } else {
            (self.to, self.from)
        };
        c - lo >= margin && hi - c >= margin
    }
}

/// Which part of a bus a routed [`Segment`] realizes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SegmentKind {
    /// Trunk waypoint pair `i`: `waypoints[i] -> waypoints[i+1]` (driver,
    /// gates, primary sink).
    Trunk(usize),
    /// A branch tying the named extra endpoint (fanout sink, or wired-OR
    /// driver) into the trunk at a dust junction.
    Branch(String),
    /// A FORM ADAPTER for the named port: the row->stack pivot that lets a bus
    /// terminate on a port whose native geometry is a horizontal row.
    ///
    /// It belongs to the BUS, not to the component: promotion is minimal and
    /// in-place (the port keeps its native form), and the adapter is created
    /// and RIPPED with the bus. Owning it in a per-instance promotion patch —
    /// which is where it used to live — left it behind as orphaned geometry
    /// when the bus was ripped.
    Adapter(String),
}

/// One independently-routed piece of a bus: a trunk waypoint pair
/// (straight, or L-shaped through one implicit corner) or a branch.
/// Segments are the rip granularity of the drag APIs: `move_gate` rips
/// exactly the two segments adjacent to the gate.
#[derive(Clone, Debug)]
pub struct Segment {
    pub kind: SegmentKind,
    /// Bit-0 anchor the segment starts from.
    pub a: P3,
    /// Bit-0 anchor the segment ends at.
    pub b: P3,
    /// The straight runs realizing the segment (1, or 2 through a corner).
    pub runs: Vec<RunInfo>,
    /// Cells owned by the segment (subset of the bus fragment).
    pub cells: BTreeSet<P3>,
}

/// A bus layer: endpoints with roles, gates, style, state, and the OWNED
/// voxel fragment.
#[derive(Clone, Debug)]
pub struct BusLayer {
    pub name: String,
    /// Primary driver port name.
    pub driver: String,
    /// Additional drivers — legal only with `merge_or` (wired-OR), realized
    /// as dust-merge joins into the trunk; LVS intent stays ONE net.
    pub extra_drivers: Vec<String>,
    /// `true` when multiple drivers were explicitly declared as a wired-OR
    /// merge (`merge="or"`); multiple drivers without it are rejected.
    pub merge_or: bool,
    /// Sink port names.
    pub sinks: Vec<String>,
    pub gates: Vec<Gate>,
    pub style: BusStyle,
    pub state: BusState,
    /// The owned voxel fragment (block per cell), empty unless `Routed`.
    pub fragment: BTreeMap<P3, String>,
    /// The straight runs realized (crossing detection input; the union of
    /// every segment's runs).
    pub runs: Vec<RunInfo>,
    /// Per-segment realization (rip granularity for the drag APIs). Empty
    /// on documents loaded from formats predating segments — the drag APIs
    /// then fall back to a full reroute.
    pub segments: Vec<Segment>,
    /// The electrical joint columns of the gates, per gate name.
    pub gate_cells: BTreeMap<String, BTreeSet<P3>>,
    /// Optional net-class discipline enforced by [`Design::check`]
    /// (`max_len_rt` delay budget, `y_band` layer assignment).
    pub rule: Option<NetClassRule>,
    /// Ports this bus PROMOTED for itself on the way in, one human-readable
    /// note each (see [`Design::set_auto_promote`]). Non-empty means routing
    /// changed instance hardware, which the studio has to tell the user about —
    /// it is reversible, but it is not nothing.
    pub promotions: Vec<String>,
    /// The resolved bit mapping when the driver and sink widths DIFFER — see
    /// [`WidthMap`]. `None` means the widths matched and every bit pairs with
    /// its own index.
    pub width_map: Option<WidthMap>,
    /// Cost weights this bus is optimised against (compact / fast / balanced).
    pub cost: BusCost,
}

impl BusLayer {
    /// Every driver name, primary first.
    pub fn driver_names(&self) -> Vec<String> {
        let mut v = vec![self.driver.clone()];
        v.extend(self.extra_drivers.iter().cloned());
        v
    }
}

/// What occupies a cell in the design-wide spatial index.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Occupant {
    /// The loose block layer (the base schematic).
    Loose,
    /// An instance layer's transformed footprint.
    Instance(String),
    /// A routed bus's owned fragment.
    Bus(String),
}

/// The spatial occupancy index: hard cells (loose blocks, instance
/// footprints, routed bus fragments) plus instance influence halos
/// ([`crate::io_contract::PhysicalContract`] keepouts, or the cell bounds
/// grown by one where a cell declares none). Routing refuses halo cells;
/// the drag APIs use halos to compute the affected bus set.
#[derive(Clone, Debug, Default)]
pub struct OccupancyIndex {
    /// Hard cells: block state + owner.
    pub cells: BTreeMap<P3, (String, Occupant)>,
    /// Influence halo cells -> owning instance name (never hard-occupied).
    pub halos: BTreeMap<P3, String>,
    /// The subset of [`Self::halos`] that is only a PROXY for electrical
    /// interference: the default one-cell dilation a cell gets when its
    /// contract declares no explicit keepouts.
    ///
    /// A designer-declared keepout is intent and stays absolute. This set is
    /// not: it was a scalar stand-in for "something in here might interact
    /// with a bus", and the router now answers that question exactly, with
    /// [`nucleation_routing::transport::interferes`]. An inert stone flank
    /// emits nothing and reads nothing, so a bus may lay dust flush against
    /// it — which the blanket shell forbade, and which was the single largest
    /// exclusion bucket in `tests/design_routability.rs`.
    pub soft_halos: BTreeSet<P3>,
    /// PORT ESCAPE LANES: every vertical-stack port anchor in the design, as
    /// `(bit-0 cell, step, width)`.
    ///
    /// A port on the flank of a solid cell body has exactly ONE column it can
    /// leave along — the other three neighbours are the body itself. Routing
    /// one bus at a time, an early bus that runs down that column strands the
    /// port, and the bus that terminates there later fails with "every
    /// neighbouring column is occupied". That is not an occupancy problem (the
    /// cells really are taken) and no clearance predicate can recover it; it is
    /// an ORDERING problem, and the fix is to make the early bus pay for the
    /// lane so it prefers a detour while one exists. See
    /// [`crate::design_corridor::BusFabric::column_reserved`].
    ///
    /// Only vertical-stack ports (`step` along y) are listed: the corridor
    /// search models a bus as one column per bit-0 cell, so a horizontal ROW
    /// port's escape geometry is a different question this does not answer.
    pub port_lanes: Vec<(P3, P3, u8)>,
}

/// A [`crate::routing::transport::BlockView`] over placed geometry PLUS a bus
/// fragment, so the clearance predicates see the route being judged.
///
/// The fragment shadows the index: a route's own cells are what the mechanism
/// rules must reason about (its supports are the cut cells that sever a foreign
/// diagonal), and the occupancy index does not contain them until the bus is
/// committed.
struct FragmentView<'a> {
    occ: &'a OccupancyIndex,
    frag: &'a BTreeMap<P3, String>,
}

impl crate::routing::transport::BlockView for FragmentView<'_> {
    fn block_at(&self, p: crate::routing::Pos) -> Option<&str> {
        let k = (p.x, p.y, p.z);
        self.frag
            .get(&k)
            .map(|s| s.as_str())
            .or_else(|| self.occ.cells.get(&k).map(|(b, _)| b.as_str()))
    }
}

/// A [`FragmentView`] with one prospective dust/support pair overlaid. Run
/// planning asks about many candidate cells, so this avoids cloning the whole
/// fragment for every bit and offset merely to make the diagonal law see the
/// support that will be stamped with the dust.
struct PlannedDustView<'a> {
    occ: &'a OccupancyIndex,
    frag: &'a BTreeMap<P3, String>,
    dust: P3,
    support: P3,
    support_block: &'a str,
}

impl crate::routing::transport::BlockView for PlannedDustView<'_> {
    fn block_at(&self, p: crate::routing::Pos) -> Option<&str> {
        let k = (p.x, p.y, p.z);
        if k == self.dust {
            return Some(rblocks::DUST);
        }
        self.frag
            .get(&k)
            .map(|s| s.as_str())
            .or_else(|| (k == self.support).then_some(self.support_block))
            .or_else(|| self.occ.cells.get(&k).map(|(b, _)| b.as_str()))
    }
}

/// Can this mechanism carry or read a signal? An inert flank couples to
/// nothing, which is exactly why a bus may lay dust flush against a cell body.
fn is_live_mech(m: crate::routing::transport::Mechanism) -> bool {
    use crate::routing::transport::Mechanism as M;
    !matches!(m, M::SolidSupport | M::TransparentSupport | M::Inert)
}

/// Order-independent key for a short between two nets, so the same pair matches
/// whichever way the extractor happened to report it.
fn short_key(a: &str, b: &str) -> (String, String) {
    if a <= b {
        (a.to_string(), b.to_string())
    } else {
        (b.to_string(), a.to_string())
    }
}

/// Chebyshev distance in cells — the natural metric for "n cells of clearance".
fn chebyshev(a: P3, b: P3) -> i32 {
    (a.0 - b.0)
        .abs()
        .max((a.1 - b.1).abs())
        .max((a.2 - b.2).abs())
}

/// The cells whose contents could couple to `p`, out to `extra` cells of
/// additional declared separation.
///
/// At `extra = 0` this is the mechanism reach: the six faces, plus the eight
/// horizontal-with-1y-step offsets that dust's wire connection adds — the
/// DIAGONAL cases, which is where `X02`'s defect lived. Beyond that it is a
/// plain cube, because declared spacing is a distance demand rather than a
/// mechanism relation.
fn clearance_scan(p: P3, extra: i32) -> Vec<P3> {
    let mut out = Vec::new();
    if extra <= 0 {
        out.push((p.0, p.1 + 1, p.2));
        out.push((p.0, p.1 - 1, p.2));
        for (dx, dz) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
            for dy in [-1, 0, 1] {
                out.push((p.0 + dx, p.1 + dy, p.2 + dz));
            }
        }
        return out;
    }
    let r = extra + 1;
    for dx in -r..=r {
        for dy in -r..=r {
            for dz in -r..=r {
                if (dx, dy, dz) != (0, 0, 0) {
                    out.push((p.0 + dx, p.1 + dy, p.2 + dz));
                }
            }
        }
    }
    out
}

/// One cell a port-mode switch rewrote, with both sides of the change so a UI
/// can say exactly what happened ("removed lever at (19,5,5)").
#[derive(Clone, Debug)]
pub struct PortModeChange {
    /// World position (the instance transform already applied).
    pub at: P3,
    pub from: Option<String>,
    pub to: Option<String>,
}

/// Outcome of [`Design::set_port_mode`].
#[derive(Clone, Debug)]
pub struct PortModeReport {
    /// `{instance}.{port}`.
    pub port: String,
    /// The mode now in effect.
    pub mode: PortMode,
    /// Every cell the switch rewrote, in position order.
    pub changed: Vec<PortModeChange>,
    /// Buses deleted because they terminated on this port.
    pub removed_buses: Vec<String>,
    /// Reroute outcome for buses that merely crossed the changed space.
    pub moves: MoveReport,
    /// The reversible patch, as JSON.
    pub patch_json: String,
    /// One human sentence, ready for a toast.
    pub note: String,
}

impl PortModeReport {
    /// `{"port":..,"mode":..,"note":..,"changed":[{"at":[x,y,z],"from":..,
    ///   "to":..}],"removed_buses":[..],"moves":{..},"patch":{..}}`
    pub fn to_json(&self) -> String {
        let changed: Vec<String> = self
            .changed
            .iter()
            .map(|c| {
                format!(
                    "{{\"at\":[{},{},{}],\"from\":{},\"to\":{}}}",
                    c.at.0,
                    c.at.1,
                    c.at.2,
                    c.from
                        .as_ref()
                        .map(|s| format!("{s:?}"))
                        .unwrap_or("null".into()),
                    c.to.as_ref()
                        .map(|s| format!("{s:?}"))
                        .unwrap_or("null".into()),
                )
            })
            .collect();
        let removed: Vec<String> = self
            .removed_buses
            .iter()
            .map(|n| format!("{n:?}"))
            .collect();
        format!(
            "{{\"port\":{:?},\"mode\":{:?},\"note\":{:?},\"changed\":[{}],\
             \"removed_buses\":[{}],\"moves\":{},\"patch\":{}}}",
            self.port,
            self.mode.as_str(),
            self.note,
            changed.join(","),
            removed.join(","),
            self.moves.to_json(),
            self.patch_json,
        )
    }
}

/// Outcome of a drag ([`Design::move_instance`]): the move itself always
/// succeeds (the document's truth); buses fail VISIBLY, never half-routed.
#[derive(Clone, Debug, Default)]
pub struct MoveReport {
    /// Buses ripped and successfully co-rerouted, in name order.
    pub rerouted: Vec<String>,
    /// Buses left in `FAILED(reason)` after the bounded negotiation.
    pub failed: Vec<(String, String)>,
    /// EVERY bus layer whose realized geometry was rewritten, in name order —
    /// the studio's redraw set. See [`Design::changed_layers_since`] for the
    /// guarantee: it is a superset of `rerouted` + `failed`, because it also
    /// names buses amended INDIRECTLY (a crossing station stamped into a bus
    /// that was never ripped) and buses that were deleted.
    pub changed: Vec<String>,
}

impl MoveReport {
    /// JSON: `{"rerouted": [...], "failed": {name: reason}}`.
    pub fn to_json(&self) -> String {
        let r: Vec<String> = self.rerouted.iter().map(|n| format!("{n:?}")).collect();
        let f: Vec<String> = self
            .failed
            .iter()
            .map(|(n, why)| format!("{n:?}:{why:?}"))
            .collect();
        let c: Vec<String> = self.changed.iter().map(|n| format!("{n:?}")).collect();
        format!(
            "{{\"rerouted\":[{}],\"failed\":{{{}}},\"changed\":[{}]}}",
            r.join(","),
            f.join(","),
            c.join(",")
        )
    }
}

/// Outcome of [`Design::remove_instance`].
#[derive(Clone, Debug)]
pub struct RemoveReport {
    /// Buses deleted because they terminated on the removed instance.
    pub removed_buses: Vec<String>,
    /// Reroute outcome for the buses that merely crossed its space.
    pub moves: MoveReport,
}

impl RemoveReport {
    /// `{"removed_buses":[...],"rerouted":[...],"failed":{...}}`.
    pub fn to_json(&self) -> String {
        let removed: Vec<String> = self
            .removed_buses
            .iter()
            .map(|b| format!("{b:?}"))
            .collect();
        let moves = self.moves.to_json();
        format!(
            "{{\"removed_buses\":[{}],{}",
            removed.join(","),
            &moves[1..]
        )
    }
}

/// Outcome of [`Design::move_gate`].
#[derive(Clone, Debug)]
pub struct GateMoveReport {
    /// The bus state after the move.
    pub state: BusState,
    /// Segments ripped and rerouted (2 for a partial gate drag; the full
    /// segment count when the bus needed a whole-bus reroute).
    pub rerouted_segments: usize,
    /// Every bus layer whose geometry was rewritten — the dragged bus, plus
    /// any bus a crossing amendment touched. See
    /// [`Design::changed_layers_since`].
    pub changed: Vec<String>,
}

/// Outcome of [`Design::check`].
#[derive(Clone, Debug)]
pub struct DesignCheck {
    /// No DRC violations, no LVS opens/shorts/cycles.
    pub clean: bool,
    /// Full JSON report: `{"clean", "drc": [...], "lvs": {...}}`.
    pub json: String,
}

/// The composition document. See module docs.
#[derive(Clone, Debug)]
pub struct Design {
    name: String,
    base: UniversalSchematic,
    cells: BTreeMap<String, CellDef>,
    instances: Vec<Instance>,
    ports: BTreeMap<String, DesignPort>,
    buses: BTreeMap<String, BusLayer>,
    auto_promote: bool,
    /// GEOMETRY REVISION per bus layer — see [`Design::changed_layers_since`].
    /// Runtime-only (never serialized): a reloaded document starts every layer
    /// at revision 1, which is correct, because a fresh reader has drawn
    /// nothing yet.
    bus_revs: BTreeMap<String, u64>,
    /// Monotonic clock stamped into `bus_revs`.
    rev_clock: u64,
}

impl Design {
    /// An empty design.
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        Design {
            base: UniversalSchematic::new(name.clone()),
            name,
            cells: BTreeMap::new(),
            instances: Vec::new(),
            ports: BTreeMap::new(),
            buses: BTreeMap::new(),
            auto_promote: true,
            bus_revs: BTreeMap::new(),
            rev_clock: 0,
        }
    }

    // ------------------------------------------------------------------
    // The CHANGED-LAYER CONTRACT
    // ------------------------------------------------------------------

    /// The current geometry revision. Read it BEFORE a mutating call, pass it
    /// to [`Design::changed_layers_since`] after, and redraw exactly the
    /// layers it names.
    pub fn layer_revision(&self) -> u64 {
        self.rev_clock
    }

    /// Bus layers whose realized geometry may have been REWRITTEN since
    /// revision `rev`, in name order. This is the studio's redraw set, and it
    /// is **complete by construction**: the revision is stamped at every
    /// single write to a layer's fragment, so no operation can change a layer
    /// without naming it. Specifically it includes
    ///
    /// - the bus an operation was aimed at, whether it ended `Routed` or
    ///   `FAILED` (both directions of the transition are stamped);
    /// - every bus RIPPED and co-rerouted because a moved instance's
    ///   footprint, influence halo, or PORTS touched it;
    /// - every bus amended INDIRECTLY — a crossing stamps a through-bus
    ///   station into a bus that was never ripped and is not otherwise named
    ///   in any report. Missing these is the classic "I moved a component and
    ///   the bus didn't update" stale-mesh bug;
    /// - every bus DELETED (a layer named here that [`Design::bus`] no longer
    ///   knows is a removal: drop the mesh).
    ///
    /// It may over-report: a bus ripped and re-routed to byte-identical
    /// geometry is still named. Redrawing it is wasted work, never a wrong
    /// picture, and `tests/design_reroute_stress.rs` pins the guarantee by
    /// comparing this set against a block-by-block diff.
    pub fn changed_layers_since(&self, rev: u64) -> Vec<String> {
        self.bus_revs
            .iter()
            .filter(|(_, r)| **r > rev)
            .map(|(n, _)| n.clone())
            .collect()
    }

    /// Stamp a layer as rewritten. Called from EVERY write to a bus
    /// fragment — including the indirect ones (crossing amendments) — so
    /// [`Design::changed_layers_since`] cannot under-report.
    fn touch_bus(&mut self, name: &str) {
        self.rev_clock += 1;
        self.bus_revs.insert(name.to_string(), self.rev_clock);
    }

    /// Every bus layer's realized geometry — the independent oracle the
    /// changed-layer contract is tested against (and a cheap way for a caller
    /// that would rather diff than track revisions).
    pub fn bus_geometry(&self) -> BTreeMap<String, BTreeMap<P3, String>> {
        self.buses
            .iter()
            .map(|(n, b)| (n.clone(), b.fragment.clone()))
            .collect()
    }

    /// Bus layers whose blocks actually differ from a [`Design::bus_geometry`]
    /// snapshot, in name order — appearances and removals included.
    pub fn layers_differing_from(
        &self,
        before: &BTreeMap<String, BTreeMap<P3, String>>,
    ) -> Vec<String> {
        let now = self.bus_geometry();
        let mut out: BTreeSet<String> = BTreeSet::new();
        for (n, frag) in &now {
            if before.get(n) != Some(frag) {
                out.insert(n.clone());
            }
        }
        for n in before.keys() {
            if !now.contains_key(n) {
                out.insert(n.clone());
            }
        }
        out.into_iter().collect()
    }

    /// A design whose loose block layer is `base` (endpoint hardware placed
    /// with raw `set_block`, the `design_step1.py` workflow).
    pub fn for_schematic(name: impl Into<String>, base: UniversalSchematic) -> Self {
        let mut d = Design::new(name);
        d.base = base;
        d
    }

    /// Does [`Design::route_bus`] promote executor-only endpoints by itself?
    /// On by default.
    pub fn auto_promote(&self) -> bool {
        self.auto_promote
    }

    /// Turn automatic promotion off (or back on).
    ///
    /// With it ON — the default — routing to a community cell's LEVER input
    /// just works: `route_bus` switches the port to [`PortMode::Bus`] first and
    /// records what it did. With it OFF, such a bus is refused with the
    /// instruction to promote explicitly, which is what a UI wants when the
    /// user must confirm a hardware change before it happens.
    pub fn set_auto_promote(&mut self, on: bool) {
        self.auto_promote = on;
    }

    /// The design name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The loose block layer.
    pub fn base(&self) -> &UniversalSchematic {
        &self.base
    }

    /// A declared port.
    pub fn port(&self, name: &str) -> Option<&DesignPort> {
        self.ports.get(name)
    }

    /// A bus layer.
    pub fn bus(&self, name: &str) -> Option<&BusLayer> {
        self.buses.get(name)
    }

    /// The resolved bit mapping of a width-adapted bus, as JSON, plus the
    /// sentence to show the user — `null` when the widths matched.
    ///
    /// `{"map":{...},"note":"u1.bcd_hundreds[3] -> u3.bcd[4], msb-aligned; sink
    /// bit(s) 0 left undriven, which reads 0"}`
    pub fn bus_width_map_json(&self, name: &str) -> Result<String, String> {
        let bus = self
            .buses
            .get(name)
            .ok_or_else(|| format!("unknown bus `{name}`"))?;
        Ok(match &bus.width_map {
            None => "null".to_string(),
            Some(m) => format!(
                "{{\"map\":{},\"note\":{:?}}}",
                m.to_json(),
                m.note(
                    &bus.driver,
                    bus.sinks.first().map(String::as_str).unwrap_or("?")
                )
            ),
        })
    }

    /// The state of a bus layer.
    pub fn bus_state(&self, name: &str) -> Option<&BusState> {
        self.buses.get(name).map(|b| &b.state)
    }

    // ------------------------------------------------------------------
    // Cells + instances
    // ------------------------------------------------------------------

    /// Register a cell in the design's library. The contract is resolved
    /// from the schematic itself (embedded metadata first, Insign signs as
    /// fallback); registration fails loudly when no source defines one.
    /// Returns resolution warnings (source conflicts).
    pub fn add_cell(
        &mut self,
        name: impl Into<String>,
        schematic: UniversalSchematic,
    ) -> Result<Vec<String>, String> {
        let name = name.into();
        let (contract, warnings) = schematic
            .resolve_cell_contract()?
            .ok_or_else(|| format!("cell `{name}`: no contract (embedded metadata or Insign)"))?;
        self.cells.insert(
            name,
            CellDef {
                schematic,
                contract,
            },
        );
        Ok(warnings)
    }

    /// Register a cell with an explicitly provided contract (the explicit
    /// API wins over every embedded source).
    pub fn add_cell_with_contract(
        &mut self,
        name: impl Into<String>,
        schematic: UniversalSchematic,
        contract: CellContract,
    ) {
        self.cells.insert(
            name.into(),
            CellDef {
                schematic,
                contract,
            },
        );
    }

    /// Place an instance layer referencing a library cell. `rot_y` is in
    /// degrees, a multiple of 90, applied about the cell's min corner
    /// before translating to `at`. Two instances may reference one cell.
    pub fn place(
        &mut self,
        name: impl Into<String>,
        cell: &str,
        at: P3,
        rot_y: i32,
    ) -> Result<(), String> {
        let name = name.into();
        if !self.cells.contains_key(cell) {
            return Err(format!("unknown cell `{cell}`"));
        }
        if rot_y.rem_euclid(90) != 0 {
            return Err(format!("rot_y must be a multiple of 90, got {rot_y}"));
        }
        if self.instances.iter().any(|i| i.name == name) {
            return Err(format!("instance `{name}` already exists"));
        }
        self.instances.push(Instance {
            name,
            cell: cell.to_string(),
            at,
            rot_y: rot_y.rem_euclid(360),
            port_modes: BTreeMap::new(),
        });
        Ok(())
    }

    // ------------------------------------------------------------------
    // Port modes (promotion): executor hardware <-> routable dust
    // ------------------------------------------------------------------

    /// The mode a port currently presents in ([`PortMode::Executor`] unless it
    /// has been switched).
    pub fn port_mode(&self, instance: &str, port: &str) -> PortMode {
        self.instances
            .iter()
            .find(|i| i.name == instance)
            .and_then(|i| i.port_modes.get(port))
            .map(|o| o.mode)
            .unwrap_or(PortMode::Executor)
    }

    /// Switch a port between executor hardware and a routable dust input.
    ///
    /// This is the composability switch: community cells name LEVERS for their
    /// inputs, and nothing in redstone drives a lever, so `add.sum -> bcd.bin`
    /// is impossible until `bin` is in [`PortMode::Bus`]. The conversion is a
    /// reversible per-instance patch (see [`crate::design_promote`]) — the cell
    /// library is untouched, so switching back restores the original blocks
    /// byte-exactly.
    ///
    /// Buses attached to the port are RIPPED (their endpoint physically stops
    /// existing) and named in the report; every other affected bus is
    /// co-rerouted exactly as for a drag, so a toggle never leaves stale
    /// geometry.
    pub fn set_port_mode(
        &mut self,
        instance: &str,
        port: &str,
        mode: PortMode,
    ) -> Result<PortModeReport, String> {
        let idx = self
            .instances
            .iter()
            .position(|i| i.name == instance)
            .ok_or_else(|| format!("unknown instance `{instance}`"))?;
        if self.port_mode(instance, port) == mode {
            return Ok(PortModeReport {
                port: format!("{instance}.{port}"),
                mode,
                changed: Vec::new(),
                removed_buses: Vec::new(),
                moves: MoveReport::default(),
                patch_json: self.instances[idx]
                    .port_modes
                    .get(port)
                    .map(|o| o.patch.to_json())
                    .unwrap_or_else(|| "null".to_string()),
                note: format!("`{instance}.{port}` is already in {} mode", mode.as_str()),
            });
        }
        let rev0 = self.layer_revision();
        // Plan the patch once and remember it, so toggling is symmetric.
        if !self.instances[idx].port_modes.contains_key(port) {
            let patch = self.plan_port_patch(instance, port)?;
            self.instances[idx].port_modes.insert(
                port.to_string(),
                PortOverride {
                    mode: PortMode::Executor,
                    patch,
                },
            );
        }
        // Buses that terminate on this port lose their endpoint geometry.
        let full = format!("{instance}.{port}");
        let doomed: Vec<String> = self
            .buses
            .values()
            .filter(|b| {
                b.driver_names()
                    .iter()
                    .chain(b.sinks.iter())
                    .any(|p| *p == full)
            })
            .map(|b| b.name.clone())
            .collect();
        for b in &doomed {
            self.touch_bus(b);
            self.buses.remove(b);
        }
        // Everything that touched the instance's space is re-attempted.
        let old_region = self.instance_region(idx);
        self.instances[idx]
            .port_modes
            .get_mut(port)
            .expect("just inserted")
            .mode = mode;
        let new_region = self.instance_region(idx);
        let mut affected: BTreeSet<String> = BTreeSet::new();
        for bus in self.buses.values() {
            match &bus.state {
                BusState::Routed
                    if bus
                        .fragment
                        .keys()
                        .any(|p| old_region.contains(p) || new_region.contains(p)) =>
                {
                    affected.insert(bus.name.clone());
                }
                BusState::Failed(_) => {
                    affected.insert(bus.name.clone());
                }
                _ => {}
            }
        }
        let moves = self.co_reroute(affected, rev0);
        let over = self.instances[idx].port_modes[port].clone();
        let inst = &self.instances[idx];
        let cell = &self.cells[&inst.cell];
        let bbox = cell_bounds(&cell.schematic);
        let map = |p: P3| transform_pos(p, bbox.min, bbox.max, inst.rot_y, inst.at);
        let mut changed = Vec::new();
        for (p, want) in &over.patch.writes {
            let before = over.patch.saved.get(p).and_then(|o| o.clone());
            let (from, to) = match mode {
                PortMode::Bus => (before, want.clone()),
                PortMode::Executor => (want.clone(), before),
            };
            changed.push(PortModeChange {
                at: map(*p),
                from,
                to,
            });
        }
        let note = match mode {
            PortMode::Bus => format!(
                "`{full}` is now a BUS input: {} — bit 0 lands on dust at {:?}",
                over.patch.note,
                over.patch
                    .wires
                    .first()
                    .map(|w| map(*w))
                    .unwrap_or((0, 0, 0))
            ),
            PortMode::Executor => format!(
                "`{full}` is back to EXECUTOR hardware: {} cell(s) restored exactly as shipped",
                over.patch.writes.len()
            ),
        };
        Ok(PortModeReport {
            port: full,
            mode,
            changed,
            removed_buses: doomed,
            moves,
            patch_json: over.patch.to_json(),
            note,
        })
    }

    /// Promote `endpoint` if — and only if — that is what stands between it and
    /// terminating a bus. Returns the note to report, or `None` to leave the
    /// endpoint (and its own error message) exactly as it was.
    ///
    /// Deliberately conservative: it promotes ONLY when the port does not
    /// currently resolve, is still in [`PortMode::Executor`], and promoting
    /// actually makes it resolve. Anything else — a width mismatch, an unknown
    /// port, a ceiling lever that cannot be promoted at all — is left for the
    /// caller's own error path, so auto-promotion can never mask a different
    /// problem or half-apply a patch. A promotion that does not help is rolled
    /// back to `Executor`.
    fn auto_promote_endpoint(&mut self, endpoint: &str) -> Option<String> {
        if self.resolve_port(endpoint).is_ok() {
            return None;
        }
        let (inst, port) = endpoint.split_once('.')?;
        if self.port_mode(inst, port) != PortMode::Executor {
            return None;
        }
        let (inst, port) = (inst.to_string(), port.to_string());
        // Refuse to touch anything unless the patch plans cleanly first.
        self.plan_port_patch(&inst, &port).ok()?;
        let report = self.set_port_mode(&inst, &port, PortMode::Bus).ok()?;
        if self.resolve_port(endpoint).is_err() {
            // Promotion was not the blocker. Put the hardware back.
            let _ = self.set_port_mode(&inst, &port, PortMode::Executor);
            return None;
        }
        Some(format!("auto-promoted `{endpoint}`: {}", report.note))
    }

    /// [`Design::set_port_mode`] to [`PortMode::Bus`] — the "promote this
    /// lever input to something a bus can land on" verb.
    pub fn promote_input(&mut self, instance: &str, port: &str) -> Result<PortModeReport, String> {
        self.set_port_mode(instance, port, PortMode::Bus)
    }

    /// [`Design::set_port_mode`] to [`PortMode::Bus`] for an OUTPUT port: a
    /// dust tap on its lamps, so a bus can pick the value up. The lamps stay,
    /// so the port remains readable through the typed executor too.
    pub fn promote_output(&mut self, instance: &str, port: &str) -> Result<PortModeReport, String> {
        self.set_port_mode(instance, port, PortMode::Bus)
    }

    /// Plan (but do not apply) the Bus-mode patch for a port. Useful for a UI
    /// that wants to describe the change before the user commits to it.
    pub fn plan_port_patch(
        &self,
        instance: &str,
        port: &str,
    ) -> Result<crate::design_promote::PortPatch, String> {
        let inst = self
            .instances
            .iter()
            .find(|i| i.name == instance)
            .ok_or_else(|| format!("unknown instance `{instance}`"))?;
        let cell = &self.cells[&inst.cell];
        let (dirn, mapping) = if let Some(m) = cell.contract.io.inputs.get(port) {
            (PortDirection::Input, m)
        } else if let Some(m) = cell.contract.io.outputs.get(port) {
            (PortDirection::Output, m)
        } else {
            let have: Vec<&str> = cell
                .contract
                .io
                .inputs
                .keys()
                .chain(cell.contract.io.outputs.keys())
                .map(String::as_str)
                .collect();
            return Err(format!(
                "instance `{instance}` (cell `{}`) has no port `{port}` (has: {})",
                inst.cell,
                have.join(", ")
            ));
        };
        match dirn {
            PortDirection::Input => {
                crate::design_promote::plan_input(&cell.schematic, &mapping.positions)
            }
            PortDirection::Output => {
                crate::design_promote::plan_output(&cell.schematic, &mapping.positions)
            }
        }
        .map_err(|e| format!("cannot promote `{instance}.{port}`: {e}"))
    }

    /// Every port's mode as JSON, for a UI:
    /// `[{"name":"u0.bin","mode":"bus","patch":{..}}, ..]`
    pub fn port_modes_json(&self) -> String {
        let mut items = Vec::new();
        for inst in &self.instances {
            for (port, over) in &inst.port_modes {
                items.push(format!(
                    "{{\"name\":{:?},\"mode\":{:?},\"patch\":{}}}",
                    format!("{}.{}", inst.name, port),
                    over.mode.as_str(),
                    over.patch.to_json()
                ));
            }
        }
        format!("[{}]", items.join(","))
    }

    /// Bus-mode patches in effect for an instance.
    fn active_patches<'a>(&self, inst: &'a Instance) -> Vec<&'a crate::design_promote::PortPatch> {
        inst.port_modes
            .values()
            .filter(|o| o.mode == PortMode::Bus)
            .map(|o| &o.patch)
            .collect()
    }

    /// The CELL-LOCAL blocks an instance contributes, with its Bus-mode port
    /// patches applied. This is the one place that knows a placed cell is the
    /// library body PLUS its promotions — every occupancy, flatten and scan
    /// path goes through it, so a promoted lever can never be half-visible.
    fn instance_local_blocks(&self, inst: &Instance) -> Vec<(P3, crate::BlockState)> {
        let cell = &self.cells[&inst.cell];
        let patches = self.active_patches(inst);
        if patches.is_empty() {
            return cell
                .schematic
                .iter_blocks()
                .map(|(bp, bs)| ((bp.x, bp.y, bp.z), bs.clone()))
                .collect();
        }
        let mut overlay: BTreeMap<P3, Option<String>> = BTreeMap::new();
        for pa in &patches {
            for (p, b) in &pa.writes {
                overlay.insert(*p, b.clone());
            }
        }
        let mut out = Vec::new();
        for (bp, bs) in cell.schematic.iter_blocks() {
            let p = (bp.x, bp.y, bp.z);
            match overlay.remove(&p) {
                Some(Some(b)) => {
                    if let Ok(st) = crate::BlockState::from_block_string(&b) {
                        out.push((p, st));
                    }
                }
                Some(None) => {}
                None => out.push((p, bs.clone())),
            }
        }
        for (p, b) in overlay {
            if let Some(b) = b {
                if let Ok(st) = crate::BlockState::from_block_string(&b) {
                    out.push((p, st));
                }
            }
        }
        out
    }

    /// The transformed contract an instance exposes: port cells and step
    /// vectors mapped through the instance transform; types, delays and
    /// bit order unchanged.
    pub fn instance_contract(&self, name: &str) -> Result<CellContract, String> {
        let inst = self
            .instances
            .iter()
            .find(|i| i.name == name)
            .ok_or_else(|| format!("unknown instance `{name}`"))?;
        let cell = &self.cells[&inst.cell];
        let bbox = cell_bounds(&cell.schematic);
        let mut contract = cell.contract.clone();
        // A port in Bus mode presents its promoted CONNECTION CELLS, not the
        // executor hardware it replaced.
        for (port, over) in &inst.port_modes {
            if over.mode != PortMode::Bus {
                continue;
            }
            if let Some(m) = contract.io.inputs.get_mut(port) {
                m.positions = over.patch.wires.clone();
            } else if let Some(m) = contract.io.outputs.get_mut(port) {
                m.positions = over.patch.wires.clone();
            }
        }
        let map = |p: P3| transform_pos(p, bbox.min, bbox.max, inst.rot_y, inst.at);
        for mapping in contract
            .io
            .inputs
            .values_mut()
            .chain(contract.io.outputs.values_mut())
        {
            for p in mapping.positions.iter_mut() {
                *p = map(*p);
            }
        }
        for bus in contract.io.buses.values_mut() {
            bus.bit0 = map(bus.bit0);
        }
        for keepout in contract.physical.keepouts.iter_mut() {
            let a = map(keepout.min);
            let b = map(keepout.max);
            keepout.min = (a.0.min(b.0), a.1.min(b.1), a.2.min(b.2));
            keepout.max = (a.0.max(b.0), a.1.max(b.1), a.2.max(b.2));
        }
        Ok(contract)
    }

    /// Remove an instance layer. Buses that terminate on one of its ports
    /// lose their endpoint and are DELETED (named in the report); buses that
    /// merely ran through its footprint or halo are ripped and co-rerouted,
    /// as for a drag.
    pub fn remove_instance(&mut self, name: &str) -> Result<RemoveReport, String> {
        let idx = self
            .instances
            .iter()
            .position(|i| i.name == name)
            .ok_or_else(|| format!("unknown instance `{name}`"))?;
        let rev0 = self.layer_revision();
        let region = self.instance_region(idx);
        let prefix = format!("{name}.");

        // Buses whose declaration names a port of this instance cannot
        // survive it.
        let doomed: Vec<String> = self
            .buses
            .values()
            .filter(|b| {
                b.driver_names()
                    .iter()
                    .chain(b.sinks.iter())
                    .any(|p| p.starts_with(&prefix))
            })
            .map(|b| b.name.clone())
            .collect();
        // Buses to re-attempt: anything that touched the vacated space, plus
        // every already-FAILED bus (the removal may have unblocked it).
        let mut affected: BTreeSet<String> = BTreeSet::new();
        for bus in self.buses.values() {
            if doomed.contains(&bus.name) {
                continue;
            }
            match &bus.state {
                BusState::Routed if bus.fragment.keys().any(|p| region.contains(p)) => {
                    affected.insert(bus.name.clone());
                }
                BusState::Failed(_) => {
                    affected.insert(bus.name.clone());
                }
                _ => {}
            }
        }
        for b in &doomed {
            self.touch_bus(b);
            self.buses.remove(b);
        }
        self.instances.remove(idx);
        let moves = self.co_reroute(affected, rev0);
        Ok(RemoveReport {
            removed_buses: doomed,
            moves,
        })
    }

    // ------------------------------------------------------------------
    // Instance ports (derived routing endpoints)
    // ------------------------------------------------------------------

    /// Every routing endpoint the placed instances expose, in
    /// `{instance}.{port}` name order. Ports that cannot terminate a bus
    /// are included with `blocked` set, so a UI can list them and say why.
    pub fn instance_ports(&self) -> Result<Vec<InstancePort>, String> {
        let overlay = self.instance_blocks();
        let mut out = Vec::new();
        let names: Vec<String> = self.instances.iter().map(|i| i.name.clone()).collect();
        for inst in &names {
            let contract = self.instance_contract(inst)?;
            for (dirn, mappings) in [
                (PortDirection::Input, &contract.io.inputs),
                (PortDirection::Output, &contract.io.outputs),
            ] {
                for (pname, mapping) in mappings {
                    out.push(self.derive_instance_port(
                        inst,
                        pname,
                        dirn,
                        mapping.io_type.clone(),
                        mapping.positions.clone(),
                        &overlay,
                    ));
                }
            }
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(out)
    }

    /// [`Design::instance_ports`] as a JSON array.
    pub fn instance_ports_json(&self) -> Result<String, String> {
        let items: Vec<String> = self.instance_ports()?.iter().map(|p| p.to_json()).collect();
        Ok(format!("[{}]", items.join(",")))
    }

    fn derive_instance_port(
        &self,
        instance: &str,
        port: &str,
        cell_direction: PortDirection,
        ty: IoType,
        hardware: Vec<P3>,
        overlay: &BTreeMap<P3, String>,
    ) -> InstancePort {
        let name = format!("{instance}.{port}");
        let width = hardware.len().min(u8::MAX as usize) as u8;
        let mut wires = Vec::with_capacity(hardware.len());
        let mut blocked = None;
        let mut step = None;
        for (k, hp) in hardware.iter().enumerate() {
            match self.dust_tap(*hp, overlay) {
                Some(w) => wires.push(w),
                None => {
                    // Actionable, because there IS an action: this is exactly
                    // what `set_port_mode(.., PortMode::Bus)` exists for.
                    blocked = Some(format!(
                        "bit {k}: no dust connection cell at or beside {:?} (holds `{}`) — this \
                         port is executor-only hardware and cannot terminate a bus. PROMOTE it \
                         (switch the port to Bus mode) to swap the hardware for a dust input; the \
                         switch is reversible",
                        hp,
                        self.block_at(*hp, overlay)
                            .unwrap_or_else(|| "air".to_string())
                    ));
                    break;
                }
            }
        }
        if blocked.is_none() {
            if wires.is_empty() {
                blocked = Some("port declares no positions".to_string());
            } else if wires.len() == 1 {
                // A 1-bit port has no measurable pitch: adopt the canonical
                // vertical bus form so bools are routable.
                step = Some((0, 2, 0));
            } else {
                let s = (
                    wires[1].0 - wires[0].0,
                    wires[1].1 - wires[0].1,
                    wires[1].2 - wires[0].2,
                );
                if s == (0, 0, 0) {
                    blocked = Some("connection cells collapse onto one cell".to_string());
                } else if !wires
                    .windows(2)
                    .all(|w| (w[1].0 - w[0].0, w[1].1 - w[0].1, w[1].2 - w[0].2) == s)
                {
                    blocked = Some(format!(
                        "connection cells {wires:?} do not lie on a uniform step"
                    ));
                } else {
                    step = Some(s);
                }
            }
        }
        InstancePort {
            name,
            instance: instance.to_string(),
            port: port.to_string(),
            cell_direction,
            ty,
            width,
            hardware,
            wires: blocked.is_none().then_some(wires),
            step,
            blocked,
        }
    }

    /// Resolve a routing endpoint name: a declared design port, or an
    /// instance port `{instance}.{port}` derived from the instance's
    /// transformed contract.
    ///
    /// The returned [`DesignPort::direction`] is DESIGN-facing — which way
    /// signal flows in the fabric — so a cell OUTPUT resolves to
    /// `PortDirection::Input` (it drives buses) and a cell INPUT resolves to
    /// `PortDirection::Output` (it receives them).
    pub fn resolve_port(&self, name: &str) -> Result<DesignPort, String> {
        if let Some(p) = self.ports.get(name) {
            return Ok(p.clone());
        }
        let Some((inst, port)) = name.split_once('.') else {
            return Err(format!("unknown port `{name}`"));
        };
        if !self.instances.iter().any(|i| i.name == inst) {
            return Err(format!(
                "unknown port `{name}`: nothing declared under that name and no instance `{inst}`"
            ));
        }
        let ports = self.instance_ports()?;
        let ip = ports.iter().find(|p| p.name == name).ok_or_else(|| {
            let have: Vec<&str> = ports
                .iter()
                .filter(|p| p.instance == inst)
                .map(|p| p.port.as_str())
                .collect();
            format!(
                "instance `{inst}` has no contract port `{port}` (has: {})",
                have.join(", ")
            )
        })?;
        if let Some(why) = &ip.blocked {
            return Err(format!(
                "instance port `{name}` cannot terminate a bus: {why}"
            ));
        }
        let wires = ip.wires.clone().expect("a routable port has wires");
        let overlay = self.instance_blocks();
        let bits = wires
            .iter()
            .map(|w| self.scan_bit_with(*w, &overlay))
            .collect();
        Ok(DesignPort {
            name: name.to_string(),
            anchor: wires[0],
            step: ip.step.expect("a routable port has a step"),
            width: ip.width,
            ty: ip.ty.clone(),
            direction: match ip.cell_direction {
                PortDirection::Output => PortDirection::Input,
                PortDirection::Input => PortDirection::Output,
            },
            bits,
        })
    }

    // ------------------------------------------------------------------
    // Ports
    // ------------------------------------------------------------------

    /// Declare a typed port over existing hardware: anchor = bit-0
    /// connection cell, `step` to the next bit, `width` bits of `ty`.
    /// The hardware is scanned (lever ⇒ drivable, lamp ⇒ readable, dust ⇒
    /// connectable) and validated loudly: every connection cell must hold
    /// dust; a declared input must be drivable on every bit; a declared
    /// output readable on every bit.
    pub fn declare_port(
        &mut self,
        name: impl Into<String>,
        anchor: P3,
        step: P3,
        width: u8,
        ty: IoType,
        direction: PortDirection,
    ) -> Result<&DesignPort, String> {
        let name = name.into();
        if self.ports.contains_key(&name) {
            return Err(format!("port `{name}` already declared"));
        }
        if width == 0 {
            return Err(format!("port `{name}`: width must be at least 1"));
        }
        if step == (0, 0, 0) {
            return Err(format!("port `{name}`: step must be non-zero"));
        }
        if ty.bit_count() != width as usize {
            return Err(format!(
                "port `{name}`: width {} does not match type bit count {}",
                width,
                ty.bit_count()
            ));
        }
        // Instance bodies count as hardware: a design port may be declared
        // over a placed cell's dust, not only over loose blocks.
        let overlay = self.instance_blocks();
        let mut bits = Vec::with_capacity(width as usize);
        for k in 0..width {
            let cell = add(anchor, scale(step, k as i32));
            let hw = self.scan_bit_with(cell, &overlay);
            if !hw.connectable {
                return Err(format!(
                    "port `{name}` bit {k}: connection cell {:?} holds `{}`, not dust",
                    cell,
                    self.block_at(cell, &overlay).unwrap_or_default()
                ));
            }
            match direction {
                PortDirection::Input if hw.lever.is_none() => {
                    return Err(format!(
                        "port `{name}` bit {k}: declared input but no adjacent lever at {cell:?} \
                         (not drivable)"
                    ));
                }
                PortDirection::Output if hw.lamp.is_none() => {
                    return Err(format!(
                        "port `{name}` bit {k}: declared output but no adjacent lamp at {cell:?} \
                         (not readable)"
                    ));
                }
                _ => {}
            }
            bits.push(hw);
        }
        let port = DesignPort {
            name: name.clone(),
            anchor,
            step,
            width,
            ty,
            direction,
            bits,
        };
        self.ports.insert(name.clone(), port);
        Ok(&self.ports[&name])
    }

    /// Sugar: declare a drivable input port (asserts lever capability).
    pub fn declare_input(
        &mut self,
        name: impl Into<String>,
        anchor: P3,
        step: P3,
        width: u8,
        ty: IoType,
    ) -> Result<&DesignPort, String> {
        self.declare_port(name, anchor, step, width, ty, PortDirection::Input)
    }

    /// Sugar: declare a readable output port (asserts lamp capability).
    pub fn declare_output(
        &mut self,
        name: impl Into<String>,
        anchor: P3,
        step: P3,
        width: u8,
        ty: IoType,
    ) -> Result<&DesignPort, String> {
        self.declare_port(name, anchor, step, width, ty, PortDirection::Output)
    }

    fn base_block_string(&self, p: P3) -> Option<String> {
        self.base
            .get_block(p.0, p.1, p.2)
            .map(|b| b.to_string())
            .filter(|s| !s.contains("minecraft:air"))
    }

    /// The blocks the instance layers contribute, transformed — the overlay
    /// a hardware scan needs so it sees cell bodies as well as loose
    /// hardware. Built on demand; scans are one-shot (declaration, port
    /// resolution), never per-planned-cell.
    fn instance_blocks(&self) -> BTreeMap<P3, String> {
        let mut out = BTreeMap::new();
        for inst in &self.instances {
            let cell = &self.cells[&inst.cell];
            let bbox = cell_bounds(&cell.schematic);
            for (bp, bs) in self.instance_local_blocks(inst) {
                let s = transform_state(&bs, inst.rot_y).to_string();
                if s.contains("minecraft:air") {
                    continue;
                }
                let p = transform_pos(bp, bbox.min, bbox.max, inst.rot_y, inst.at);
                out.insert(p, s);
            }
        }
        out
    }

    /// The block at `p`: loose layer first, then the instance overlay.
    fn block_at(&self, p: P3, overlay: &BTreeMap<P3, String>) -> Option<String> {
        self.base_block_string(p)
            .or_else(|| overlay.get(&p).cloned())
    }

    /// The dust CONNECTION CELL for one piece of executor hardware: the cell
    /// itself when it already holds dust, else the first dust neighbour in
    /// [`AROUND`] order.
    fn dust_tap(&self, hardware: P3, overlay: &BTreeMap<P3, String>) -> Option<P3> {
        if self
            .block_at(hardware, overlay)
            .is_some_and(|b| rblocks::is_dust(&b))
        {
            return Some(hardware);
        }
        AROUND.iter().map(|d| add(hardware, *d)).find(|q| {
            self.block_at(*q, overlay)
                .is_some_and(|b| rblocks::is_dust(&b))
        })
    }

    /// Hardware scan of one connection cell, seeing `overlay` (instance
    /// bodies) as well as the loose layer.
    fn scan_bit_with(&self, cell: P3, overlay: &BTreeMap<P3, String>) -> BitHardware {
        let mut hw = BitHardware::default();
        hw.connectable = self
            .block_at(cell, overlay)
            .is_some_and(|b| rblocks::is_dust(&b));
        // Levers power adjacent dust: the 4 horizontal neighbours, the cell
        // above and the support below.
        for d in AROUND {
            let q = add(cell, d);
            if let Some(b) = self.block_at(q, overlay) {
                if hw.lever.is_none() && rblocks::is_lever(&b) {
                    hw.lever = Some(q);
                }
                if hw.lamp.is_none() && b.contains("redstone_lamp") {
                    hw.lamp = Some(q);
                }
            }
        }
        hw
    }

    // ------------------------------------------------------------------
    // Buses
    // ------------------------------------------------------------------

    /// Declare AND realize a bus from `driver` to `sinks`, threading the
    /// optional `gates` in order. One driver, N sinks: sinks beyond the
    /// first branch off the trunk at dust junctions. Declaration errors
    /// (unknown port, width mismatch, invalid style, duplicate name) are
    /// `Err`; geometric unroutability is a returned [`BusState::Failed`] —
    /// realization is atomic and never leaves a half-routed fragment.
    pub fn route_bus(
        &mut self,
        name: impl Into<String>,
        driver: &str,
        sinks: &[&str],
        gates: Vec<Gate>,
        style: BusStyle,
    ) -> Result<BusState, String> {
        self.route_bus_inner(
            name.into(),
            &[driver],
            sinks,
            gates,
            style,
            false,
            WidthAdapt::default(),
        )
    }

    /// [`Design::route_bus`] with an explicit WIDTH-ADAPTATION policy.
    ///
    /// A width mismatch is a layout question, not an error. 3 BCD-hundreds bits
    /// fit inside a 4-bit `bcd` input; the only decision is which 3 of the 4
    /// they drive, and the destination bits nothing drives read 0 with no
    /// hardware at all (undriven dust IS logical 0 — verified in-sim by
    /// `tests/design_width_adapt.rs`).
    ///
    /// - [`BusAlign::Lsb`] (the default): bit 0 to bit 0, magnitude preserved.
    /// - [`BusAlign::Msb`]: top bit to top bit — a shift up by the width
    ///   difference, which is what fixed-point fields want.
    /// - [`BusAlign::Shift`]: place the word anywhere.
    /// - `truncate`: permit dropping source bits that fall outside. Refused by
    ///   default, because losing a word's high bits is not the router's call.
    ///
    /// Adaptation applies to a single driver and a single sink; a fanout or a
    /// wired-OR merge still requires one common width, so nobody has to reason
    /// about several different mappings sharing one trunk.
    pub fn route_bus_adapted(
        &mut self,
        name: impl Into<String>,
        driver: &str,
        sinks: &[&str],
        gates: Vec<Gate>,
        style: BusStyle,
        adapt: WidthAdapt,
    ) -> Result<BusState, String> {
        self.route_bus_inner(name.into(), &[driver], sinks, gates, style, false, adapt)
    }

    /// Declare AND realize a wired-OR bus: multiple drivers are legal ONLY
    /// through this explicit merge (`merge="or"`). Extra drivers join the
    /// trunk as dust-merge branches (diode-isolated); the LVS intent stays
    /// ONE net per bit.
    pub fn route_bus_or(
        &mut self,
        name: impl Into<String>,
        drivers: &[&str],
        sinks: &[&str],
        gates: Vec<Gate>,
        style: BusStyle,
    ) -> Result<BusState, String> {
        self.route_bus_inner(
            name.into(),
            drivers,
            sinks,
            gates,
            style,
            true,
            WidthAdapt::default(),
        )
    }

    fn route_bus_inner(
        &mut self,
        name: String,
        drivers: &[&str],
        sinks: &[&str],
        gates: Vec<Gate>,
        style: BusStyle,
        merge_or: bool,
        adapt: WidthAdapt,
    ) -> Result<BusState, String> {
        if self.buses.contains_key(&name) {
            return Err(format!("bus `{name}` already exists"));
        }
        style.validate()?;
        if drivers.is_empty() {
            return Err(format!("bus `{name}` needs at least one driver"));
        }
        if drivers.len() > 1 && !merge_or {
            return Err(format!(
                "bus `{name}`: {} drivers are only legal as an explicit wired-OR merge \
                 (route_bus_or / merge=\"or\")",
                drivers.len()
            ));
        }
        // Promote executor-only endpoints before resolving them, so routing to
        // a community cell's lever input just works. Nothing else about the
        // route changes: a promoted port resolves like any other dust port.
        // Ordered and deduplicated so the promotions recorded on the bus are
        // deterministic regardless of how the endpoints were listed.
        let mut promotions: Vec<String> = Vec::new();
        if self.auto_promote {
            let mut seen: BTreeSet<String> = BTreeSet::new();
            for ep in drivers.iter().chain(sinks.iter()) {
                if !seen.insert(ep.to_string()) {
                    continue;
                }
                if let Some(note) = self.auto_promote_endpoint(ep) {
                    promotions.push(note);
                }
            }
        }

        let mut driver_ports: Vec<DesignPort> = Vec::new();
        for dn in drivers {
            let drv = self
                .resolve_port(dn)
                .map_err(|e| format!("bus `{name}`: driver {e}"))?;
            if drv.direction == PortDirection::Output {
                return Err(format!(
                    "bus `{name}`: `{dn}` receives signal, it cannot drive — swap the endpoints \
                     (a design output, or a cell's input port, is a sink)"
                ));
            }
            if let Some(first) = driver_ports.first() {
                if drv.width != first.width {
                    return Err(format!(
                        "bus `{name}`: driver `{dn}` width {} != driver `{}` width {}",
                        drv.width, first.name, first.width
                    ));
                }
            }
            driver_ports.push(drv);
        }
        if sinks.is_empty() {
            return Err(format!("bus `{name}` needs at least one sink"));
        }
        let mut sink_ports = Vec::new();
        let mut width_map: Option<WidthMap> = None;
        for s in sinks {
            let sp = self
                .resolve_port(s)
                .map_err(|e| format!("bus `{name}`: sink {e}"))?;
            if sp.direction == PortDirection::Input {
                return Err(format!(
                    "bus `{name}`: `{s}` drives signal, it cannot be a sink — swap the endpoints \
                     (a design input, or a cell's output port, is a driver)"
                ));
            }
            // Adapt when the widths differ, and ALSO when the caller asked for
            // a specific placement: `shift(2)` between two 8-bit ports is a real
            // request, and ignoring it because the widths happen to match would
            // be the worst kind of surprise.
            let asked = !matches!(adapt.align, BusAlign::Lsb) || adapt.truncate;
            if sp.width != driver_ports[0].width || asked {
                // A width mismatch is a LAYOUT question, and the router answers
                // it — but only where one answer is unambiguous. Several sinks
                // sharing a trunk would each want their own mapping, so those
                // still need one common width.
                if sp.width != driver_ports[0].width && (sinks.len() > 1 || drivers.len() > 1) {
                    return Err(format!(
                        "bus `{name}`: sink `{s}` width {} != driver width {} — width adaptation \
                         applies to a single driver and a single sink, so a fanout or wired-OR \
                         merge needs one common width (route the odd sink as its own bus)",
                        sp.width, driver_ports[0].width
                    ));
                }
                let m = plan_width_map(driver_ports[0].width, sp.width, adapt)
                    .map_err(|e| format!("bus `{name}`: {e}"))?;
                // Equal widths, no shift, nothing dropped: nothing to say, so
                // leave the bus unadorned.
                if !m.is_identity() {
                    width_map = Some(m);
                }
            }
            // Two integer words of DIFFERENT widths are different `IoType`s by
            // construction, so the type check has to look past the width once
            // an adaptation has resolved it; everything else still has to match.
            if sp.ty != driver_ports[0].ty
                && !(width_map.is_some() && same_type_family(&driver_ports[0].ty, &sp.ty))
            {
                return Err(format!(
                    "bus `{name}`: sink `{s}` type {:?} != driver `{}` type {:?}",
                    sp.ty, driver_ports[0].name, driver_ports[0].ty
                ));
            }
            sink_ports.push(sp);
        }

        let mut layer = BusLayer {
            name: name.clone(),
            driver: drivers[0].to_string(),
            extra_drivers: drivers[1..].iter().map(|s| s.to_string()).collect(),
            merge_or,
            sinks: sinks.iter().map(|s| s.to_string()).collect(),
            gates,
            style,
            state: BusState::Intended,
            fragment: BTreeMap::new(),
            runs: Vec::new(),
            segments: Vec::new(),
            gate_cells: BTreeMap::new(),
            rule: None,
            promotions,
            width_map,
            cost: BusCost::default(),
        };

        match self.realize(
            Some(&name),
            &driver_ports,
            &sink_ports,
            &layer.gates,
            &layer.style,
            layer.width_map.as_ref(),
        ) {
            Ok(real) => {
                Self::fill_layer(&mut layer, real.fragment, real.segments, real.gate_cells);
                self.apply_amendments(real.amendments);
            }
            Err(reason) => {
                layer.state = BusState::Failed(reason);
            }
        }
        let state = layer.state.clone();
        self.touch_bus(&name);
        self.buses.insert(name.clone(), layer);
        // A ROUTE IS NOT A SUCCESS UNTIL IT CONDUCTS. Placement succeeding says
        // only that the cells fit; it says nothing about the signal arriving.
        let state = if matches!(state, BusState::Routed) {
            self.accept_if_conducting(&name)
        } else {
            state
        };
        // FIRST-COME-FIRST-SERVED IS THE BUG. A bus declared later competes for
        // space that earlier buses already took, and the loser is whoever asked
        // last — not whoever had the worse alternative. Before accepting the
        // failure, rip the buses that are in the way and let this one go first.
        // This runs for an electrical failure too: a lane shorted against a
        // neighbour is exactly the kind of thing reordering can cure.
        //
        // Least invasive repair first: STAGE the bus's own detour (touches
        // nobody), then reorder against the neighbours. Multi-net negotiation
        // is deliberately not an automatic third rung: the measured five-bus
        // residue is a two-page odd cycle, so it cannot route without adding a
        // real crossing or another level, while PathFinder adds minutes to this
        // interactive failure path.
        let state = if matches!(state, BusState::Failed(_)) {
            match self.self_stage(&name) {
                BusState::Routed => BusState::Routed,
                _ => self.rip_up_and_retry(&name),
            }
        } else {
            state
        };
        Ok(state)
    }

    /// Buses currently Routed whose geometry sits in the workspace `name` needs.
    ///
    /// The region is the bounding box of `name`'s own endpoints and gates, grown
    /// by the corridor search's first-rung margin — the area a detour for this
    /// bus could plausibly want. Deliberately geometric rather than parsed out
    /// of the failure reason: the reason is a user-facing sentence and must stay
    /// free to change wording.
    fn contesting_buses(&self, name: &str) -> BTreeSet<String> {
        let Some(layer) = self.buses.get(name) else {
            return BTreeSet::new();
        };
        let mut pts: Vec<P3> = Vec::new();
        for ep in layer.driver_names().iter().chain(layer.sinks.iter()) {
            if let Ok(p) = self.resolve_port(ep) {
                // Both ends of the stack: an 8-bit port spans 16 levels, and a
                // box around bit 0 alone would miss what blocks bit 7.
                pts.push(p.anchor);
                pts.push(p.wire(p.width.saturating_sub(1)));
            }
        }
        for g in &layer.gates {
            pts.push(g.anchor);
        }
        if pts.is_empty() {
            return BTreeSet::new();
        }
        let m = crate::design_corridor::LADDER[0].margin;
        let lo = (
            pts.iter().map(|p| p.0).min().unwrap() - m,
            pts.iter().map(|p| p.1).min().unwrap() - m,
            pts.iter().map(|p| p.2).min().unwrap() - m,
        );
        let hi = (
            pts.iter().map(|p| p.0).max().unwrap() + m,
            pts.iter().map(|p| p.1).max().unwrap() + m,
            pts.iter().map(|p| p.2).max().unwrap() + m,
        );
        let inside = |p: &P3| {
            (lo.0..=hi.0).contains(&p.0)
                && (lo.1..=hi.1).contains(&p.1)
                && (lo.2..=hi.2).contains(&p.2)
        };
        self.buses
            .values()
            .filter(|b| b.name != name && matches!(b.state, BusState::Routed))
            .filter(|b| b.fragment.keys().any(inside))
            .map(|b| b.name.clone())
            .collect()
    }

    /// How many buses are Routed right now — the quantity rip-up-and-retry is
    /// allowed to improve and forbidden to trade away.
    fn routed_count(&self) -> usize {
        self.buses
            .values()
            .filter(|b| matches!(b.state, BusState::Routed))
            .count()
    }

    /// SELF-STAGING: retry a failed bus with a waypoint the router derives
    /// itself, instead of printing one and asking the user for it.
    ///
    /// The adversarial audit's cheapest finding: a `t5_03` refusal routes
    /// successfully with ONE caller-supplied waypoint, and the router's own
    /// failure text already names the clear level it should go to — so the
    /// information needed to succeed is in hand at the moment of failure and was
    /// being thrown away. Across the sweep 23 problems are beaten by a
    /// caller-supplied `gate*` variant, on a knob that has always been public
    /// API. The router can try it itself.
    ///
    /// Candidates, cheapest first:
    /// 1. a waypoint on the straight line between the endpoints, at the bus's
    ///    OWN level — this stages a long span into two shorter problems, which
    ///    is what `gate_early_src` / `gate_late_src` do by hand;
    /// 2. the same fractions on each level [`crate::design_corridor::clear_levels`]
    ///    reports clear, nearest level first — this stages a level change to a
    ///    lane that is known to exist.
    ///
    /// The gate is recorded on the bus under an `auto` name, so a staged route
    /// is inspectable and rips with the bus like any other. Tried BEFORE
    /// rip-up-and-retry: staging disturbs nobody, while ripping rearranges the
    /// neighbours, and the least invasive repair that works is the right one.
    fn self_stage(&mut self, name: &str) -> BusState {
        let Some(layer) = self.buses.get(name) else {
            return BusState::Intended;
        };
        // Only single-driver / single-sink, ungated buses: a bus that already
        // carries waypoints was staged by its author, and second-guessing a
        // fanout's junction geometry is a different problem.
        if !layer.gates.is_empty() || layer.sinks.len() != 1 || !layer.extra_drivers.is_empty() {
            return layer.state.clone();
        }
        let (Ok(drv), Ok(snk)) = (
            self.resolve_port(&layer.driver),
            self.resolve_port(&layer.sinks[0]),
        ) else {
            return layer.state.clone();
        };
        let (a, b) = (drv.anchor, snk.anchor);
        let step = drv.step;
        let width = drv.width;
        let failed = layer.state.clone();

        let lerp = |num: i32, den: i32, y: i32| -> P3 {
            (
                a.0 + (b.0 - a.0) * num / den,
                y,
                a.2 + (b.2 - a.2) * num / den,
            )
        };
        let mut levels = vec![a.1];
        if a.1 == b.1 {
            let occ = self.occupancy_index();
            levels.extend(crate::design_corridor::clear_levels(&occ, a, b, width));
        }
        let mut candidates: Vec<P3> = Vec::new();
        for y in levels {
            for (num, den) in [(1, 2), (1, 4), (3, 4)] {
                let c = lerp(num, den, y);
                if c != a && c != b && !candidates.contains(&c) {
                    candidates.push(c);
                }
            }
        }

        for anchor in candidates {
            let before = self.buses[name].gates.clone();
            self.buses.get_mut(name).unwrap().gates = vec![Gate {
                name: "auto0".to_string(),
                anchor,
                step,
            }];
            if let BusState::Routed = self.reroute_one(name) {
                return BusState::Routed;
            }
            self.buses.get_mut(name).unwrap().gates = before;
        }
        // Nothing staged: leave the bus exactly as it failed, with its original
        // reason rather than the last candidate's.
        self.set_failed(
            name,
            match &failed {
                BusState::Failed(r) => r.clone(),
                _ => "unroutable".to_string(),
            },
        )
    }

    /// RIP-UP-AND-RETRY for a bus that could not be routed: rip the buses in its
    /// way, route IT first, then put them back.
    ///
    /// Measured on `tests/design_routability.rs`: the residual failures are not
    /// occupancy and not search budget (a 1.5M-node rung recovered zero of
    /// them). They are ORDERING — `skip4` fails because `skip0`, routed four
    /// declarations earlier, took the one lane crossing the span `skip4` needs.
    /// Nothing a single-net search can see will fix that; only reconsidering the
    /// earlier bus will.
    ///
    /// STRICTLY IMPROVING, and that is the whole safety argument. The retry is
    /// attempted on a snapshot and kept only if it raises the routed count. A
    /// swap that routes this bus by failing another is a lateral move that
    /// churns geometry for nothing, so it is discarded and the original failure
    /// stands. Nothing that routed before can end up unrouted.
    ///
    /// DETERMINISTIC: the rip set is a `BTreeSet`, so the retry order is name
    /// order; [`Design::co_reroute`] then runs its own bounded rounds in the
    /// same order. No randomness, seeded or otherwise, anywhere in the loop.
    ///
    /// Cost: one `Design` clone on the failure path only. A bus that routes
    /// never pays it.
    fn rip_up_and_retry(&mut self, name: &str) -> BusState {
        let failed_state = self.bus_state(name).cloned().unwrap_or(BusState::Intended);
        let contesting = self.contesting_buses(name);
        if contesting.is_empty() {
            return failed_state;
        }
        let before = self.routed_count();
        let snapshot = self.clone();
        for b in &contesting {
            let _ = self.rip(b);
        }
        // The failing bus goes FIRST. Reversing the order is the entire
        // mechanism; everything else here is bookkeeping and safety.
        let state = self.reroute_one(name);
        let rev0 = self.layer_revision();
        let _ = self.co_reroute(contesting, rev0);
        if self.routed_count() > before {
            state
        } else {
            *self = snapshot;
            failed_state
        }
    }

    /// Attach a net-class discipline to a bus; [`Design::check`] enforces
    /// its `max_len_rt` delay budget and `y_band` layer assignment.
    pub fn set_bus_rule(&mut self, bus: &str, rule: NetClassRule) -> Result<(), String> {
        self.buses
            .get_mut(bus)
            .ok_or_else(|| format!("unknown bus `{bus}`"))?
            .rule = Some(rule);
        Ok(())
    }

    /// Edit the loose block layer: plain `set_block` on the base
    /// schematic. The cell participates in occupancy and flatten like any
    /// other loose hardware.
    pub fn set_block(&mut self, p: P3, block: &str) -> Result<(), String> {
        self.base
            .set_block_from_string(p.0, p.1, p.2, block)
            .map(|_| ())
            .map_err(|e| e.to_string())
    }

    fn fill_layer(
        layer: &mut BusLayer,
        fragment: BTreeMap<P3, String>,
        segments: Vec<Segment>,
        gate_cells: BTreeMap<String, BTreeSet<P3>>,
    ) {
        layer.fragment = fragment;
        layer.runs = segments.iter().flat_map(|s| s.runs.clone()).collect();
        layer.segments = segments;
        layer.gate_cells = gate_cells;
        layer.state = BusState::Routed;
    }

    /// Apply crossing amendments to the buses they target, keeping their
    /// fragments AND per-segment cell sets consistent.
    /// An amendment rewrites a bus that was never ripped and is named in NO
    /// report, so it is stamped as changed here — otherwise the studio, which
    /// redraws only what the engine reports, leaves the crossed bus showing
    /// its pre-station geometry.
    fn apply_amendments(&mut self, amendments: Vec<(String, Vec<P3>, BTreeMap<P3, String>)>) {
        let mut touched: Vec<String> = Vec::new();
        for (bus, removals, additions) in amendments {
            self.touch_bus(&bus);
            let target = self.buses.get_mut(&bus).expect("amended bus exists");
            // The segment losing cells also receives the station cells.
            let seg_idx = removals
                .iter()
                .find_map(|p| target.segments.iter().position(|s| s.cells.contains(p)));
            for p in &removals {
                target.fragment.remove(p);
                for seg in target.segments.iter_mut() {
                    seg.cells.remove(p);
                }
            }
            if let Some(i) = seg_idx {
                target.segments[i].cells.extend(additions.keys().copied());
            }
            target.fragment.extend(additions);
            touched.push(bus);
        }
        // An amendment REMOVES dust from the bus it stations, and a removal
        // changes the connection state of every wire that pointed at it. Draw
        // the amended bus again rather than leaving dots around the station.
        if !touched.is_empty() {
            let occ = self.occupancy_index();
            for bus in touched {
                if let Some(target) = self.buses.get_mut(&bus) {
                    let mut frag = std::mem::take(&mut target.fragment);
                    Self::rewire_fragment(&mut frag, &occ);
                    self.buses.get_mut(&bus).unwrap().fragment = frag;
                }
            }
        }
    }

    // ------------------------------------------------------------------
    // Drag APIs (Phase 2): moves always succeed — they are the document's
    // truth; buses fail VISIBLY (`FAILED(reason)`), never half-routed.
    // ------------------------------------------------------------------

    /// Move (and optionally re-rotate) an instance layer. Computes the
    /// AFFECTED bus set — routed buses whose fragments intersect the old
    /// or new footprint + influence halo, plus every already-`FAILED` bus
    /// (a move may have unblocked it) — rips exactly that set and
    /// co-reroutes it deterministically in name order with bounded retry
    /// rounds. Unroutable buses end `FAILED(reason)`.
    pub fn move_instance(&mut self, name: &str, at: P3, rot_y: i32) -> Result<MoveReport, String> {
        if rot_y.rem_euclid(90) != 0 {
            return Err(format!("rot_y must be a multiple of 90, got {rot_y}"));
        }
        let idx = self
            .instances
            .iter()
            .position(|i| i.name == name)
            .ok_or_else(|| format!("unknown instance `{name}`"))?;
        let rev0 = self.layer_revision();
        let old_region = self.instance_region(idx);
        // The move itself always succeeds.
        self.instances[idx].at = at;
        self.instances[idx].rot_y = rot_y.rem_euclid(360);
        let new_region = self.instance_region(idx);

        // Buses WIRED to this instance move with it: their endpoint anchors
        // are derived from the instance transform, so a bus that keeps its old
        // fragment is now wired to where the ports USED to be. This must not
        // depend on the fragment intersecting the region — a cell that
        // declares explicit `keepouts` can have a halo that excludes the very
        // cell its port's bus leaves along, and then the fragment test misses
        // it. That was the "I moved a component and the bus didn't update"
        // bug: the geometry silently kept pointing at the old position.
        let mut affected: BTreeSet<String> = self.buses_wired_to(name);
        for bus in self.buses.values() {
            match &bus.state {
                BusState::Routed => {
                    if bus
                        .fragment
                        .keys()
                        .any(|p| old_region.contains(p) || new_region.contains(p))
                    {
                        affected.insert(bus.name.clone());
                    }
                }
                // A FAILED bus is re-attempted on every move: the drag that
                // blocked it can also be the drag that unblocks it.
                BusState::Failed(_) => {
                    affected.insert(bus.name.clone());
                }
                BusState::Intended => {}
            }
        }
        Ok(self.co_reroute(affected, rev0))
    }

    /// Buses whose declaration names a port OF this instance (`inst.port`) —
    /// the buses an instance carries with it when it moves, and the ones that
    /// cannot survive its removal.
    fn buses_wired_to(&self, instance: &str) -> BTreeSet<String> {
        let prefix = format!("{instance}.");
        self.buses
            .values()
            .filter(|b| {
                b.driver_names()
                    .iter()
                    .chain(b.sinks.iter())
                    .any(|p| p.starts_with(&prefix))
            })
            .map(|b| b.name.clone())
            .collect()
    }

    /// Footprint + influence halo of an instance, as a cell set.
    fn instance_region(&self, idx: usize) -> BTreeSet<P3> {
        let inst = &self.instances[idx];
        let cell = &self.cells[&inst.cell];
        let bbox = cell_bounds(&cell.schematic);
        let map = |p: P3| transform_pos(p, bbox.min, bbox.max, inst.rot_y, inst.at);
        let mut region = BTreeSet::new();
        for (bp, bs) in self.instance_local_blocks(inst) {
            if bs.to_string().contains("minecraft:air") {
                continue;
            }
            region.insert(map(bp));
        }
        for (min, max) in Self::halo_boxes(cell, bbox.min, bbox.max) {
            let a = map(min);
            let b = map(max);
            let (lo, hi) = (
                (a.0.min(b.0), a.1.min(b.1), a.2.min(b.2)),
                (a.0.max(b.0), a.1.max(b.1), a.2.max(b.2)),
            );
            for x in lo.0..=hi.0 {
                for y in lo.1..=hi.1 {
                    for z in lo.2..=hi.2 {
                        region.insert((x, y, z));
                    }
                }
            }
        }
        region
    }

    /// The influence-halo boxes of a cell, untransformed:
    /// `PhysicalContract.keepouts` where declared, else the cell bounds
    /// grown by one (electrical clearance — dust one step up/down shorts
    /// without sharing a cell).
    fn halo_boxes(cell: &CellDef, min: P3, max: P3) -> Vec<(P3, P3)> {
        if cell.contract.physical.keepouts.is_empty() {
            vec![(
                (min.0 - 1, min.1 - 1, min.2 - 1),
                (max.0 + 1, max.1 + 1, max.2 + 1),
            )]
        } else {
            cell.contract
                .physical
                .keepouts
                .iter()
                .map(|k| (k.min, k.max))
                .collect()
        }
    }

    /// Rip and co-reroute a bus set: deterministic name order (seeded by
    /// the BTree ordering), bounded negotiation rounds — a bus that fails
    /// because a peer's fresh fragment contested its cells is retried
    /// after the peers commit. No exceptions: survivors are `Routed`,
    /// the rest `FAILED(reason)`.
    fn co_reroute(&mut self, affected: BTreeSet<String>, rev0: u64) -> MoveReport {
        const ROUNDS: usize = 3;
        for name in &affected {
            let _ = self.rip(name);
        }
        let mut pending: Vec<String> = affected.iter().cloned().collect();
        let mut report = MoveReport::default();
        for round in 0..ROUNDS {
            let mut still = Vec::new();
            for name in &pending {
                match self.reroute_one(name) {
                    BusState::Routed => report.rerouted.push(name.clone()),
                    BusState::Failed(_) => still.push(name.clone()),
                    BusState::Intended => {}
                }
            }
            let no_progress = still.len() == pending.len();
            pending = still;
            if pending.is_empty() || (no_progress && round > 0) {
                break;
            }
        }
        for name in &affected {
            if let Some(BusState::Failed(reason)) = self.bus_state(name) {
                report.failed.push((name.clone(), reason.clone()));
            }
        }
        // The redraw set is MEASURED from the revision stamps, not inferred
        // from `affected`: it also picks up buses that were never ripped but
        // had a crossing station amended into them by a peer's fresh route.
        report.changed = self.changed_layers_since(rev0);
        report
    }

    /// Re-realize one bus from its stored declaration. The bus keeps its
    /// endpoints, gates, style and rule; only the fragment is rebuilt.
    fn reroute_one(&mut self, name: &str) -> BusState {
        let Some(layer) = self.buses.get(name) else {
            return BusState::Intended;
        };
        let driver_names = layer.driver_names();
        let sink_names = layer.sinks.clone();
        let gates = layer.gates.clone();
        let style = layer.style.clone();
        // The bit mapping is part of the bus's INTENT: a reroute keeps it, so a
        // width-adapted bus never silently re-pairs its bits.
        let width_map = layer.width_map.clone();
        let mut driver_ports = Vec::new();
        for dn in &driver_names {
            match self.resolve_port(dn) {
                Ok(p) => driver_ports.push(p),
                Err(why) => {
                    let state = BusState::Failed(format!("driver port `{dn}`: {why}"));
                    self.touch_bus(name);
                    self.buses.get_mut(name).unwrap().state = state.clone();
                    return state;
                }
            }
        }
        let mut sink_ports = Vec::new();
        for sn in &sink_names {
            match self.resolve_port(sn) {
                Ok(p) => sink_ports.push(p),
                Err(why) => {
                    let state = BusState::Failed(format!("sink port `{sn}`: {why}"));
                    self.touch_bus(name);
                    self.buses.get_mut(name).unwrap().state = state.clone();
                    return state;
                }
            }
        }
        match self.realize(
            Some(name),
            &driver_ports,
            &sink_ports,
            &gates,
            &style,
            width_map.as_ref(),
        ) {
            Ok(real) => {
                self.touch_bus(name);
                let layer = self.buses.get_mut(name).unwrap();
                Self::fill_layer(layer, real.fragment, real.segments, real.gate_cells);
                self.apply_amendments(real.amendments);
                // Same gate as the fresh-declaration path: a reroute that lays
                // non-conducting geometry has not rerouted anything.
                self.accept_if_conducting(name)
            }
            Err(reason) => {
                self.touch_bus(name);
                let layer = self.buses.get_mut(name).unwrap();
                layer.fragment.clear();
                layer.runs.clear();
                layer.segments.clear();
                layer.gate_cells.clear();
                layer.state = BusState::Failed(reason.clone());
                BusState::Failed(reason)
            }
        }
    }

    /// Add a gate to an existing bus (splitting the segment it lands in)
    /// and re-realize the bus. Returns the resulting state.
    pub fn add_gate(
        &mut self,
        bus: &str,
        name: &str,
        anchor: P3,
        step: P3,
    ) -> Result<BusState, String> {
        let layer = self
            .buses
            .get(bus)
            .ok_or_else(|| format!("unknown bus `{bus}`"))?;
        if layer.gates.iter().any(|g| g.name == name) {
            return Err(format!("bus `{bus}` already has a gate `{name}`"));
        }
        // Insert position: the trunk waypoint pair the anchor is nearest
        // to (Manhattan distance to the pair midpoint) — deterministic.
        //
        // Resolve through `resolve_port`, NOT the declared-port table: an
        // endpoint may be an INSTANCE port (`add0.sum` -> `bcd0.bin`), which is
        // derived from the cell's contract and never appears in `self.ports`.
        // Looking only there made `add_gate` refuse every bus between two
        // placed cells — exactly the buses a user most wants a checkpoint on —
        // while `move_gate` worked fine on the same bus.
        let (driver_name, sink0_name) = (layer.driver.clone(), layer.sinks[0].clone());
        let gate_anchors: Vec<P3> = layer.gates.iter().map(|g| g.anchor).collect();
        let driver = self
            .resolve_port(&driver_name)
            .map_err(|e| format!("bus `{bus}`: driver {e}"))?;
        let sink0 = self
            .resolve_port(&sink0_name)
            .map_err(|e| format!("bus `{bus}`: sink {e}"))?;
        let mut wps = vec![driver.anchor];
        wps.extend(gate_anchors);
        wps.push(sink0.anchor);
        let mut best = (0usize, i32::MAX);
        for (i, pair) in wps.windows(2).enumerate() {
            let mid = (
                (pair[0].0 + pair[1].0) / 2,
                (pair[0].1 + pair[1].1) / 2,
                (pair[0].2 + pair[1].2) / 2,
            );
            let dist =
                (anchor.0 - mid.0).abs() + (anchor.1 - mid.1).abs() + (anchor.2 - mid.2).abs();
            if dist < best.1 {
                best = (i, dist);
            }
        }
        let layer = self.buses.get_mut(bus).unwrap();
        layer.gates.insert(
            best.0,
            Gate {
                name: name.to_string(),
                anchor,
                step,
            },
        );
        let _ = self.rip(bus);
        Ok(self.reroute_one(bus))
    }

    /// Undo a port declaration.
    ///
    /// A DESIGN port (`declare_input` / `declare_output`) is a document entry
    /// and this removes it. An INSTANCE port (`inst.port`) is derived from the
    /// cell's contract and cannot be removed — what a UI means there is
    /// "return it to Executor mode", which is
    /// [`Design::set_port_mode`]; this says so rather than silently doing
    /// nothing.
    ///
    /// GATES AND ENDPOINTS ARE NOT THE SAME THING. Removing a gate relaxes a
    /// constraint: the bus survives and re-routes straighter
    /// ([`Design::remove_gate`]). Removing an ENDPOINT changes the netlist: the
    /// bus loses a terminal, so every bus that named this port is DELETED, and
    /// they are returned so a UI can say which. Nothing is blurred, and nothing
    /// is deleted silently: pass `force = false` to be refused with the list
    /// instead, and confirm first.
    ///
    /// Returns `(removed buses, reroute outcome for the buses that merely used
    /// the space)`.
    pub fn remove_port(
        &mut self,
        name: &str,
        force: bool,
    ) -> Result<(Vec<String>, MoveReport), String> {
        let rev0 = self.layer_revision();
        if !self.ports.contains_key(name) {
            if name.contains('.') {
                return Err(format!(
                    "`{name}` is an INSTANCE port derived from its cell's contract, not a \
                     declaration, so there is nothing to remove. To undo its promotion, set it \
                     back to Executor mode (`set_port_mode`); to remove the port itself, remove \
                     the instance"
                ));
            }
            return Err(format!(
                "unknown port `{name}` (declared: {})",
                if self.ports.is_empty() {
                    "none".to_string()
                } else {
                    self.ports.keys().cloned().collect::<Vec<_>>().join(", ")
                }
            ));
        }
        let doomed: Vec<String> = self
            .buses
            .values()
            .filter(|b| {
                b.driver_names()
                    .iter()
                    .chain(b.sinks.iter())
                    .any(|p| p == name)
            })
            .map(|b| b.name.clone())
            .collect();
        if !force && !doomed.is_empty() {
            return Err(format!(
                "port `{name}` is an ENDPOINT of {} bus(es) ({}); removing it changes the netlist, \
                 so those buses would be deleted. Re-run with force to confirm, or re-point them \
                 first",
                doomed.len(),
                doomed.join(", ")
            ));
        }
        for b in &doomed {
            self.touch_bus(b);
            self.buses.remove(b);
        }
        self.ports.remove(name);
        // Freeing the port's space may unblock a bus that failed near it.
        let affected: BTreeSet<String> = self
            .buses
            .values()
            .filter(|b| matches!(b.state, BusState::Failed(_)))
            .map(|b| b.name.clone())
            .collect();
        Ok((doomed, self.co_reroute(affected, rev0)))
    }

    /// Remove a gate by INDEX (its position in the bus's gate list) and
    /// re-realize the bus, so the two spans it separated MERGE and are routed
    /// as one.
    ///
    /// Removing a gate RELAXES a constraint, so the result should be shorter
    /// and straighter — not the two old legs stitched together. That is why
    /// this re-plans the merged span from scratch instead of splicing: with the
    /// waypoint gone, `A -> gate -> C` becomes the single pair `A -> C`, which
    /// the templates take as one straight run or one L.
    ///
    /// The bus survives either way: an unroutable result leaves it
    /// `FAILED(reason)`, visible, never half-routed. The change is in the
    /// changed-layer report ([`Design::changed_layers_since`]) like every other
    /// mutation.
    ///
    /// See also [`Design::remove_port`]: a gate and an endpoint are NOT the
    /// same thing, and deleting them means different things.
    pub fn remove_gate(&mut self, bus: &str, index: usize) -> Result<GateMoveReport, String> {
        let rev0 = self.layer_revision();
        let layer = self
            .buses
            .get(bus)
            .ok_or_else(|| format!("unknown bus `{bus}`"))?;
        let n = layer.gates.len();
        if index >= n {
            return Err(format!(
                "bus `{bus}` has {n} gate(s) ({}), so there is no gate at index {index}",
                if n == 0 {
                    "none".to_string()
                } else {
                    layer
                        .gates
                        .iter()
                        .map(|g| format!("`{}`", g.name))
                        .collect::<Vec<_>>()
                        .join(", ")
                }
            ));
        }
        self.buses.get_mut(bus).unwrap().gates.remove(index);
        let _ = self.rip(bus);
        let state = self.reroute_one(bus);
        Ok(GateMoveReport {
            state,
            rerouted_segments: self.buses[bus].segments.len(),
            changed: self.changed_layers_since(rev0),
        })
    }

    /// Remove a gate by NAME — the same as [`Design::remove_gate`], for a UI
    /// that tracks gates by their label rather than their order.
    pub fn remove_gate_named(&mut self, bus: &str, gate: &str) -> Result<GateMoveReport, String> {
        let layer = self
            .buses
            .get(bus)
            .ok_or_else(|| format!("unknown bus `{bus}`"))?;
        let index = layer
            .gates
            .iter()
            .position(|g| g.name == gate)
            .ok_or_else(|| {
                format!(
                    "bus `{bus}` has no gate `{gate}` (has: {})",
                    layer
                        .gates
                        .iter()
                        .map(|g| g.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })?;
        self.remove_gate(bus, index)
    }

    /// Drag a gate: the anchor moves unconditionally (the document's
    /// truth), then EXACTLY the two segments adjacent to the gate are
    /// ripped and rerouted atomically against the design-wide occupancy.
    /// An unroutable move leaves the bus `FAILED(reason)` with the
    /// fragment cleared — visible, never half-routed.
    pub fn move_gate(
        &mut self,
        bus: &str,
        gate: &str,
        anchor: P3,
    ) -> Result<GateMoveReport, String> {
        let rev0 = self.layer_revision();
        let layer = self
            .buses
            .get(bus)
            .ok_or_else(|| format!("unknown bus `{bus}`"))?;
        let gi = layer
            .gates
            .iter()
            .position(|g| g.name == gate)
            .ok_or_else(|| format!("bus `{bus}` has no gate `{gate}`"))?;
        let was_routed = layer.state == BusState::Routed && !layer.segments.is_empty();
        // Trunk waypoints BEFORE the move (gate gi is waypoint gi+1).
        let old_wps: Option<(P3, P3)> = if was_routed {
            let seg_a = layer
                .segments
                .iter()
                .find(|s| s.kind == SegmentKind::Trunk(gi));
            let seg_b = layer
                .segments
                .iter()
                .find(|s| s.kind == SegmentKind::Trunk(gi + 1));
            match (seg_a, seg_b) {
                (Some(a), Some(b)) => Some((a.a, b.b)),
                _ => None,
            }
        } else {
            None
        };
        self.buses.get_mut(bus).unwrap().gates[gi].anchor = anchor;

        let Some((wp_before, wp_after)) = old_wps else {
            // No per-segment record (unrouted, FAILED, or a loaded
            // document): whole-bus reroute.
            let _ = self.rip(bus);
            let state = self.reroute_one(bus);
            let n = self.buses[bus].segments.len();
            return Ok(GateMoveReport {
                state,
                rerouted_segments: n,
                changed: self.changed_layers_since(rev0),
            });
        };

        // A branch whose junction rides an affected trunk segment moves
        // with it: fall back to the whole-bus reroute in that case.
        let layer = &self.buses[bus];
        let seg_a_idx = layer
            .segments
            .iter()
            .position(|s| s.kind == SegmentKind::Trunk(gi))
            .unwrap();
        let seg_b_idx = layer
            .segments
            .iter()
            .position(|s| s.kind == SegmentKind::Trunk(gi + 1))
            .unwrap();
        let branch_rides = layer.segments.iter().any(|s| {
            matches!(s.kind, SegmentKind::Branch(_))
                && [seg_a_idx, seg_b_idx].iter().any(|&i| {
                    let t = &layer.segments[i];
                    t.cells.contains(&s.a)
                        || t.cells.contains(&s.b)
                        || t.runs.iter().any(|r| {
                            let (jx, jz) = if r.along_x {
                                (s.a.0, s.a.2)
                            } else {
                                (s.a.2, s.a.0)
                            };
                            jz == r.fixed && r.strictly_inside(jx, 0)
                        })
                })
        });
        if branch_rides {
            let _ = self.rip(bus);
            let state = self.reroute_one(bus);
            let n = self.buses[bus].segments.len();
            return Ok(GateMoveReport {
                state,
                rerouted_segments: n,
                changed: self.changed_layers_since(rev0),
            });
        }

        // Rip exactly the two adjacent segments + the gate's joint column.
        let mut ripped: BTreeSet<P3> = BTreeSet::new();
        ripped.extend(layer.segments[seg_a_idx].cells.iter().copied());
        ripped.extend(layer.segments[seg_b_idx].cells.iter().copied());
        if let Some(cells) = layer.gate_cells.get(gate) {
            ripped.extend(cells.iter().copied());
        }
        let width = layer
            .segments
            .get(seg_a_idx)
            .and_then(|s| s.runs.first())
            .map(|r| r.width)
            .unwrap_or(1);
        let style = layer.style.clone();

        let endpoints: Vec<String> = layer
            .driver_names()
            .into_iter()
            .chain(layer.sinks.iter().cloned())
            .collect();
        let occ = self.occupancy_for_plan(&ripped, &self.halo_exempt(&endpoints));
        let mut planner = Planner::new(self, Some(bus), &style, &occ);
        let plan = (|| -> Result<(), String> {
            // The strength entering a mid-bus segment is unknown — the geometry
            // upstream belongs to somebody else's route — so there is nothing to
            // measure and a conservative half-budget arrival stands in.
            planner.begin_segment(SegmentKind::Trunk(gi), wp_before, anchor);
            let since =
                planner.plan_pair(wp_before, anchor, width, &BTreeSet::new(), UNKNOWN_ARRIVAL)?;
            planner.end_segment();
            planner.begin_segment(SegmentKind::Trunk(gi + 1), anchor, wp_after);
            planner.plan_pair(
                anchor,
                wp_after,
                width,
                &BTreeSet::new(),
                since.saturating_add(1),
            )?;
            planner.end_segment();
            planner.plan_column(gate, anchor, width)
        })();
        let real = planner.finish();

        match plan {
            Ok(()) => {
                self.touch_bus(bus);
                let layer = self.buses.get_mut(bus).unwrap();
                for p in &ripped {
                    layer.fragment.remove(p);
                }
                layer.fragment.extend(real.fragment);
                let mut new_segments = real.segments;
                layer.segments[seg_a_idx] = new_segments.remove(0);
                layer.segments[seg_b_idx] = new_segments.remove(0);
                layer.gate_cells.insert(
                    gate.to_string(),
                    real.gate_cells.get(gate).cloned().unwrap_or_default(),
                );
                layer.runs = layer.segments.iter().flat_map(|s| s.runs.clone()).collect();
                self.apply_amendments(real.amendments);
                Ok(GateMoveReport {
                    state: BusState::Routed,
                    rerouted_segments: 2,
                    changed: self.changed_layers_since(rev0),
                })
            }
            Err(reason) => {
                let reason = format!(
                    "segment {:?} -> {:?} -> {:?} (gate `{gate}`): {reason}",
                    wp_before, anchor, wp_after
                );
                self.touch_bus(bus);
                let layer = self.buses.get_mut(bus).unwrap();
                layer.fragment.clear();
                layer.runs.clear();
                layer.segments.clear();
                layer.gate_cells.clear();
                layer.state = BusState::Failed(reason.clone());
                Ok(GateMoveReport {
                    state: BusState::Failed(reason),
                    rerouted_segments: 2,
                    changed: self.changed_layers_since(rev0),
                })
            }
        }
    }

    /// Rip a bus: clear its fragment and return it to `Intended`. Station
    /// amendments stamped into OTHER buses by crossings stay (they remain
    /// electrically sound straight-line refreshes).
    pub fn rip(&mut self, name: &str) -> Result<(), String> {
        if !self.buses.contains_key(name) {
            return Err(format!("unknown bus `{name}`"));
        }
        self.touch_bus(name);
        let bus = self.buses.get_mut(name).expect("checked above");
        bus.fragment.clear();
        bus.runs.clear();
        bus.segments.clear();
        bus.gate_cells.clear();
        bus.state = BusState::Intended;
        Ok(())
    }

    /// Re-realize a bus from its stored declaration (endpoints, gates, style
    /// and rule all kept). The counterpart to [`Design::rip`]: rip to free
    /// the space, reroute to try again once the obstacle moved.
    pub fn reroute(&mut self, name: &str) -> Result<BusState, String> {
        if !self.buses.contains_key(name) {
            return Err(format!("unknown bus `{name}`"));
        }
        let _ = self.rip(name);
        Ok(self.reroute_one(name))
    }

    /// Delete a bus outright: its fragment AND its declaration. Unlike
    /// [`Design::rip`] (which keeps the declaration so it can be rerouted),
    /// the name becomes free again.
    pub fn remove_bus(&mut self, name: &str) -> Result<(), String> {
        self.rip(name)?; // stamps the layer as changed
        self.buses.remove(name);
        Ok(())
    }

    /// The design-wide spatial occupancy index: loose blocks, instance
    /// footprints, routed bus fragments, and instance influence halos.
    pub fn occupancy_index(&self) -> OccupancyIndex {
        self.occupancy_for_plan(&BTreeSet::new(), &BTreeSet::new())
    }

    /// The instances whose influence halo a bus with these endpoints may
    /// enter: the ones that own an endpoint. Routing *into* the cell you are
    /// connecting to is legal — that is what a pin is for — while the
    /// instance's hard body cells still protect themselves, and every other
    /// instance's halo still blocks.
    fn halo_exempt(&self, endpoints: &[String]) -> BTreeSet<String> {
        endpoints
            .iter()
            .filter_map(|p| p.split_once('.').map(|(i, _)| i.to_string()))
            .filter(|i| self.instances.iter().any(|inst| &inst.name == i))
            .collect()
    }

    /// The occupancy index minus `skip` (cells a partial rip vacated), with
    /// the halos of `halo_exempt` instances suppressed (pin access).
    fn occupancy_for_plan(
        &self,
        skip: &BTreeSet<P3>,
        halo_exempt: &BTreeSet<String>,
    ) -> OccupancyIndex {
        let mut idx = OccupancyIndex::default();
        for (bp, bs) in self.base.iter_blocks() {
            let s = bs.to_string();
            if s.contains("minecraft:air") {
                continue;
            }
            let p = (bp.x, bp.y, bp.z);
            if skip.contains(&p) {
                continue;
            }
            idx.cells.insert(p, (s, Occupant::Loose));
        }
        for inst in &self.instances {
            let cell = &self.cells[&inst.cell];
            let bbox = cell_bounds(&cell.schematic);
            for (bp, bs) in self.instance_local_blocks(inst) {
                let s = transform_state(&bs, inst.rot_y).to_string();
                if s.contains("minecraft:air") {
                    continue;
                }
                let p = transform_pos(bp, bbox.min, bbox.max, inst.rot_y, inst.at);
                if skip.contains(&p) {
                    continue;
                }
                idx.cells
                    .insert(p, (s, Occupant::Instance(inst.name.clone())));
            }
        }
        for bus in self.buses.values() {
            for (p, b) in &bus.fragment {
                if skip.contains(p) {
                    continue;
                }
                idx.cells
                    .insert(*p, (b.clone(), Occupant::Bus(bus.name.clone())));
            }
        }
        // Influence halos never shadow hard cells.
        for inst in &self.instances {
            if halo_exempt.contains(&inst.name) {
                continue;
            }
            let cell = &self.cells[&inst.cell];
            let bbox = cell_bounds(&cell.schematic);
            let map = |p: P3| transform_pos(p, bbox.min, bbox.max, inst.rot_y, inst.at);
            // A declared keepout is designer INTENT and stays absolute; the
            // default dilation is only a proxy for electrical interference,
            // which the transport model now decides exactly.
            let soft = cell.contract.physical.keepouts.is_empty();
            for (min, max) in Self::halo_boxes(cell, bbox.min, bbox.max) {
                let a = map(min);
                let b = map(max);
                let lo = (a.0.min(b.0), a.1.min(b.1), a.2.min(b.2));
                let hi = (a.0.max(b.0), a.1.max(b.1), a.2.max(b.2));
                for x in lo.0..=hi.0 {
                    for y in lo.1..=hi.1 {
                        for z in lo.2..=hi.2 {
                            let p = (x, y, z);
                            if idx.cells.contains_key(&p) || skip.contains(&p) {
                                continue;
                            }
                            idx.halos.insert(p, inst.name.clone());
                            if soft {
                                idx.soft_halos.insert(p);
                            }
                        }
                    }
                }
            }
        }
        idx.port_lanes = self.vertical_port_lanes();
        idx
    }

    /// Every VERTICAL-STACK port in the design — declared design ports and
    /// derived instance ports alike — as `(bit-0 cell, step, width)`, for
    /// [`OccupancyIndex::port_lanes`].
    ///
    /// Ports whose bits advance horizontally are omitted on purpose: the
    /// corridor search's unit is a column of the 2y-pitch stack, so it can
    /// reason about "the lane this port leaves along" only when the port IS
    /// such a stack. A row port's bits each need their own escape and that is a
    /// different geometry.
    ///
    /// A port whose bus is already routed needs no protection — its lane is
    /// occupied by that bus, so the freeness test in
    /// [`crate::design_corridor::BusFabric::column_reserved`] finds nothing to
    /// reserve. The list is therefore safe to compute unconditionally.
    fn vertical_port_lanes(&self) -> Vec<(P3, P3, u8)> {
        let vertical = |step: P3| step.0 == 0 && step.2 == 0 && step.1 != 0;
        let mut out: Vec<(P3, P3, u8)> = self
            .ports
            .values()
            .filter(|p| vertical(p.step))
            .map(|p| (p.anchor, p.step, p.width))
            .collect();
        // Instance ports are DERIVED from the contract, so a contract error
        // must not take the occupancy index down with it: an escape lane is an
        // optimisation, and the caller that really needs the port will report
        // the error itself through `resolve_port`.
        if let Ok(ports) = self.instance_ports() {
            for p in ports {
                if !p.routable() {
                    continue;
                }
                let (Some(wires), Some(step)) = (p.wires.as_ref(), p.step) else {
                    continue;
                };
                if let (Some(anchor), true) = (wires.first(), vertical(step)) {
                    out.push((*anchor, step, p.width));
                }
            }
        }
        out.sort();
        out.dedup();
        out
    }

    /// Realize a bus (pure planning: no mutation). `Err` is the
    /// user-facing failure reason. `exclude` names the bus being planned
    /// so its own surviving runs are not treated as crossings.
    ///
    /// Realization shape: a TRUNK (primary driver -> gates -> primary
    /// sink; straight runs, or one implicit L corner per waypoint pair)
    /// plus a BRANCH per extra sink (fanout) and per extra driver
    /// (wired-OR), each joining the trunk at a plain-dust junction,
    /// diode-isolated by a repeater on the branch side.
    #[allow(clippy::too_many_arguments)]
    fn realize(
        &self,
        exclude: Option<&str>,
        drivers: &[DesignPort],
        sinks: &[DesignPort],
        gates: &[Gate],
        style: &BusStyle,
        width_map: Option<&WidthMap>,
    ) -> Result<Realization, String> {
        let step = (0, 2, 0);
        // WIDTH ADAPTATION is pure geometry once the mapping is resolved: route
        // the OVERLAPPING bits only, and slide each end's bit-0 anchor to the
        // first bit it actually carries. The stack pitch is unchanged, so every
        // template, crossing rule and DRC downstream sees an ordinary bus that
        // happens to be narrower. Sink bits nothing drives are simply not built
        // — undriven dust is logical 0, so tying them costs no hardware.
        let width = width_map.map_or(drivers[0].width, |m| m.bits);
        let (drivers, sinks) = match width_map {
            None => (drivers.to_vec(), sinks.to_vec()),
            Some(m) => {
                let slide = |p: &DesignPort, bit: i32| -> DesignPort {
                    let mut q = p.clone();
                    q.anchor = add(q.anchor, scale(q.step, bit));
                    q.width = m.bits;
                    q
                };
                (
                    vec![slide(&drivers[0], m.from_bit as i32)],
                    vec![slide(&sinks[0], m.from_bit as i32 + m.shift)],
                )
            }
        };
        let (drivers, sinks) = (&drivers[..], &sinks[..]);
        let x_row = |s: P3| s.0 != 0 && s.1 == 0 && s.2 == 0;
        let z_row = |s: P3| s.0 == 0 && s.1 == 0 && s.2 != 0;
        let balanced_flat_turn = drivers.len() == 1
            && sinks.len() == 1
            && ((x_row(drivers[0].step) && z_row(sinks[0].step))
                || (z_row(drivers[0].step) && x_row(sinks[0].step)));
        for p in drivers.iter().chain(sinks.iter()) {
            if p.step != step && p.step.1 != 0 {
                return Err(format!(
                    "unsupported bus form: this design realizes the verified vertical 2y-pitch \
                     stack (step (0,2,0)), and can adapt a HORIZONTAL row onto it; port `{}` has \
                     step {:?}, which is neither",
                    p.name, p.step
                ));
            }
        }
        for g in gates {
            if g.step != step {
                return Err(format!(
                    "gate `{}`: step {:?} does not match the bus form (0,2,0)",
                    g.name, g.step
                ));
            }
        }

        // Pin access: this bus may enter the halo of the instances it
        // terminates on.
        let endpoints: Vec<String> = drivers
            .iter()
            .chain(sinks.iter())
            .map(|p| p.name.clone())
            .collect();
        let mut occ = self.occupancy_for_plan(&BTreeSet::new(), &self.halo_exempt(&endpoints));

        // CONGRUENT PORTS NEED NO FORM AT ALL.
        //
        // The realizer is FORM-FIRST: it converts every port to the canonical
        // 2y stack, transports one dense bundle, and converts back. When both
        // ports already share a geometry that is not the canonical stack, that
        // pipeline builds TWO adapters — a gather bar and 8 climbing lanes at
        // each end — to reach a form it then immediately leaves. The bus is
        // really just N PARALLEL WIRES: bit k to bit k, no gather, no stack, no
        // fan. Detect that and route it that way.
        //
        // Deliberately NOT taken for the canonical stack: there the dense form
        // shares supports and separators between bits, so one 8-bit run beats
        // eight 1-bit lanes. This path exists to avoid conversions that buy
        // nothing, not to replace the form that pays for itself.
        if gates.is_empty() && drivers.len() == 1 && sinks.len() == 1 {
            if let Some(lanes) = Self::congruent_lanes(&drivers[0], &sinks[0], step) {
                let mut planner = Planner::new(self, exclude, style, &occ);
                let mut ok = true;
                for (k, (a, b)) in lanes.iter().enumerate() {
                    planner.begin_segment(SegmentKind::Trunk(k), *a, *b);
                    // Each lane is its own 1-bit run, so it gets its own
                    // refreshes and the ladder's full retry vocabulary; the
                    // ports being congruent is what keeps them parallel and
                    // skew-matched without an explicit bundle constraint.
                    if let Err(e) = planner.plan_pair(*a, *b, 1, &BTreeSet::new(), 0) {
                        ok = false;
                        let _ = e;
                        break;
                    }
                    planner.end_segment();
                }
                if ok {
                    let mut real = planner.finish();
                    if !real.fragment.is_empty() {
                        Self::rewire_fragment(&mut real.fragment, &occ);
                        for (_, _, additions) in real.amendments.iter_mut() {
                            Self::rewire_fragment(additions, &occ);
                        }
                        return Ok(real);
                    }
                }
                // Falling through to the form pipeline is always legal: the
                // parallel form is an OPTIMISATION, never the only answer.
            }
        }

        // FORM ADAPTATION IS THE BUS'S JOB. A port whose native geometry is a
        // horizontal row gets a row->stack adapter planned into THIS BUS's
        // fragment, so it is created and ripped with the bus and the component
        // is never edited beyond its own minimal in-place promotion.
        let mut adapters: Vec<(String, P3, crate::design_promote::PivotPlan)> = Vec::new();
        let mut anchor_of: BTreeMap<String, P3> = BTreeMap::new();
        for p in drivers.iter().chain(sinks.iter()) {
            if p.step == step {
                continue;
            }
            // The other end of the bus is what this adapter has to reach.
            let partner = if std::ptr::eq(p, &drivers[0]) {
                sinks.first().map(|q| q.anchor)
            } else {
                drivers.first().map(|q| q.anchor)
            };
            // A flat 90-degree turn uses two row-to-stack adapters. Gathering
            // both rows toward the same numbered bit makes their per-bit
            // gather distances ADD, so the early bits ride the shared trunk
            // and loop back while the late bits take a short path. Opposite
            // gather ends make those distances cancel: 2*i + 2*(n-1-i) is
            // constant. Coordinate the pair here; choosing each adapter in
            // isolation cannot see that end-to-end invariant.
            let gather_end = balanced_flat_turn.then(|| !std::ptr::eq(p, &drivers[0]));
            let plan = self.plan_form_adapter(p, &occ, partner, gather_end)?;
            anchor_of.insert(p.name.clone(), plan.column[0]);
            adapters.push((p.name.clone(), p.anchor, plan));
        }
        // The adapter's cells are the bus's own: other legs must route AROUND
        // them (so add them to the occupancy the planner sees) while the
        // planner is still allowed to write them (so mark them vacated).
        let mut adapter_cells: BTreeSet<P3> = BTreeSet::new();
        for (name, _, plan) in &adapters {
            for (q, blk) in &plan.cells {
                adapter_cells.insert(*q);
                occ.cells.insert(
                    *q,
                    (
                        blk.clone(),
                        Occupant::Bus(exclude.unwrap_or(name).to_string()),
                    ),
                );
            }
        }
        let occ = occ;

        // WHAT THE ADAPTERS ALREADY SPENT, measured off their stamped cells.
        //
        // A form adapter's gather column is not a fresh 15: the deepest bit's
        // gather leg can be seven dust cells past its last diode, so a run
        // LEAVING that column starts seven cells down, and a run ARRIVING at
        // one must leave seven cells in hand for it. Neither was accounted
        // anywhere; the old blanket `REFRESH_AT = 7` reserved exactly this
        // much slack by halving dust's reach for every run in the design,
        // which is why widening it broke the form conversions and nothing
        // else. Measuring it instead pays for it only where it is owed.
        //
        // Read off the geometry, not re-derived from `design_promote`'s pitch
        // arithmetic: a plan is the truth about what was stamped, and the two
        // cannot drift apart.
        let adapter_debt: BTreeMap<String, u32> = adapters
            .iter()
            .map(|(name, _, plan)| {
                // The station pattern is identical for every bit (matched skew),
                // so the binding constraint is the WORST bit's debt.
                let debt = plan
                    .column
                    .iter()
                    .map(|&c| {
                        tile_dust_debt(c, |q| {
                            plan.cells.get(&q).is_some_and(|b| rblocks::is_dust(b))
                        })
                    })
                    .max()
                    .unwrap_or(0);
                (name.clone(), debt)
            })
            .collect();

        // Downstream everything — waypoints, branch geometry, the planner —
        // works from the ADAPTED port: its anchor is the adapter's column head
        // and its form is the canonical stack. Nothing else needs to know.
        let adapt = |p: &DesignPort| -> DesignPort {
            let mut q = p.clone();
            if let Some(a) = anchor_of.get(&p.name) {
                q.anchor = *a;
                q.step = step;
            }
            q
        };
        let drivers: Vec<DesignPort> = drivers.iter().map(adapt).collect();
        let sinks: Vec<DesignPort> = sinks.iter().map(adapt).collect();
        let (drivers, sinks) = (&drivers[..], &sinks[..]);

        // Trunk waypoint chain: primary driver, gates, primary sink.
        let mut waypoints = vec![drivers[0].anchor];
        waypoints.extend(gates.iter().map(|g| g.anchor));
        waypoints.push(sinks[0].anchor);
        // A pair whose anchors sit on different levels is NOT a failure: the
        // planner inserts the verified level-shift tile (`shift_plan`) and the
        // bus changes level in form. Only a pair with too little run for the
        // tile fails, and it says so with the numbers.

        // Branch junctions must sit on the trunk the planner ACTUALLY lays,
        // and a trunk pair may now detour around an obstacle instead of
        // taking the x-first template. So when there are branches, plan the
        // trunk once as a probe to learn its real runs, then plan for real
        // with the junctions kept as plain dust. Without branches the probe
        // is pure waste, so skip it.
        let has_branches = sinks.len() > 1 || drivers.len() > 1;
        let trunk_runs = if has_branches {
            Self::probe_trunk_runs(self, exclude, style, &occ, &waypoints, width)?
        } else {
            Vec::new()
        };
        let mut branches: Vec<(String, RunInfo, P3, bool, P3)> = Vec::new();
        let mut keep: BTreeSet<P3> = BTreeSet::new();
        for sp in &sinks[1..] {
            let (run, junction) = Self::branch_geometry(&trunk_runs, sp, false)?;
            keep.insert(junction);
            branches.push((sp.name.clone(), run, junction, false, sp.anchor));
        }
        for dp in &drivers[1..] {
            let (run, junction) = Self::branch_geometry(&trunk_runs, dp, true)?;
            keep.insert(junction);
            branches.push((dp.name.clone(), run, junction, true, dp.anchor));
        }

        let mut planner = Planner::new(self, exclude, style, &occ);
        // Every SINK's adapter debt becomes an exit reserve at its anchor, so a
        // run that ends there stops spending in time for the adapter to finish
        // the job. Sink branches are covered too: they end at their own anchor.
        for sp in sinks.iter() {
            if let Some(&debt) = adapter_debt.get(&sp.name) {
                planner.reserves.insert(sp.anchor, debt);
            }
        }
        // Stamp the form adapters FIRST: they are this bus's cells, so the
        // planner must be allowed to write them even though they are in `occ`
        // (which is what makes the other legs route around them).
        planner.vacated.extend(adapter_cells.iter().copied());
        for (port, row_anchor, plan) in &adapters {
            planner.begin_segment(
                SegmentKind::Adapter(port.clone()),
                *row_anchor,
                plan.column[0],
            );
            for (q, blk) in &plan.cells {
                planner
                    .put(*q, blk)
                    .map_err(|e| format!("form adapter for `{port}`: {e}"))?;
            }
            planner.end_segment();
        }
        // The trunk leaves the primary driver's adapter already in debt — and if
        // the driver is an INSTANCE port, with an unknown debt on top of that.
        //
        // A cell OUTPUT port is a dust tap on the cell's own wire, and how far
        // that wire has already run inside the cell lives in the cell's
        // schematic, which the router never reads. The arrival is therefore
        // opaque and the conservative value is the only honest one — the exact
        // fallback the adversarial report prescribes for geometry whose budget is
        // not modelled, and what `plan_port_patch` already does for a mid-bus
        // splice. A SINK instance port needs nothing: `design_promote::plan_input`
        // puts a repeater into the attachment block, so that boundary refreshes.
        //
        // This is the whole of the BCD-chain regression. Every endpoint in the
        // adversarial corpus is loose lever/lamp hardware the router adapts
        // itself, so 103 problems never exercised an opaque arrival and the
        // chained adder -> BCD pipeline went 8/8 -> 1/8 while they stayed green.
        // It costs zero repeaters on that corpus (1956 either way) and restores
        // `bcd_arith`/`bcd_sevenseg` to 8/8.
        let mut since = adapter_debt.get(&drivers[0].name).copied().unwrap_or(0);
        if drivers[0].name.contains('.') {
            since = since.max(UNKNOWN_ARRIVAL);
        }
        for (i, pair) in waypoints.windows(2).enumerate() {
            planner.begin_segment(SegmentKind::Trunk(i), pair[0], pair[1]);
            since = planner
                .plan_pair(pair[0], pair[1], width, &keep, since)
                .map_err(|e| format!("segment {:?} -> {:?}: {e}", pair[0], pair[1]))?;
            planner.end_segment();
            // The gate joint between pairs is one more dust cell.
            since = since.saturating_add(1);
        }
        for g in gates {
            planner.plan_column(&g.name, g.anchor, width)?;
        }
        for (port, run, junction, is_driver, port_anchor) in &branches {
            // The junction must have survived as plain dust on the trunk
            // (a flipped corner or a crossing window would have eaten it).
            if !planner
                .real
                .fragment
                .get(junction)
                .is_some_and(|b| rblocks::is_dust(b))
            {
                return Err(format!(
                    "branch for `{port}`: junction {:?} did not survive as plain dust on the \
                     trunk; add a gate to shift the join",
                    junction
                ));
            }
            let (a, b) = if *is_driver {
                (*port_anchor, *junction)
            } else {
                (*junction, *port_anchor)
            };
            planner.begin_segment(SegmentKind::Branch(port.clone()), a, b);
            // A SINK branch opens with a forced diode at the junction, so it
            // starts fresh; a DRIVER branch starts at its own adapter's debt.
            // (Its exit reserve is already registered above when the far end is
            // a sink anchor with an adapter.)
            let since0 = if *is_driver {
                adapter_debt.get(port).copied().unwrap_or(0)
            } else {
                0
            };
            planner
                .plan_run(run, &BTreeSet::new(), since0, !*is_driver, *is_driver)
                .map_err(|e| format!("branch for `{port}`: {e}"))?;
            planner.end_segment();
        }
        let mut real = planner.finish();

        // TWO STRUCTURAL INVARIANTS, checked here because this is the ONLY
        // place a bus's geometry comes from. A "routed" bus with nothing built
        // is the worst possible outcome — green status, empty layer, and a
        // viewer that trusts the status shows nothing and says everything is
        // fine. Make it unrepresentable rather than merely unlikely.
        if real.fragment.is_empty() {
            return Err(format!(
                "internal: the plan for {:?} -> {:?} produced NO cells. A routed bus always \
                 builds something; refusing rather than reporting an empty layer as routed",
                waypoints[0],
                waypoints[waypoints.len() - 1]
            ));
        }
        // A gate is a CHECKPOINT: the realized path must actually pass through
        // it. `plan_column` lays the joint, so a missing gate cell means the
        // column was never planned — the waypoint was silently skipped.
        for g in gates {
            for k in 0..width {
                let p = add(g.anchor, (0, 2 * k as i32, 0));
                if !real.fragment.contains_key(&p) {
                    return Err(format!(
                        "internal: gate `{}` was not realized — bit {k} of its checkpoint column \
                         at {:?} is absent from the route, so the bus does not pass through the \
                         gate it was given",
                        g.name, p
                    ));
                }
            }
        }

        // DRAW THE WIRE, not a trail of dots. Every dust cell above was
        // authored in the fully-spelled-out DEFAULT state — which is right for
        // interning (a bare `redstone_wire` interns a property-less state that
        // tick engines never normalise, and those cells sit INERT) but is
        // geometrically a DOT. Minecraft derives the connection state from the
        // neighbours at placement time; so do we, here, once the whole fragment
        // is known. No simulation, no bake: cheap and deterministic.
        Self::rewire_fragment(&mut real.fragment, &occ);
        for (_, _, additions) in real.amendments.iter_mut() {
            Self::rewire_fragment(additions, &occ);
        }
        Ok(real)
    }

    /// Give every dust cell in `cells` its geometrically derived connection
    /// state, reading the rest of the world out of `occ`.
    fn rewire_fragment(cells: &mut BTreeMap<P3, String>, occ: &OccupancyIndex) {
        let outside = |q: P3| -> Option<String> { occ.cells.get(&q).map(|(b, _)| b.clone()) };
        crate::routing::engine::wire::rewire(cells, &outside);
    }

    /// Bit-to-bit lane endpoints when the two ports are CONGRUENT — same bit
    /// count, same pitch, same axis — and their shared form is NOT the
    /// canonical stack (where the dense form is cheaper than separate lanes).
    ///
    /// `None` means the forms differ, so a conversion really is needed.
    fn congruent_lanes(
        driver: &DesignPort,
        sink: &DesignPort,
        canonical: P3,
    ) -> Option<Vec<(P3, P3)>> {
        if driver.width != sink.width || driver.width == 0 {
            return None;
        }
        if driver.step != sink.step || driver.step == canonical {
            return None;
        }
        // Every lane must run the same way, or they are not a bundle: the pair
        // has to differ on exactly the axes the pitch does NOT use, and by the
        // same amount for every bit (which congruent steps guarantee).
        let (a0, b0) = (driver.anchor, sink.anchor);
        let delta = (b0.0 - a0.0, b0.1 - a0.1, b0.2 - a0.2);
        if delta == (0, 0, 0) {
            return None;
        }
        // A lane that has to change LEVEL as well is still fine (the level
        // shift handles it), but a lane running along its own pitch axis would
        // overlap its neighbours.
        let pitch_axis = |s: P3| (s.0 != 0, s.1 != 0, s.2 != 0);
        let (px, _py, pz) = pitch_axis(driver.step);
        if (px && delta.0 != 0) || (pz && delta.2 != 0) {
            return None;
        }
        Some(
            (0..driver.width)
                .map(|k| (driver.wire(k), sink.wire(k)))
                .collect(),
        )
    }

    /// Plan the row->stack FORM ADAPTER for a port whose native geometry is a
    /// horizontal row, against the design-wide occupancy.
    ///
    /// The cells come back as a pure plan; the caller stamps them into the
    /// BUS's fragment. That ownership is the point: promotion is minimal and
    /// in-place (a horizontal row of 8 stays a horizontal row of 8 at its
    /// native pitch, inside the cell's own footprint), and the adapter — which
    /// exists only to serve one bus and reaches well outside the component —
    /// is created and RIPPED with that bus.
    fn plan_form_adapter(
        &self,
        port: &DesignPort,
        occ: &OccupancyIndex,
        toward: Option<P3>,
        gather_end: Option<bool>,
    ) -> Result<crate::design_promote::PivotPlan, String> {
        let row: Vec<P3> = (0..port.width as i32)
            .map(|i| {
                (
                    port.anchor.0 + port.step.0 * i,
                    port.anchor.1 + port.step.1 * i,
                    port.anchor.2 + port.step.2 * i,
                )
            })
            .collect();
        // What the adapter must treat as taken: hard cells, and any halo it is
        // not exempt from (`occ` already has the endpoint instances' halos
        // suppressed, so pin access still works).
        let at = |q: P3| -> Option<String> {
            occ.cells.get(&q).map(|(b, _)| b.clone()).or_else(|| {
                occ.halos
                    .get(&q)
                    .map(|i| format!("the influence halo of `{i}`"))
            })
        };
        // Grow AWAY from the owning instance's body, so the adapter leaves the
        // component instead of burrowing into it.
        let away = port
            .name
            .split_once('.')
            .and_then(|(inst, _)| self.instances.iter().find(|i| i.name == inst))
            .map(|inst| {
                let blocks = self.placed_instance_blocks(inst);
                let n = blocks.len().max(1) as i64;
                let (sx, sy, sz) = blocks.keys().fold((0i64, 0i64, 0i64), |a, q| {
                    (a.0 + q.0 as i64, a.1 + q.1 as i64, a.2 + q.2 as i64)
                });
                ((sx / n) as i32, (sy / n) as i32, (sz / n) as i32)
            })
            .unwrap_or(port.anchor);
        // A port that DRIVES the fabric flows out of the row into the column;
        // a sink flows the other way.
        let flow_out = port.direction == PortDirection::Input;
        // Where the bus has to GO from here: the adapter's column head should
        // land on the side facing its partner, or the transport leg pays for
        // the detour. This is the end-to-end half of the cost — a cheap gather
        // that forces an expensive run is not cheap.
        crate::design_promote::plan_pivot(&row, port.step, away, flow_out, &at, toward, gather_end)
            .map_err(|e| format!("port `{}`: {e}", port.name))
    }

    /// Plan the trunk as a throwaway probe and report the runs it actually
    /// laid down. Branch junctions are derived from THESE runs, not from the
    /// x-first template guess: a pair that had to detour around an obstacle
    /// ends up nowhere near its template, and a junction chosen off the guess
    /// would not exist on the real trunk.
    ///
    /// The probe is deterministic, so the real pass reproduces its geometry
    /// exactly (the only difference is the `keep` set, which changes whether a
    /// refresh repeater may land on a junction cell, never the corridor).
    fn probe_trunk_runs(
        &self,
        exclude: Option<&str>,
        style: &BusStyle,
        occ: &OccupancyIndex,
        waypoints: &[P3],
        width: u8,
    ) -> Result<Vec<RunInfo>, String> {
        let mut probe = Planner::new(self, exclude, style, occ);
        let mut since = 0u32;
        for (i, pair) in waypoints.windows(2).enumerate() {
            probe.begin_segment(SegmentKind::Trunk(i), pair[0], pair[1]);
            since = probe
                .plan_pair(pair[0], pair[1], width, &BTreeSet::new(), since)
                .map_err(|e| format!("segment {:?} -> {:?}: {e}", pair[0], pair[1]))?;
            probe.end_segment();
            since = since.saturating_add(1);
        }
        Ok(probe
            .finish()
            .segments
            .iter()
            .flat_map(|s| s.runs.clone())
            .collect())
    }

    /// The trunk's straight runs from its waypoint chain, choosing the
    /// x-first corner for non-straight pairs (deterministic; the planner
    /// may flip a congested corner z-first at plan time).
    #[allow(dead_code)]
    fn trunk_geometry(waypoints: &[P3], width: u8) -> Result<Vec<RunInfo>, String> {
        let mut runs = Vec::new();
        for pair in waypoints.windows(2) {
            let (a, b) = (pair[0], pair[1]);
            if a == b {
                return Err(format!("segment {:?} -> {:?}: zero length", a, b));
            }
            if a.2 == b.2 && a.0 != b.0 {
                runs.push(RunInfo {
                    along_x: true,
                    fixed: a.2,
                    y0: a.1,
                    from: a.0,
                    to: b.0,
                    width,
                });
            } else if a.0 == b.0 && a.2 != b.2 {
                runs.push(RunInfo {
                    along_x: false,
                    fixed: a.0,
                    y0: a.1,
                    from: a.2,
                    to: b.2,
                    width,
                });
            } else {
                runs.push(RunInfo {
                    along_x: true,
                    fixed: a.2,
                    y0: a.1,
                    from: a.0,
                    to: b.0,
                    width,
                });
                runs.push(RunInfo {
                    along_x: false,
                    fixed: b.0,
                    y0: a.1,
                    from: a.2,
                    to: b.2,
                    width,
                });
            }
        }
        Ok(runs)
    }

    /// Find the trunk run an extra endpoint can join with one
    /// perpendicular straight shot; returns the branch run and the
    /// junction cell (bit 0) on the trunk.
    fn branch_geometry(
        trunk: &[RunInfo],
        port: &DesignPort,
        is_driver: bool,
    ) -> Result<(RunInfo, P3), String> {
        let s = port.anchor;
        for r in trunk {
            if r.y0 != s.1 {
                continue;
            }
            let (along_coord, cross_coord) = if r.along_x { (s.0, s.2) } else { (s.2, s.0) };
            if cross_coord == r.fixed || !r.strictly_inside(along_coord, 2) {
                continue;
            }
            let junction = if r.along_x {
                (s.0, s.1, r.fixed)
            } else {
                (r.fixed, s.1, s.2)
            };
            let (from, to) = if is_driver {
                (cross_coord, r.fixed)
            } else {
                (r.fixed, cross_coord)
            };
            let run = RunInfo {
                along_x: !r.along_x,
                fixed: along_coord,
                y0: s.1,
                from,
                to,
                width: port.width,
            };
            return Ok((run, junction));
        }
        Err(format!(
            "no trunk run aligns with `{}` at {:?} (needs a perpendicular straight shot into \
             the trunk interior); add a gate",
            port.name, s
        ))
    }

    // ------------------------------------------------------------------
    // flatten / check / bake
    // ------------------------------------------------------------------

    /// One instance's non-air blocks in WORLD space, transform applied.
    ///
    /// The single definition of "where an instance's blocks actually are",
    /// shared by [`Design::flatten`] and
    /// [`Design::instance_blocks_json`] so a viewer can never disagree with an
    /// export about an instance's position.
    fn placed_instance_blocks(&self, inst: &Instance) -> BTreeMap<P3, crate::BlockState> {
        let cell = &self.cells[&inst.cell];
        let bbox = cell_bounds(&cell.schematic);
        let mut out = BTreeMap::new();
        for (bp, bs) in self.instance_local_blocks(inst) {
            if bs.to_string().contains("minecraft:air") {
                continue;
            }
            let p = transform_pos(bp, bbox.min, bbox.max, inst.rot_y, inst.at);
            out.insert(p, transform_state(&bs, inst.rot_y));
        }
        // A PROMOTED port's dust is authored before any bus exists, so in
        // isolation it is correctly a dot; once a bus lands on it, it must be
        // drawn connected. This is the single definition of where an instance's
        // blocks are — shared by `flatten` and `instance_blocks_json` — so
        // deriving here is what keeps a viewer and an export agreeing about it.
        //
        // ONLY the promotion patch's OWN cells. A placed cell is a verified
        // black box: its interior wire states were authored by whoever built
        // it, over blocks the wire model does not classify, and rewriting them
        // breaks working redstone — measured, when this pass covered every dust
        // in the body it turned the ADD007 -> BINTOBCD001 chain's arithmetic
        // wrong (1+1 read 0).
        let ours: BTreeSet<P3> = inst
            .port_modes
            .values()
            .filter(|o| o.mode == PortMode::Bus)
            .flat_map(|o| o.patch.writes.keys())
            .map(|bp| transform_pos(*bp, bbox.min, bbox.max, inst.rot_y, inst.at))
            .collect();
        let dust: Vec<P3> = out
            .iter()
            .filter(|(p, b)| ours.contains(p) && rblocks::is_dust(&b.to_string()))
            .map(|(p, _)| *p)
            .collect();
        if !dust.is_empty() {
            let mine: BTreeMap<P3, String> = out.iter().map(|(p, b)| (*p, b.to_string())).collect();
            let at = |q: P3| -> Option<String> {
                mine.get(&q).cloned().or_else(|| self.neighbour_block(q))
            };
            for p in dust {
                let power = crate::routing::engine::wire::power_of(&mine[&p]);
                let derived = crate::routing::engine::wire::derive(p, power, &at);
                if let Ok(bs) = crate::BlockState::from_block_string(&derived) {
                    out.insert(p, bs);
                }
            }
        }
        out
    }

    /// The block at `p` from the layers that can sit beside an instance: the
    /// routed bus fragments and the loose layer. Other INSTANCES are skipped on
    /// purpose — influence halos keep two of them from ever touching, so paying
    /// to scan them all on every neighbour lookup would buy nothing.
    fn neighbour_block(&self, p: P3) -> Option<String> {
        for bus in self.buses.values() {
            if let Some(b) = bus.fragment.get(&p) {
                return Some(b.clone());
            }
        }
        self.base
            .get_block(p.0, p.1, p.2)
            .map(|b| b.to_string())
            .filter(|b| !b.contains("minecraft:air"))
    }

    /// `[[x,y,z,"block"],..]` for ONE bus layer's cells.
    ///
    /// Exists for live re-routing: fetching a single changed bus through
    /// [`Design::flatten`] means rebuilding every layer in the document (~22ms
    /// on a real design) to read back a few hundred cells. This reads the bus's
    /// own fragment directly. An unrouted bus has no cells and yields `[]` —
    /// that is a legal answer, not an error, so a caller can poll a bus it just
    /// failed to route without special-casing.
    ///
    /// Positional array-of-arrays rather than `{"at":..,"block":..}` on purpose:
    /// the whole point is byte volume across the bridge.
    pub fn bus_blocks_json(&self, name: &str) -> Result<String, String> {
        let bus = self
            .buses
            .get(name)
            .ok_or_else(|| format!("unknown bus `{name}`"))?;
        Ok(Self::cells_json(
            bus.fragment.iter().map(|(p, b)| (*p, b.as_str())),
        ))
    }

    /// `[[x,y,z,"block"],..]` for ONE instance's placed blocks, transform
    /// applied. Same reasoning as [`Design::bus_blocks_json`].
    pub fn instance_blocks_json(&self, name: &str) -> Result<String, String> {
        let inst = self
            .instances
            .iter()
            .find(|i| i.name == name)
            .ok_or_else(|| format!("unknown instance `{name}`"))?;
        let placed: Vec<(P3, String)> = self
            .placed_instance_blocks(inst)
            .into_iter()
            .map(|(p, b)| (p, b.to_string()))
            .collect();
        Ok(Self::cells_json(
            placed.iter().map(|(p, b)| (*p, b.as_str())),
        ))
    }

    /// Render `(pos, block)` pairs as `[[x,y,z,"block"],..]`.
    fn cells_json<'a>(cells: impl Iterator<Item = (P3, &'a str)>) -> String {
        let items: Vec<String> = cells
            .map(|(p, b)| {
                // Block states are `ns:name[k=v,..]` — no quotes to escape in
                // practice, but go through the serializer rather than trusting
                // that: a malformed state must not be able to forge JSON.
                let block = serde_json::to_string(b).unwrap_or_else(|_| "\"\"".to_string());
                format!("[{},{},{},{}]", p.0, p.1, p.2, block)
            })
            .collect();
        format!("[{}]", items.join(","))
    }

    /// Collapse the layer stack into ONE self-describing schematic: the
    /// loose layer stays in the base regions, every instance becomes region
    /// `inst:{name}`, every routed bus region `bus:{name}`, and the merged
    /// transformed contract is embedded in the metadata — the artifact is
    /// itself placeable as a cell.
    pub fn flatten(&self) -> Result<UniversalSchematic, String> {
        let mut flat = self.base.clone();
        flat.metadata.name = Some(self.name.clone());

        for inst in &self.instances {
            let region = format!("inst:{}", inst.name);
            for (p, state) in self.placed_instance_blocks(inst) {
                if !flat.set_block_in_region(&region, p.0, p.1, p.2, &state) {
                    return Err(format!(
                        "flatten: could not place {state} at {p:?} in region {region}"
                    ));
                }
            }
        }

        for bus in self.buses.values() {
            if bus.state != BusState::Routed {
                continue;
            }
            let region = format!("bus:{}", bus.name);
            for (p, b) in &bus.fragment {
                flat.try_set_block_in_region_str(&region, p.0, p.1, p.2, b)?;
            }
        }

        let contract = self.merged_contract()?;
        flat.set_cell_contract(&contract)?;
        Ok(flat)
    }

    /// The electrical artifact needed to validate one freshly routed bus.
    ///
    /// Unrelated placed instances are verified black boxes behind keepouts: the
    /// acceptance checks below explicitly discard findings inside them, and the
    /// clearance pass has already proved that this bus does not couple to them.
    /// Materialising every block of every unrelated cell here made validation
    /// scale with the whole canvas (1.8 s for one route beside ten idle cells).
    /// Keep the loose layer, every routed bus, and only the instances that own
    /// this bus's endpoints. That preserves pin-access electrical context while
    /// making validation scale with the route being accepted.
    fn validation_flat(&self, name: &str) -> Result<UniversalSchematic, String> {
        let layer = self
            .buses
            .get(name)
            .ok_or_else(|| format!("unknown bus `{name}`"))?;
        let endpoints: Vec<String> = layer
            .driver_names()
            .into_iter()
            .chain(layer.sinks.iter().cloned())
            .collect();
        // Only the pin-access neighbourhood participates electrically in the
        // design fabric. The rest of an endpoint instance is the black box we
        // deliberately exempt below, so feeding its thousands of internal
        // cells through LVS/DRC buys no coverage. One-cell context includes the
        // terminal dust, its support/cut cells, and directional diode inputs.
        let mut pin_context: BTreeMap<String, BTreeSet<P3>> = BTreeMap::new();
        for endpoint in &endpoints {
            let Some((instance, _)) = endpoint.split_once('.') else {
                continue;
            };
            let Ok(port) = self.resolve_port(endpoint) else {
                continue;
            };
            let mut pins = port.wires();
            for bit in &port.bits {
                pins.extend(bit.lever);
                pins.extend(bit.lamp);
            }
            let context = pin_context.entry(instance.to_string()).or_default();
            for p in pins {
                for dx in -1..=1 {
                    for dy in -1..=1 {
                        for dz in -1..=1 {
                            context.insert((p.0 + dx, p.1 + dy, p.2 + dz));
                        }
                    }
                }
            }
        }

        let mut flat = self.base.clone();
        flat.metadata.name = Some(format!("{}:{name}:validation", self.name));
        for inst in &self.instances {
            let Some(context) = pin_context.get(&inst.name) else {
                continue;
            };
            let region = format!("inst:{}", inst.name);
            for (p, state) in self.placed_instance_blocks(inst) {
                if !context.contains(&p) {
                    continue;
                }
                if !flat.set_block_in_region(&region, p.0, p.1, p.2, &state) {
                    return Err(format!(
                        "validation: could not place {state} at {p:?} in region {region}"
                    ));
                }
            }
        }
        for bus in self.buses.values() {
            if bus.state != BusState::Routed {
                continue;
            }
            let region = format!("bus:{}", bus.name);
            for (p, block) in &bus.fragment {
                flat.try_set_block_in_region_str(&region, p.0, p.1, p.2, block)?;
            }
        }
        Ok(flat)
    }

    /// The merged contract of the flattened artifact: every design port
    /// (executor-facing positions: levers for drivable inputs, connection
    /// dust for outputs) plus every instance port under `{inst}.{port}`,
    /// transformed.
    pub fn merged_contract(&self) -> Result<CellContract, String> {
        let mut builder = crate::io_contract::IoLayoutBuilder::new();
        for port in self.ports.values() {
            match port.direction {
                PortDirection::Input => {
                    let levers: Vec<P3> = port
                        .bits
                        .iter()
                        .enumerate()
                        .map(|(k, hw)| {
                            hw.lever.ok_or_else(|| {
                                format!("input `{}` bit {k} lost its lever", port.name)
                            })
                        })
                        .collect::<Result<_, String>>()?;
                    builder = builder.add_input(
                        port.name.clone(),
                        port.ty.clone(),
                        LayoutFunction::OneToOne,
                        levers,
                    )?;
                }
                PortDirection::Output => {
                    builder = builder.add_output(
                        port.name.clone(),
                        port.ty.clone(),
                        LayoutFunction::OneToOne,
                        port.wires(),
                    )?;
                }
            }
        }
        for inst in &self.instances {
            let transformed = self.instance_contract(&inst.name)?;
            for (pname, mapping) in &transformed.io.inputs {
                builder = builder.add_input(
                    format!("{}.{}", inst.name, pname),
                    mapping.io_type.clone(),
                    mapping.layout.clone(),
                    mapping.positions.clone(),
                )?;
            }
            for (pname, mapping) in &transformed.io.outputs {
                builder = builder.add_output(
                    format!("{}.{}", inst.name, pname),
                    mapping.io_type.clone(),
                    mapping.layout.clone(),
                    mapping.positions.clone(),
                )?;
            }
        }
        Ok(CellContract::new(self.name.clone(), builder.build()))
    }

    /// The LVS intent netlist of the routed buses: one net per bit, its
    /// terminals the driver and sink connection cells.
    pub fn intent_nets(&self) -> Vec<crate::routing::IntentNet> {
        use crate::routing::Pos;
        let mut nets = Vec::new();
        for bus in self.buses.values() {
            if bus.state != BusState::Routed {
                continue;
            }
            let Ok(driver) = self.resolve_port(&bus.driver) else {
                continue;
            };
            // A WIDTH-ADAPTED bus does not pair bit k with bit k: driver bit
            // `from_bit + i` drives sink bit `from_bit + i + shift`, and the
            // sink bits nothing drives are not part of any net (undriven dust is
            // logical 0, not a broken connection). Pairing by index here would
            // report the whole bus as opens and shorts.
            let (first, count, shift) = bus
                .width_map
                .as_ref()
                .map_or((0u8, driver.width, 0i32), |m| (m.from_bit, m.bits, m.shift));
            for i in 0..count {
                let bit = first + i;
                let sink_bit = bit as i32 + shift;
                // ONE net per bit: every driver (wired-OR merges stay one
                // intent net) plus every sink.
                // `resolve_port`, NOT `self.ports`: an INSTANCE port (`u0.q`) is
                // derived from the cell contract and is not in the declared-port
                // map, so looking there produced NO terminals, hence no intent
                // net, hence no LVS coverage whatsoever for any bus wired
                // between placed cells. Every such bus was silently exempt from
                // the open/short check — which is most of
                // `tests/design_routability.rs` and the whole studio use case.
                let mut terminals = Vec::new();
                for dn in bus.driver_names() {
                    if let Ok(dp) = self.resolve_port(&dn) {
                        terminals.push(dp.wire(bit));
                    }
                }
                for s in &bus.sinks {
                    if let Ok(sp) = self.resolve_port(s) {
                        terminals.push(sp.wire(sink_bit.max(0) as u8));
                    }
                }
                nets.push(crate::routing::IntentNet {
                    name: format!("{}[{}]", bus.name, bit),
                    terminals: terminals
                        .into_iter()
                        .map(|(x, y, z)| Pos::new(x, y, z))
                        .collect(),
                });
            }
        }
        nets
    }

    /// Intent nets for one bus only. Completed-route acceptance has already run
    /// mechanism-aware clearance against foreign geometry, so LVS here needs to
    /// prove this bus's lanes end-to-end and against one another—not re-extract
    /// every unrelated net on the canvas.
    fn intent_nets_for_bus(&self, name: &str) -> Vec<crate::routing::IntentNet> {
        let prefix = format!("{name}[");
        self.intent_nets()
            .into_iter()
            .filter(|net| net.name.starts_with(&prefix))
            .collect()
    }

    /// Why this bus's realized geometry must NOT be reported as a success, if
    /// there is a reason.
    ///
    /// A ROUTE THAT REPORTS SUCCESS AND DOES NOT CONDUCT IS WORSE THAN ONE THAT
    /// HONESTLY FAILS. Until this existed, realization asked only "did every
    /// cell get placed without colliding" — a STRUCTURAL question. It never
    /// asked the electrical one: does the signal ARRIVE? The corpus found the
    /// gap with a one-wall fixture (`O03_flat_obstacle`): a flat bundle detoured
    /// around an obstacle, came back `routed`, and in simulation carried 1 of 12
    /// words, some lanes dead and some shorted together.
    ///
    /// The question is asked over the SAME extractor `check` uses, so the two
    /// can never disagree: conduction components are extracted from the emitted
    /// cells and compared against this bus's per-bit intent
    /// ([`Design::intent_nets`]). An intent net split across components is a
    /// DEAD LANE; two intent nets sharing a component are LANES SHORTED
    /// TOGETHER; both are reported as the failure they are, with the bit named.
    ///
    /// Structural DRC on the bus's own cells is folded in too, because a bus
    /// that lays an accidental repeater ring is not routed either — that is the
    /// other half of what O03 emitted.
    ///
    /// Deliberately NOT a simulation: this is symbolic reachability over placed
    /// blocks, the same cost as `check`, so it can run on every accepted route.
    fn conduction_reason(&self, name: &str) -> Option<String> {
        let flat = match self.validation_flat(name) {
            Ok(f) => f,
            Err(e) => return Some(format!("the realized geometry could not be flattened: {e}")),
        };
        let ws = crate::routing::workspace_from_schematic(&flat);
        let lvs = crate::routing::lvs(ws.cells(), &self.intent_nets_for_bus(name));
        let prefix = format!("{name}[");
        let mine = |n: &String| n.starts_with(&prefix);
        let mut why: Vec<String> = Vec::new();

        // THE CELL BOUNDARY APPLIES HERE TOO, and forgetting it produced a
        // spectacular false positive: the ADD007 -> BINTOBCD001 chain, verified
        // 8/8 in simulation, was rejected as "all eight bits shorted". Its
        // terminals are the adder's own stacked output LAMPS, and lamps are
        // solid conductors, so the extractor merges the whole column — inside a
        // placed cell, which is a verified black box behind its keepout. A
        // finding whose every witness lies inside one instance is that cell's
        // internal business, exactly as `Design::check` already treats it.
        let bodies = self.instance_bodies();
        let port_hw = self.port_hardware_cells();
        let in_a_cell = |cells: &[crate::routing::Pos]| -> bool {
            !cells.is_empty()
                && cells.iter().all(|q| {
                    let p = (q.x, q.y, q.z);
                    bodies.iter().any(|b| b.contains(&p))
                })
        };
        // Port hardware excuses a SHORT (a lever bank merges its own bits) but
        // never an OPEN. An open's witnesses ARE the terminals, which are port
        // wires by definition, so folding port hardware in here would skip every
        // dead lane there is — including `O03_flat_obstacle`, the fixture this
        // gate was built for.
        let interior = |cells: &[crate::routing::Pos]| -> bool {
            in_a_cell(cells)
                || (!cells.is_empty() && cells.iter().all(|q| port_hw.contains(&(q.x, q.y, q.z))))
        };

        for o in &lvs.opens {
            if !mine(&o.net) || in_a_cell(&o.fragments.concat()) {
                continue;
            }
            let ends: Vec<String> = o
                .fragments
                .iter()
                .map(|f| {
                    let ps: Vec<String> = f
                        .iter()
                        .map(|p| format!("({},{},{})", p.x, p.y, p.z))
                        .collect();
                    format!("[{}]", ps.join(" "))
                })
                .collect();
            why.push(format!(
                "net `{}` does NOT conduct end to end: its terminals fall in {} separate \
                 conduction groups {} — the route was laid but the signal cannot cross",
                o.net,
                o.fragments.len(),
                ends.join(" vs ")
            ));
        }
        // A SHORT THIS ROUTE DID NOT CAUSE IS NOT THIS ROUTE'S FAILURE.
        //
        // Two false positives were found this way, and the second proved the
        // first fix was too narrow. A port's own hardware column frequently
        // merges its bits all by itself: the ADD007 adder's stacked output LAMPS
        // do it inside an instance (caught by the cell-boundary rule below), and
        // a LEVER BANK in the design's own loose layer does it with no instance
        // anywhere — same wrong verdict, no black box to blame it on.
        //
        // So the question asked is differential: which shorts appear only WITH
        // this bus's cells in place. `pre_shorts` is the same extraction over the
        // same geometry minus this bus's fragment, with its intent nets still
        // declared so the pairs remain comparable. Anything already merged
        // without us is the port's construction, not our route.
        //
        // Deliberately NOT done for OPENS: with the fragment removed every net
        // of this bus is trivially open — that is the whole point of the route —
        // so baselining them would mask exactly the dead lanes this gate exists
        // to catch.
        // Differential short baselining is expensive: it rebuilds the flattened
        // design and extracts every conduction component a second time.  The
        // baseline is only consulted for a short involving THIS bus, so do not
        // pay for it on the overwhelmingly common clean path.  Cell-interior and
        // port-hardware shorts are already exempt and need no baseline either.
        let needs_short_baseline = lvs
            .shorts
            .iter()
            .any(|s| (mine(&s.net_a) || mine(&s.net_b)) && !interior(&[s.at_a, s.at_b]));
        let pre_shorts = needs_short_baseline
            .then(|| self.shorts_without_fragment(name))
            .unwrap_or_default();
        for s in &lvs.shorts {
            if !mine(&s.net_a) && !mine(&s.net_b) {
                continue;
            }
            if interior(&[s.at_a, s.at_b]) {
                continue;
            }
            if pre_shorts.contains(&short_key(&s.net_a, &s.net_b)) {
                continue;
            }
            why.push(format!(
                "nets `{}` and `{}` are SHORTED: they share one conduction component, \
                 witnessed at ({},{},{}) and ({},{},{}) — the lanes would carry each \
                 other's value",
                s.net_a, s.net_b, s.at_a.x, s.at_a.y, s.at_a.z, s.at_b.x, s.at_b.y, s.at_b.z
            ));
        }

        // Structural findings on cells THIS bus laid. Scoped to our own
        // fragment so a pre-existing defect elsewhere (a community cell's
        // interior, another layer's mess) is never blamed on this route.
        let fragment: BTreeSet<P3> = self
            .buses
            .get(name)
            .map(|b| b.fragment.keys().copied().collect())
            .unwrap_or_default();
        let ours = |cells: &[P3]| cells.iter().any(|c| fragment.contains(c));
        for ring in &lvs.cycles {
            if interior(ring) {
                continue; // a register's latch IS a repeater ring, by design
            }
            let cells: Vec<P3> = ring.iter().map(|p| (p.x, p.y, p.z)).collect();
            if ours(&cells) {
                why.push(format!(
                    "the route closes a REPEATER RING through {cells:?} — an accidental latch, \
                     so the bus would hold a value of its own instead of passing one through"
                ));
            }
        }
        let opts = crate::routing::DrcOptions {
            aliases: vec![],
            skip_decay: true,
        };
        // `ws` was built from this exact flattened artifact for LVS above.
        // Reuse it instead of walking the schematic and allocating the same
        // workspace again for DRC.
        for v in crate::routing::drc(&ws, &opts) {
            if self.is_inside_an_instance(&v) {
                continue; // a placed cell's interior is its own business
            }
            if ours(&Self::violation_cells(&v)) {
                why.push(format!("the route violates a design rule: {v:?}"));
            }
        }

        if why.is_empty() {
            return None;
        }
        // Bounded: a bundle that fails wholesale would otherwise produce one
        // line per bit and bury the cause.
        let shown = why.len().min(4);
        let more = why.len() - shown;
        Some(format!(
            "routed geometry does not conduct: {}{}",
            why[..shown].join("; "),
            if more > 0 {
                format!(" (and {more} more)")
            } else {
                String::new()
            }
        ))
    }

    /// Every cell that belongs to a PORT's own hardware: its connection wires,
    /// its levers and its lamps, for declared and instance ports alike.
    ///
    /// A port's hardware routinely merges its own bits — eight levers or eight
    /// lamps stacked on one conducting support column is the normal shape of a
    /// bank — and that merge is a property of the port, not of any route that
    /// lands on it. The design did not author it and cannot change it without
    /// `set_port_mode`, so blaming a bus for it makes `check` permanently dirty
    /// on geometry that simulates correctly.
    fn port_hardware_cells(&self) -> BTreeSet<P3> {
        let mut out = BTreeSet::new();
        let mut add = |p: &DesignPort| {
            out.extend(p.wires());
            for b in &p.bits {
                out.extend(b.lever);
                out.extend(b.lamp);
            }
        };
        for p in self.ports.values() {
            add(p);
        }
        if let Ok(ports) = self.instance_ports() {
            for ip in ports {
                if let Some(wires) = &ip.wires {
                    out.extend(wires.iter().copied());
                }
                out.extend(ip.hardware.iter().copied());
            }
        }
        out
    }

    /// The net pairs already merged when this bus's cells are taken away.
    ///
    /// The baseline for [`Design::conduction_reason`]'s short check: the same
    /// extraction over the same geometry with this bus's fragment replaced by
    /// air, its intent nets still declared so the reported pairs stay
    /// comparable. Whatever is merged here was merged by the ports' own
    /// hardware — a lever bank or lamp column on a shared conducting support —
    /// and blaming the route for it rejects perfectly good geometry.
    fn shorts_without_fragment(&self, name: &str) -> BTreeSet<(String, String)> {
        let Some(layer) = self.buses.get(name) else {
            return BTreeSet::new();
        };
        let Ok(mut flat) = self.flatten() else {
            return BTreeSet::new();
        };
        for (p, _) in &layer.fragment {
            let _ = flat.set_block_from_string(p.0, p.1, p.2, "minecraft:air");
        }
        let ws = crate::routing::workspace_from_schematic(&flat);
        crate::routing::lvs(ws.cells(), &self.intent_nets_for_bus(name))
            .shorts
            .iter()
            .map(|s| short_key(&s.net_a, &s.net_b))
            .collect()
    }

    /// Why this bus's geometry must not be accepted on CLEARANCE grounds.
    ///
    /// The router avoided every OCCUPIED cell correctly and then ran its own
    /// wire alongside a live foreign one. `X02_hex_cross_vertical`: bit 0 was
    /// laid at (7,2,-1)..(9,2,-1), DIAGONALLY adjacent to a hex trunk's live
    /// readout dust at (8,1,0) — one down, one over, which is a conducting dust
    /// diagonal — and bit 0 came out stuck high whenever the trunk carried a
    /// value. The control with the trunk idle passes 12/12, so the geometry was
    /// never the problem; the missing clearance was.
    ///
    /// WHY THIS IS CHECKED HERE AND NOT IN THE SEARCH. Until now
    /// `nucleation_routing::transport::interferes` had exactly ONE caller, the
    /// corridor search in [`crate::design_corridor`]. Straight runs, L corners,
    /// form adapters and level-shift tiles emit geometry without ever asking —
    /// which is why a defect this basic survived: most routes never touch the
    /// one code path that knew the rule. Asking over the finished fragment
    /// covers every emitter at once, including the three that have no search.
    ///
    /// LVS cannot substitute for this. LVS compares INTENT NETS, and the hex
    /// trunk is a fixture with no intent net at all, so a bit merging with it is
    /// not a short between two intents — there is no pair to report. Coupling to
    /// something that was never declared as a net is invisible to it by
    /// construction.
    ///
    /// [`NetClassRule::spacing`] is finally read on the routing path here: it is
    /// EXTRA clearance beyond the mechanism rules, so `spacing = n` additionally
    /// demands `n` cells of empty separation from foreign live redstone (a clock
    /// line asking not to be coupled at all).
    fn clearance_reason(&self, name: &str) -> Option<String> {
        let layer = self.buses.get(name)?;
        if layer.fragment.is_empty() {
            return None;
        }
        let extra = layer.rule.as_ref().map_or(0i32, |r| i32::from(r.spacing));
        // Foreign geometry: everything placed EXCEPT this bus's own cells.
        // Instances that own an endpoint are exempt wholesale, matching
        // `halo_exempt`: routing INTO the cell you are wiring to is what a pin
        // is for, and its port dust is supposed to touch ours.
        let endpoints: Vec<String> = layer
            .driver_names()
            .into_iter()
            .chain(layer.sinks.iter().cloned())
            .collect();
        let pin_access = self.halo_exempt(&endpoints);
        let occ = self.occupancy_index();
        let mut ours_cells: BTreeSet<P3> = layer.fragment.keys().copied().collect();
        // THE BUS'S OWN TERMINALS ARE NOT A CLEARANCE VIOLATION. A declared
        // design port sits on hardware in the BASE schematic, so it is owned by
        // the loose layer rather than an instance and `halo_exempt` does not
        // reach it — and the route is supposed to land on that dust and drive
        // that lever. Without this the check rejected essentially every bus in
        // the suite for touching its own port.
        for ep in &endpoints {
            if let Ok(p) = self.resolve_port(ep) {
                ours_cells.extend(p.wires());
                for b in &p.bits {
                    ours_cells.extend(b.lever);
                    ours_cells.extend(b.lamp);
                }
            }
        }
        let view = FragmentView {
            occ: &occ,
            frag: &layer.fragment,
        };
        const OURS: &str = "\0bus-under-test";

        let mut why: Vec<String> = Vec::new();
        for (p, block) in &layer.fragment {
            let ours = crate::routing::transport::Placement {
                mech: crate::routing::transport::mech_of(block),
                cell: crate::routing::Pos::new(p.0, p.1, p.2),
                fwd: crate::routing::transport::fwd_of(block),
                net: OURS,
            };
            for q in clearance_scan(*p, extra) {
                if ours_cells.contains(&q) {
                    continue; // our own geometry is one net by construction
                }
                let Some((fblock, owner)) = occ.cells.get(&q) else {
                    continue;
                };
                let fowner = match owner {
                    Occupant::Loose => "loose block".to_string(),
                    Occupant::Instance(n) => {
                        if pin_access.contains(n) {
                            continue; // the cell this bus terminates on
                        }
                        format!("instance `{n}`")
                    }
                    Occupant::Bus(n) => {
                        if n == name {
                            continue;
                        }
                        format!("bus `{n}`")
                    }
                };
                let theirs = crate::routing::transport::Placement {
                    mech: crate::routing::transport::mech_of(fblock),
                    cell: crate::routing::Pos::new(q.0, q.1, q.2),
                    fwd: crate::routing::transport::fwd_of(fblock),
                    net: &fowner,
                };
                // Only LIVE foreign hardware couples. An inert flank emits
                // nothing and reads nothing; that exemption is the whole point
                // of the mechanism model and must survive.
                if !is_live_mech(theirs.mech) {
                    continue;
                }
                if let Some(rel) = crate::routing::transport::interferes(&theirs, &ours, &view) {
                    why.push(format!(
                        "{fowner} at {q:?} couples to this bus at {p:?}: {rel}"
                    ));
                    continue;
                }
                // EXTRA spacing is a separation demand, not a mechanism
                // relation: at `spacing = n` no foreign live cell may sit
                // within n cells at all, coupling or not.
                if extra > 0 && chebyshev(*p, q) <= extra {
                    why.push(format!(
                        "{fowner} at {q:?} is within the declared spacing of {extra} \
                         cell(s) of this bus at {p:?}"
                    ));
                }
            }
        }
        if why.is_empty() {
            return None;
        }
        why.sort();
        why.dedup();
        let shown = why.len().min(3);
        let more = why.len() - shown;
        Some(format!(
            "routed geometry has insufficient clearance from live redstone: {}{}. \
             Move one of them, or give the bus a lane 2 cells clear (dust one cell \
             apart shorts, and a 1-y diagonal conducts unless the cut cell is solid)",
            why[..shown].join("; "),
            if more > 0 {
                format!(" (and {more} more)")
            } else {
                String::new()
            }
        ))
    }

    /// Drop a bus's realized geometry and record why it failed.
    fn set_failed(&mut self, name: &str, reason: String) -> BusState {
        self.touch_bus(name);
        let layer = self.buses.get_mut(name).expect("caller holds the bus");
        layer.fragment.clear();
        layer.runs.clear();
        layer.segments.clear();
        layer.gate_cells.clear();
        layer.state = BusState::Failed(reason.clone());
        BusState::Failed(reason)
    }

    /// Gate a freshly realized route: `Routed` only if the signal actually
    /// arrives AND nothing live is close enough to corrupt it. Otherwise
    /// `Failed` with the electrical reason.
    ///
    /// Clearance is asked FIRST: a bus coupled to a foreign live net is the more
    /// specific diagnosis, and reporting "does not conduct" for geometry whose
    /// real problem is a neighbour would send the user looking in the wrong
    /// place.
    fn accept_if_conducting(&mut self, name: &str) -> BusState {
        if let Some(why) = self.clearance_reason(name) {
            return self.set_failed(name, why);
        }
        match self.conduction_reason(name) {
            None => BusState::Routed,
            Some(why) => self.set_failed(name, why),
        }
    }

    /// DRC + LVS + STA/skew over the flattened artifact, plus the per-bus
    /// net-class rules. `clean` requires clean DRC, clean LVS and zero
    /// rule violations; STA numbers are advisory unless a rule bounds
    /// them (`max_len_rt`).
    pub fn check(&self) -> Result<DesignCheck, String> {
        let flat = self.flatten()?;
        let opts = crate::routing::DrcOptions {
            aliases: vec![],
            skip_decay: true,
        };
        let all = crate::routing::drc_schematic(&flat, &opts);
        // Split the DRC report at the cell boundary. A placed cell is a
        // VERIFIED BLACK BOX behind its keepout: hand-built community redstone
        // legitimately breaks the route-oriented conventions these rules
        // encode (one 8-bit community adder reports 253 "floating" cells for
        // dust our support predicate does not recognise), and blaming the
        // design for a library cell's interior means `check()` is never clean
        // and the whole report becomes noise. Interior findings are reported
        // under `cells` for information; only what the DESIGN itself owns —
        // the loose layer and the routed bus fragments — gates `clean`.
        let (violations, cell_violations): (Vec<_>, Vec<_>) = all
            .into_iter()
            .partition(|v| !self.is_inside_an_instance(v));
        let ws = crate::routing::workspace_from_schematic(&flat);
        let lvs = crate::routing::lvs(ws.cells(), &self.intent_nets());
        let (sta_json, rule_violations) = self.sta_and_rules(&flat);
        // The cell boundary applies to LVS too, and here it is not merely
        // noise-reduction: a register's latch IS a repeater ring, so
        // `lvs.cycles` reports every memory cell in the library as an
        // "accidental latch". A ring living entirely inside one placed cell is
        // that cell's verified internal state, not a design error.
        let bodies = self.instance_bodies();
        // A finding nobody could act on is not a gating violation: either it
        // lives inside a placed cell (a verified black box), or its witnesses
        // are a PORT's own hardware — eight levers on one conducting support
        // column merge their bits by construction, whoever wires them.
        let port_hw = self.port_hardware_cells();
        let in_a_cell = |cells: &[crate::routing::Pos]| -> bool {
            !cells.is_empty()
                && cells.iter().all(|q| {
                    let p = (q.x, q.y, q.z);
                    bodies.iter().any(|b| b.contains(&p))
                })
        };
        // Port hardware excuses a SHORT, never an OPEN: an open's witnesses are
        // the terminals themselves, so folding it in there would hide every
        // dead net in the design.
        let interior = |cells: &[crate::routing::Pos]| -> bool {
            in_a_cell(cells)
                || (!cells.is_empty() && cells.iter().all(|q| port_hw.contains(&(q.x, q.y, q.z))))
        };
        let design_cycles = lvs.cycles.iter().filter(|ring| !interior(ring)).count();
        let design_shorts = lvs
            .shorts
            .iter()
            .filter(|s| !interior(&[s.at_a, s.at_b]))
            .count();
        let design_opens = lvs
            .opens
            .iter()
            .filter(|o| !in_a_cell(&o.fragments.concat()))
            .count();
        // A bus reported ROUTED must have built something. Nothing upstream can
        // produce this any more (`realize` refuses an empty plan outright), but
        // it is asserted here too because it is the single worst state to ship:
        // green status, empty layer, and a viewer that trusts the status draws
        // nothing and reports success.
        let empty_routed: Vec<String> = self
            .buses
            .values()
            .filter(|b| b.state == BusState::Routed && b.fragment.is_empty())
            .map(|b| b.name.clone())
            .collect();
        let clean = violations.is_empty()
            && design_opens == 0
            && design_shorts == 0
            && design_cycles == 0
            && rule_violations.is_empty()
            && empty_routed.is_empty();
        let bus_states: Vec<String> = self
            .buses
            .values()
            .map(|b| {
                let state = match &b.state {
                    BusState::Intended => "\"intended\"".to_string(),
                    BusState::Routed => "\"routed\"".to_string(),
                    BusState::Failed(r) => format!("{{\"failed\":{:?}}}", r),
                };
                // Report the VECTOR, not a scalar: five components per bus, so
                // a human can see why a route was chosen and no single
                // dimension can be optimised in isolation again.
                let cost = self.bus_cost(b);
                format!(
                    "{:?}:{{\"state\":{state},\"cost\":{},\"weighted\":{:.1}}}",
                    b.name,
                    cost.to_json(),
                    b.cost.total(&cost)
                )
            })
            .collect();
        let mut rules: Vec<String> = rule_violations.iter().map(|r| format!("{r:?}")).collect();
        for name in &empty_routed {
            rules.push(format!(
                "{:?}",
                format!("bus `{name}` reports ROUTED but built no cells")
            ));
        }
        let json = format!(
            "{{\"clean\":{clean},\"drc\":{},\"cells\":{},\"lvs\":{},\"buses\":{{{}}},\
             \"sta\":{sta_json},\"rules\":[{}]}}",
            crate::routing::violations_json(&violations),
            crate::routing::violations_json(&cell_violations),
            crate::routing::lvs_report_json(&lvs),
            bus_states.join(","),
            rules.join(",")
        );
        Ok(DesignCheck { clean, json })
    }

    /// Whether every cell a DRC violation points at lies inside some placed
    /// instance's own footprint — i.e. the finding is about a library cell's
    /// interior, not about anything this design laid down.
    ///
    /// A violation straddling the boundary (a cell's dust shorting against a
    /// bus, say) is NOT interior: it stays in the gating report, which is
    /// exactly where an integration error belongs.
    fn is_inside_an_instance(&self, v: &crate::routing::Violation) -> bool {
        let cells = Self::violation_cells(v);
        if cells.is_empty() {
            return false;
        }
        let bodies = self.instance_bodies();
        cells
            .iter()
            .all(|c| bodies.iter().any(|body| body.contains(c)))
    }

    /// Every placed instance's occupied cells, one set per instance.
    fn instance_bodies(&self) -> Vec<BTreeSet<P3>> {
        (0..self.instances.len())
            .map(|i| self.instance_region(i))
            .collect()
    }

    /// The cells a DRC violation implicates.
    fn violation_cells(v: &crate::routing::Violation) -> Vec<P3> {
        use crate::routing::Violation as V;
        let p = |q: &crate::routing::Pos| (q.x, q.y, q.z);
        match v {
            V::Short { at_a, at_b, .. } => vec![p(at_a), p(at_b)],
            V::Floating { at, .. } => vec![p(at)],
            V::UnattachedWallTorch { at, anchor } => vec![p(at), p(anchor)],
            V::RepeaterCycle { diodes } => diodes.iter().map(p).collect(),
            V::PowerStarved { at, .. } => vec![p(at)],
        }
    }

    /// Per-bit repeater delay (redstone ticks) of a routed bus, from its
    /// fragment: a repeater at even offset from the canonical level
    /// belongs to that bit's straight run, at odd offset to the bit's dip
    /// station one level down.
    /// MEASURE a realized bus against all five terms. See [`BusCostVector`].
    ///
    /// Coherence is the term that matters and the one that was missing: for each
    /// slice along the route's principal axis, take the cross-section bounding
    /// box of that slice's cells and charge whatever its area exceeds the
    /// CANONICAL form's (a `1 x (2w-1)` column for the 2y stack). A bundle
    /// travelling together scores 0; a gather bar with eight lanes hanging off
    /// it scores enormously, at identical length. Form conversions carry a fixed
    /// charge on top, because a conversion is a structural decision, not a
    /// routing detail.
    pub fn bus_cost(&self, bus: &BusLayer) -> BusCostVector {
        let f = &bus.fragment;
        if f.is_empty() {
            return BusCostVector::default();
        }
        let (width, step) = self
            .resolve_port(&bus.driver)
            .map(|p| (p.width.max(1) as i32, p.step))
            .unwrap_or((1, (0, 2, 0)));
        let delays = self.bus_bit_delays(bus);
        let (delay_rt, skew_rt) = match (delays.iter().max(), delays.iter().min()) {
            (Some(hi), Some(lo)) => (*hi as u32, (hi - lo) as u32),
            _ => (0, 0),
        };

        // Principal axis: the one the route spans furthest.
        let (mut lo, mut hi) = (
            (i32::MAX, i32::MAX, i32::MAX),
            (i32::MIN, i32::MIN, i32::MIN),
        );
        for p in f.keys() {
            lo = (lo.0.min(p.0), lo.1.min(p.1), lo.2.min(p.2));
            hi = (hi.0.max(p.0), hi.1.max(p.1), hi.2.max(p.2));
        }
        let along_x = (hi.0 - lo.0) >= (hi.2 - lo.2);
        // The canonical bundle's cross-section, derived from the PORT'S OWN
        // FORM rather than assumed. A 2y stack is one column `2w` tall
        // (dust + support per bit); a row at pitch `p` is `p*(w-1)+1` wide and 2
        // tall. Assuming the stack charged every row-form bundle for merely
        // being a row — the baseline has to be the form the bits are actually
        // in, or the metric penalises shape instead of DISPERSION.
        let pitch = step.0.abs().max(step.1.abs()).max(step.2.abs()).max(1);
        let canonical = if step.1 != 0 {
            (pitch * width) as u32
        } else {
            (2 * (pitch * (width - 1) + 1)) as u32
        };
        let mut coherence = 0u32;
        let mut slices: BTreeMap<i32, ((i32, i32), (i32, i32))> = BTreeMap::new();
        for p in f.keys() {
            let (key, a, b) = if along_x {
                (p.0, p.1, p.2)
            } else {
                (p.2, p.1, p.0)
            };
            let e = slices.entry(key).or_insert(((a, b), (a, b)));
            e.0 = (e.0 .0.min(a), e.0 .1.min(b));
            e.1 = (e.1 .0.max(a), e.1 .1.max(b));
        }
        for (_, (slo, shi)) in slices {
            let area = ((shi.0 - slo.0 + 1) * (shi.1 - slo.1 + 1)) as u32;
            coherence += area.saturating_sub(canonical);
        }
        // A form conversion is a STRUCTURAL decision; charge it as such.
        let conversions = bus
            .segments
            .iter()
            .filter(|s| matches!(s.kind, SegmentKind::Adapter(_)))
            .count() as u32;
        coherence += conversions * 64;

        // Footprint: occupied volume plus a one-cell clearance shell, which is
        // what the route actually denies to its neighbours.
        let mut shell: BTreeSet<P3> = BTreeSet::new();
        for p in f.keys() {
            for dx in -1..=1 {
                for dy in -1..=1 {
                    for dz in -1..=1 {
                        shell.insert((p.0 + dx, p.1 + dy, p.2 + dz));
                    }
                }
            }
        }
        BusCostVector {
            length: f.len() as u32,
            delay_rt,
            skew_rt,
            coherence,
            footprint: shell.len() as u32,
        }
    }

    /// Repeater delay charged to each bit, in bit order.
    ///
    /// A bit is identified by PROJECTING the repeater onto the driving port's
    /// own bit axis — [`DesignPort::step`] — not by its height. Keying off `y`
    /// is only correct for the canonical 2y stack; a bundle laid out as a flat
    /// row steps in `z`, so every one of its repeaters has `y == y0`, all the
    /// delay lands on bit 0, and the bus reports a large phantom skew for a
    /// bundle whose true skew is zero.
    ///
    /// The projection reproduces the old arithmetic exactly on a 2y stack
    /// (a repeater on a support level rounds up to the bit above it, which is
    /// the bit it refreshes) and is correct for every other bundle geometry.
    pub fn bus_bit_delays(&self, bus: &BusLayer) -> Vec<u64> {
        let Ok(driver) = self.resolve_port(&bus.driver) else {
            return Vec::new();
        };
        let width = driver.width as usize;
        let mut per = vec![0u64; width];
        let s = driver.step;
        let norm = (s.0 * s.0 + s.1 * s.1 + s.2 * s.2) as i64;
        if norm == 0 {
            // A degenerate or single-bit port: every repeater serves bit 0.
            for (_, b) in bus.fragment.iter().filter(|(_, b)| rblocks::is_repeater(b)) {
                if let Some(slot) = per.first_mut() {
                    *slot += rblocks::repeater_delay(b) as u64;
                }
            }
            return per;
        }
        let a = driver.anchor;
        for (p, b) in &bus.fragment {
            if !rblocks::is_repeater(b) {
                continue;
            }
            let d = (p.0 - a.0, p.1 - a.1, p.2 - a.2);
            let dot = (d.0 * s.0 + d.1 * s.1 + d.2 * s.2) as i64;
            // Nearest bit, halves rounding up, in integer arithmetic.
            let bit = (2 * dot + norm).div_euclid(2 * norm);
            if bit >= 0 && (bit as usize) < width {
                per[bit as usize] += rblocks::repeater_delay(b) as u64;
            }
        }
        per
    }

    /// Per-bus skew as JSON: `{"per_bit_rt": [...], "skew_rt", "max_rt"}`.
    pub fn bus_skew_json(&self, name: &str) -> Option<String> {
        let bus = self.buses.get(name)?;
        let per = self.bus_bit_delays(bus);
        let max = per.iter().max().copied().unwrap_or(0);
        let min = per.iter().min().copied().unwrap_or(0);
        Some(format!(
            "{{\"per_bit_rt\":{:?},\"skew_rt\":{},\"max_rt\":{max}}}",
            per,
            max - min
        ))
    }

    /// STA over the design (buses as nets, drivers as sources, repeaters
    /// charged per net by the existing sta machinery) plus per-bus skew
    /// and the net-class rule violations.
    fn sta_and_rules(&self, flat: &UniversalSchematic) -> (String, Vec<String>) {
        use crate::routing::Pos;
        let mut ws = crate::routing::workspace_from_schematic(flat);
        let mut sinks_of: BTreeSet<String> = BTreeSet::new();
        let mut net_gates: Vec<crate::routing::sta::Gate> = Vec::new();
        let mut bus_json: Vec<String> = Vec::new();
        let mut rules: Vec<String> = Vec::new();
        for bus in self.buses.values() {
            if bus.state != BusState::Routed {
                continue;
            }
            // Label the fragment with the driving signal so the sta
            // machinery attributes the bus's repeaters to its net.
            for p in bus.fragment.keys() {
                ws.set_label(Pos::new(p.0, p.1, p.2), &bus.driver);
            }
            for s in &bus.sinks {
                sinks_of.insert(s.clone());
                net_gates.push(crate::routing::sta::Gate {
                    out: s.clone(),
                    ins: bus.driver_names(),
                    delay_rt: 0,
                });
            }
            let per = self.bus_bit_delays(bus);
            let max = per.iter().max().copied().unwrap_or(0);
            let min = per.iter().min().copied().unwrap_or(0);
            let skew = max - min;
            let mut len_ok = true;
            if let Some(rule) = &bus.rule {
                if let Some(limit) = rule.max_len_rt {
                    if max > limit as u64 {
                        len_ok = false;
                        rules.push(format!(
                            "bus `{}`: max bit delay {max}rt exceeds max_len_rt {limit}rt",
                            bus.name
                        ));
                    }
                }
                if let Some((lo, hi)) = rule.y_band {
                    if let Some(p) = bus.fragment.keys().find(|p| p.1 < lo || p.1 > hi) {
                        rules.push(format!(
                            "bus `{}`: cell {:?} outside y_band {lo}..={hi}",
                            bus.name, p
                        ));
                    }
                }
            }
            bus_json.push(format!(
                "{:?}:{{\"per_bit_rt\":{:?},\"skew_rt\":{skew},\"max_rt\":{max},\"len_ok\":{len_ok}}}",
                bus.name, per
            ));
        }
        let inputs: Vec<String> = self
            .buses
            .values()
            .filter(|b| b.state == BusState::Routed)
            .flat_map(|b| b.driver_names())
            .filter(|d| !sinks_of.contains(d))
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect();
        let core = if net_gates.is_empty() {
            "{\"arrival_rt\":{},\"critical\":[]}".to_string()
        } else {
            match crate::routing::sta::sta(&ws, &inputs, &net_gates) {
                Ok(rep) => {
                    let arr: Vec<String> = rep
                        .arrival_rt
                        .iter()
                        .map(|(k, v)| format!("{k:?}:{v}"))
                        .collect();
                    let crit: Vec<String> = rep.critical.iter().map(|s| format!("{s:?}")).collect();
                    format!(
                        "{{\"arrival_rt\":{{{}}},\"critical\":[{}]}}",
                        arr.join(","),
                        crit.join(",")
                    )
                }
                Err(e) => format!("{{\"error\":{:?}}}", format!("{e:?}")),
            }
        };
        let json = format!("{{\"design\":{core},\"buses\":{{{}}}}}", bus_json.join(","));
        (json, rules)
    }

    /// Settle the flattened artifact in the vanilla-accurate tick engine,
    /// write every settled state back, stamp `InitialState::Baked` into the
    /// embedded contract and return the baked artifact — the cell deploys
    /// trusting its saved states.
    #[cfg(all(feature = "simulation", feature = "bridge", feature = "mc-tick"))]
    pub fn bake(&self, budget: u32) -> Result<UniversalSchematic, String> {
        use crate::io_contract::InitialState;
        use crate::simulation::typed_executor::BackendCircuitExecutor;

        let mut flat = self.flatten()?;
        let mut contract = flat
            .embedded_cell_contract()?
            .ok_or("flatten() embeds a contract; none found")?;
        let extra = executor_extra_states();
        let extra_refs: Vec<&str> = extra.iter().map(String::as_str).collect();
        let mut cell = BackendCircuitExecutor::for_cell(flat.clone(), &contract, &extra_refs)?;
        cell.settle(budget);
        cell.bake_to(&mut flat)?;

        let mut port_values = std::collections::BTreeMap::new();
        let output_names: Vec<String> = contract.io.outputs.keys().cloned().collect();
        for name in output_names {
            if let Ok(v) = cell.read_output(&name) {
                port_values.insert(name, value_to_u64(&v));
            }
        }
        contract.physical.initial_state = InitialState::Baked { port_values };
        flat.set_cell_contract(&contract)?;
        Ok(flat)
    }

    /// Flatten and save the artifact as `.schem` bytes (the flat-artifact
    /// serialization tier; the embedded contract rides along).
    /// The flattened artifact as a SINGLE-REGION composite.
    ///
    /// `.schem` has no layer concept, and a layered schematic pushed through
    /// the region merge loses every named-layer cell that the loose layer's
    /// bounding box shadows — the merge mirrors [`UniversalSchematic::get_block`],
    /// which answers from the default region first whenever a coordinate falls
    /// inside its (dense) bounds, so a bus fragment threading the endpoint
    /// hardware's own bounding box reads back as air. Compositing the layers
    /// explicitly, topmost non-air wins, keeps the artifact whole. Layers are
    /// disjoint by construction (the planner refuses collisions), so the
    /// union is unambiguous.
    pub fn flatten_composite(&self) -> Result<UniversalSchematic, String> {
        let layered = self.flatten()?;
        let mut flat = UniversalSchematic::new(self.name.clone());
        for (pos, state) in layered.iter_blocks() {
            if state.name == "minecraft:air" {
                continue;
            }
            let s = state.to_string();
            flat.set_block_from_string(pos.x, pos.y, pos.z, &s)
                .map_err(|e| format!("composite: {s} at {:?}: {e}", (pos.x, pos.y, pos.z)))?;
        }
        flat.metadata = layered.metadata.clone();
        flat.metadata.name = Some(self.name.clone());
        Ok(flat)
    }

    pub fn to_schem_bytes(&self) -> Result<Vec<u8>, String> {
        let flat = self.flatten_composite()?;
        crate::formats::schematic::to_schematic(&flat).map_err(|e| e.to_string())
    }

    /// Flatten and save to a file.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn save(&self, path: &str) -> Result<(), String> {
        std::fs::write(path, self.to_schem_bytes()?).map_err(|e| e.to_string())
    }

    // ------------------------------------------------------------------
    // Serialization hooks (`src/design_io.rs` owns the document formats:
    // `.nucm` project tier + `.litematic` layered interchange tier)
    // ------------------------------------------------------------------

    /// The document's parts, for the serialization module.
    #[allow(clippy::type_complexity)]
    pub(crate) fn io_parts(
        &self,
    ) -> (
        &str,
        &UniversalSchematic,
        &BTreeMap<String, CellDef>,
        &[Instance],
        &BTreeMap<String, DesignPort>,
        &BTreeMap<String, BusLayer>,
    ) {
        (
            &self.name,
            &self.base,
            &self.cells,
            &self.instances,
            &self.ports,
            &self.buses,
        )
    }

    /// Rebuild a design from deserialized parts (serialization module
    /// only — the loading format is responsible for internal consistency).
    pub(crate) fn from_io_parts(
        name: String,
        base: UniversalSchematic,
        cells: BTreeMap<String, CellDef>,
        instances: Vec<Instance>,
        ports: BTreeMap<String, DesignPort>,
        buses: BTreeMap<String, BusLayer>,
    ) -> Self {
        Design {
            name,
            base,
            cells,
            instances,
            ports,
            buses,
            // Policy, not document state: a reloaded design routes the same way
            // a fresh one does.
            auto_promote: true,
            // A reloaded document starts every layer at revision 0: a fresh
            // reader has drawn nothing yet, so nothing needs reporting until
            // the first edit.
            bus_revs: BTreeMap::new(),
            rev_clock: 0,
        }
    }
}

/// A planned realization: the new bus's fragment (broken down per
/// segment), the gate joint columns, plus amendments (removals +
/// additions) to the buses it crosses.
#[derive(Clone, Default)]
struct Realization {
    fragment: BTreeMap<P3, String>,
    amendments: Vec<(String, Vec<P3>, BTreeMap<P3, String>)>,
    segments: Vec<Segment>,
    gate_cells: BTreeMap<String, BTreeSet<P3>>,
}

/// The bus planner: plans cells against the design-wide occupancy index
/// (collisions and instance halos fail loudly AT PLAN TIME, keeping
/// realization atomic), tracks which segment owns each cell, and carries
/// the crossing logic — dip-under tiles where we cross a routed bus,
/// through-bus stations where a routed bus already dips under us.
struct Planner<'a> {
    design: &'a Design,
    /// The bus being planned (its own surviving runs are not crossings).
    exclude: Option<&'a str>,
    style: &'a BusStyle,
    occ: &'a OccupancyIndex,
    /// Cells this plan's amendments vacate (free for re-use).
    vacated: BTreeSet<P3>,
    real: Realization,
    cur_seg: Option<Segment>,
    cur_gate: Option<(String, BTreeSet<P3>)>,
    /// Level hops taken on the current pair. The hop rung plans cross-level
    /// legs, which recurse into `plan_pair`; without this a pair that cannot be
    /// routed at ANY level would hop forever.
    hops: u32,
    /// Signal-strength headroom a run ENDING at each anchor must leave behind,
    /// in dust cells: the debt of a form adapter downstream of that anchor,
    /// measured from the adapter's stamped geometry by
    /// [`crate::design_decay::tile_dust_debt`].
    ///
    /// The router plans the trunk to the ADAPTED anchor and then stops, so
    /// without this the strength the sink's own gather column spends is spent
    /// by nobody's budget. It is the second half of what the old blanket
    /// `REFRESH_AT = 7` was silently reserving.
    reserves: BTreeMap<P3, u32>,
}

impl<'a> Planner<'a> {
    fn new(
        design: &'a Design,
        exclude: Option<&'a str>,
        style: &'a BusStyle,
        occ: &'a OccupancyIndex,
    ) -> Self {
        Planner {
            design,
            exclude,
            style,
            occ,
            vacated: BTreeSet::new(),
            real: Realization::default(),
            cur_seg: None,
            cur_gate: None,
            hops: 0,
            reserves: BTreeMap::new(),
        }
    }

    /// The exit headroom a run ending at `anchor` must leave (0 unless a form
    /// adapter downstream of it is going to spend some).
    fn exit_reserve(&self, anchor: P3) -> u32 {
        self.reserves.get(&anchor).copied().unwrap_or(0)
    }

    /// Would plain dust at `p` join or energise foreign live redstone?
    ///
    /// The completed-route clearance check remains the authority, but a run
    /// has one cheap repair available before it gets that far: keep this cell
    /// as a directional repeater. This is how the old dense refresh pitch
    /// happened to protect X02; the per-segment strength ledger must preserve
    /// the electrical isolation deliberately rather than by accident.
    fn dust_would_interfere(&self, p: P3) -> bool {
        const OURS: &str = "\0planned-dust";
        // The diagonal law reads the candidate dust's SUPPORT cell. Model the
        // pair together; checking dust against today's fragment (before this
        // run is stamped) would see air underneath it and miss the exact
        // downhill connection we are trying to prevent.
        let view = PlannedDustView {
            occ: self.occ,
            frag: &self.real.fragment,
            dust: p,
            support: (p.0, p.1 - 1, p.2),
            support_block: &self.style.bus_block,
        };
        let ours = crate::routing::transport::Placement {
            mech: crate::routing::transport::Mechanism::Dust,
            cell: crate::routing::Pos::new(p.0, p.1, p.2),
            fwd: (1, 0, 0),
            net: OURS,
        };
        for q in clearance_scan(p, 0) {
            if self.real.fragment.contains_key(&q) || self.vacated.contains(&q) {
                continue;
            }
            let Some((block, owner)) = self.occ.cells.get(&q) else {
                continue;
            };
            let foreign_net = match owner {
                Occupant::Loose => "\0loose",
                Occupant::Instance(name) => name.as_str(),
                Occupant::Bus(name) => {
                    if self.exclude == Some(name.as_str()) {
                        continue;
                    }
                    name.as_str()
                }
            };
            let theirs = crate::routing::transport::Placement {
                mech: crate::routing::transport::mech_of(block),
                cell: crate::routing::Pos::new(q.0, q.1, q.2),
                fwd: crate::routing::transport::fwd_of(block),
                net: foreign_net,
            };
            if is_live_mech(theirs.mech)
                && crate::routing::transport::interferes(&theirs, &ours, &view).is_some()
            {
                return true;
            }
        }
        false
    }

    fn begin_segment(&mut self, kind: SegmentKind, a: P3, b: P3) {
        self.cur_seg = Some(Segment {
            kind,
            a,
            b,
            runs: Vec::new(),
            cells: BTreeSet::new(),
        });
    }

    fn end_segment(&mut self) {
        if let Some(seg) = self.cur_seg.take() {
            self.real.segments.push(seg);
        }
    }

    fn finish(self) -> Realization {
        self.real
    }

    #[allow(clippy::type_complexity)]
    fn snapshot(&self) -> (Realization, Option<Segment>, BTreeSet<P3>) {
        (
            self.real.clone(),
            self.cur_seg.clone(),
            self.vacated.clone(),
        )
    }

    fn restore(&mut self, s: (Realization, Option<Segment>, BTreeSet<P3>)) {
        self.real = s.0;
        self.cur_seg = s.1;
        self.vacated = s.2;
    }

    /// Add a planned cell. Identical double-writes are fine (shared
    /// supports); diverging ones are a planner bug; cells hard-occupied by
    /// anything else, or inside an instance's influence halo, fail with
    /// the owner named.
    fn put(&mut self, p: P3, block: &str) -> Result<(), String> {
        if let Some(existing) = self.real.fragment.get(&p) {
            if existing != block {
                return Err(format!(
                    "internal plan conflict at {:?}: `{existing}` vs `{block}`",
                    p
                ));
            }
            return Ok(());
        }
        if !self.vacated.contains(&p) {
            if let Some((existing, owner)) = self.occ.cells.get(&p) {
                if existing != block {
                    let owner = match owner {
                        Occupant::Loose => "loose block layer".to_string(),
                        Occupant::Instance(n) => format!("instance `{n}`"),
                        Occupant::Bus(n) => format!("bus `{n}`"),
                    };
                    return Err(format!(
                        "collision at {:?}: `{existing}` ({owner}) already there, wanted \
                         `{block}`",
                        p
                    ));
                }
            } else if let Some(inst) = self.occ.halos.get(&p) {
                return Err(format!(
                    "cell {:?} lies inside the influence halo of instance `{inst}`",
                    p
                ));
            }
        }
        self.real.fragment.insert(p, block.to_string());
        if let Some(seg) = self.cur_seg.as_mut() {
            seg.cells.insert(p);
        } else if let Some((_, cells)) = self.cur_gate.as_mut() {
            cells.insert(p);
        }
        Ok(())
    }

    /// Plan one trunk waypoint pair, climbing a retry ladder instead of
    /// giving up on the first blocked template:
    ///
    /// 1. the straight run (axis-aligned pairs) or the two single-corner Ls
    ///    (x-first then z-first) — the deterministic templates, tried first so
    ///    an unobstructed design realizes byte-for-byte as it always did;
    /// 2. a real rectilinear corridor from [`crate::design_corridor`], which
    ///    routes AROUND whatever blocked the templates (a foreign instance's
    ///    body or halo, a loose wall, another bus), at three escalating
    ///    efforts — tidier corridors first, then wider search bounds.
    ///
    /// Every rung's failure is collected, so the reason a pair is finally
    /// unroutable names each shape that was tried and why it lost.
    ///
    /// `since0` is the dust count since the last refresh entering the pair;
    /// the exit count is returned so refresh spacing stays sound across
    /// joints.
    fn plan_pair(
        &mut self,
        a: P3,
        b: P3,
        width: u8,
        keep: &BTreeSet<P3>,
        since0: u32,
    ) -> Result<u32, String> {
        if a == b {
            return Err("zero-length segment".to_string());
        }
        // Anchors on different levels are not a failure: the bus changes
        // level BY CONSTRUCTION with the verified level-shift tile.
        if a.1 != b.1 {
            return self.plan_pair_across_levels(a, b, width, keep, since0);
        }
        let snap = self.snapshot();
        let mut tried: Vec<String> = Vec::new();

        if let Some(run) = axis_run(a, b, width) {
            match self.plan_run(&run, keep, since0, false, false) {
                Ok(out) => return Ok(out),
                Err(e) => {
                    self.restore(snap.clone());
                    tried.push(format!("straight run: {e}"));
                }
            }
        } else {
            for (corner, x_first) in [((b.0, a.1, a.2), true), ((a.0, a.1, b.2), false)] {
                match self.plan_l(a, b, corner, x_first, width, keep, since0) {
                    Ok(out) => return Ok(out),
                    Err(e) => {
                        self.restore(snap.clone());
                        tried.push(format!(
                            "L corner {}: {e}",
                            if x_first { "x-first" } else { "z-first" }
                        ));
                    }
                }
            }
        }

        // The templates are out of ideas; search for an actual corridor.
        //
        // A corridor may loop back near itself. That is electrically harmless
        // here: every cell a bus lays belongs to ONE net and, at a given
        // level, to one BIT, so two nearby legs carry the same signal — a
        // redundant path, not a short. Different bits cannot meet because the
        // 2y pitch keeps their dust two levels apart, and dust never reads the
        // block above it. `Design::check` (DRC + LVS) is the backstop.
        let mut seen: Vec<Vec<P3>> = Vec::new();
        for (rung, effort) in crate::design_corridor::LADDER.iter().enumerate() {
            let Some(chain) = crate::design_corridor::search(self.occ, a, b, width, *effort) else {
                continue;
            };
            // A rung that reproduces a corridor an earlier rung already failed
            // on cannot do better; skip the replan.
            if seen.contains(&chain) {
                continue;
            }
            seen.push(chain.clone());
            match self.plan_chain(&chain, width, keep, since0) {
                Ok(out) => return Ok(out),
                Err(e) => {
                    self.restore(snap.clone());
                    tried.push(format!(
                        "corridor (effort {}, {} legs via {:?}): {e}",
                        rung + 1,
                        chain.len() - 1,
                        &chain[1..chain.len().saturating_sub(1)]
                    ));
                }
            }
        }
        // LAST RUNG: HOP TO A CLEAR LEVEL.
        //
        // The pair's own level is congested, but the diagnostic's cross-level
        // probe often proves a clear corridor exists a few blocks up or down.
        // That used to be the end of the road — the reason literally said "the
        // bus form cannot ramp between levels, so shift an endpoint's instance
        // in y". It CAN ramp now, so use the level shift to go get that lane
        // instead of asking the user to move a component: hop up, cross at the
        // clear level, hop back down onto the sink.
        //
        // Each leg is cross-level, so it recurses through
        // `plan_pair_across_levels`; `hops` bounds that.
        if self.hops == 0 {
            for dy in [2i32, -2, 4, -4, 6, -6, 8, -8] {
                let y2 = a.1 + dy;
                if y2 < 1 {
                    continue; // the stack's supports would go under the world
                }
                let k = dy.unsigned_abs();
                // Each end needs a shift, plus a cell so neither lands on a port.
                let leg = shift_len_max(k, dy < 0, self.exit_reserve(b)) + 1;
                let along_x = (b.0 - a.0).abs() >= (b.2 - a.2).abs();
                let (span, sign) = if along_x {
                    ((b.0 - a.0).abs(), (b.0 - a.0).signum())
                } else {
                    ((b.2 - a.2).abs(), (b.2 - a.2).signum())
                };
                if span < 2 * leg + 1 {
                    continue;
                }
                let (m1, m2) = if along_x {
                    ((a.0 + sign * leg, y2, a.2), (b.0 - sign * leg, y2, b.2))
                } else {
                    ((a.0, y2, a.2 + sign * leg), (b.0, y2, b.2 - sign * leg))
                };
                self.hops += 1;
                let hop = (|| -> Result<u32, String> {
                    let s1 = self.plan_pair(a, m1, width, keep, since0)?;
                    let s2 = self.plan_pair(m1, m2, width, keep, s1.saturating_add(1))?;
                    self.plan_pair(m2, b, width, keep, s2.saturating_add(1))
                })();
                self.hops -= 1;
                match hop {
                    Ok(out) => return Ok(out),
                    Err(e) => {
                        self.restore(snap.clone());
                        tried.push(format!("level hop to y={y2}: {e}"));
                    }
                }
            }
        }

        Err(crate::design_corridor::diagnose(
            self.occ, a, b, width, &tried,
        ))
    }

    /// Plan a waypoint pair whose anchors sit on DIFFERENT levels: two FLAT
    /// legs (planned by the ordinary machinery — templates, corners,
    /// corridors, crossings) joined by the verified level-shift tile.
    ///
    /// The tile needs `shift_len` cells of straight run on one horizontal
    /// axis, so every placement is a `(axis, position)` pair; they are tried
    /// cheapest-clearance first (the end with more room), and each failure is
    /// collected so an unroutable pair names every placement it tried.
    fn plan_pair_across_levels(
        &mut self,
        a: P3,
        b: P3,
        width: u8,
        keep: &BTreeSet<P3>,
        since0: u32,
    ) -> Result<u32, String> {
        let k = (b.1 - a.1).unsigned_abs();
        let down = b.1 < a.1;
        let len = shift_len_max(k, down, self.exit_reserve(b));
        let places = Self::shift_placements(self.occ, a, b, len, width, keep);
        if places.is_empty() {
            return Err(format!(
                "the anchors are {k} level(s) apart, so the bus must change level: the verified \
                 level-shift tile needs {len} cells of straight run (plus 1 to clear the port) on \
                 one horizontal axis, but the pair only spans {} in x and {} in z between {:?} and \
                 {:?}. Lengthen the run, or split it with a gate so one leg has room",
                (b.0 - a.0).abs(),
                (b.2 - a.2).abs(),
                a,
                b
            ));
        }
        let snap = self.snapshot();
        let mut tried: Vec<String> = Vec::new();
        for (entry, exit, along_x, sign, what) in places {
            match self.plan_shift_route(a, b, entry, along_x, sign, k, down, width, keep, since0) {
                Ok(out) => return Ok(out),
                Err(e) => {
                    self.restore(snap.clone());
                    tried.push(format!("level shift {what} ({entry:?} -> {exit:?}): {e}"));
                }
            }
        }
        Err(format!(
            "the anchors are {k} level(s) apart and every placement of the {len}-cell level-shift \
             tile was blocked: {}",
            tried.join("; ")
        ))
    }

    /// One placement attempt: flat leg into the tile, the tile, flat leg out.
    #[allow(clippy::too_many_arguments)]
    fn plan_shift_route(
        &mut self,
        a: P3,
        b: P3,
        entry: P3,
        along_x: bool,
        sign: i32,
        k: u32,
        down: bool,
        width: u8,
        keep: &BTreeSet<P3>,
        since0: u32,
    ) -> Result<u32, String> {
        let mut since = since0;
        if a != entry {
            since = self
                .plan_pair(a, entry, width, keep, since)
                .map_err(|e| format!("leg into the shift: {e}"))?;
        }
        // A tile whose exit IS the far anchor has nothing after it to carry the
        // sink adapter's debt, so the tile itself must leave the headroom.
        let tile_reserve = self.exit_reserve(b);
        let (out, exit) =
            self.plan_level_shift(entry, along_x, sign, k, down, width, since, tile_reserve)?;
        since = out;
        if exit != b {
            // The tile's exit cell is one more dust cell between refreshes.
            since = self
                .plan_pair(exit, b, width, keep, since)
                .map_err(|e| format!("leg out of the shift: {e}"))?;
        }
        Ok(since)
    }

    /// Candidate placements of a `len`-cell level-shift tile between `a` and
    /// `b`, ordered by clearance (emptiest footprint first). On each axis with
    /// room: hard against the driver end, mid-run, and hard against the sink
    /// end — so a congested endpoint falls through to the open one.
    fn shift_placements(
        occ: &OccupancyIndex,
        a: P3,
        b: P3,
        len: i32,
        width: u8,
        keep: &BTreeSet<P3>,
    ) -> Vec<(P3, P3, bool, i32, &'static str)> {
        let mut out: Vec<(usize, P3, P3, bool, i32, &'static str)> = Vec::new();
        // Longer axis first, so the tie-break after scoring is the roomier one.
        let mut axes = [(true, (b.0 - a.0).abs()), (false, (b.2 - a.2).abs())];
        axes.sort_by_key(|(_, span)| std::cmp::Reverse(*span));
        for (along_x, span) in axes {
            // One cell must stay clear at each end so the tile never lands on
            // a port's own anchor cell.
            if span < len + 1 {
                continue;
            }
            let sign = if along_x {
                (b.0 - a.0).signum()
            } else {
                (b.2 - a.2).signum()
            };
            let a_c = if along_x { a.0 } else { a.2 };
            let slack = span - len - 1;
            for (offset, what) in [
                (1, "at the driver end"),
                (1 + slack / 2, "mid-run"),
                (1 + slack, "at the sink end"),
            ] {
                let start = a_c + sign * offset;
                // Driver-end and mid placements ride the driver's cross-axis
                // row; the sink-end one rides the sink's, so the flat leg out
                // is a straight shot.
                let cross = if offset == 1 + slack {
                    if along_x {
                        b.2
                    } else {
                        b.0
                    }
                } else if along_x {
                    a.2
                } else {
                    a.0
                };
                let (entry, exit) = if along_x {
                    ((start, a.1, cross), (start + sign * (len - 1), b.1, cross))
                } else {
                    ((cross, a.1, start), (cross, b.1, start + sign * (len - 1)))
                };
                let Some(score) = Self::shift_clearance(occ, entry, exit, along_x, width, keep)
                else {
                    continue; // a branch junction falls inside the footprint
                };
                if out.iter().any(|c| c.1 == entry && c.3 == along_x) {
                    continue; // slack 0/1 collapses the three positions
                }
                out.push((score, entry, exit, along_x, sign, what));
            }
        }
        out.sort_by_key(|c| c.0);
        out.into_iter()
            .map(|(_, e, x, ax, s, w)| (e, x, ax, s, w))
            .collect()
    }

    /// How congested a candidate tile footprint is (occupied + halo cells), or
    /// `None` when a branch junction we must keep as plain dust falls inside
    /// it — the tile would eat the junction, so the placement is void.
    fn shift_clearance(
        occ: &OccupancyIndex,
        entry: P3,
        exit: P3,
        along_x: bool,
        width: u8,
        keep: &BTreeSet<P3>,
    ) -> Option<usize> {
        let (lo_a, hi_a) = if along_x {
            (entry.0.min(exit.0), entry.0.max(exit.0))
        } else {
            (entry.2.min(exit.2), entry.2.max(exit.2))
        };
        // The stack sweeps from the lower level's support to the top bit.
        let lo_y = entry.1.min(exit.1) - 1;
        let hi_y = entry.1.max(exit.1) + 2 * (width as i32 - 1);
        let mut score = 0usize;
        for c in lo_a..=hi_a {
            for y in lo_y..=hi_y {
                let p = if along_x {
                    (c, y, entry.2)
                } else {
                    (entry.0, y, c)
                };
                if keep.contains(&p) {
                    return None;
                }
                if occ.cells.contains_key(&p) {
                    score += 4; // a hard cell is worse than a soft halo
                } else if occ.halos.contains_key(&p) {
                    score += 1;
                }
            }
        }
        Some(score)
    }

    /// Stamp the verified BUS LEVEL-SHIFT tile: the whole `width`-bit
    /// 2y-pitch stack changes level by `k`, in form, over
    /// [`shift_len`] cells of straight run from `entry` (bit 0) along the
    /// axis. See [`shift_plan`] for the column plan and its verification.
    ///
    /// Every bit moves in LOCKSTEP, so the 2 y pitch — and with it the
    /// interleave that isolates the bits — is invariant through the shift; an
    /// odd `k` changes the stack's absolute y PARITY, which matters only to
    /// crossings, and those are evaluated per run at the level it actually
    /// runs on.
    #[allow(clippy::too_many_arguments)]
    fn plan_level_shift(
        &mut self,
        entry: P3,
        along_x: bool,
        sign: i32,
        k: u32,
        down: bool,
        width: u8,
        since0: u32,
        exit_reserve: u32,
    ) -> Result<(u32, P3), String> {
        let bus_block = self.style.bus_block.clone();
        let transparent = self.style.transparent_block.clone();
        // Repeater INPUT side faces the driver.
        let toward_driver = if along_x {
            rblocks::facing_name(-sign, 0)
        } else {
            rblocks::facing_name(0, -sign)
        }
        .expect("axis-aligned unit step");
        let (cols, since_out) = shift_plan(k, down, since0, exit_reserve);
        let pos_at = |o: i32, y: i32| -> P3 {
            if along_x {
                (entry.0 + o * sign, y, entry.2)
            } else {
                (entry.0, y, entry.2 + o * sign)
            }
        };
        for bit in 0..width {
            let base = entry.1 + 2 * bit as i32;
            for &(o, dy, kind) in &cols {
                let y = base + dy;
                match kind {
                    // The station blocks float, exactly as in the dip tile.
                    ShiftCell::Entry | ShiftCell::Exit => self.put(pos_at(o, y), &bus_block)?,
                    ShiftCell::Rep => {
                        self.put(pos_at(o, y - 1), &bus_block)?;
                        self.put(pos_at(o, y), &rblocks::repeater(toward_driver, 1))?;
                    }
                    ShiftCell::Flat => {
                        self.put(pos_at(o, y - 1), &bus_block)?;
                        self.put(pos_at(o, y), rblocks::DUST)?;
                    }
                    ShiftCell::Step | ShiftCell::Land => {
                        // THE ALTERNATION, and it FLIPS WITH DIRECTION.
                        //
                        // Descending, the step-off dust is the diagonal's
                        // UPPER end, so its support must CONDUCT (a 1y step
                        // passes down only over a conducting upper support —
                        // the diode law), while the landed dust's support is
                        // the cap sitting directly above bit n-1's in-use
                        // diagonal and must NOT cut it.
                        //
                        // Ascending, up-steps conduct over anything, so the
                        // two roles SWAP: the step-off support becomes the
                        // cap that must insulate, and the landed support is
                        // the conductor that severs the cross-bit diagonal
                        // (bit n's step-off dust and bit n-1's landed dust
                        // are 1 y apart in adjacent columns — an unintended
                        // connection, cut by the conductor above the lower).
                        //
                        // Bit 0 has nothing below to protect, so it is
                        // unconstrained: solid, per "transparency only where
                        // a diagonal must survive".
                        let insulate = bit > 0 && (kind == ShiftCell::Land) == down;
                        let support = if insulate { &transparent } else { &bus_block };
                        self.put(pos_at(o, y - 1), support)?;
                        self.put(pos_at(o, y), rblocks::DUST)?;
                    }
                }
            }
        }
        // The EXIT is wherever the plan actually ended, not where a
        // pre-computed length said it would: the caller continues from here.
        let last = cols.last().expect("a shift plan is never empty");
        Ok((since_out, pos_at(last.0, entry.1 + last.1)))
    }

    /// Plan a multi-leg corridor: a straight run per leg with a joint column
    /// at every interior corner — the same vocabulary [`Planner::plan_l`] uses
    /// for its single corner, generalized to N.
    fn plan_chain(
        &mut self,
        chain: &[P3],
        width: u8,
        keep: &BTreeSet<P3>,
        since0: u32,
    ) -> Result<u32, String> {
        let mut since = since0;
        for (i, leg) in chain.windows(2).enumerate() {
            let (a, b) = (leg[0], leg[1]);
            let run = axis_run(a, b, width)
                .ok_or_else(|| format!("corridor leg {:?} -> {:?} is not axis-aligned", a, b))?;
            since = self.plan_run(&run, keep, since, false, false)?;
            if i + 2 < chain.len() {
                self.column(b, width)?;
                // The corner joint is one more dust cell between refreshes.
                since = since.saturating_add(1);
            }
        }
        Ok(since)
    }

    /// One L-shaped pair through `corner`.
    #[allow(clippy::too_many_arguments)]
    fn plan_l(
        &mut self,
        a: P3,
        b: P3,
        corner: P3,
        x_first: bool,
        width: u8,
        keep: &BTreeSet<P3>,
        since0: u32,
    ) -> Result<u32, String> {
        let (r1, r2) = if x_first {
            (
                RunInfo {
                    along_x: true,
                    fixed: a.2,
                    y0: a.1,
                    from: a.0,
                    to: corner.0,
                    width,
                },
                RunInfo {
                    along_x: false,
                    fixed: corner.0,
                    y0: a.1,
                    from: a.2,
                    to: b.2,
                    width,
                },
            )
        } else {
            (
                RunInfo {
                    along_x: false,
                    fixed: a.0,
                    y0: a.1,
                    from: a.2,
                    to: corner.2,
                    width,
                },
                RunInfo {
                    along_x: true,
                    fixed: corner.2,
                    y0: a.1,
                    from: a.0,
                    to: b.0,
                    width,
                },
            )
        };
        let mid = self.plan_run(&r1, keep, since0, false, false)?;
        self.column(corner, width)?;
        // The corner joint is one more dust cell between refreshes.
        self.plan_run(&r2, keep, mid.saturating_add(1), false, false)
    }

    /// A gate's electrical joint column, recorded under the gate's name.
    fn plan_column(&mut self, gate: &str, anchor: P3, width: u8) -> Result<(), String> {
        self.cur_gate = Some((gate.to_string(), BTreeSet::new()));
        let r = self.column(anchor, width);
        if let Some((name, cells)) = self.cur_gate.take() {
            self.real.gate_cells.entry(name).or_default().extend(cells);
        }
        r
    }

    /// A dust-on-support joint column at every bit (gates and L corners).
    fn column(&mut self, anchor: P3, width: u8) -> Result<(), String> {
        let bus_block = self.style.bus_block.clone();
        for k in 0..width {
            let p = add(anchor, (0, 2 * k as i32, 0));
            self.put(p, rblocks::DUST)?;
            self.put((p.0, p.1 - 1, p.2), &bus_block)?;
        }
        Ok(())
    }

    /// Does `other` already dip under our line at the shared column?
    /// (Its dip dust sits one level below its canonical dust level, one
    /// cell before / three after the crossing center along its own axis.)
    fn dips_at(other: &BusLayer, orun: &RunInfo, center_on_their_axis: i32) -> bool {
        let sa = orun.sign();
        let poso = |c: i32, y: i32| -> P3 {
            if orun.along_x {
                (c, y, orun.fixed)
            } else {
                (orun.fixed, y, c)
            }
        };
        let d = orun.y0 - 1;
        // The dip cells hold DUST one level down; a straight run's support
        // blocks at the same level must not count.
        other
            .fragment
            .get(&poso(center_on_their_axis - sa, d))
            .is_some_and(|b| rblocks::is_dust(b))
            || other
                .fragment
                .get(&poso(center_on_their_axis + 3 * sa, d))
                .is_some_and(|b| rblocks::is_dust(b))
    }

    /// Plan one straight run: supports + dust, refresh repeaters, forced
    /// diode repeaters for branch joins (`first_rep` right after the
    /// junction on sink branches, `last_rep` right before it on wired-OR
    /// driver branches), implicit dip-under crossings against
    /// already-routed buses, and through-bus stations where a routed bus
    /// already dips under this line.
    fn plan_run(
        &mut self,
        run: &RunInfo,
        keep: &BTreeSet<P3>,
        since0: u32,
        first_rep: bool,
        last_rep: bool,
    ) -> Result<u32, String> {
        let sign = run.sign();
        let bus_block = self.style.bus_block.clone();
        let transparent = self.style.transparent_block.clone();
        let pos_at = |c: i32, y: i32| -> P3 {
            if run.along_x {
                (c, y, run.fixed)
            } else {
                (run.fixed, y, c)
            }
        };
        // Repeater INPUT side faces the driver.
        let toward_driver = if run.along_x {
            rblocks::facing_name(-sign, 0)
        } else {
            rblocks::facing_name(0, -sign)
        }
        .expect("axis-aligned unit step");

        // Crossings against every OTHER routed bus's perpendicular runs.
        let mut dips: Vec<i32> = Vec::new(); // centers along OUR axis
        let mut stations: Vec<i32> = Vec::new();
        for other in self.design.buses.values() {
            if Some(other.name.as_str()) == self.exclude || other.state != BusState::Routed {
                continue;
            }
            for orun in &other.runs {
                if orun.along_x == run.along_x {
                    continue; // parallel: overlap shows up as a collision
                }
                let center = orun.fixed;
                if !run.strictly_inside(center, 3) || !orun.strictly_inside(run.fixed, 3) {
                    continue;
                }
                // Two lines that cross in plan view but occupy DISJOINT
                // vertical bands never touch: no dip, no station, nothing to
                // adapt. Only an actual overlap needs the crossing tile, and
                // only then does a level/width mismatch matter.
                let ours = (run.y0 - 1, run.y0 + 2 * (run.width as i32 - 1));
                let theirs = (orun.y0 - 1, orun.y0 + 2 * (orun.width as i32 - 1));
                if theirs.1 < ours.0 || ours.1 < theirs.0 {
                    continue;
                }
                if orun.y0 != run.y0 || orun.width != run.width {
                    return Err(format!(
                        "crossing with bus `{}` at {:?}: the two stacks overlap vertically (ours \
                         y {}..={} at {} bits, theirs y {}..={} at {} bits) but do not share a \
                         level, so the dip-under tile does not apply. Give the two buses \
                         non-overlapping y bands (a `y_band` net-class rule), or make their \
                         widths and bit-0 levels match — vertical level adapters are not \
                         implemented yet",
                        other.name,
                        (run.fixed, orun.fixed),
                        ours.0,
                        ours.1,
                        run.width,
                        theirs.0,
                        theirs.1,
                        orun.width
                    ));
                }
                if Self::dips_at(other, orun, run.fixed) {
                    // They already dip under this line: WE are the through
                    // bus and pay the station (one repeater per bit).
                    stations.push(center);
                } else {
                    dips.push(center);
                    self.plan_station_amendment(other, orun, run.fixed)?;
                }
            }
        }
        dips.sort();
        dips.dedup();
        stations.sort();
        stations.dedup();
        let mut centers: Vec<i32> = dips.iter().chain(stations.iter()).copied().collect();
        centers.sort();
        for w in centers.windows(2) {
            if (w[1] - w[0]).abs() < 8 {
                return Err(format!(
                    "crossing windows at {} and {} overlap (need 8 cells of spacing)",
                    w[0], w[1]
                ));
            }
        }

        // Cell coordinates strictly between the anchors.
        let in_dip = |c: i32| {
            dips.iter()
                .any(|&cc| ((c - cc) * sign) >= -2 && ((c - cc) * sign) <= 4)
        };
        let near_dip = |c: i32| {
            dips.iter()
                .any(|&cc| ((c - cc) * sign) >= -4 && ((c - cc) * sign) <= 6)
        };
        let in_station = |c: i32| {
            stations
                .iter()
                .any(|&cc| ((c - cc) * sign) >= 0 && ((c - cc) * sign) <= 2)
        };
        let near_station = |c: i32| {
            stations
                .iter()
                .any(|&cc| ((c - cc) * sign) >= -2 && ((c - cc) * sign) <= 4)
        };

        // A kept-dust junction inside a crossing window cannot merge.
        for k in keep {
            let on_this_run = k.1 == run.y0
                && if run.along_x {
                    k.2 == run.fixed
                } else {
                    k.0 == run.fixed
                };
            if !on_this_run {
                continue;
            }
            let c = if run.along_x { k.0 } else { k.2 };
            if in_dip(c) || in_station(c) || near_dip(c) {
                return Err(format!("junction {:?} falls inside a crossing window", k));
            }
        }

        // ------------------------------------------------------------------
        // THE ELECTRICAL CHAIN, decided ONCE for the whole run.
        //
        // Every bit gets the same cell kinds at the same offsets (matched skew
        // is a requirement, not a nicety), so the refresh decision is made once
        // here from a decay ledger and then merely STAMPED per bit below.
        //
        // The chain is what the signal actually traverses, which is not the
        // same as the cells this run writes: a crossing window contributes two
        // dust cells before its own repeater and two after, and the run used to
        // skip all of them as if the window were free. Debiting them is why a
        // widened budget is safe here where a widened constant was not.
        // ------------------------------------------------------------------
        #[derive(Clone, Copy, PartialEq, Eq)]
        enum Slot {
            /// Ordinary run dust. `station_ok` = a refresh station may stand here.
            Dust { station_ok: bool },
            /// A repeater this run must emit whatever the budget says (a branch
            /// diode), or one the ledger asked for.
            Rep,
            /// A crossing window's own repeater: written by the window loops
            /// below, refreshes the chain here.
            WindowRefresh,
            /// A crossing window's block: written below, spends nothing.
            WindowBlock,
            /// A crossing window's dust: written below, spends one cell.
            WindowDust,
        }
        let window_slot = |o: i32| match o {
            0 | 2 => Slot::WindowBlock,
            1 => Slot::WindowRefresh,
            _ => Slot::WindowDust,
        };
        // What the geometry PAST this run's exit spends without refreshing (a
        // sink's form adapter). Needed before the chain, because a run that owes
        // one is allowed to refresh in a cell an unencumbered run would leave
        // alone — see `station_ok` below.
        let reserve = self.exit_reserve(pos_at(run.to, run.y0));
        let mut chain: Vec<(i32, Slot)> = Vec::new();
        {
            let mut c = run.from + sign;
            while c != run.to {
                let slot = if let Some(o) = dips
                    .iter()
                    .map(|&cc| (c - cc) * sign)
                    .find(|o| (-2..=4).contains(o))
                {
                    window_slot(o)
                } else if let Some(o) = stations
                    .iter()
                    .map(|&cc| (c - cc) * sign)
                    .find(|o| (0..=2).contains(o))
                {
                    window_slot(o)
                } else {
                    let is_first = c == run.from + sign;
                    let is_last = c == run.to - sign;
                    if (first_rep && is_first) || (last_rep && is_last) {
                        Slot::Rep
                    } else {
                        let steps_from_ends = (c - run.from).abs().min((run.to - c).abs());
                        // Stations normally keep two cells clear of both
                        // anchors. A run that OWES an exit reserve may use its
                        // last cell anyway: a short final leg into a form
                        // adapter has nowhere else to stand, and the alternative
                        // is not a tidier route but a dead word — `t3_02`'s
                        // one-cell leg out of its level shift into a 7-cell
                        // gather column is exactly that case, and it is the same
                        // placement `last_rep` already uses for branch diodes.
                        //
                        // The ENTRY side is the same problem mirrored, and it
                        // bites hardest: a leg out of a level-shift tile can
                        // arrive with the tile's whole dust cap already spent,
                        // which is more than the budget, and then the two cells
                        // it may not refresh in overspend before the first legal
                        // station. `P02_permute8` routes eight 1-bit buses
                        // through 8-level shifts and loses three vectors exactly
                        // there. So a run that arrives with no room refreshes in
                        // its FIRST cell.
                        let arrives_broke = since0 + 1 + 1 > DUST_BUDGET - CROSSING_ALLOWANCE;
                        let room = steps_from_ends >= 2
                            || (reserve > 0 && is_last)
                            || (arrives_broke && is_first);
                        let station_ok = room
                            && !keep.contains(&pos_at(c, run.y0))
                            && !near_dip(c)
                            && !near_station(c);
                        // Decide for the whole matched bundle. If dust on ANY
                        // bit would couple to foreign live redstone, every bit
                        // keeps a diode here so latency remains matched.
                        let isolation_diode = station_ok
                            && (0..run.width).any(|bit| {
                                self.dust_would_interfere(pos_at(c, run.y0 + 2 * bit as i32))
                            });
                        if isolation_diode {
                            Slot::Rep
                        } else {
                            Slot::Dust { station_ok }
                        }
                    }
                };
                chain.push((c, slot));
                c += sign;
            }
        }

        // MANDATORY TAIL per slot: how many cells AFTER this one must be
        // carried before anything could possibly refresh again — a window's
        // approach cells, the two cells at each end of the run, a kept
        // junction — plus `reserve` when the run simply ENDS with no station
        // site left, because the sink's own geometry spends that much more.
        //
        // Without this lookahead the ledger would happily spend its last cell
        // one step before a stretch it cannot legally refresh in, and the word
        // would die inside a crossing window or inside a form adapter.
        let mut tail = vec![0u32; chain.len()];
        {
            let mut acc = reserve;
            for i in (0..chain.len()).rev() {
                tail[i] = acc;
                match chain[i].1 {
                    Slot::Rep | Slot::WindowRefresh => acc = 0,
                    Slot::Dust { station_ok: true } => acc = 0,
                    Slot::Dust { station_ok: false } | Slot::WindowDust => {
                        acc = acc.saturating_add(1)
                    }
                    Slot::WindowBlock => {}
                }
            }
        }

        // Spend the budget: carry while the ledger admits it, refresh when it
        // would otherwise strand the signal. Placing each station as LATE as
        // the physics allows is what minimizes their number.
        let mut ledger = DecayLedger::entering(Carrier::Dust, since0)
            .reserving(reserve)
            .allowing(CROSSING_ALLOWANCE);
        for (i, slot) in chain.iter_mut().enumerate() {
            match slot.1 {
                Slot::WindowBlock => {}
                Slot::Rep | Slot::WindowRefresh => ledger.refresh(),
                Slot::WindowDust => ledger.carry_cell(),
                Slot::Dust { station_ok } => {
                    if station_ok && ledger.needs_station(tail[i]) {
                        slot.1 = Slot::Rep;
                        ledger.refresh();
                    } else {
                        ledger.carry_cell();
                    }
                }
            }
        }
        let since_out = ledger.spent();

        for bit in 0..run.width {
            let y = run.y0 + 2 * bit as i32;
            let d = y - 1;
            for &(c, slot) in &chain {
                match slot {
                    Slot::WindowBlock | Slot::WindowRefresh | Slot::WindowDust => continue,
                    Slot::Rep => {
                        self.put(pos_at(c, y - 1), &bus_block)?;
                        self.put(pos_at(c, y), &rblocks::repeater(toward_driver, 1))?;
                    }
                    Slot::Dust { .. } => {
                        self.put(pos_at(c, y - 1), &bus_block)?;
                        self.put(pos_at(c, y), rblocks::DUST)?;
                    }
                }
            }

            // Dip-under windows (bus8_cross.py v2 canonical tile): step
            // down, dip dust, entry block / repeater / exit block on the
            // shared column's interleaved levels, dip dust, step up.
            // Transparent supports appear ONLY at the dip's slope
            // transitions for bits > 0, where bit n-1's diagonal below
            // must survive.
            for &cc in &dips {
                let at = |o: i32, y: i32| pos_at(cc + o * sign, y);
                // o = -2 and 4: the step upper cells (conductor support —
                // the diode law — which also severs cross-bit diagonals).
                self.put(at(-2, y - 1), &bus_block)?;
                self.put(at(-2, y), rblocks::DUST)?;
                self.put(at(4, y - 1), &bus_block)?;
                self.put(at(4, y), rblocks::DUST)?;
                // o = -1 and 3: the dip dust cells; their supports sit
                // directly above bit n-1's dip dust diagonal.
                let dip_support = if bit > 0 {
                    transparent.as_str()
                } else {
                    bus_block.as_str()
                };
                self.put(at(-1, d - 1), dip_support)?;
                self.put(at(-1, d), rblocks::DUST)?;
                self.put(at(3, d - 1), dip_support)?;
                self.put(at(3, d), rblocks::DUST)?;
                // o = 0..2: the block-sandwich station at the dip level.
                self.put(at(0, d), &bus_block)?;
                self.put(at(1, d - 1), &bus_block)?;
                self.put(at(1, d), &rblocks::repeater(toward_driver, 1))?;
                self.put(at(2, d), &bus_block)?;
            }

            // Through-bus stations (the other bus dips): entry block,
            // repeater on a conductor floor, exit block — the same cells
            // the amendment would have stamped, planned first-hand.
            for &cc in &stations {
                let at = |o: i32, y: i32| pos_at(cc + o * sign, y);
                self.put(at(0, y), &bus_block)?;
                self.put(at(1, y - 1), &bus_block)?;
                self.put(at(1, y), &rblocks::repeater(toward_driver, 1))?;
                self.put(at(2, y), &bus_block)?;
            }
        }
        if let Some(seg) = self.cur_seg.as_mut() {
            seg.runs.push(run.clone());
        }
        Ok(since_out)
    }

    /// The station upgrade a crossing stamps into the THROUGH bus at the
    /// crossing column: its plain dust run over o = 0..2 becomes entry
    /// block / repeater / exit block (the crossed bus pays one repeater
    /// per bit, doubling as its refresh).
    fn plan_station_amendment(
        &mut self,
        other: &BusLayer,
        orun: &RunInfo,
        center: i32,
    ) -> Result<(), String> {
        let sa = orun.sign();
        let toward_driver = if orun.along_x {
            rblocks::facing_name(-sa, 0)
        } else {
            rblocks::facing_name(0, -sa)
        }
        .expect("axis-aligned unit step");
        let pos_at = |c: i32, y: i32| -> P3 {
            if orun.along_x {
                (c, y, orun.fixed)
            } else {
                (orun.fixed, y, c)
            }
        };
        let mut removals = Vec::new();
        let mut additions = BTreeMap::new();
        for bit in 0..orun.width {
            let y = orun.y0 + 2 * bit as i32;
            for o in 0..=2 {
                let c = center + o * sa;
                // Vacate the through bus's dust + support at the station.
                for p in [pos_at(c, y), pos_at(c, y - 1)] {
                    if other.fragment.contains_key(&p) {
                        removals.push(p);
                    }
                }
            }
            let bus_block = other.style.bus_block.clone();
            // Entry block (floats: it is also the cap severing every read
            // to/from the dipping bus one level down), repeater on a
            // conductor floor, exit block (fresh 15).
            additions.insert(pos_at(center, y), bus_block.clone());
            additions.insert(pos_at(center + sa, y - 1), bus_block.clone());
            additions.insert(pos_at(center + sa, y), rblocks::repeater(toward_driver, 1));
            additions.insert(pos_at(center + 2 * sa, y), bus_block);
        }
        self.vacated.extend(removals.iter().copied());
        self.real
            .amendments
            .push((other.name.clone(), removals, additions));
        Ok(())
    }
}

/// Map a position through an instance transform: Y-rotation in quarter
/// turns about the cell bounding box's min corner (the same convention as
/// `Region::rotate_y`), then translation to `at`.
fn transform_pos(p: P3, min: P3, max: P3, rot_y: i32, at: P3) -> P3 {
    let mut rel = (p.0 - min.0, p.1 - min.1, p.2 - min.2);
    let mut size = (max.0 - min.0 + 1, max.2 - min.2 + 1); // (sx, sz)
    for _ in 0..(rot_y.rem_euclid(360) / 90) {
        // (rx, rz) -> (sz - 1 - rz, rx); sizes swap.
        rel = (size.1 - 1 - rel.2, rel.1, rel.0);
        size = (size.1, size.0);
    }
    (at.0 + rel.0, at.1 + rel.1, at.2 + rel.2)
}

/// Rotate a block state's orientation properties to match the instance
/// transform.
fn transform_state(bs: &crate::BlockState, rot_y: i32) -> crate::BlockState {
    let mut out = bs.clone();
    for _ in 0..(rot_y.rem_euclid(360) / 90) {
        out = crate::transforms::transform_block_state_rotate(&out, crate::transforms::Axis::Y, 90);
    }
    out
}

/// The block states a design's endpoints and routes can visit at runtime —
/// interned up front so late-placed cells never sit inert in the tick
/// engine. Delegates to the executor backend's standard list.
#[cfg(feature = "simulation")]
pub fn executor_extra_states() -> Vec<String> {
    crate::simulation::typed_executor::standard_io_extra_states()
}

#[cfg(all(feature = "simulation", feature = "bridge", feature = "mc-tick"))]
fn value_to_u64(v: &crate::io_contract::Value) -> u64 {
    use crate::io_contract::Value;
    match v {
        Value::Bool(b) => *b as u64,
        Value::U32(x) => *x as u64,
        Value::U64(x) => *x,
        Value::I32(x) => *x as u64,
        Value::I64(x) => *x as u64,
        _ => 0,
    }
}

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

    const STONE: &str = "minecraft:stone";
    const LAMP: &str = "minecraft:redstone_lamp[lit=false]";
    const LEVER: &str = "minecraft:lever[face=floor,facing=north,powered=false]";

    /// The design_step1.py endpoint hardware: 8 levers stacked at 2y pitch,
    /// each with its connection dust one step toward the field.
    fn lever_bank(s: &mut UniversalSchematic, x: i32, z: i32, dx: i32, dz: i32) -> P3 {
        for i in 0..8 {
            let y = 2 + 2 * i;
            s.set_block_from_string(x, y - 1, z, STONE).unwrap();
            s.set_block_from_string(x, y, z, LEVER).unwrap();
            s.set_block_from_string(x + dx, y - 1, z + dz, STONE)
                .unwrap();
            s.set_block_from_string(x + dx, y, z + dz, rblocks::DUST)
                .unwrap();
        }
        (x + dx, 2, z + dz)
    }

    /// 8 lamps stacked at 2y pitch, each lamp supporting its own dust.
    fn lamp_bank(s: &mut UniversalSchematic, x: i32, z: i32) -> P3 {
        for i in 0..8 {
            let y = 2 + 2 * i;
            s.set_block_from_string(x, y - 1, z, LAMP).unwrap();
            s.set_block_from_string(x, y, z, rblocks::DUST).unwrap();
        }
        (x, 2, z)
    }

    /// 8 lamps in a horizontal ROW at 2z pitch — a port whose form is NOT the
    /// canonical 2y stack, so routing to it builds a form adapter.
    fn lamp_row(s: &mut UniversalSchematic, x: i32, z: i32) -> P3 {
        for i in 0..8 {
            let zz = z + 2 * i;
            s.set_block_from_string(x, 1, zz, LAMP).unwrap();
            s.set_block_from_string(x, 2, zz, rblocks::DUST).unwrap();
        }
        (x, 2, z)
    }

    /// The refresh stations on bit 0 of a straight bus, along its run axis.
    fn station_pitches(d: &Design, bus: &str, along_x: bool) -> Vec<i32> {
        let layer = d.buses.get(bus).expect("bus");
        let mut at: Vec<i32> = layer
            .fragment
            .iter()
            .filter(|(p, b)| p.1 == 2 && b.starts_with("minecraft:repeater"))
            .map(|(p, _)| if along_x { p.0 } else { p.2 })
            .collect();
        at.sort();
        at.dedup();
        at.windows(2).map(|w| w[1] - w[0]).collect()
    }

    /// A LONG STRAIGHT RUN BETWEEN TWO NATIVE-FORM PORTS SPENDS THE WHOLE
    /// BUDGET.
    ///
    /// This is the measured win: nothing upstream or downstream of the anchors
    /// spends any strength, so the ledger has all 14 cells to give and the
    /// stations sit ~15 apart instead of ~8. Pinning the pitch is what stops a
    /// future edit from quietly reintroducing the unconditional constant.
    #[test]
    fn a_clear_straight_run_refreshes_at_the_full_dust_budget() {
        let mut s = UniversalSchematic::new("long".to_string());
        let a = lever_bank(&mut s, 0, 8, 1, 0);
        let b = lamp_bank(&mut s, 80, 8);
        let mut d = Design::for_schematic("long", s);
        let step = (0, 2, 0);
        let ty = IoType::UnsignedInt { bits: 8 };
        d.declare_input("a", a, step, 8, ty.clone()).unwrap();
        d.declare_output("b", b, step, 8, ty).unwrap();
        d.route_bus("w", "a", &["b"], vec![], BusStyle::default())
            .unwrap();
        assert_eq!(
            d.bus_state("w"),
            Some(&BusState::Routed),
            "the bus must route"
        );
        let pitches = station_pitches(&d, "w", true);
        assert!(!pitches.is_empty(), "a 79-cell run must refresh at all");
        for p in &pitches {
            assert!(
                *p >= 8,
                "the ledger placed a station every {p} cells; the whole point is that a clear \
                 run no longer pays the old ~8-cell pitch (pitches {pitches:?})"
            );
            assert!(
                *p as u32 <= DUST_BUDGET - CROSSING_ALLOWANCE + 1,
                "a {p}-cell gap means {} dust cells, past the budget a run may spend \
                 (pitches {pitches:?})",
                p - 1
            );
        }
        // The interior gaps should be AT the budget: latest-legal placement.
        assert!(
            pitches
                .iter()
                .any(|p| *p as u32 == DUST_BUDGET - CROSSING_ALLOWANCE + 1),
            "no gap reached the full budget; the placement is not latest-legal ({pitches:?})"
        );
    }

    /// Sparse refresh placement must not turn a diode back into dust when that
    /// dust would join a foreign diagonal. Before the clearance-aware choice,
    /// this exact shape routed and was then rejected by the completed-route
    /// check: (8,2,-1) connected downhill to the loose wire at (8,1,0).
    #[test]
    fn a_run_keeps_a_diode_beside_a_foreign_dust_diagonal() {
        let mut s = UniversalSchematic::new("clearance-diode".to_string());
        s.set_block_from_string(0, 1, -1, STONE).unwrap();
        s.set_block_from_string(0, 2, -1, LEVER).unwrap();
        s.set_block_from_string(1, 1, -1, STONE).unwrap();
        s.set_block_from_string(1, 2, -1, rblocks::DUST).unwrap();
        s.set_block_from_string(14, 1, -1, LAMP).unwrap();
        s.set_block_from_string(14, 2, -1, rblocks::DUST).unwrap();
        // Foreign live wire, one down and one across from the planned run.
        s.set_block_from_string(8, 0, 0, STONE).unwrap();
        s.set_block_from_string(8, 1, 0, rblocks::DUST).unwrap();

        let mut d = Design::for_schematic("clearance-diode", s);
        let ty = IoType::Boolean;
        d.declare_input("a", (1, 2, -1), (0, 2, 0), 1, ty.clone())
            .unwrap();
        d.declare_output("b", (14, 2, -1), (0, 2, 0), 1, ty)
            .unwrap();
        let state = d
            .route_bus("w", "a", &["b"], vec![], BusStyle::default())
            .unwrap();
        assert_eq!(state, BusState::Routed, "{state:?}");
        assert!(
            d.bus("w")
                .unwrap()
                .fragment
                .get(&(8, 2, -1))
                .is_some_and(|b| rblocks::is_repeater(b)),
            "the unsafe dust cell must remain a directional diode"
        );
    }

    /// A FORM CONVERSION KEEPS ITS APPROACH TIGHT.
    ///
    /// The adversarial sweep's nine failures are all runs into or out of a form
    /// adapter, whose gather column spends strength the run never saw. The
    /// ledger charges that debt, so the stretch touching the adapter must stay
    /// SHORTER than the budget even though the interior of the same bus widens.
    #[test]
    fn a_run_into_a_form_adapter_leaves_it_headroom() {
        let mut s = UniversalSchematic::new("conv".to_string());
        let a = lever_bank(&mut s, 0, 8, 1, 0);
        let b = lamp_row(&mut s, 80, 8);
        let mut d = Design::for_schematic("conv", s);
        let ty = IoType::UnsignedInt { bits: 8 };
        d.declare_input("a", a, (0, 2, 0), 8, ty.clone()).unwrap();
        d.declare_output("b", b, (0, 0, 2), 8, ty).unwrap();
        d.route_bus("w", "a", &["b"], vec![], BusStyle::default())
            .unwrap();
        assert_eq!(
            d.bus_state("w"),
            Some(&BusState::Routed),
            "the bus must route"
        );
        let layer = d.buses.get("w").expect("bus");
        // The adapter owes something: it is a row->stack gather with a diode at
        // the mouth and one per gather leg, so its column is not a fresh 15.
        let debt = layer
            .fragment
            .keys()
            .filter(|p| p.1 == 2)
            .map(|&p| {
                tile_dust_debt(p, |q| {
                    layer.fragment.get(&q).is_some_and(|b| rblocks::is_dust(b))
                })
            })
            .max()
            .unwrap_or(0);
        assert!(
            debt <= DUST_BUDGET,
            "some dust chain on bit 0 runs {debt} cells with nothing refreshing it, past the \
             {DUST_BUDGET}-cell budget — the ledger is not charging something it should"
        );
    }

    fn crossing_design() -> Design {
        let mut s = UniversalSchematic::new("crossing".to_string());
        let a_in = lever_bank(&mut s, 0, 8, 1, 0);
        let a_out = lamp_bank(&mut s, 16, 8);
        let b_in = lever_bank(&mut s, 8, 0, 0, 1);
        let b_out = lamp_bank(&mut s, 8, 16);
        let mut d = Design::for_schematic("crossing", s);
        let step = (0, 2, 0);
        let ty = IoType::UnsignedInt { bits: 8 };
        d.declare_input("a_in", a_in, step, 8, ty.clone()).unwrap();
        d.declare_output("a_out", a_out, step, 8, ty.clone())
            .unwrap();
        d.declare_input("b_in", b_in, step, 8, ty.clone()).unwrap();
        d.declare_output("b_out", b_out, step, 8, ty).unwrap();
        d
    }

    #[test]
    fn capability_scan_validates_loudly() {
        let mut s = UniversalSchematic::new("caps".to_string());
        lever_bank(&mut s, 0, 8, 1, 0);
        let mut d = Design::for_schematic("caps", s);
        // Anchor on the lever's support (not dust): refused, names the block.
        let err = d
            .declare_input(
                "bad",
                (0, 1, 8),
                (0, 2, 0),
                8,
                IoType::UnsignedInt { bits: 8 },
            )
            .unwrap_err();
        assert!(err.contains("not dust"), "{err}");
        // Output on lever hardware: not readable.
        let err = d
            .declare_output(
                "bad",
                (1, 2, 8),
                (0, 2, 0),
                8,
                IoType::UnsignedInt { bits: 8 },
            )
            .unwrap_err();
        assert!(err.contains("no adjacent lamp"), "{err}");
        // Input over the same cells: drivable, fine.
        d.declare_input(
            "good",
            (1, 2, 8),
            (0, 2, 0),
            8,
            IoType::UnsignedInt { bits: 8 },
        )
        .unwrap();
    }

    /// A library cell shaped like the community ones: its contract names
    /// EXECUTOR hardware (levers in, lamps out), not dust. Bit 0 of `dead`
    /// is a bare lamp with no dust anywhere near it.
    fn buffer_cell() -> UniversalSchematic {
        let mut s = UniversalSchematic::new("buf".to_string());
        let d_hw: Vec<P3> = (0..8).map(|i| (0, 2 + 2 * i, 0)).collect();
        let q_hw: Vec<P3> = (0..8).map(|i| (4, 1 + 2 * i, 0)).collect();
        for i in 0..8 {
            let y = 2 + 2 * i;
            // input lever + its connection dust one step in
            s.set_block_from_string(0, y - 1, 0, STONE).unwrap();
            s.set_block_from_string(0, y, 0, LEVER).unwrap();
            s.set_block_from_string(1, y - 1, 0, STONE).unwrap();
            s.set_block_from_string(1, y, 0, rblocks::DUST).unwrap();
            // output lamp supporting its connection dust
            s.set_block_from_string(4, y - 1, 0, LAMP).unwrap();
            s.set_block_from_string(4, y, 0, rblocks::DUST).unwrap();
        }
        // A lamp with no dust neighbour at all: executor-readable, never
        // bus-routable.
        s.set_block_from_string(4, 40, 0, LAMP).unwrap();
        let layout = crate::io_contract::IoLayoutBuilder::new()
            .add_input(
                "d".to_string(),
                IoType::UnsignedInt { bits: 8 },
                LayoutFunction::OneToOne,
                d_hw,
            )
            .unwrap()
            .add_output(
                "q".to_string(),
                IoType::UnsignedInt { bits: 8 },
                LayoutFunction::OneToOne,
                q_hw,
            )
            .unwrap()
            .add_output(
                "dead".to_string(),
                IoType::Boolean,
                LayoutFunction::OneToOne,
                vec![(4, 40, 0)],
            )
            .unwrap()
            .build();
        s.set_cell_contract(&CellContract::new("buf".to_string(), layout))
            .unwrap();
        s
    }

    /// The blocker this module exists to remove: a PLACED INSTANCE exposes
    /// its contract ports as routable endpoints under `{inst}.{port}`,
    /// transformed, with the dust connection cell derived by hardware scan —
    /// so `route_bus` takes `u0.q` directly.
    #[test]
    fn instance_ports_are_first_class_routing_endpoints() {
        let mut s = UniversalSchematic::new("host".to_string());
        let out = lamp_bank(&mut s, 24, 8);
        let mut d = Design::for_schematic("host", s);
        d.add_cell("buf", buffer_cell()).unwrap();
        // The cell's own bbox starts at y=1, so `at` y=1 lands bit 0's
        // connection dust on the design's canonical y=2 bus level.
        d.place("u0", "buf", (0, 1, 8), 0).unwrap();
        d.declare_output("q_out", out, (0, 2, 0), 8, IoType::UnsignedInt { bits: 8 })
            .unwrap();

        let ports = d.instance_ports().unwrap();
        let names: Vec<&str> = ports.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["u0.d", "u0.dead", "u0.q"], "{names:?}");

        // The contract names the lamp column; the routable endpoint is the
        // dust ON those lamps, one cell up, transformed by the placement.
        let q = ports.iter().find(|p| p.name == "u0.q").unwrap();
        assert!(q.routable(), "{:?}", q.blocked);
        assert_eq!(q.hardware[0], (4, 1, 8));
        assert_eq!(q.wires.as_ref().unwrap()[0], (4, 2, 8));
        assert_eq!(q.step, Some((0, 2, 0)));

        // A lamp with no dust anywhere near it is reported, not mis-routed.
        let dead = ports.iter().find(|p| p.name == "u0.dead").unwrap();
        assert!(!dead.routable());
        assert!(
            dead.blocked
                .as_ref()
                .unwrap()
                .contains("no dust connection cell"),
            "{:?}",
            dead.blocked
        );

        // resolve_port flips to the DESIGN-facing direction: the cell's
        // output drives the fabric.
        let rq = d.resolve_port("u0.q").unwrap();
        assert_eq!(rq.direction, PortDirection::Input);
        assert_eq!(
            d.resolve_port("u0.d").unwrap().direction,
            PortDirection::Output
        );
        let err = d.resolve_port("u0.nope").unwrap_err();
        assert!(err.contains("no contract port `nope`"), "{err}");

        // ...and a bus takes the instance port by name. The endpoint sits on
        // the instance's own body, so pin access must beat its halo.
        let state = d
            .route_bus("chain", "u0.q", &["q_out"], vec![], BusStyle::default())
            .unwrap();
        assert_eq!(state, BusState::Routed, "{state:?}");
        assert!(d.check().unwrap().clean, "{}", d.check().unwrap().json);

        // Driving into a cell input is legal; driving OUT of one is not.
        let err = d
            .route_bus("bad", "u0.d", &["q_out"], vec![], BusStyle::default())
            .unwrap_err();
        assert!(err.contains("cannot drive"), "{err}");

        // Removing the instance takes its bus with it, loudly.
        let report = d.remove_instance("u0").unwrap();
        assert_eq!(report.removed_buses, vec!["chain".to_string()]);
        assert!(d.instance_ports().unwrap().is_empty());
    }

    #[test]
    fn two_crossing_buses_route_with_an_implicit_dip_under() {
        let mut d = crossing_design();
        let a = d
            .route_bus("bus_a", "a_in", &["a_out"], vec![], BusStyle::default())
            .unwrap();
        assert_eq!(a, BusState::Routed);
        let mut style_b = BusStyle::default();
        style_b.bus_block = "minecraft:cyan_concrete".to_string();
        let b = d
            .route_bus("bus_b", "b_in", &["b_out"], vec![], style_b)
            .unwrap();
        assert_eq!(b, BusState::Routed, "{:?}", d.bus_state("bus_b"));

        // The crossing is implicit: bus_b dips (dust at the odd level) and
        // bus_a got its station upgrade (a repeater in its fragment).
        let bus_b = d.bus("bus_b").unwrap();
        assert!(bus_b.fragment.contains_key(&(8, 1, 7)), "dip dust");
        let bus_a = d.bus("bus_a").unwrap();
        assert!(
            bus_a.fragment.values().any(|b| rblocks::is_repeater(b)),
            "station repeater in the through bus"
        );

        // Flatten: one region per layer + embedded merged contract.
        let flat = d.flatten().unwrap();
        let regions = flat.get_region_names();
        assert!(regions.iter().any(|r| r == "bus:bus_a"), "{regions:?}");
        assert!(regions.iter().any(|r| r == "bus:bus_b"), "{regions:?}");
        let contract = flat.embedded_cell_contract().unwrap().unwrap();
        assert!(contract.io.get_input("a_in").is_some());
        assert!(contract.io.get_output("b_out").is_some());

        // check(): DRC + LVS come back clean.
        let check = d.check().unwrap();
        assert!(check.clean, "{}", check.json);
    }

    #[test]
    fn unroutable_is_a_state_not_an_exception() {
        let mut d = crossing_design();
        // A SEALED stone wall across the a-line. A single blocking column is
        // no longer enough — the corridor search routes around one of those —
        // so unroutability now needs a wall the bus genuinely cannot get past.
        // The reason must name the blocker and what to do about it.
        for z in -260..=260 {
            for y in 0..=20 {
                d.set_block((12, y, z), STONE).unwrap();
            }
        }
        let state = d
            .route_bus("bus_a", "a_in", &["a_out"], vec![], BusStyle::default())
            .unwrap();
        match state {
            BusState::Failed(reason) => {
                assert!(reason.contains("no corridor"), "{reason}");
                assert!(
                    reason.contains("(12,"),
                    "names the blocker location: {reason}"
                );
                assert!(reason.contains("loose block"), "names the owner: {reason}");
                // And it must say whether the LEVEL is the problem or the
                // workspace is genuinely full — the two need opposite fixes, and
                // "no path" told the user neither. Here the wall spans y 0..=20,
                // so no level is clear.
                assert!(
                    reason.contains("No level within 8 blocks"),
                    "must report the cross-level verdict: {reason}"
                );
            }
            other => panic!("expected Failed, got {other:?}"),
        }
        assert!(d.bus("bus_a").unwrap().fragment.is_empty());
        // The failed layer does not poison later routing.
        let b = d
            .route_bus("bus_b", "b_in", &["b_out"], vec![], BusStyle::default())
            .unwrap();
        assert_eq!(b, BusState::Routed, "{:?}", d.bus_state("bus_b"));
    }

    #[test]
    fn a_dogleg_routes_through_an_implicit_corner() {
        let mut d = crossing_design();
        // a_in (1,2,8) -> b_out (8,2,16): not axis-aligned; the planner
        // bends through one implicit corner joint instead of failing.
        let state = d
            .route_bus("diag", "a_in", &["b_out"], vec![], BusStyle::default())
            .unwrap();
        assert_eq!(state, BusState::Routed, "{:?}", d.bus_state("diag"));
        let bus = d.bus("diag").unwrap();
        // One trunk segment realized as two perpendicular runs + the
        // corner joint dust at (8, 2, 8).
        assert_eq!(bus.segments.len(), 1);
        assert_eq!(bus.segments[0].runs.len(), 2);
        assert!(bus.fragment.contains_key(&(8, 2, 8)), "corner joint dust");
        let check = d.check().unwrap();
        assert!(check.clean, "{}", check.json);
    }

    #[test]
    fn embedded_contract_round_trips_through_schem_bytes() {
        let mut d = crossing_design();
        d.route_bus("bus_a", "a_in", &["a_out"], vec![], BusStyle::default())
            .unwrap();
        let bytes = d.to_schem_bytes().unwrap();
        let back = crate::formats::schematic::from_schematic(&bytes).unwrap();
        let (contract, warnings) = back.resolve_cell_contract().unwrap().unwrap();
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(contract.name, "crossing");
        // Executor-facing positions: inputs are the LEVER cells.
        let a_in = contract.io.get_input("a_in").unwrap();
        assert_eq!(a_in.positions[0], (0, 2, 8));
        let a_out = contract.io.get_output("a_out").unwrap();
        assert_eq!(a_out.positions[0], (16, 2, 8));
    }
}