delvewright-dsl 0.22.0

Staged JSON DSL types and schemas for Delvewright adventure-map campaigns — the format the delvec compiler reads.
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
//! **The whole owns the space and hands out boxes** (spec-0049 §4) — pipeline
//! stage 4, the geometric embedding of the layout graph.
//!
//! One campaign stage document, `site-plan.json`: the whole map's design of
//! record. It says where the region is, which plane each place stands on, what
//! footprint each place gets, where two places connect and through what opening,
//! what mass the whole itself owns, and which of the brief's numbers the plan is
//! held to.
//!
//! Everything here is decided **upstream of any geometry**. No block exists yet;
//! nothing in this module reads one. What is being judged is whether the plan is
//! a plan — whether the boxes fit in the region and not in each other, whether
//! two places that claim to connect really touch, and whether the numbers the
//! brief fixed still hold once the boxes are drawn.
//!
//! # Extent flows down, and it is unrepresentable for it to flow up
//!
//! The reset this stage answers was caused by parts choosing their own size and
//! the whole becoming whatever they added up to. So [`SitePlanContent::region`]
//! is a **required field with no derived spelling**: there is no
//! `"region": "fit"`, no default, and no constructor anywhere that computes one
//! from the boxes. A plan cannot state its extent as a consequence; it can only
//! state it, and `DW0826` then refuses a box that does not fit, naming the box
//! rather than the region. That is not a check — it is the absence of a way to
//! write the other thing.
//!
//! # Seams are allocated, not discovered
//!
//! A seam is placed by the plan, on a face the two boxes already share, at cells
//! the plan names. Two places therefore connect **by construction**: the
//! two-pieces-cannot-mate failure is resolved here, where both boxes are still
//! free to move, and never later between two finished buildings. `DW0828` and
//! `DW0829` are what make the allocation real rather than a claim.
//!
//! # One authority per fact
//!
//! Three places where the obvious shape would have carried two:
//!
//! * A box's floor is its **datum** and nothing else. The spec's `min` carried a
//!   `y` beside the declared floor, which is two numbers for one plane and no
//!   rule about which wins; here a box is a footprint (`min`/`extent` on `x`
//!   and `z`) standing at a [`Floor`]. §9 records the departure.
//! * A seam's **rise is derived** from the two boxes' floors. Authoring it would
//!   be authoring arithmetic — unlike the layout graph's `critical_path`, which
//!   is authored precisely because it is a *choice* among many, a rise is the
//!   consequence of where the plan already put the two places. §9 records it.
//! * The plan's `lighting` is [`crate::stages::AreaLighting`], the engine's
//!   existing "which fixture, to what light level" object, not a twin of it.
//!
//! # No opt-out exists
//!
//! Not one check here has an acknowledgement, an override or an exemption
//! field. That is deliberate and it is the cheapest possible answer to
//! `CLAUDE.md`'s question of every escape hatch — *could the defect this hatch
//! exists to catch supply the hatch's own proof obligation?* — because a hatch
//! that does not exist cannot be supplied.
//!
//! Determinism (ADR-0006): every set and map is a `BTreeSet`/`BTreeMap` and
//! every walk is over a slice in document order.

use std::collections::{BTreeMap, BTreeSet};
use std::num::NonZeroU32;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::diagnostic::{Diagnostic, DwCode, ExitTier};
use crate::envelope::Campaign;
use crate::ids::{DatumId, EdgeId, FactId, NodeId, ViewId, VolumeId};
use crate::layout::{Edge, LayoutGraphContent, StationKind};
use crate::metrics::{
    MAX_JUMP_RISE_16, MetricKind, MetricValue, Metrics, Pitch, Reads, SizeClass, WayClass,
    passable_clearance_cells, passable_width_cells,
};
use crate::stages::AreaLighting;

/// `DW0824`: the graph and the plan do not agree exactly.
pub const DW_PLAN_AGREEMENT: DwCode = DwCode::new("DW0824", ExitTier::Build);

/// `DW0825`: a box leaves the kit grid.
pub const DW_BOX_OFF_GRID: DwCode = DwCode::new("DW0825", ExitTier::Build);

/// `DW0826`: a box leaves the region.
pub const DW_BOX_LEAVES_REGION: DwCode = DwCode::new("DW0826", ExitTier::Build);

/// `DW0827`: two boxes overlap.
pub const DW_BOXES_OVERLAP: DwCode = DwCode::new("DW0827", ExitTier::Build);

/// `DW0828`: a seam is not on a shared face.
pub const DW_SEAM_NOT_SHARED: DwCode = DwCode::new("DW0828", ExitTier::Build);

/// **How many cells stand between two connected boxes: the wall they share.**
///
/// The one number every geometric check in this stage is written against, and
/// the one an author has to know before the first box goes down. A box is the
/// **play space** of a place — the cells a body can be in — so the shell is not
/// inside it: it stands in this gap, and two places that connect leave exactly
/// this much room for it. Boxes placed flush have no wall to cut a seam through
/// and `DW0828` refuses them.
///
/// It is a constant rather than a literal because the authoring documents state
/// it: [`PlanBox`]'s schema description carries this value, and
/// `crates/dsl/tests/v14_site_plan.rs` asserts the exported description against
/// this constant, so the rule a person reads and the rule the checks enforce
/// cannot drift apart.
pub const SHARED_FACE_GAP_CELLS: i64 = 1;

/// `DW0829`: a seam's opening is not a standard, or does not fit.
pub const DW_SEAM_OPENING: DwCode = DwCode::new("DW0829", ExitTier::Build);

/// `DW0830`: a stair seam cannot be built at standard pitch.
pub const DW_STAIR_PITCH: DwCode = DwCode::new("DW0830", ExitTier::Build);

/// `DW0831`: a drop seam falls outside the drop policy.
pub const DW_DROP_POLICY: DwCode = DwCode::new("DW0831", ExitTier::Build);

/// `DW0876`: a seam does not declare a connection this engine builds
/// (spec-0053 §6).
///
/// **One code, four shapes of one claim** — the claim being that this seam
/// states a crossing the derivation can build and the observer can measure:
///
/// 1. it declares neither an `opening` nor a `contact`, or both;
/// 2. its contact's span leaves the shared face `DW0828` established;
/// 3. its contact's span is not **wider than the broadest standard opening**;
/// 4. it is a contact on a `stair`, `barred` or `vision` connection.
///
/// They are one code rather than four because the author's next action is the
/// same in every case — say which kind of hand-off this is and give it a shape
/// the engine has — and because a seam exhibiting one of them has no crossing
/// for any rule below to judge. It is the shape `DW0830` already carries for a
/// stair ("three shapes of one claim") and `DW0829` for an opening ("two halves
/// of one claim that the opening is usable").
///
/// Shape 3 is the floor that keeps the whole surface honest, and it is
/// **structural rather than seeded**: it is derived from the standard opening
/// set, so anything at or under it COULD have been a portal, and a doorway
/// declared a contact to dodge the standard set is refused by its own width.
/// That is the property `CLAUDE.md` demands of an escape hatch — the defect this
/// exists to catch is incapable of supplying the hatch's proof obligation.
pub const DW_CONTACT: DwCode = DwCode::new("DW0876", ExitTier::Build);

/// `DW0832`: a box violates its node's size class.
pub const DW_SIZE_CLASS: DwCode = DwCode::new("DW0832", ExitTier::Build);

/// `DW0833`: a brief identity does not hold.
pub const DW_IDENTITY_FALSE: DwCode = DwCode::new("DW0833", ExitTier::Build);

/// `DW0834`: the identity gate binds nothing. Warning — see [`identities`].
pub const DW_IDENTITY_EMPTY: DwCode = DwCode::new("DW0834", ExitTier::Build);

/// `DW0835`: a whole-owned volume enters a box.
pub const DW_VOLUME_IN_BOX: DwCode = DwCode::new("DW0835", ExitTier::Build);

/// `DW0839`: two placement authorities in one campaign — a `site-plan.json` and
/// a non-empty `areas[]` both present.
pub const DW_TWO_AUTHORITIES: DwCode = DwCode::new("DW0839", ExitTier::Build);

/// `DW0883`: a box is not placed exactly once (spec-0059 §5). Two shapes of one
/// claim: a connected component of the seam graph in which no box is pinned, so
/// nothing places it; and a pinned box the packing also reaches, at a different
/// corner, so two things place it.
pub const DW_UNPLACED: DwCode = DwCode::new("DW0883", ExitTier::Build);

// ---------------------------------------------------------------------------
// The vocabulary the derivation synthesizes (spec-0049 §5.2)
// ---------------------------------------------------------------------------

/// **The one area a site-plan campaign has.**
///
/// A campaign places its pieces either with `areas[]` or with a site plan, never
/// both (`DW0839`), so a site-plan campaign has exactly one place for an NPC to
/// stand in and one area for a quest to belong to. The name is fixed rather than
/// authored because there is nothing to choose: the site plan is the whole map,
/// and a second name for it would be a second way to spell one thing.
pub const SITE_AREA: &str = "area/site";

/// The anchor name the campaign's **entry** stands under.
///
/// A *name*, and only a name: what makes this anchor the entry is the declared
/// entry **role** (spec-0046) the derivation gives it, which is the one thing
/// the compiler's resolution consults. The spelling survives because a
/// site-plan campaign's quests and NPCs may address the entry cell like any
/// other anchor, and `spawn` is the word the rest of the vocabulary already
/// uses; nothing resolves through it.
pub const ENTRY_ANCHOR: &str = "spawn";

/// The anchor at a place's floor centre — where quests, NPCs and waves in a
/// site-plan campaign stand.
///
/// `node/near-hall` becomes `anchor/node-near-hall`, and the reshaping is not
/// cosmetic: a campaign reaches an anchor through [`crate::ids::AnchorId`],
/// which is `anchor/<kebab>`, so `node/<id>` — spec-0049 §5.2's spelling — is
/// not a name any document could write. The three families (`node-`, `seam-`,
/// `unlock-`) are disjoint by their first segment, so no two synthesized
/// anchors can collide however the graph is named.
#[must_use]
pub fn node_anchor(node: &NodeId) -> String {
    format!("anchor/node-{}", slug(node.0.as_str()))
}

/// The gate region over a `barred` seam's opening — what an `open-gate` or a
/// `shortcut` names.
#[must_use]
pub fn seam_anchor(edge: &EdgeId) -> String {
    format!("anchor/seam-{}", slug(edge.0.as_str()))
}

/// The anchor on the openable side of a one-sided `barred` seam, where a
/// shortcut's far-side affordance stands.
#[must_use]
pub fn seam_unlock_anchor(edge: &EdgeId) -> String {
    format!("anchor/unlock-{}", slug(edge.0.as_str()))
}

/// The part of an id after its kind prefix.
fn slug(id: &str) -> &str {
    id.split_once('/').map_or(id, |(_, rest)| rest)
}

/// **What a sealed `barred` seam stands in until content opens it.**
///
/// One definition, here rather than in the derivation that lays it, for the same
/// structural reason the metrics table owns the nav model's constants: two
/// parties need this block and they need the *same* one. The derivation writes it
/// into the gate region and declares it on the synthesized gate anchor; every
/// verb that needs a gate's fill block — `close-gate`, a `shortcut`'s clear, a
/// `timed-gate`'s clock — asks [`synthesized_gate_block`] whether this campaign
/// declares one. A copy in each place would be an agreement rather than a fact.
pub const SEAM_BAR: &str = "minecraft:iron_bars";

/// The fill block a **synthesized** gate anchor declares, or `None` when `anchor`
/// is not one of this campaign's derived seam gates.
///
/// This exists because `DW0343`'s question — *can the compiler fill and clear
/// this gate?* — used to be answered by one instrument only, the prefab registry,
/// and a derived world has no prefab. The answer came back honest and about a
/// smaller world than the campaign has: a `shortcut` naming the very
/// `anchor/seam-<edge>` the derivation seals with [`SEAM_BAR`] was refused for
/// declaring no fill block, while the block sat in the derivation's own
/// `AnchorSpec::Gate`. Nothing was red, because the check was refusing content.
///
/// `None` for a campaign with no site plan, and for any anchor the derivation
/// does not synthesize — those are the prefab registry's to answer for, and this
/// function never overrides it.
#[must_use]
pub fn synthesized_gate_block(c: &Campaign, anchor: &str) -> Option<&'static str> {
    // Asks the ONE kind authority rather than re-walking the edges, and that is
    // the whole repair: this used to enumerate `Edge::Barred` alone, so a
    // `close-gate`, `shortcut` or `timed-gate` naming a **gate station**
    // (spec-0052) would have been refused by `DW0343` for declaring no fill
    // block — a refusal whose message says "declare the gate on an anchor of a
    // piece an area binds", which a site-plan campaign cannot do at all
    // (`DW0839` refuses a campaign that carries both `areas[]` and a plan).
    // A narrow binding on the general mechanism, reading as a missing feature.
    matches!(
        synthesized_anchor_kinds(c).get(anchor),
        Some(StationKind::Gate)
    )
    .then_some(SEAM_BAR)
}

/// **Every anchor a site-plan campaign's blockout provides, and what SHAPE each
/// one is** — the single authority behind [`synthesized_anchors`].
///
/// The kind travels with the name because a kind is a property of the **anchor**,
/// not of the verb that first needed one: `synthesized_gate_block` needed to know
/// whether a name was a gate and answered by privately re-walking the edges, and
/// a second consumer wanting the same fact would have re-walked them again. One
/// function answers it, and everything that needs a shape asks here.
///
/// The mapping, and it is total:
///
/// * [`ENTRY_ANCHOR`] and every `anchor/node-…` — [`StationKind::Point`], the
///   floor centre a body stands on.
/// * every `anchor/unlock-…` — [`StationKind::Point`], where the shortcut's
///   far-side affordance stands.
/// * every `anchor/seam-…` — [`StationKind::Gate`], the region the derivation
///   fills with [`SEAM_BAR`] and content opens.
/// * every declared station — the kind its node declared (spec-0052 §3).
///
/// Empty for a campaign with no site plan — it has prefabs instead, and their
/// metadata is the authority.
#[must_use]
pub fn synthesized_anchor_kinds(c: &Campaign) -> BTreeMap<String, StationKind> {
    let mut out: BTreeMap<String, StationKind> = BTreeMap::new();
    if c.site_plan.is_none() {
        return out;
    }
    let Some(graph) = c.layout_graph.as_ref().map(|g| &g.content) else {
        return out; // `DW0824` refused the plan; there is nothing to name.
    };
    out.insert(ENTRY_ANCHOR.to_string(), StationKind::Point);
    for n in &graph.nodes {
        out.insert(node_anchor(&n.id), StationKind::Point);
        // A station whose name collides with a synthesized one is `DW0869`, and
        // one that collides with another station is `DW0870`; both are errors,
        // so this insert never silently reinterprets a name a campaign builds
        // with. Inserting anyway keeps the set EXACT for the refused document
        // too, which is what lets the kind check name the declared kind rather
        // than a shape the author did not write.
        for s in &n.stations {
            out.insert(s.anchor.as_str().to_string(), s.kind);
        }
    }
    for e in &graph.edges {
        let Edge::Barred { id, opens_from, .. } = e else {
            continue;
        };
        out.insert(seam_anchor(id), StationKind::Gate);
        if !matches!(opens_from, crate::layout::OpensFrom::Either) {
            out.insert(seam_unlock_anchor(id), StationKind::Point);
        }
    }
    out
}

/// **Every anchor a site-plan campaign's blockout provides**, derived from the
/// documents alone.
///
/// One authority, and that is why it lives here rather than in the derivation
/// that places them: validation resolves a campaign's anchor references against
/// this set, the derivation creates exactly these anchors, and a name that
/// validated could therefore never fail to exist at build time. Two functions
/// agreeing about the spelling is the drift this one removes.
///
/// Empty for a campaign with no site plan — it has prefabs instead, and their
/// metadata is the authority.
#[must_use]
pub fn synthesized_anchors(c: &Campaign) -> BTreeSet<String> {
    // The names ARE the keys of the kind table, taken rather than re-derived:
    // two functions walking the graph and agreeing about the spelling is the
    // exact drift this module's note exists to remove, and a station made the
    // walk long enough that a second copy would eventually diverge.
    synthesized_anchor_kinds(c).into_keys().collect()
}

/// **The synthesized names one PLACE owes** (spec-0050 §6) — the subset of
/// [`synthesized_anchors`] whose bearer is this box.
///
/// Its own `anchor/node-…`; [`ENTRY_ANCHOR`] when it is the entry node; each
/// `anchor/unlock-…` whose `opens_from` side it is — the side the derivation
/// stands that affordance in. A gate region (`anchor/seam-…`) is **never** owed:
/// it is whole fabric, standing in a party plane the piece does not own.
///
/// Here rather than in `crate::detailplan` because the answer is a fact about
/// the graph, and [`synthesized_anchors`] is the one authority for what a
/// site-plan campaign provides — a second module deciding which names belong to
/// which place is exactly the two-functions-agreeing-about-spelling drift that
/// note exists to remove.
///
/// `crates/delvec/tests/blockout.rs`'s
/// `the_owed_anchors_partition_the_synthesized_set` proves the two PARTITION
/// rather than merely overlap: every synthesized name is owed by exactly one
/// place or is a gate region no place owes. A name in neither would be one a
/// campaign resolves and no piece is ever asked for; a name in both would be two
/// pieces claiming one anchor.
///
/// Empty for a campaign with no site plan, and for a node the graph does not
/// have.
#[must_use]
pub fn owed_anchors(c: &Campaign, node: &NodeId) -> BTreeSet<String> {
    let mut out: BTreeSet<String> = BTreeSet::new();
    if c.site_plan.is_none() {
        return out;
    }
    let Some(graph) = c.layout_graph.as_ref().map(|g| &g.content) else {
        return out; // `DW0824` refused the plan; there is nothing to name.
    };
    let Some(n) = graph.nodes.iter().find(|n| &n.id == node) else {
        return out; // `DW0842` names a row whose place the graph does not have.
    };
    out.insert(node_anchor(node));
    if &graph.entry == node {
        out.insert(ENTRY_ANCHOR.to_string());
    }
    // Every station of this node (spec-0052 §6). The owed set grows **upstream**,
    // and that one widening is what carries the whole binding chain: the
    // `detail-plan` `anchors` map must now bind each of them, and it still
    // refuses every key outside this set, so a binding cannot invent vocabulary
    // and a typo cannot pass as intent.
    for s in &n.stations {
        out.insert(s.anchor.as_str().to_string());
    }
    for e in &graph.edges {
        let Edge::Barred { id, opens_from, .. } = e else {
            continue;
        };
        let side = match opens_from {
            crate::layout::OpensFrom::A => e.a(),
            crate::layout::OpensFrom::B => e.b(),
            crate::layout::OpensFrom::Either => continue,
        };
        if side == node {
            out.insert(seam_unlock_anchor(id));
        }
    }
    out
}

// ---------------------------------------------------------------------------
// The document (spec-0049 §4.1)
// ---------------------------------------------------------------------------

/// The `site-plan` stage document's payload: the geometric embedding of the
/// layout graph, and the whole map's design of record.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SitePlanContent {
    /// **The whole map's one region, in world coordinates.**
    ///
    /// Required, with no way to omit it and no way to derive it: the schema has
    /// no "compute this from the boxes" spelling, so extent-flows-up is
    /// unrepresentable rather than merely forbidden. The number comes from the
    /// geometry brief and the identities hold the plan to it.
    ///
    /// The water plane is deliberately **not** site-plan surface: `horizon:
    /// ocean` in the stage-1 world document already fixes sea level, and the
    /// plan reads that single authority rather than restating it.
    pub region: WorldBox,
    /// Named ground planes the boxes stand on.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub datums: Vec<Datum>,
    /// **Exactly one box per graph node** (`DW0824`).
    pub boxes: Vec<PlanBox>,
    /// **Exactly one seam per traversal edge** (`DW0824`). A `vision` edge
    /// carries a [`Sightline`] instead — see [`Sightline`] for why.
    pub seams: Vec<Seam>,
    /// The mass the WHOLE owns: the mountain a cave system is inside, the ground
    /// under a village, the sky a silhouette needs kept empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub volumes: Vec<Volume>,
    /// The guarded comparisons binding this plan to the geometry brief's facts.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub identities: Vec<Identity>,
    /// One per `vision` edge (`DW0824`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sightlines: Vec<Sightline>,
    /// The named exterior vantages the walk judges the silhouette from. Optional;
    /// a plan with zero views has that zero stated in the binding line.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub views: Vec<View>,
    /// One lighting setting applied to every enclosed box, so a blockout
    /// interior is walkable at night without per-box surface.
    ///
    /// **The engine's existing object**, not a twin of it: [`AreaLighting`] is
    /// already "which fixture, to what light level", and the relight pass that
    /// consumes it is the same pass either way. A second two-field struct here
    /// would be the private-copy defect `CLAUDE.md` names, and it would fork the
    /// range check the moment one of them grew a third field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lighting: Option<AreaLighting>,
}

/// A box of world cells: its low corner and its extent, in blocks.
///
/// The cells are `min[i] ..= min[i] + extent[i] - 1` on each axis. The extent is
/// [`NonZeroU32`] rather than a `u32` a check refuses: a zero-extent region is
/// not a small region, it is a document that does not describe a volume, and the
/// schema says so (`minimum: 1`) so the parse refuses it as an ordinary
/// `DW0100`. One fewer diagnostic to write and one fewer to forget.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WorldBox {
    /// Low corner `[x, y, z]`, in world coordinates.
    pub min: [i64; 3],
    /// Extent `[dx, dy, dz]`, in blocks.
    pub extent: [NonZeroU32; 3],
}

impl WorldBox {
    /// The high corner (inclusive).
    #[must_use]
    pub fn max(&self) -> [i64; 3] {
        [
            self.min[0] + i64::from(self.extent[0].get()) - 1,
            self.min[1] + i64::from(self.extent[1].get()) - 1,
            self.min[2] + i64::from(self.extent[2].get()) - 1,
        ]
    }
}

/// A named ground plane a box's floor sits on.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Datum {
    /// Datum id (`datum/<kebab>`), unique within the plan.
    pub id: DatumId,
    /// The world `y` of the walk plane.
    pub y: i64,
    /// What this plane is, for a reader of the plan.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// Where a place's walk plane is.
///
/// Two spellings of one number, and the second is not redundant: a plane several
/// places stand on is named once as a [`Datum`] and moved once, while a place
/// that stands alone at its own height has no plane to name. An `identities[]`
/// entry can only bind to a *named* one, which is the pressure toward naming.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum Floor {
    /// A plane the plan names (`DW0112` if the plan declares no such datum).
    Datum(DatumId),
    /// A world `y` this place alone stands at.
    Y(i64),
}

/// What closes a place overhead.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum Ceiling {
    /// Cells of headroom over the walk plane. A body's feet are at the floor and
    /// the ceiling course sits at `floor + clearance`.
    Clearance(NonZeroU32),
    /// A sky-open place — a courtyard, a shore, a summit.
    ///
    /// The plan claims the ground and its size class's own minimum clearance,
    /// and **nothing above that**: an open place is precisely one that makes no
    /// claim on the air over it, so a `clearance` volume above a courtyard is
    /// the whole reserving sky rather than two authorities over one cell.
    Open,
}

/// One place, embedded: a footprint standing on a plane.
///
/// **A box is a plan, not a prism.** Its `min`/`extent` are the two horizontal
/// axes and its vertical position is [`PlanBox::floor`] — one authority for the
/// plane, where a `y` inside `min` beside a declared floor would have been two
/// numbers with no rule about which the derivation believes.
///
/// **A box is the PLAY SPACE, and connected boxes are separated by exactly one
/// cell.** `extent` is the interior a body can stand in; the shell the blockout
/// derivation builds is not inside it. That shell stands in the one-cell gap
/// between two neighbours, and on the course under the floor and over the
/// ceiling. So two places that connect are placed one cell apart on the face
/// they share — that cell is the wall they have in common, written once — and
/// two boxes placed flush have no wall for a seam to be cut through, which
/// `DW0828` refuses. Worked: a box at `min: [4, 4]` with `extent: [4, 4]`
/// occupies x 4..7, so its eastern neighbour's `min` x is 9, never 8.
///
/// Two consequences follow, and they are what make the checks say what they look
/// like they say: the size-class ladder judges `extent` directly (`DW0832`),
/// its smallest rung `4 × 4` being exactly one kit quantum; and a plan never
/// states a wall's thickness anywhere, because the gap is where the wall is.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlanBox {
    /// The graph node this box embeds.
    ///
    /// **The ordering tooth, at the type level**: there is no way to write a box
    /// that does not name a place, so a site plan cannot describe a space the
    /// layout graph has not declared (spec-0049 §7.1).
    pub node: NodeId,
    /// **A pin**: the low corner `[x, z]` in world coordinates, when the author
    /// chooses where this box stands. Optional (spec-0059 §2): a box with no pin
    /// stands where the packing puts it — one cell beyond the face of the box
    /// its first seam in document order hangs it off. At least one box of every
    /// connected component of the seam graph is pinned, or nothing places the
    /// component (`DW0883`); a pinned box the packing also reaches at a
    /// different corner is refused naming both (`DW0883`). Two horizontal
    /// numbers, never three — the vertical position is `floor`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min: Option<[i64; 2]>,
    /// Interior footprint `[dx, dz]`, in blocks, on the kit grid (`DW0825`).
    /// Two horizontal numbers, never three — the vertical size is `ceiling`.
    ///
    /// **This is play space, not the building.** The box covers `min` to
    /// `min + extent - 1` inclusive, and the walls stand outside it, in the
    /// one-cell gap that separates connected places (`DW0828`).
    pub extent: [NonZeroU32; 2],
    /// The walk plane.
    pub floor: Floor,
    /// What closes it overhead.
    pub ceiling: Ceiling,
}

/// Which side of a box a seam sits on.
///
/// The engine's existing face vocabulary — the same six names a prefab's face
/// contract writes (`compiler::faces`), so a reader who knows one knows the
/// other and no translation table exists to disagree with itself.
#[derive(
    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "kebab-case")]
pub enum Face {
    /// `+x`.
    East,
    /// `-x`.
    West,
    /// `+y`.
    Up,
    /// `-y`.
    Down,
    /// `+z`.
    South,
    /// `-z`.
    North,
}

impl Face {
    /// The unit vector this face points along.
    #[must_use]
    pub fn vector(self) -> [i64; 3] {
        match self {
            Face::East => [1, 0, 0],
            Face::West => [-1, 0, 0],
            Face::Up => [0, 1, 0],
            Face::Down => [0, -1, 0],
            Face::South => [0, 0, 1],
            Face::North => [0, 0, -1],
        }
    }

    /// True for a face whose plane is horizontal (a floor or a ceiling).
    #[must_use]
    pub fn is_horizontal_plane(self) -> bool {
        matches!(self, Face::Up | Face::Down)
    }

    /// The name a refusal prints.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Face::East => "east",
            Face::West => "west",
            Face::Up => "up",
            Face::Down => "down",
            Face::South => "south",
            Face::North => "north",
        }
    }
}

/// A crossing's position on one box's face, from that box's own low corner.
///
/// One integer on a wall face (cells along the face's horizontal axis), a pair
/// through a floor or ceiling (cells along `x` and `z`). Untagged, so the
/// document writes `"at": 2` or `"at": [2, 3]`; the face decides which shape is
/// a position and the other is `DW0828`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum Offset {
    /// Cells along a vertical face's horizontal axis.
    Along(i64),
    /// Cells along `x` and `z` on a horizontal face.
    Plane([i64; 2]),
}

/// One traversal edge, allocated: an opening on a face the two boxes share.
///
/// The seam carries **no rise** and **no sill**. A rise is `floor(b) − floor(a)`, which the plan
/// has already stated by putting the two places where it put them; a second
/// declaration of it could only ever agree or be a refusal teaching nothing the
/// datums did not already say. `DW0830` and `DW0831` judge the derived number,
/// and the stage-5 observer of the built bytes judges the realized one against
/// the same derivation rather than against an author's copy of it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Seam {
    /// The graph edge this seam allocates.
    pub edge: EdgeId,
    /// Which face **of the edge's `a` box** the seam sits on. The `b` box is the
    /// neighbour across it (`DW0828`).
    pub face: Face,
    /// Where the crossing sits on **`a`'s** face: an offset from `a`'s own low
    /// corner along the face, never a world coordinate (spec-0059 §2).
    ///
    /// * on a vertical face (`east`/`west`/`north`/`south`) — one integer, cells
    ///   along the face's horizontal axis (`z` for east/west, `x` for
    ///   north/south). The **sill is not written**: it is
    ///   `max(floor(a), floor(b))`, which the plan has already stated.
    /// * on a horizontal face (`up`/`down`) — `[dx, dz]`, cells along `x` and
    ///   `z`.
    ///
    /// Omitted, the crossing is **centred** on the face: `(extent - width) div
    /// 2`. An offset that leaves the face, or of the wrong shape for the face,
    /// is `DW0828`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at: Option<Offset>,
    /// Where the same crossing sits on **`b`'s** face — the same offset, taken
    /// from `b`'s own low corner. Omitted, centred on `b`'s face. The packing
    /// places `b` so that the two agree: `corner(b) = corner(a) + at - meets`
    /// along the face (spec-0059 §3). On a seam whose two boxes both already
    /// stand, the two must name the same cells (`DW0828`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meets: Option<Offset>,
    /// **A PORTAL**: a named opening from the metrics table's standard set
    /// (`DW0812` on a name the table does not define, `DW0829` on one that does
    /// not fit). A body crosses at exactly the cells `at` and this standard
    /// allocate.
    ///
    /// **Exactly one of this and [`Seam::contact`]** (`DW0876`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub opening: Option<String>,
    /// **A CONTACT**: the two places simply meet along a front, rather than
    /// through a doorway (spec-0053 §4).
    ///
    /// **Exactly one of this and [`Seam::opening`]** (`DW0876`).
    ///
    /// The width of a front where two places meet is a fact of those two boxes'
    /// shared face — per-campaign geometry, continuous — so it is never a named
    /// standard. A table that enumerated it would gain a new entry per campaign,
    /// which is the size ladder's own failure mode reproduced in the opening
    /// set: an `opening.gate-front` of 21×4 is content wearing a standard's
    /// clothes (spec-0053 §7).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contact: Option<Contact>,
    /// Which of the edge's two boxes hosts the stair massing. Required on a
    /// `stair` edge and refused on any other (`DW0830`, `DW0824`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stair_in: Option<NodeId>,
}

/// A mass the whole itself owns.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Volume {
    /// Volume id (`volume/<kebab>`), unique within the plan.
    pub id: VolumeId,
    /// The cells it covers.
    pub region: WorldBox,
    /// What the whole is doing with them.
    pub role: VolumeRole,
    /// What this mass is, for a reader of the plan.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// What a whole-owned volume is for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum VolumeRole {
    /// Solid mass the places are cut into — the mountain around a cave system.
    Massif,
    /// The ground the places stand on.
    Ground,
    /// Air the whole keeps empty — the sky a silhouette needs, the drop a
    /// vista looks over.
    Clearance,
}

/// One guarded comparison binding the plan to a fact of the written brief.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Identity {
    /// The brief fact this holds the plan to (`DW0112` if the brief has no such
    /// fact).
    pub fact: FactId,
    /// What is measured off the plan.
    pub measure: Measure,
    /// How the measurement must stand to the fact's value.
    pub cmp: Cmp,
}

/// What an identity measures off the plan.
///
/// A small **fixed** vocabulary, spelled as a tagged union rather than as the
/// spec's `box(<node>).extent.x` string. The vocabulary is exactly the spec's
/// five; what changes is that a measure is parsed by serde instead of by a
/// grammar this module would have had to write, own and document — so an
/// unknown measure is an ordinary `DW0100`, a node it names is checked like
/// every other reference, and the growth the spec's marked judgement predicts is
/// a variant rather than a second escaping rule. §9 records the departure.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "of", rename_all = "kebab-case", deny_unknown_fields)]
pub enum Measure {
    /// The whole region's extent on one axis, in blocks.
    RegionExtent {
        /// Which axis.
        axis: Axis,
    },
    /// One place's footprint on one horizontal axis, in blocks.
    BoxExtent {
        /// The place.
        node: NodeId,
        /// Which horizontal axis.
        axis: PlanAxis,
    },
    /// One place's headroom over its walk plane, in blocks. A sky-open place
    /// measures its size class's own minimum clearance — the least air the
    /// ladder says such a place has.
    BoxHeight {
        /// The place.
        node: NodeId,
    },
    /// The horizontal distance between two places' footprint centres, in blocks.
    /// Euclidean on `x`/`z`; the standoff a brief states between two things.
    DistanceXz {
        /// One place.
        from: NodeId,
        /// The other.
        to: NodeId,
    },
    /// A named ground plane's world `y`.
    DatumY {
        /// The plane.
        datum: DatumId,
    },
}

/// One of the three world axes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Axis {
    /// East–west.
    X,
    /// Up–down.
    Y,
    /// North–south.
    Z,
}

/// One of the two horizontal axes.
///
/// A separate type from [`Axis`] rather than a `y` some check refuses: a box is
/// a footprint, so its extent has no `y` to ask about, and an unrepresentable
/// state needs no diagnostic to police it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum PlanAxis {
    /// East–west.
    X,
    /// North–south.
    Z,
}

/// How a measurement must stand to its fact's value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Cmp {
    /// Exactly.
    Eq,
    /// Strictly under.
    Lt,
    /// At most.
    Le,
    /// Strictly over.
    Gt,
    /// At least.
    Ge,
}

impl Cmp {
    fn holds(self, measured: f64, fact: f64) -> bool {
        match self {
            Cmp::Eq => (measured - fact).abs() < 1e-9,
            Cmp::Lt => measured < fact,
            Cmp::Le => measured <= fact,
            Cmp::Gt => measured > fact,
            Cmp::Ge => measured >= fact,
        }
    }

    fn as_str(self) -> &'static str {
        match self {
            Cmp::Eq => "exactly",
            Cmp::Lt => "under",
            Cmp::Le => "at most",
            Cmp::Gt => "over",
            Cmp::Ge => "at least",
        }
    }
}

/// A `vision` edge, embedded: the segment the stage-5 battery walks.
///
/// A vision edge gets a sightline rather than a seam because a vista's two ends
/// are routinely not adjacent — a bell tower seen from a shore shares no face
/// with it — so the seam construct cannot state the one thing a vision edge
/// asserts. A window between neighbours is simply a short sightline
/// (spec-0049 §4.4).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Sightline {
    /// The `vision` edge this embeds.
    pub edge: EdgeId,
    /// The eye end, in world coordinates — inside the edge's `a` box
    /// (`DW0824`).
    pub from: [i64; 3],
    /// The seen end — inside the edge's `b` box (`DW0824`).
    pub to: [i64; 3],
}

/// A named exterior vantage the walk judges the silhouette from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct View {
    /// View id (`view/<kebab>`), unique within the plan.
    pub id: ViewId,
    /// Where the eye stands, in world coordinates.
    pub eye: [i64; 3],
    /// What it looks at.
    pub look_at: [i64; 3],
    /// What this view is for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

// ---------------------------------------------------------------------------
// Resolution — the plan read once, so no check re-derives a number
// ---------------------------------------------------------------------------

/// One box with everything the checks below need already worked out.
///
/// **The model every geometric check depends on** is stated where an author
/// reads it — on [`PlanBox`], whose schema description carries it — and the
/// number itself is [`SHARED_FACE_GAP_CELLS`]. In short: a box is the **play
/// space** of a place, the shell stands in the one-cell gap between two
/// neighbours, `extent` is therefore the interior footprint the size-class
/// ladder judges directly (`DW0832`), and two connected places sit exactly
/// [`SHARED_FACE_GAP_CELLS`] apart on the face they share (`DW0828`).
#[derive(Debug, Clone)]
struct Placed<'a> {
    index: usize,
    plan: &'a PlanBox,
    /// Footprint, inclusive: `[x0, x1, z0, z1]`.
    foot: [i64; 4],
    /// The walk plane.
    floor: i64,
    /// Cells of headroom over the walk plane, or `None` when the place is
    /// sky-open and its classification did not resolve.
    clearance: Option<u32>,
    /// How the place is classified, when the name resolved.
    class: Option<PlaceClass>,
    /// How its corner was obtained (spec-0059 §3).
    by: Provenance,
}

/// **How a place is classified** — the two kinds of standard a box is judged
/// against (spec-0053 §3).
///
/// The classification belongs to the PLACE, so it is one field of two kinds
/// rather than two fields. Written as a second `Option<WayClass>` beside the
/// first, every consumer would have had to remember to look at both, and the
/// one that forgot would silently judge a road against nothing — which is the
/// state this whole surface exists to end, reintroduced one layer down.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PlaceClass {
    /// A rung of the size ladder: both horizontal extents bounded.
    Size(SizeClass),
    /// A way: the cross-section bounded, the run free.
    Way(WayClass),
}

impl PlaceClass {
    /// The least interior clearance the class demands.
    ///
    /// The one question both kinds answer identically, which is why a sky-open
    /// box needs no arm: an open place claims exactly its class's minimum
    /// headroom and nothing above it, and that sentence is true of a road as it
    /// is of a hall.
    fn min_clearance(self) -> u32 {
        match self {
            PlaceClass::Size(c) => c.min_clearance,
            PlaceClass::Way(w) => w.min_clearance,
        }
    }
}

impl Placed<'_> {
    fn x0(&self) -> i64 {
        self.foot[0]
    }
    fn x1(&self) -> i64 {
        self.foot[1]
    }
    fn z0(&self) -> i64 {
        self.foot[2]
    }
    fn z1(&self) -> i64 {
        self.foot[3]
    }

    /// The inclusive vertical span of the play space, when it is bounded.
    fn y_span(&self) -> Option<(i64, i64)> {
        let c = i64::from(self.clearance?);
        Some((self.floor, self.floor + c - 1))
    }

    /// The centre of the footprint, in blocks.
    fn centre_xz(&self) -> (f64, f64) {
        (
            (self.x0() as f64 + self.x1() as f64) / 2.0,
            (self.z0() as f64 + self.z1() as f64) / 2.0,
        )
    }
}

// ---------------------------------------------------------------------------
// The resolved plan, in world cells — ONE authority, three readers
// ---------------------------------------------------------------------------

/// One place, resolved into world cells: the play space the plan gives it.
///
/// Public because three readers need the same answer and two of them are in
/// another crate: the stage-4 checks here, the **blockout derivation** that
/// builds the mass, and the **stage-5 battery** that judges the built bytes
/// against the plan. Two of those computing "where is this box" independently is
/// how a builder and its observer come to agree about a world neither of them
/// describes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlacedBox {
    /// The place this embeds.
    pub node: NodeId,
    /// Inclusive footprint `[x0, x1, z0, z1]`.
    pub foot: [i64; 4],
    /// The walk plane's world `y`.
    pub floor: i64,
    /// Cells of headroom over the walk plane.
    pub clearance: u32,
    /// True when the plan declared no ceiling — a courtyard, a shore, a summit.
    /// The place still claims its size class's own minimum headroom (which is
    /// what [`PlacedBox::clearance`] holds); what it makes no claim on is the
    /// air above that.
    pub open: bool,
}

impl PlacedBox {
    /// The play space's inclusive world AABB.
    #[must_use]
    pub fn space(&self) -> ([i64; 3], [i64; 3]) {
        (
            [self.foot[0], self.floor, self.foot[2]],
            [
                self.foot[1],
                self.floor + i64::from(self.clearance) - 1,
                self.foot[3],
            ],
        )
    }

    /// The floor centre — where a body seated in this place stands.
    #[must_use]
    pub fn centre(&self) -> [i64; 3] {
        [
            (self.foot[0] + self.foot[1]) / 2,
            self.floor,
            (self.foot[2] + self.foot[3]) / 2,
        ]
    }
}

/// One connection, resolved into world cells: the wall the two places share and
/// the hole the plan cut in it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlacedSeam {
    /// The connection this allocates.
    pub edge: EdgeId,
    /// Its class, as the graph spells it.
    pub class: &'static str,
    /// The `a` end.
    pub a: NodeId,
    /// The `b` end.
    pub b: NodeId,
    /// Which face **of `a`** the seam sits on.
    pub face: Face,
    /// The axis the shared wall is flat in: 0 = x, 1 = y, 2 = z.
    pub normal_axis: usize,
    /// The wall's coordinate on that axis — one cell thick, so one number.
    pub plane: i64,
    /// The opening's inclusive world AABB (flat in [`Self::normal_axis`]).
    pub opening: ([i64; 3], [i64; 3]),
    /// The whole rectangle the two boxes share on that wall, inclusive.
    pub shared: ([i64; 3], [i64; 3]),
    /// Which kind of connection this seam allocates (spec-0053 §4). A portal's
    /// `opening` is a standard's rectangle; a contact's is its span.
    pub crossing: Crossing,
    /// `floor(b) − floor(a)`, derived — never authored (see [`Seam`]).
    pub rise: i64,
    /// Which place hosts the stair massing, on a `stair`.
    pub stair_in: Option<NodeId>,
}

/// The plan's boxes, resolved by the code the stage-4 checks judge with.
///
/// A box whose floor names an undeclared datum is **absent** — `DW0112` has
/// refused it, and a place with no plane has no cells for any reader to work in.
/// A sky-open box whose size class did not resolve is absent for the same reason
/// (`DW0812` refused the class, so the plan states no headroom for it at all).
#[must_use]
pub fn placed_boxes(c: &Campaign, reads: &mut Reads) -> Vec<PlacedBox> {
    let (Some(plan), Some(graph)) = (
        c.site_plan.as_ref().map(|p| &p.content),
        c.layout_graph.as_ref().map(|g| &g.content),
    ) else {
        return Vec::new();
    };
    let table = Metrics::table();
    let mut sink = Vec::new();
    resolve(plan, graph, &table, reads, &mut sink)
        .0
        .into_iter()
        .filter_map(|p| {
            Some(PlacedBox {
                node: p.plan.node.clone(),
                foot: p.foot,
                floor: p.floor,
                clearance: p.clearance?,
                open: matches!(p.plan.ceiling, Ceiling::Open),
            })
        })
        .collect()
}

/// **The one place a seam's crossing rectangle is computed**, for either kind
/// of connection (spec-0053 §4).
///
/// A portal's rectangle is the named standard's `width × height` anchored at
/// `at`. A contact's is its span: `at` plus the declared `extent`, or `at` to
/// the far edge of the shared face when no extent is declared.
///
/// One function rather than one per kind, and one call rather than a copy in
/// each reader, because this rectangle is simultaneously the derivation's carve,
/// `DW0836`'s allocation, `DW0838`'s allocation set and `DW0877`'s span. Two
/// implementations of it would be a plan-time green and a byte-time green about
/// two different rectangles, which is the defect `shared_face` already has one
/// implementation to prevent.
///
/// `None` when the seam names an opening the table does not define — `DW0812`
/// refused it and there is no rectangle to build or measure.
fn crossing_rect(
    s: &Seam,
    at: [i64; 2],
    face: &SharedFace,
    table: &Metrics,
    reads: &mut Reads,
) -> Option<(Crossing, [i64; 2])> {
    if s.contact.is_some() {
        return Some((Crossing::Contact, contact_extent(s, at, face)));
    }
    let named = s.opening.as_ref()?;
    let entry = table.resolve(MetricKind::Opening, named).ok()?;
    match entry.value(reads) {
        MetricValue::Opening(o) => {
            Some((Crossing::Portal, [i64::from(o.width), i64::from(o.height)]))
        }
        _ => None,
    }
}

/// **How big a contact's span is** — the one authority, read by
/// [`crossing_rect`] and by the refusal that judges it (`DW0876`).
///
/// A declared `extent` is taken as written. With none declared the span runs
/// from `at` to the far edge of the shared face on both axes, which is how a
/// contact along the whole of a face is spelled. An `at` already past that edge
/// would give a negative extent, so it is clamped to one cell: the rectangle
/// stays well-formed and `DW0876` describes it, rather than the arithmetic
/// producing a rectangle nothing downstream could reason about.
fn contact_extent(s: &Seam, at: [i64; 2], face: &SharedFace) -> [i64; 2] {
    match s.contact.as_ref().and_then(|c| c.extent) {
        Some(e) => [i64::from(e[0].get()), i64::from(e[1].get())],
        None => [(face.u.1 - at[0] + 1).max(1), (face.v.1 - at[1] + 1).max(1)],
    }
}

/// Which axis a face is flat in: 0 = x, 1 = y, 2 = z.
#[must_use]
pub fn normal_axis_of(face: Face) -> usize {
    match face {
        Face::East | Face::West => 0,
        Face::Up | Face::Down => 1,
        Face::South | Face::North => 2,
    }
}

/// A seam's crossing rectangle as an inclusive world AABB, flat in the face's
/// normal axis — [`crossing_rect`]'s two numbers put where the world is.
///
/// Extracted rather than written twice because [`stair_run`] needs the same
/// rectangle at validation tier, before any `PlacedSeam` exists.
fn crossing_aabb(
    s: &Seam,
    at: [i64; 2],
    face: &SharedFace,
    extent: [i64; 2],
) -> ([i64; 3], [i64; 3]) {
    let normal_axis = normal_axis_of(s.face);
    let (u_axis, v_axis) = in_plane_axes(s.face);
    let mut lo = [0i64; 3];
    let mut hi = [0i64; 3];
    lo[normal_axis] = face.plane;
    hi[normal_axis] = face.plane;
    lo[u_axis] = at[0];
    hi[u_axis] = at[0] + extent[0] - 1;
    lo[v_axis] = at[1];
    hi[v_axis] = at[1] + extent[1] - 1;
    (lo, hi)
}

/// **What a stair costs the box that hosts it** — the one place the geometry of
/// a run is worked out, for both the check that refuses a plan (`DW0830`) and
/// the derivation that lays the treads.
///
/// # Why this is one function and not two
///
/// It was two, and the two disagreed. `DW0830` measured the run against the
/// seam's **rise** and against the host's whole **extent**; the derivation
/// measures it against the **climb** the opening really asks for and against
/// the run the host really has beside the hole. Both readings are defensible
/// in isolation and neither is the other, so a plan could pass the check by one
/// arithmetic and be refused by the other at build time — the treads then went
/// unlaid, and the place they were the only way into came back as `DW0837` with
/// nothing pointing at the stair. Found by building: a two-place plan whose
/// lower room is entered through a hole in the upper room's floor reached green
/// at stage 4 with `needs 8, affords 8` and built no stair at all, because the
/// climb to the pierced plane is 7 and the run beside a centred hole is 6.
///
/// So the rule lives here and both readers call it. A plan that reaches green
/// is a plan the derivation can build, by construction rather than by two
/// arithmetics agreeing.
///
/// # What the numbers mean
///
/// * `climb` — how high the courses must carry a body. Across a **vertical**
///   face that is the seam's own sill, because the body stands at the sill and
///   steps through; through a **floor or ceiling** it is the pierced plane,
///   because the body stands in the hole and steps out beside it. Both come out
///   as the floor difference on an ordinary plan and differ exactly where the
///   plan puts the sill somewhere other than the far floor.
/// * `run_axis` — the horizontal axis the run is spent on. Across a vertical
///   face it is that face's normal; through a floor or ceiling the run may go
///   either way, so it is the host's longer horizontal axis.
/// * `start`/`step` — the stair arrives AT its seam, so course 0 is the one the
///   body steps off and the run walks back into the room.
/// * `available` — how many cells of that walk the host really has. Across a
///   vertical face the run walks the whole footprint. Through a floor or a
///   ceiling it leaves along **one** side of the hole, so it is the room on the
///   roomier side plus the hole's own width — never the host's whole extent,
///   which is a run that only exists if the stair could run both ways at once.
///
/// `None` where there is no run to lay or judge: a host at or above what the
/// stair has to reach (the plan named the higher place, which `DW0830` refuses
/// by name), or a hole that is not over this host at all (`DW0828`'s finding).
#[must_use]
pub fn stair_run(
    host_floor: i64,
    host_foot: [i64; 4],
    normal_axis: usize,
    plane: i64,
    opening: ([i64; 3], [i64; 3]),
) -> Option<StairRun> {
    let (olo, ohi) = opening;
    let lo = [host_foot[0], host_floor, host_foot[2]];
    let hi = [host_foot[1], host_floor, host_foot[3]];
    let target = if normal_axis == 1 { plane } else { olo[1] };
    let climb = target - host_floor;
    if climb <= 0 {
        return None;
    }
    let run_axis = if normal_axis == 1 {
        let ex = host_foot[1] - host_foot[0] + 1;
        let ez = host_foot[3] - host_foot[2] + 1;
        if ex >= ez { 0usize } else { 2 }
    } else {
        normal_axis
    };
    let (start, step, available) = if normal_axis == 1 {
        let (olo_r, ohi_r) = (
            olo[run_axis].max(lo[run_axis]),
            ohi[run_axis].min(hi[run_axis]),
        );
        if olo_r > ohi_r {
            return None;
        }
        let width = ohi_r - olo_r + 1;
        let room_lo = olo_r - lo[run_axis];
        let room_hi = hi[run_axis] - ohi_r;
        if room_lo >= room_hi {
            (ohi_r, -1, room_lo + width)
        } else {
            (olo_r, 1, room_hi + width)
        }
    } else if plane > hi[run_axis] {
        (hi[run_axis], -1, hi[run_axis] - lo[run_axis] + 1)
    } else {
        (lo[run_axis], 1, hi[run_axis] - lo[run_axis] + 1)
    };
    Some(StairRun {
        climb,
        run_axis,
        start,
        step,
        available,
    })
}

/// What a stair's treads cost their host — see [`stair_run`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StairRun {
    /// How high the courses must carry a body, off the host's own walk plane.
    pub climb: i64,
    /// The horizontal axis the run walks: 0 = x, 2 = z.
    pub run_axis: usize,
    /// Where course 0 — the one the body steps off — stands on `run_axis`.
    pub start: i64,
    /// Which way the run walks back into the host: `+1` or `-1`.
    pub step: i64,
    /// How many cells of that walk the host really affords.
    pub available: i64,
}

/// The run one standard pitch costs a climb, rounded up: a course is a whole
/// cell, and a run two-thirds of a cell short is a run the host does not have.
#[must_use]
pub fn run_of(pitch: &Pitch, climb: i64) -> i64 {
    let (span, per) = (climb.abs() * i64::from(pitch.run), i64::from(pitch.rise));
    if per == 0 {
        span
    } else {
        span / per + i64::from(span % per != 0)
    }
}

/// **The gentlest standard pitch a climb fits in `available` cells of run**, or
/// `None` when the table defines none that does.
///
/// The walk is over [`Metrics::names_of`] in table order — gentlest first — and
/// takes the first that fits. One authority, so the verdict `DW0830` reaches and
/// the geometry the derivation lays cannot be about different standards.
#[must_use]
pub fn gentlest_pitch(
    table: &Metrics,
    reads: &mut Reads,
    climb: i64,
    available: i64,
) -> Option<Pitch> {
    for name in table.names_of(MetricKind::Pitch) {
        let Ok(entry) = table.resolve(MetricKind::Pitch, name) else {
            continue;
        };
        let MetricValue::Pitch(p) = entry.value(reads) else {
            continue;
        };
        if p.rise == 0 {
            continue;
        }
        if run_of(p, climb) <= available {
            return Some(*p);
        }
    }
    None
}

/// The standard pitch that costs a climb the LEAST run, and what that run is —
/// the number `DW0830`'s refusal quotes, because it is the shortest run any
/// standard could do the climb in.
#[must_use]
pub fn tightest_pitch(
    table: &Metrics,
    reads: &mut Reads,
    climb: i64,
) -> Option<(&'static str, i64)> {
    let mut best: Option<(&'static str, i64)> = None;
    for name in table.names_of(MetricKind::Pitch) {
        let Ok(entry) = table.resolve(MetricKind::Pitch, name) else {
            continue;
        };
        let MetricValue::Pitch(p) = entry.value(reads) else {
            continue;
        };
        if p.rise == 0 {
            continue;
        }
        let needed = run_of(p, climb);
        if best.is_none_or(|(_, b)| needed < b) {
            best = Some((name, needed));
        }
    }
    best
}

/// The plan's seams, resolved by the code the stage-4 checks judge with.
///
/// A seam whose face the two boxes do not share, or whose opening the table does
/// not define, is **absent**: `DW0828`/`DW0812` refused it, and there is no hole
/// for a reader to build or measure.
#[must_use]
pub fn placed_seams(c: &Campaign, boxes: &[PlacedBox], reads: &mut Reads) -> Vec<PlacedSeam> {
    let (Some(plan), Some(graph)) = (
        c.site_plan.as_ref().map(|p| &p.content),
        c.layout_graph.as_ref().map(|g| &g.content),
    ) else {
        return Vec::new();
    };
    let table = Metrics::table();
    let by_node: BTreeMap<&str, &PlacedBox> =
        boxes.iter().map(|b| (b.node.0.as_str(), b)).collect();
    let edges: BTreeMap<&str, &Edge> = graph.edges.iter().map(|e| (e.id().0.as_str(), e)).collect();
    // The seam anchors come from the same packing that placed `boxes`: one
    // arithmetic, so the derivation and its observer cannot disagree about
    // where a hole is.
    let mut sink = Vec::new();
    let (_, packed) = resolve(plan, graph, &table, reads, &mut sink);
    let mut out = Vec::new();
    for (i, s) in plan.seams.iter().enumerate() {
        let Some(at) = packed.seam_at[i] else {
            continue; // the packing refused or could not place this seam
        };
        let Some(edge) = edges.get(s.edge.0.as_str()) else {
            continue;
        };
        if matches!(edge, Edge::Vision { .. }) {
            continue;
        }
        let (Some(a), Some(b)) = (
            by_node.get(edge.a().0.as_str()).copied(),
            by_node.get(edge.b().0.as_str()).copied(),
        ) else {
            continue;
        };
        let Ok(face) = shared_face_of(a, b, s.face) else {
            continue;
        };
        let Some((crossing, extent)) = crossing_rect(s, at, &face, &table, reads) else {
            continue;
        };
        let normal_axis = normal_axis_of(s.face);
        // The face's two in-plane axes, in the order `at` names them.
        let (u_axis, v_axis) = in_plane_axes(s.face);
        let (lo, hi) = crossing_aabb(s, at, &face, extent);
        let mut smin = [0i64; 3];
        let mut smax = [0i64; 3];
        smin[normal_axis] = face.plane;
        smax[normal_axis] = face.plane;
        smin[u_axis] = face.u.0;
        smax[u_axis] = face.u.1;
        smin[v_axis] = face.v.0;
        smax[v_axis] = face.v.1;
        out.push(PlacedSeam {
            edge: s.edge.clone(),
            class: edge.class(),
            a: edge.a().clone(),
            b: edge.b().clone(),
            face: s.face,
            normal_axis,
            plane: face.plane,
            opening: (lo, hi),
            shared: (smin, smax),
            crossing,
            rise: b.floor - a.floor,
            stair_in: s.stair_in.clone(),
        });
    }
    out
}

/// **A contact**: the span of a shared face along which two places simply meet
/// (spec-0053 §4).
///
/// # What a contact MEANS
///
/// The boundary is continuous ground. The derivation writes **no wall along the
/// span** — and wall as ever outside it — and crossing is legitimate anywhere
/// along it the step rule admits. It is not a wide door: `DW0829`'s standard-name
/// resolution and sill rule are portal checks and do not apply, because a
/// contact has no opening name to resolve and no single sill. Calling a 55-cell
/// front a door would make every downstream door check wrong.
///
/// # What the author allocates and what the engine measures
///
/// The author allocates **where** the places meet. The engine measures the
/// **crossing profile** from assembled bytes — which columns of the span a body
/// actually crosses under the step rule — and `DW0877` refuses a contact nothing
/// can cross. *"This face is fine"* is never a declaration this engine accepts.
///
/// Seams stay **allocated, never discovered**: the span is the edge's allocation
/// set for `DW0838`, so a crossing outside it is still a refusal.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Contact {
    /// The span, `[u, v]` in cells on the face's own two in-plane axes, anchored
    /// at the seam's `at`.
    ///
    /// **Omitted, the span runs from `at` to the far edge of the shared face on
    /// both axes** — which is how a contact along the whole of a face is
    /// written, by putting `at` at the face's low corner. `DW0828`'s refusal
    /// prints that corner, so the number an author needs is in the message they
    /// would already be reading.
    ///
    /// There is no `width` standard and no `length` here, and both absences are
    /// the design (spec-0053 §7).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extent: Option<[NonZeroU32; 2]>,
}

/// **Which kind of connection a seam allocates** (spec-0053 §4).
///
/// Carried on the resolved seam rather than re-derived from the authored one at
/// each reader, so that the derivation and the byte observer cannot disagree
/// about which kind a seam is — the same reason `shared_face` has one
/// implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Crossing {
    /// A standard opening. Every allocated cell must be passable (`DW0836`).
    Portal,
    /// A front where two places meet. No wall along the span, and **at least
    /// one** passable column of body width somewhere in it (`DW0877`) — not
    /// every cell, because a contact is ground rather than a hole and the
    /// massing standing on it is content.
    Contact,
}

/// The two world axes a face's `at` names, in that order.
fn in_plane_axes(face: Face) -> (usize, usize) {
    match face {
        // `[along, y]` — `z` for east/west, `x` for north/south.
        Face::East | Face::West => (2, 1),
        Face::South | Face::North => (0, 1),
        // `[x, z]`.
        Face::Up | Face::Down => (0, 2),
    }
}

/// A footprint's inclusive span on one WORLD axis (0 = x, 2 = z). Axis 1 has no
/// answer here — a footprint is horizontal — and no caller asks for it.
fn span(foot: [i64; 4], axis: usize) -> (i64, i64) {
    if axis == 0 {
        (foot[0], foot[1])
    } else {
        (foot[2], foot[3])
    }
}

/// Inclusive overlap of two ranges, or `None`.
fn overlap(a: (i64, i64), b: (i64, i64)) -> Option<(i64, i64)> {
    let lo = a.0.max(b.0);
    let hi = a.1.min(b.1);
    (lo <= hi).then_some((lo, hi))
}

/// Is `[lo, hi]` inside `[within_lo, within_hi]`?
fn within(r: (i64, i64), w: (i64, i64)) -> bool {
    r.0 >= w.0 && r.1 <= w.1
}

/// The region's inclusive span on one axis.
fn region_span(region: &WorldBox, axis: usize) -> (i64, i64) {
    (region.min[axis], region.max()[axis])
}

// ---------------------------------------------------------------------------
// The binding ledger's site-plan half
// ---------------------------------------------------------------------------

/// What a run's site-plan checks bound to.
///
/// Carried inside [`crate::LayoutBinding`] rather than as a second ledger: the
/// map pipeline's documents are counted by one struct with one constructor, so
/// the number the CLI prints and the number a diagnostic quotes cannot disagree
/// about how many places there are.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
pub struct PlanBinding {
    /// Places embedded — what `DW0825`, `DW0826` and `DW0832` examine.
    pub boxes: usize,
    /// Unordered box pairs — what `DW0827` examines. Zero at one box, which is
    /// the honest count and not a pass.
    pub box_pairs: usize,
    /// Connections allocated — what `DW0828` and `DW0829` examine.
    pub seams: usize,
    /// Of those, seams whose edge is a `stair` — what `DW0830` examines.
    pub stair_seams: usize,
    /// Of those, seams whose edge is a `drop` — what `DW0831` examines.
    pub drop_seams: usize,
    /// Named ground planes.
    pub datums: usize,
    /// Whole-owned masses — what `DW0835` examines.
    pub volumes: usize,
    /// Guarded comparisons against the brief — what `DW0833` examines.
    pub identities: usize,
    /// Sightlines embedded.
    pub sightlines: usize,
    /// Named exterior vantages the walk judges the silhouette from.
    pub views: usize,
    /// Boxes whose corner the author pinned (spec-0059 §3).
    pub pinned: usize,
    /// Boxes whose corner a seam derived.
    pub derived: usize,
    /// Connected components of the seam graph.
    pub components: usize,
}

impl PlanBinding {
    /// Count what a campaign's site plan offers the checks.
    #[must_use]
    pub fn of(c: &Campaign) -> PlanBinding {
        let Some(plan) = c.site_plan.as_ref().map(|p| &p.content) else {
            return PlanBinding::default();
        };
        let classes: BTreeMap<&str, &'static str> = c
            .layout_graph
            .as_ref()
            .map(|g| {
                g.content
                    .edges
                    .iter()
                    .map(|e| (e.id().0.as_str(), e.class()))
                    .collect()
            })
            .unwrap_or_default();
        let n = plan.boxes.len();
        let (pinned, derived, components) = match c.layout_graph.as_ref() {
            Some(g) => {
                let table = Metrics::table();
                let mut reads = Reads::new();
                let mut sink = Vec::new();
                let (_, packed) = resolve(plan, &g.content, &table, &mut reads, &mut sink);
                (packed.pinned, packed.derived, packed.components)
            }
            None => (0, 0, 0),
        };
        PlanBinding {
            pinned,
            derived,
            components,
            boxes: n,
            box_pairs: n * n.saturating_sub(1) / 2,
            seams: plan.seams.len(),
            stair_seams: plan
                .seams
                .iter()
                .filter(|s| classes.get(s.edge.0.as_str()) == Some(&"stair"))
                .count(),
            drop_seams: plan
                .seams
                .iter()
                .filter(|s| classes.get(s.edge.0.as_str()) == Some(&"drop"))
                .count(),
            datums: plan.datums.len(),
            volumes: plan.volumes.len(),
            identities: plan.identities.len(),
            sightlines: plan.sightlines.len(),
            views: plan.views.len(),
        }
    }

    /// The site-plan half of the binding line.
    #[must_use]
    pub fn line(&self) -> String {
        format!(
            "site-plan binding: {b} box(es) ({p} pair(s) compared; {pn} pinned, {dv} derived, \
             in {cc} component(s)), {s} seam(s) ({st} stair, {sd} drop), {d} datum(s), {v} \
             whole-owned volume(s), {i} identity(ies), {sl} sightline(s), {w} view(s).",
            pn = self.pinned,
            dv = self.derived,
            cc = self.components,
            b = self.boxes,
            p = self.box_pairs,
            s = self.seams,
            st = self.stair_seams,
            sd = self.drop_seams,
            d = self.datums,
            v = self.volumes,
            i = self.identities,
            sl = self.sightlines,
            w = self.views,
        )
    }
}

// ---------------------------------------------------------------------------
// Validation (spec-0049 §4.3) — every rule, all upstream of any geometry
// ---------------------------------------------------------------------------

/// Every check the site plan owes, at **validation** tier (exit 1).
///
/// # What invokes this, and what happens without it
///
/// [`crate::validate::validate_campaign_with`], whenever the campaign directory
/// holds a `site-plan.json` — the same event-bound shape stages 2, 3 and 7 use.
/// That function is what **every** `delvec` subcommand's validation stage calls,
/// so there is no path from a campaign directory to a verdict, a world or a
/// datapack that goes round it: `validate`, `analyze` and `build` all enter
/// through it, and a caller who somehow skipped it would have no `Campaign` to
/// hand anything downstream. There is no flag to pass, no step in a document to
/// remember, and no second entry point.
///
/// # Why every rule is here and none is at analysis tier
///
/// Round 2 put the layout graph's *reachability* proofs at analysis tier because
/// reachability is a question about a whole graph, the tier its quest-graph
/// siblings answer at. Nothing here is that question. Every rule below is a
/// property of the document in front of it — does this box fit, do these two
/// boxes touch, does this number match the brief's — so all of it is validation,
/// and a plan that is wrong is wrong before anything is analyzed.
///
/// # What is deliberately NOT here, and where it went
///
/// Three obligations of this stage are only decidable once the blockout exists,
/// and each is named rather than approximated:
///
/// * whether a built seam is the opening the plan allocated, whether every node's
///   floor is reached, and whether any crossing was *discovered* outside a seam;
/// * `DW0833`'s second call site, the identities recomputed from assembled bytes;
/// * whether a declared sightline is unobstructed.
///
/// All three read blocks. Writing a version of them here that read the plan
/// instead would be the derivation's arithmetic replayed against itself — the
/// opposite of an independent observer — so they belong to the round that builds
/// the blockout, and this module states the plan-side half they will be checked
/// against.
pub fn check(c: &Campaign, reads: &mut Reads, d: &mut Vec<Diagnostic>) {
    let Some(plan) = c.site_plan.as_ref().map(|p| &p.content) else {
        return;
    };
    let table = Metrics::table();

    // Plan-internal wellformedness first: the ids every rule below quotes.
    ids(plan, d);
    one_authority(c, d);

    // ------------------------------------------------------------- the tooth
    // A site plan validates ONLY against a layout graph and a geometry brief.
    // Both are refused by name, and the graph's absence returns: every rule
    // below reads node ids, and without a graph each would be answering about a
    // place nothing declared.
    let brief_missing = c.geometry_brief.is_none();
    if brief_missing {
        d.push(Diagnostic::error(
            DW_PLAN_AGREEMENT,
            "site-plan",
            "",
            "this campaign carries a site plan and no `geometry-brief.json`. The plan is the \
             embedding of a design, and the brief is where that design's numbers are written \
             down; with no brief there is nothing for `identities[]` to hold the map to, and \
             the region's extent is a number with no author. Write the brief first — a plan \
             cannot reach green ahead of it."
                .to_string(),
        ));
    }
    let Some(graph) = c.layout_graph.as_ref().map(|g| &g.content) else {
        d.push(Diagnostic::error(
            DW_PLAN_AGREEMENT,
            "site-plan",
            "",
            "this campaign carries a site plan and no `layout-graph.json`. A site plan is the \
             geometric embedding OF a layout graph: every box names a place and every seam \
             names a connection, so with no graph there is nothing being embedded and every \
             name in this document resolves to nothing. This is the only line this state \
             raises: the map's anchor vocabulary is derived from the graph too, so every \
             anchor a `npcs`, `quests` or effect document names is left unjudged here rather \
             than refused against an empty set, and is judged the moment the graph exists. \
             Author the graph first — that ordering \
             is what this refusal exists to make uncompilable rather than merely advised."
                .to_string(),
        ));
        return;
    };

    openers(c, graph, d);
    let (placed, packed) = resolve(plan, graph, &table, reads, d);
    agreement(plan, graph, &placed, d);
    grid(&placed, &table, reads, d);
    region(plan, &placed, d);
    disjoint(&placed, d);
    seams(plan, graph, &placed, &packed, &table, reads, d);
    size_classes(&placed, d);
    volumes_outside_boxes(plan, &placed, d);
    identities(c, plan, &placed, d);
    lighting(plan, d);
}

/// `DW0839`: a campaign has ONE placement authority.
///
/// `areas[]` places pieces on the fixed stride; the site plan places the whole
/// map in its own region. A world carrying both has two owners for one question
/// and no rule to pick between them, so the answer is not to arbitrate but to
/// refuse. Both surfaces stay legal at 0.14.0 — one per campaign.
fn one_authority(c: &Campaign, d: &mut Vec<Diagnostic>) {
    let n = c.world.content.areas.len();
    if n == 0 {
        return;
    }
    d.push(Diagnostic::error(
        DW_TWO_AUTHORITIES,
        "world",
        "/content/areas",
        format!(
            "this campaign declares {n} `areas[]` entry(ies) AND a site plan. Those are two \
             placement authorities for one world: `areas[]` seats prefab pieces on the compiler's \
             fixed stride, and the site plan seats the derived blockout inside its own declared \
             `region` — so every question about where something is has two answers and nothing \
             says which. Keep one. A campaign that places pieces keeps `areas[]` and drops \
             `site-plan.json`; a campaign whose map is the site plan declares an empty `areas` \
             list and lets the plan own the space. Both surfaces are legal — what is not legal \
             is one \
             campaign holding both."
        ),
    ));
}

/// `DW0818`'s **byte-side half** of the opener obligation, which round 3 could
/// not write and named as this round's.
///
/// The graph half already stands in [`crate::layout`]: a `barred` edge must
/// declare a `gating` that names a flag some effect really sets or a quest that
/// really exists. That says the way is *meant* to open; it does not say anything
/// in the campaign ever opens **this** way, because at stage 3 the region such
/// an effect would target does not exist yet. It exists here: the derivation
/// synthesizes [`seam_anchor`] over every `barred` seam's opening, so "something
/// opens `seam/<edge>`" is finally a question with a subject.
///
/// Raised under `DW0818` and against the layout graph, because the fault is the
/// graph's claim rather than the plan's geometry — the plan did everything asked
/// of it. Only reachable in a site-plan campaign, which is exactly the campaign
/// in which the seam anchor exists to be named.
fn openers(c: &Campaign, graph: &LayoutGraphContent, d: &mut Vec<Diagnostic>) {
    // Every gate region the campaign opens, however it opens it: an `open-gate`
    // at any nesting depth, or a `shortcut` whose far side lifts the bar.
    let mut opened: BTreeSet<&str> = BTreeSet::new();
    crate::stages::for_each_campaign_effect(c, &mut |_, _, eff| {
        eff.visit_deep(&mut |e| {
            if let Some(a) = e.open_gate_anchor() {
                opened.insert(a.0.as_str());
            }
        });
    });
    for s in &c.quests.content.shortcuts {
        opened.insert(s.gate.0.as_str());
    }

    for (i, e) in graph.edges.iter().enumerate() {
        let Edge::Barred { id, .. } = e else { continue };
        let want = seam_anchor(id);
        if opened.contains(want.as_str()) {
            continue;
        }
        d.push(Diagnostic::error(
            crate::layout::DW_GRAPH_MISSION,
            "layout-graph",
            format!("/content/edges/{i}"),
            format!(
                "`{id}` is barred and nothing in this campaign opens it. The derivation seals \
                 this seam's opening at world load and names the region `{want}`; for the way to \
                 ever be passable some effect has to address that name — an `open-gate` on the \
                 beat whose completion earns it, or a `shortcut` whose far side lifts the bar. \
                 The graph's `gating` says what a body must HOLD to pass, which is a different \
                 claim and is already checked: a way that is gated on a flag nobody spends is \
                 still a wall. This is the half of the obligation that could only be written once \
                 the region existed, so it is asked here rather than at stage 3."
            ),
        ));
    }
}

/// `datum/`, `volume/` and `view/` ids: well formed and unique, like every other
/// id in the DSL. An id is an id, so these are the ordinary `DW0110`/`DW0111`.
fn ids(plan: &SitePlanContent, d: &mut Vec<Diagnostic>) {
    let mut seen: BTreeSet<String> = BTreeSet::new();
    let mut check_id = |ok: bool, id: String, kind: &str, path: String, d: &mut Vec<Diagnostic>| {
        if !ok {
            d.push(Diagnostic::error(
                crate::codes::ID_SYNTAX,
                "site-plan",
                path.clone(),
                format!("malformed {kind} id `{id}` — expected `{kind}/<kebab-case>`."),
            ));
        }
        if !seen.insert(format!("{kind}:{id}")) {
            d.push(Diagnostic::error(
                crate::codes::ID_DUPLICATE,
                "site-plan",
                path,
                format!(
                    "duplicate {kind} id `{id}` — rename one, because anything naming it would \
                     otherwise name both."
                ),
            ));
        }
    };
    for (i, dat) in plan.datums.iter().enumerate() {
        check_id(
            dat.id.is_valid_syntax(),
            dat.id.0.clone(),
            "datum",
            format!("/content/datums/{i}/id"),
            d,
        );
    }
    for (i, v) in plan.volumes.iter().enumerate() {
        check_id(
            v.id.is_valid_syntax(),
            v.id.0.clone(),
            "volume",
            format!("/content/volumes/{i}/id"),
            d,
        );
    }
    for (i, v) in plan.views.iter().enumerate() {
        check_id(
            v.id.is_valid_syntax(),
            v.id.0.clone(),
            "view",
            format!("/content/views/{i}/id"),
            d,
        );
    }
}

// ---------------------------------------------------------------------------
// Packing — a box is placed by its seam, and the grid is derived (spec-0059 §3)
// ---------------------------------------------------------------------------

/// How a box came to stand where it stands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Provenance {
    /// The author pinned its `min`.
    Pinned,
    /// A seam hung it off a box that already stood.
    Seam {
        /// Index into `seams[]`.
        seam: usize,
        /// The connection the seam allocates.
        edge: EdgeId,
        /// The box it was hung off.
        from: NodeId,
        /// The face of `from` it hangs off — or, when `from` is the seam's `b`
        /// end, the face of this box the seam names.
        face: Face,
    },
}

impl Provenance {
    /// The words a refusal or the placing line uses.
    fn describe(&self) -> String {
        match self {
            Provenance::Pinned => "pinned".to_string(),
            Provenance::Seam {
                edge, from, face, ..
            } => format!(
                "hung off `{from}` across the {face} face by the seam for `{edge}`",
                face = face.as_str()
            ),
        }
    }
}

/// One box's corner, with its provenance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackedBox {
    /// The place.
    pub node: NodeId,
    /// Low corner `[x, z]`, in world coordinates.
    pub min: [i64; 2],
    /// Where the corner came from.
    pub by: Provenance,
}

/// The packing of one plan: every corner the pins and seams settle, and the
/// world anchor of every seam whose two ends stand.
#[derive(Debug, Default)]
struct Packed {
    /// Per `plan.boxes` index; `None` when nothing placed the box.
    boxes: Vec<Option<PackedBox>>,
    /// Per `plan.seams` index: the crossing's low corner on the face's own two
    /// world axes — `[along, sill]` on a wall, `[x, z]` through a floor or
    /// ceiling. `None` when either end is unplaced or a floor is unresolved.
    seam_at: Vec<Option<[i64; 2]>>,
    /// Seams the packing itself refused; [`seams`] does not judge them twice.
    refused: BTreeSet<usize>,
    /// Connected components of the seam graph, over boxes the graph declares.
    components: usize,
    pinned: usize,
    derived: usize,
}

/// A seam resolved far enough to place a box: its two box indices and its two
/// offsets, each `[u, v]` on a horizontal face and `[u, 0]` on a vertical one.
#[derive(Debug, Clone, Copy)]
struct Link {
    a: usize,
    b: usize,
    at: [i64; 2],
    meets: [i64; 2],
}

/// The two horizontal-axis indices a face's arithmetic uses: `(normal, along)`
/// into `[x, z]`.
fn face_axes(face: Face) -> (usize, usize) {
    match face {
        Face::East | Face::West => (0, 1),
        Face::North | Face::South => (1, 0),
        Face::Up | Face::Down => (0, 1), // unused: a horizontal face has no normal in [x, z]
    }
}

/// The width a crossing is centred by, on the face's own two axes, or `None`
/// for a contact with no extent — the whole face, so the offsets default to 0.
/// `Err` when the opening cannot be resolved (`DW0812`/`DW0876` name that).
fn centring_width(s: &Seam, table: &Metrics, reads: &mut Reads) -> Result<Option<[i64; 2]>, ()> {
    if let Some(c) = &s.contact {
        return Ok(c
            .extent
            .map(|e| [i64::from(e[0].get()), i64::from(e[1].get())]));
    }
    let Some(name) = s.opening.as_deref() else {
        return Err(());
    };
    let entry = table.resolve(MetricKind::Opening, name).map_err(|_| ())?;
    match entry.value(reads) {
        MetricValue::Opening(o) => Ok(Some([i64::from(o.width), i64::from(o.height)])),
        _ => Err(()),
    }
}

/// Why an offset is not a position on its face.
enum OffsetProblem {
    /// The shape does not match the face: an integer through a floor, a pair
    /// on a wall.
    Shape { which: &'static str },
    /// The crossing, anchored there, leaves the box's own face.
    OffFace {
        which: &'static str,
        axis: &'static str,
        value: i64,
        extent: i64,
        width: i64,
    },
}

/// Resolve `at` and `meets` for one seam against its two boxes' extents:
/// declared values taken as written, omitted ones centred (spec-0059 §3).
fn offsets(
    s: &Seam,
    ext_a: [i64; 2],
    ext_b: [i64; 2],
    width: Option<[i64; 2]>,
) -> Result<([i64; 2], [i64; 2]), OffsetProblem> {
    let horizontal = s.face.is_horizontal_plane();
    let one = |which: &'static str,
               declared: Option<Offset>,
               ext: [i64; 2]|
     -> Result<[i64; 2], OffsetProblem> {
        // Which of `[dx, dz]` each offset component runs along, and its name.
        let (axes, names): ([usize; 2], [&'static str; 2]) = if horizontal {
            ([0, 1], ["x", "z"])
        } else {
            let (_, along) = face_axes(s.face);
            ([along, 0], [if along == 0 { "x" } else { "z" }, ""])
        };
        // Centred; a crossing wider than the face centres at the corner and
        // whether it fits is `DW0829`'s or `DW0876`'s question.
        let default = |i: usize| match width {
            Some(w) => (ext[axes[i]] - w[i]).div_euclid(2).max(0),
            None => 0,
        };
        let off = match (declared, horizontal) {
            (None, true) => [default(0), default(1)],
            (None, false) => [default(0), 0],
            (Some(Offset::Plane(p)), true) => p,
            (Some(Offset::Along(u)), false) => [u, 0],
            _ => return Err(OffsetProblem::Shape { which }),
        };
        let n = if horizontal { 2 } else { 1 };
        for i in 0..n {
            // The CORNER is on the face; whether the crossing fits from there is
            // `DW0829`'s (a portal) or `DW0876`'s (a contact) question, as ever.
            let extent = ext[axes[i]];
            let w = width.map_or(1, |w| w[i]);
            if off[i] < 0 || off[i] > extent - 1 {
                return Err(OffsetProblem::OffFace {
                    which,
                    axis: names[i],
                    value: off[i],
                    extent,
                    width: w,
                });
            }
        }
        Ok(off)
    };
    Ok((one("at", s.at, ext_a)?, one("meets", s.meets, ext_b)?))
}

/// The corner of the box a seam places, from the corner of the one that
/// already stands. `from_a` places `b` off `a`; otherwise `a` off `b`.
fn derive_corner(
    face: Face,
    known: [i64; 2],
    ext_a: [i64; 2],
    ext_b: [i64; 2],
    at: [i64; 2],
    meets: [i64; 2],
    from_a: bool,
) -> [i64; 2] {
    if face.is_horizontal_plane() {
        return if from_a {
            [known[0] + at[0] - meets[0], known[1] + at[1] - meets[1]]
        } else {
            [known[0] - at[0] + meets[0], known[1] - at[1] + meets[1]]
        };
    }
    let (normal, along) = face_axes(face);
    let positive = matches!(face, Face::East | Face::South);
    let mut out = [0i64; 2];
    if from_a {
        out[along] = known[along] + at[0] - meets[0];
        out[normal] = if positive {
            known[normal] + ext_a[normal] + 1
        } else {
            known[normal] - ext_b[normal] - 1
        };
    } else {
        out[along] = known[along] - at[0] + meets[0];
        out[normal] = if positive {
            known[normal] - ext_a[normal] - 1
        } else {
            known[normal] + ext_b[normal] + 1
        };
    }
    out
}

/// The crossing's low corner in the face's own two world axes — what every
/// seam rule judges. `[along, sill]` on a wall, the sill being the higher of
/// the two floors; `[x, z]` through a floor or ceiling.
fn crossing_anchor(
    face: Face,
    a_min: [i64; 2],
    at: [i64; 2],
    floor_a: i64,
    floor_b: i64,
) -> [i64; 2] {
    if face.is_horizontal_plane() {
        [a_min[0] + at[0], a_min[1] + at[1]]
    } else {
        let (_, along) = face_axes(face);
        [a_min[along] + at[0], floor_a.max(floor_b)]
    }
}

fn ext_of(b: &PlanBox) -> [i64; 2] {
    [i64::from(b.extent[0].get()), i64::from(b.extent[1].get())]
}

/// **The packing** (spec-0059 §3): the pinned boxes seed it; then `seams[]` in
/// document order, repeatedly, each seam with exactly one end standing placing
/// the other, until a pass places nothing. A seam whose two ends both stand is
/// then checked — the corner it would derive against the corner the box has —
/// and a component of the seam graph with no pinned box is refused, because
/// nothing places it.
fn pack(
    plan: &SitePlanContent,
    graph: &LayoutGraphContent,
    table: &Metrics,
    floors: &[Option<i64>],
    reads: &mut Reads,
    d: &mut Vec<Diagnostic>,
) -> Packed {
    let mut out = Packed {
        boxes: vec![None; plan.boxes.len()],
        seam_at: vec![None; plan.seams.len()],
        ..Packed::default()
    };
    let nodes: BTreeSet<&str> = graph.nodes.iter().map(|n| n.id.0.as_str()).collect();
    let mut by_node: BTreeMap<&str, usize> = BTreeMap::new();
    for (i, b) in plan.boxes.iter().enumerate() {
        if nodes.contains(b.node.0.as_str()) {
            by_node.entry(b.node.0.as_str()).or_insert(i);
        }
    }
    let edges: BTreeMap<&str, &Edge> = graph.edges.iter().map(|e| (e.id().0.as_str(), e)).collect();

    // ---- seeds
    for (i, b) in plan.boxes.iter().enumerate() {
        if let Some(min) = b.min {
            out.boxes[i] = Some(PackedBox {
                node: b.node.clone(),
                min,
                by: Provenance::Pinned,
            });
            out.pinned += 1;
        }
    }

    // ---- the links: every seam whose edge and boxes resolve, with its offsets
    let mut pairs: Vec<(usize, usize)> = Vec::new();
    let mut links: Vec<Option<Link>> = Vec::with_capacity(plan.seams.len());
    for (i, s) in plan.seams.iter().enumerate() {
        let Some(edge) = edges.get(s.edge.0.as_str()) else {
            links.push(None);
            continue; // `DW0824` refused the reference.
        };
        if matches!(edge, Edge::Vision { .. }) {
            links.push(None);
            continue; // `DW0824` said this carries a sightline.
        }
        let (Some(&a), Some(&b)) = (
            by_node.get(edge.a().0.as_str()),
            by_node.get(edge.b().0.as_str()),
        ) else {
            links.push(None);
            continue; // `DW0824` reported the missing box.
        };
        pairs.push((a, b));
        // An unresolvable opening (`DW0812`/`DW0876` say so) centres nothing:
        // the crossing is taken one cell wide at the corner, so the seam still
        // places and the rules that name the opening run over a plan that
        // stands.
        let width = centring_width(s, table, reads).unwrap_or_default();
        match offsets(s, ext_of(&plan.boxes[a]), ext_of(&plan.boxes[b]), width) {
            Ok((at, meets)) => links.push(Some(Link { a, b, at, meets })),
            Err(problem) => {
                d.push(offset_problem(i, s, edge, problem));
                out.refused.insert(i);
                links.push(None);
            }
        }
    }

    // ---- placement passes
    loop {
        let mut changed = false;
        for (i, link) in links.iter().enumerate() {
            let Some(l) = link else { continue };
            let s = &plan.seams[i];
            let (ext_a, ext_b) = (ext_of(&plan.boxes[l.a]), ext_of(&plan.boxes[l.b]));
            match (out.boxes[l.a].clone(), out.boxes[l.b].clone()) {
                (Some(a), None) => {
                    let min = derive_corner(s.face, a.min, ext_a, ext_b, l.at, l.meets, true);
                    out.boxes[l.b] = Some(PackedBox {
                        node: plan.boxes[l.b].node.clone(),
                        min,
                        by: Provenance::Seam {
                            seam: i,
                            edge: s.edge.clone(),
                            from: a.node,
                            face: s.face,
                        },
                    });
                    out.derived += 1;
                    changed = true;
                }
                (None, Some(b)) => {
                    let min = derive_corner(s.face, b.min, ext_a, ext_b, l.at, l.meets, false);
                    out.boxes[l.a] = Some(PackedBox {
                        node: plan.boxes[l.a].node.clone(),
                        min,
                        by: Provenance::Seam {
                            seam: i,
                            edge: s.edge.clone(),
                            from: b.node,
                            face: s.face,
                        },
                    });
                    out.derived += 1;
                    changed = true;
                }
                _ => {}
            }
        }
        if !changed {
            break;
        }
    }

    // ---- every seam whose two ends stand: one placement, and the anchor
    for (i, link) in links.iter().enumerate() {
        let Some(l) = link else { continue };
        let (Some(a), Some(b)) = (&out.boxes[l.a], &out.boxes[l.b]) else {
            continue;
        };
        let s = &plan.seams[i];
        let (ext_a, ext_b) = (ext_of(&plan.boxes[l.a]), ext_of(&plan.boxes[l.b]));
        let want = derive_corner(s.face, a.min, ext_a, ext_b, l.at, l.meets, true);
        if want != b.min {
            d.push(two_placements(i, s, a, b, want));
            out.refused.insert(i);
            continue;
        }
        if let (Some(fa), Some(fb)) = (floors[l.a], floors[l.b]) {
            out.seam_at[i] = Some(crossing_anchor(s.face, a.min, l.at, fa, fb));
        }
    }

    // ---- components with nothing to place them
    let mut parent: Vec<usize> = (0..plan.boxes.len()).collect();
    fn find(p: &mut [usize], i: usize) -> usize {
        let mut r = i;
        while p[r] != r {
            r = p[r];
        }
        let mut c = i;
        while p[c] != r {
            let n = p[c];
            p[c] = r;
            c = n;
        }
        r
    }
    for &(a, b) in &pairs {
        let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
        if ra != rb {
            parent[ra.max(rb)] = ra.min(rb);
        }
    }
    let mut members: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
    for (i, b) in plan.boxes.iter().enumerate() {
        if nodes.contains(b.node.0.as_str()) {
            let r = find(&mut parent, i);
            members.entry(r).or_default().push(i);
        }
    }
    out.components = members.len();
    let entry = graph.entry.0.as_str();
    for (_, boxes) in members {
        if boxes.iter().any(|&i| plan.boxes[i].min.is_some()) {
            continue;
        }
        let names: Vec<String> = boxes
            .iter()
            .map(|&i| format!("`{}`", plan.boxes[i].node))
            .collect();
        let suggested = boxes
            .iter()
            .find(|&&i| plan.boxes[i].node.0 == entry)
            .or(boxes.first())
            .map(|&i| plan.boxes[i].node.to_string())
            .unwrap_or_default();
        d.push(Diagnostic::error(
            DW_UNPLACED,
            "site-plan",
            format!("/content/boxes/{}", boxes[0]),
            format!(
                "nothing places {list}: no box among them pins its `min`, and a box stands \
                 only where a pin puts it or where a seam hangs it off a box that already \
                 stands. Pin one of them — `{suggested}` — with `\"min\": [x, z]`, and the \
                 seams place the rest. {count} box(es) in this component.",
                list = names.join(", "),
                count = boxes.len(),
            ),
        ));
    }
    out
}

/// `DW0828`: an offset that is not a position on its own box's face.
fn offset_problem(i: usize, s: &Seam, edge: &Edge, problem: OffsetProblem) -> Diagnostic {
    let (which, detail) = match problem {
        OffsetProblem::Shape { which } => (
            which,
            if s.face.is_horizontal_plane() {
                format!(
                    "the {face} face is a floor or ceiling with two in-plane axes, and `{which}` \
                     gives one number. Write `[dx, dz]` — cells along x and z from the box's \
                     low corner",
                    face = s.face.as_str()
                )
            } else {
                format!(
                    "the {face} face is a wall with one horizontal axis, and `{which}` gives \
                     two numbers. Write one — cells along the face from the box's low corner; \
                     the sill is not written, it is the higher of the two floors",
                    face = s.face.as_str()
                )
            },
        ),
        OffsetProblem::OffFace {
            which,
            axis,
            value,
            extent,
            width,
        } => (
            which,
            format!(
                "`{which}` puts the crossing's corner at {value} along {axis} on a face that \
                 runs 0..{last} — the crossing is {width} wide and the box is {extent} on that \
                 axis. Write an offset on the face, or omit it and the crossing is centred; an \
                 offset is never quietly clamped to fit",
                last = extent - 1,
            ),
        ),
    };
    Diagnostic::error(
        DW_SEAM_NOT_SHARED,
        "site-plan",
        format!("/content/seams/{i}/{which}"),
        format!(
            "the seam for `{id}` between `{an}` and `{bn}` names no position on the {side} \
             box's face: {detail}.",
            id = s.edge,
            an = edge.a(),
            bn = edge.b(),
            side = if which == "at" { "`a`" } else { "`b`" },
        ),
    )
}

/// A seam whose two boxes both stand, and which would put `b` somewhere else:
/// `DW0883` when a pin is one of the two authorities, `DW0828` when a loop does
/// not close.
fn two_placements(i: usize, s: &Seam, a: &PackedBox, b: &PackedBox, want: [i64; 2]) -> Diagnostic {
    // Two authorities on `b`: its pin and this seam. When `b` was placed by
    // another seam, the disagreement is between seams — a loop that does not
    // close — however `a` came to stand where it stands.
    let pinned = matches!(b.by, Provenance::Pinned);
    let where_ = format!(
        "`{an}` stands at [{ax}, {az}] ({a_by}); `{bn}` stands at [{bx}, {bz}] ({b_by}); hung \
         off `{an}`'s {face} face by this seam, `{bn}` would stand at [{wx}, {wz}]",
        an = a.node,
        ax = a.min[0],
        az = a.min[1],
        a_by = a.by.describe(),
        bn = b.node,
        bx = b.min[0],
        bz = b.min[1],
        b_by = b.by.describe(),
        face = s.face.as_str(),
        wx = want[0],
        wz = want[1],
    );
    if pinned {
        Diagnostic::error(
            DW_UNPLACED,
            "site-plan",
            format!("/content/seams/{i}"),
            format!(
                "two things place one box, and they disagree: {where_}. A pin is a claim the \
                 packing verifies, never a second authority — move the pin to the corner the \
                 seam derives, delete it and let the seam place the box, or change this seam's \
                 `at`/`meets` so the two agree.",
            ),
        )
    } else {
        Diagnostic::error(
            DW_SEAM_NOT_SHARED,
            "site-plan",
            format!("/content/seams/{i}"),
            format!(
                "the seam for `{id}` closes a loop, and the loop does not close: {where_}. Every \
                 box in the loop was placed by an earlier seam, so this one can only check; \
                 change its `at`/`meets` to where the two boxes really meet, or move the \
                 offsets of the seams that placed them.",
                id = s.edge,
            ),
        )
    }
}

/// Every box's corner and how it was obtained, one line each — the derivation
/// handed back, so a creator reads a corner from the build rather than typing
/// it into the document.
#[must_use]
pub fn placements(c: &Campaign) -> Vec<String> {
    let (Some(plan), Some(graph)) = (
        c.site_plan.as_ref().map(|p| &p.content),
        c.layout_graph.as_ref().map(|g| &g.content),
    ) else {
        return Vec::new();
    };
    let table = Metrics::table();
    let mut reads = Reads::new();
    let mut sink = Vec::new();
    let (_, packed) = resolve(plan, graph, &table, &mut reads, &mut sink);
    packed
        .boxes
        .iter()
        .flatten()
        .map(|b| {
            format!(
                "site-plan placing: `{node}` stands at [{x}, {z}] — {by}.",
                node = b.node,
                x = b.min[0],
                z = b.min[1],
                by = b.by.describe(),
            )
        })
        .collect()
}

/// Resolve every box once: its footprint, its walk plane, its headroom and its
/// size class. A floor naming a datum the plan does not declare is the ordinary
/// dangling reference (`DW0112`) and the box is dropped, because a place with no
/// plane has no geometry for any rule below to judge.
/// The corners come from the packing (spec-0059 §3), which runs here so that
/// every reader of the resolved plan — the checks, the derivation, the battery
/// — holds one grid.
fn resolve<'a>(
    plan: &'a SitePlanContent,
    graph: &LayoutGraphContent,
    table: &Metrics,
    reads: &mut Reads,
    d: &mut Vec<Diagnostic>,
) -> (Vec<Placed<'a>>, Packed) {
    let datums: BTreeMap<&str, i64> = plan.datums.iter().map(|x| (x.id.0.as_str(), x.y)).collect();
    // Whichever of the two classifications the node declared. `DW0875` is what
    // refuses a node that declared both or neither; this map takes the size
    // class first so that a node which slipped past with both is judged against
    // one of the two rather than against neither — a refused campaign builds
    // nothing either way, and a check that quietly examines zero boxes is the
    // shape worth avoiding.
    let classes: BTreeMap<&str, (MetricKind, &str)> = graph
        .nodes
        .iter()
        .filter_map(|n| {
            let named = n
                .size_class
                .as_deref()
                .map(|x| (MetricKind::SizeClass, x))
                .or_else(|| n.way_class.as_deref().map(|x| (MetricKind::WayClass, x)))?;
            Some((n.id.0.as_str(), named))
        })
        .collect();
    // Floors first: the packing needs them for every sill, and a box with no
    // plane has no cells for any reader to work in.
    let mut floors: Vec<Option<i64>> = Vec::with_capacity(plan.boxes.len());
    for (i, b) in plan.boxes.iter().enumerate() {
        floors.push(match &b.floor {
            Floor::Y(y) => Some(*y),
            Floor::Datum(id) => match datums.get(id.0.as_str()) {
                Some(y) => Some(*y),
                None => {
                    d.push(Diagnostic::error(
                        crate::codes::DANGLING_REF,
                        "site-plan",
                        format!("/content/boxes/{i}/floor"),
                        format!(
                            "box for `{node}` stands on `{id}`, which this plan declares no \
                             `datums[]` entry for. Declare the plane, or give the box its own \
                             `y` — a place with no plane has no walk surface, so nothing below \
                             can say where it is.",
                            node = b.node,
                        ),
                    ));
                    None
                }
            },
        });
    }
    let packed = pack(plan, graph, table, &floors, reads, d);
    let mut out = Vec::new();
    for (i, b) in plan.boxes.iter().enumerate() {
        let (Some(floor), Some(pb)) = (floors[i], &packed.boxes[i]) else {
            continue; // `DW0112` or `DW0883` said why this box has no cells.
        };
        let class = classes
            .get(b.node.0.as_str())
            .and_then(|(kind, name)| table.resolve(*kind, name).ok())
            .and_then(|entry| match entry.value(reads) {
                MetricValue::SizeClass(sc) => Some(PlaceClass::Size(*sc)),
                MetricValue::WayClass(w) => Some(PlaceClass::Way(*w)),
                _ => None,
            });
        let clearance = match b.ceiling {
            Ceiling::Clearance(c) => Some(c.get()),
            // A sky-open place claims its class's own minimum headroom and
            // nothing above it: an open place is precisely one that makes no
            // claim on the air over it. True of both kinds of class, which is
            // why the question is asked of the classification rather than of
            // one of its variants.
            Ceiling::Open => class.map(PlaceClass::min_clearance),
        };
        out.push(Placed {
            index: i,
            plan: b,
            foot: [
                pb.min[0],
                pb.min[0] + i64::from(b.extent[0].get()) - 1,
                pb.min[1],
                pb.min[1] + i64::from(b.extent[1].get()) - 1,
            ],
            floor,
            clearance,
            class,
            by: pb.by.clone(),
        });
    }
    (out, packed)
}

/// `DW0824`: the graph and the plan agree **exactly**, in both directions.
///
/// Six correspondences and three references, all one claim: everything the graph
/// declares is embedded exactly once, and everything the plan embeds is
/// something the graph declared.
///
/// This check is also the **two-artifact question's instrument** (spec-0049
/// §10): how often it fires *alone* — a graph edit with no plan edit or the
/// reverse — is the measurable evidence that decides whether the graph and the
/// plan stay two documents or merge into one.
///
/// It reads `plan.boxes` rather than the resolved list, deliberately: a box
/// whose floor named no datum is still a box the author wrote, and reporting it
/// as a place with no box as well would answer a question nobody asked.
fn agreement(
    plan: &SitePlanContent,
    graph: &LayoutGraphContent,
    placed: &[Placed<'_>],
    d: &mut Vec<Diagnostic>,
) {
    let fault = |path: String, msg: String, d: &mut Vec<Diagnostic>| {
        d.push(Diagnostic::error(DW_PLAN_AGREEMENT, "site-plan", path, msg));
    };

    // -------------------------------------------------------------- places
    let nodes: BTreeSet<&str> = graph.nodes.iter().map(|n| n.id.0.as_str()).collect();
    let mut boxed: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
    for (i, b) in plan.boxes.iter().enumerate() {
        if !nodes.contains(b.node.0.as_str()) {
            fault(
                format!("/content/boxes/{i}/node"),
                format!(
                    "this box embeds `{n}`, which the layout graph declares no place for. A box \
                     is the geometry OF a place; one that names nothing is a room the map has \
                     no reason to contain. Declare the place, or delete the box.",
                    n = b.node,
                ),
                d,
            );
            continue;
        }
        boxed.entry(b.node.0.as_str()).or_default().push(i);
    }
    for (i, n) in graph.nodes.iter().enumerate() {
        match boxed.get(n.id.0.as_str()).map_or(0, Vec::len) {
            1 => {}
            0 => fault(
                "/content/boxes".to_string(),
                format!(
                    "place `{id}` has no box. Every place the graph declares is embedded exactly \
                     once — an unembedded place is a room the plan forgot, and nothing later can \
                     notice it, because every geometric rule quantifies over the boxes that \
                     exist. (Graph node {i} of {total}.)",
                    id = n.id,
                    total = graph.nodes.len(),
                ),
                d,
            ),
            k => fault(
                "/content/boxes".to_string(),
                format!(
                    "place `{id}` has {k} boxes. A place is one space; two boxes for it make \
                     every rule below pick one of them and no rule says which.",
                    id = n.id,
                ),
                d,
            ),
        }
    }

    // --------------------------------------------------------- connections
    let edges: BTreeMap<&str, &Edge> = graph.edges.iter().map(|e| (e.id().0.as_str(), e)).collect();
    let mut seamed: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
    for (i, s) in plan.seams.iter().enumerate() {
        match edges.get(s.edge.0.as_str()) {
            None => fault(
                format!("/content/seams/{i}/edge"),
                format!(
                    "this seam allocates `{e}`, which the layout graph declares no connection \
                     for. A seam is an opening cut for a connection; one that names nothing is a \
                     hole in a wall for no reason.",
                    e = s.edge,
                ),
                d,
            ),
            Some(Edge::Vision { .. }) => fault(
                format!("/content/seams/{i}/edge"),
                format!(
                    "`{e}` is a `vision` connection and carries a **sightline**, not a seam. A \
                     seam is an opening on a shared face, and a vista's two ends are routinely \
                     not adjacent — a tower seen from a shore shares no face with it — so the \
                     seam construct cannot state the one thing a vision connection asserts. Move \
                     it to `sightlines[]`.",
                    e = s.edge,
                ),
                d,
            ),
            Some(_) => {
                seamed.entry(s.edge.0.as_str()).or_default().push(i);
            }
        }
    }
    let mut sighted: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
    for (i, s) in plan.sightlines.iter().enumerate() {
        match edges.get(s.edge.0.as_str()) {
            None => fault(
                format!("/content/sightlines/{i}/edge"),
                format!(
                    "this sightline embeds `{e}`, which the layout graph declares no connection \
                     for.",
                    e = s.edge,
                ),
                d,
            ),
            Some(e) if !matches!(e, Edge::Vision { .. }) => fault(
                format!("/content/sightlines/{i}/edge"),
                format!(
                    "`{id}` is a `{class}` connection: a body passes along it, so it is allocated \
                     a **seam** on a shared face rather than a line of sight. Move it to \
                     `seams[]`.",
                    id = s.edge,
                    class = e.class(),
                ),
                d,
            ),
            Some(_) => {
                sighted.entry(s.edge.0.as_str()).or_default().push(i);
            }
        }
    }
    for (i, e) in graph.edges.iter().enumerate() {
        let (what, held, other) = if e.is_traversal() {
            ("seam", &seamed, "seams")
        } else {
            ("sightline", &sighted, "sightlines")
        };
        match held.get(e.id().0.as_str()).map_or(0, Vec::len) {
            1 => {}
            0 => fault(
                format!("/content/{other}"),
                format!(
                    "connection `{id}` ({class}) has no {what}. **Seams are allocated, not \
                     discovered**: two places connect because the plan cut an opening between \
                     them while both were still free to move, never because a wall happened to \
                     be low somewhere. A connection with nothing allocated is a promise the \
                     geometry has not been asked to keep. (Graph edge {i} of {total}.)",
                    id = e.id(),
                    class = e.class(),
                    total = graph.edges.len(),
                ),
                d,
            ),
            k => fault(
                format!("/content/{other}"),
                format!(
                    "connection `{id}` has {k} {what}s. One connection is one way through; two \
                     openings for it are two ways, and the graph declared one.",
                    id = e.id(),
                ),
                d,
            ),
        }
    }

    // ---------------------------------- what a seam says ABOUT its connection
    let by_node: BTreeMap<&str, &Placed<'_>> =
        placed.iter().map(|p| (p.plan.node.0.as_str(), p)).collect();
    for (i, s) in plan.seams.iter().enumerate() {
        let Some(e) = edges.get(s.edge.0.as_str()) else {
            continue;
        };
        let Some(host) = &s.stair_in else {
            continue;
        };
        if !matches!(e, Edge::Stair { .. }) {
            fault(
                format!("/content/seams/{i}/stair_in"),
                format!(
                    "this seam declares stair massing in `{host}`, and `{id}` is a `{class}` \
                     connection. Only a stair is built out of treads; on anything else the \
                     declaration is a fact about the geometry that the graph contradicts.",
                    id = s.edge,
                    class = e.class(),
                ),
                d,
            );
        } else if host != e.a() && host != e.b() {
            fault(
                format!("/content/seams/{i}/stair_in"),
                format!(
                    "this seam hosts its stair in `{host}`, which is neither end of `{id}` \
                     (`{a}` and `{b}`). A stair stands in one of the two places it joins.",
                    id = s.edge,
                    a = e.a(),
                    b = e.b(),
                ),
                d,
            );
        }
    }

    // ------------------------- what a sightline says ABOUT its two places
    for (i, s) in plan.sightlines.iter().enumerate() {
        let Some(e) = edges.get(s.edge.0.as_str()) else {
            continue;
        };
        for (end, point, node) in [("from", s.from, e.a()), ("to", s.to, e.b())] {
            let Some(p) = by_node.get(node.0.as_str()) else {
                continue;
            };
            if contains_point(p, point) {
                continue;
            }
            fault(
                format!("/content/sightlines/{i}/{end}"),
                format!(
                    "`{id}` is a line of sight between `{a}` and `{b}`, and its `{end}` end \
                     `[{x}, {y}, {z}]` is not inside `{node}`. The stage-5 proof walks exactly \
                     this segment and calls the result the vista's; a segment whose ends are \
                     somewhere else would be proving a different claim, green or red.",
                    id = s.edge,
                    a = e.a(),
                    b = e.b(),
                    x = point[0],
                    y = point[1],
                    z = point[2],
                ),
                d,
            );
        }
    }
}

/// Is a world cell inside a place's play space?
fn contains_point(p: &Placed<'_>, at: [i64; 3]) -> bool {
    if at[0] < p.x0() || at[0] > p.x1() || at[2] < p.z0() || at[2] > p.z1() {
        return false;
    }
    match p.y_span() {
        Some((lo, hi)) => at[1] >= lo && at[1] <= hi,
        // A sky-open place whose class did not resolve has no stated headroom;
        // `DW0812` already refused the name, and inventing a bound here would be
        // a second refusal for one defect.
        None => at[1] >= p.floor,
    }
}

/// `DW0825`: every box's footprint is a multiple of the kit grid's quantum.
fn grid(placed: &[Placed<'_>], table: &Metrics, reads: &mut Reads, d: &mut Vec<Diagnostic>) {
    let Some(grid) = table.grid(reads) else {
        return; // `Metrics::self_check` owns a table that defines no grid.
    };
    let q = grid.quantum;
    if q == 0 {
        return;
    }
    for p in placed {
        for (axis, name) in [(0usize, "x"), (1usize, "z")] {
            let e = p.plan.extent[axis].get();
            if !off_grid(e, q) {
                continue;
            }
            d.push(Diagnostic::error(
                DW_BOX_OFF_GRID,
                "site-plan",
                format!("/content/boxes/{}/extent/{axis}", p.index),
                format!(
                    "box for `{node}` is {e} blocks on {name}, and the kit grid's quantum is \
                     {q} — so it is not a multiple of it. Every box's footprint is a whole \
                     number of quanta on both horizontal axes, which is what lets a kit piece \
                     land in one without being cut. The nearest multiples are {lo} and {hi}.",
                    node = p.plan.node,
                    lo = e - e % q,
                    hi = e - e % q + q,
                ),
            ));
        }
    }
}

/// **`DW0825`'s own test, for one footprint on one axis.** One function so that
/// a verdict computed from a box can ask the SAME question the refusal asked,
/// rather than re-deriving the kit-grid rule beside it.
fn off_grid(extent: u32, quantum: u32) -> bool {
    quantum != 0 && !extent.is_multiple_of(quantum)
}

/// **The clause a stage-6 verdict owes when the allocation it measured against
/// is one this plan has already refused** — the DEFER shape of
/// [`crate::diagnostic`]'s "one cause, one line".
///
/// A `details[]` row is judged against a FRAME and a SEAM SET, and both are
/// computed from the site plan. When the plan's own refusals have already
/// touched them, the stage-6 line is a true, separate finding measured against a
/// number the map does not really have — and, worse, the primary is in another
/// document, so the reader has no way to see the relation. Measured: widening
/// one box by one block printed `DW0825` and `DW0828` in the site plan and then
/// `DW0843` and `DW0844` in the detail plan, five codes over three documents,
/// with nothing saying which was the edit.
///
/// So the stage-6 verdicts keep their own lines — each still names a real
/// mismatch, and suppressing them is how fixing one thing produces a fresh crop
/// of refusals nobody was shown — and gain a clause saying what they are
/// downstream of. Two things can be already-refused:
///
/// 1. the place's own box is off the kit grid (`DW0825`), so its frame is not a
///    frame this map will keep;
/// 2. the plan DECLARES a seam on this place that it did not resolve — a face
///    the two boxes do not share (`DW0828`) or an opening that does not fit
///    (`DW0829`) — so the allocated seam set this place answers is short of what
///    the author wrote.
///
/// Empty when the plan settled both, which is the ordinary case and costs one
/// pass over the plan's seams.
#[must_use]
pub fn refused_upstream(
    c: &Campaign,
    node: &NodeId,
    resolved: &[PlacedSeam],
    reads: &mut Reads,
) -> String {
    let Some(plan) = c.site_plan.as_ref().map(|p| &p.content) else {
        return String::new();
    };
    let mut parts: Vec<String> = Vec::new();

    if let Some(q) = Metrics::table().grid(reads).map(|g| g.quantum)
        && let Some(b) = plan.boxes.iter().find(|b| &b.node == node)
    {
        let axes: Vec<&str> = [(0usize, "x"), (1usize, "z")]
            .into_iter()
            .filter(|(a, _)| off_grid(b.extent[*a].get(), q))
            .map(|(_, name)| name)
            .collect();
        if !axes.is_empty() {
            parts.push(format!(
                "this place's box is off the kit grid on {axes} and `DW0825` has already refused \
                 it, so the frame above is not one this map keeps",
                axes = axes.join(" and "),
            ));
        }
    }

    // A seam the plan wrote and did not resolve: the graph edge names this
    // place, the plan has a seam row for it, and nothing came out the other end.
    let graph_edges: BTreeMap<&str, &Edge> = c
        .layout_graph
        .as_ref()
        .map(|g| {
            g.content
                .edges
                .iter()
                .map(|e| (e.id().0.as_str(), e))
                .collect()
        })
        .unwrap_or_default();
    let unresolved: Vec<String> = plan
        .seams
        .iter()
        .filter(|s| {
            graph_edges
                .get(s.edge.0.as_str())
                .is_some_and(|e| e.a() == node || e.b() == node)
                && !resolved.iter().any(|r| r.edge == s.edge)
        })
        .map(|s| format!("`{}`", s.edge))
        .collect();
    if !unresolved.is_empty() {
        parts.push(format!(
            "the plan writes {n} seam(s) on this place that it does not resolve ({list}), which \
             `DW0828` or `DW0829` has already refused, so the allocation this piece is answering \
             is short of what the plan says",
            n = unresolved.len(),
            list = unresolved.join(", "),
        ));
    }

    if parts.is_empty() {
        return String::new();
    }
    format!(
        " This measurement stands downstream of a site-plan refusal: {parts}. Repair the plan \
         first — this line moves with it.",
        parts = parts.join("; "),
    )
}

/// `DW0826`: nothing the plan places leaves the region.
///
/// **The region is the brief's number flowing down.** A box is never grounds to
/// grow it: the prescription in the message is to move or shrink the box, or to
/// change the brief's fact and re-derive *visibly* — never to let the extent be
/// whatever the parts added up to, which is the failure this whole stage was
/// bought to end.
///
/// Whole-owned volumes answer to it too. A `massif` outside the region is the
/// whole owning mass beyond its own declared extent, which is the same
/// extent-flows-up defect arriving through the back door.
///
/// **One region number is one finding, however many boxes stand outside it**
/// (`crate::diagnostic`'s "one cause, one line"). The region is a single fact
/// handed down by the brief, so a region a course too short puts *every* box
/// over the same edge and each per-box refusal prints the same two numbers with
/// a different name in front: measured on a 24-place campaign, shortening the
/// region by five courses printed 24 identical paragraphs. When more than one
/// thing leaves it, this states the count, names every offender with its own
/// overrun, and prescribes once. A single offender still gets its own line
/// exactly as before — the fold is reachable only where the copies would have
/// been.
fn region(plan: &SitePlanContent, placed: &[Placed<'_>], d: &mut Vec<Diagnostic>) {
    let r = &plan.region;
    let spans = [region_span(r, 0), region_span(r, 1), region_span(r, 2)];
    // How the region reads once, for the folded arms: the per-item clause
    // repeats it, and repeating it N times is most of what made N copies
    // unreadable.
    let region_text = format!(
        "x {}..{}, y {}..{}, z {}..{}",
        spans[0].0, spans[0].1, spans[1].0, spans[1].1, spans[2].0, spans[2].1
    );

    // ---- boxes ----
    let mut boxes_out: Vec<Overrun<'_>> = Vec::new();
    for p in placed {
        let mut bad: Vec<(&'static str, i64, i64)> = Vec::new();
        if !within((p.x0(), p.x1()), spans[0]) {
            bad.push(("x", p.x0(), p.x1()));
        }
        if let Some(y) = p.y_span()
            && !within(y, spans[1])
        {
            bad.push(("y", y.0, y.1));
        }
        if !within((p.z0(), p.z1()), spans[2]) {
            bad.push(("z", p.z0(), p.z1()));
        }
        if !bad.is_empty() {
            boxes_out.push(Overrun {
                index: p.index,
                name: p.plan.node.0.as_str(),
                axes: bad,
                by: p.by.describe(),
            });
        }
    }
    if boxes_out.len() == 1 {
        let o = &boxes_out[0];
        d.push(Diagnostic::error(
            DW_BOX_LEAVES_REGION,
            "site-plan",
            format!("/content/boxes/{}", o.index),
            format!(
                "box for `{node}` leaves the region: {bad}. It stands where it stands because it \
                 is {by}. The region is the whole map's extent, and it comes from the brief — a \
                 box is never grounds to grow it. Move the box (its pin, or the offsets of the \
                 seam that placed it), shrink it, or change the brief's fact and re-derive the \
                 region so the change is visible in the document that owns it.",
                by = o.by,
                node = o.name,
                bad = against_region(&o.axes, &spans),
            ),
        ));
    } else if boxes_out.len() > 1 {
        d.push(Diagnostic::error(
            DW_BOX_LEAVES_REGION,
            "site-plan",
            "/content/boxes",
            format!(
                "{n} of the {total} box(es) this plan places leave the region, which is \
                 {region_text}: {list}. The region is the whole map's extent, and it comes from \
                 the brief — a box is never grounds to grow it. One region is the cause of all \
                 {n} of these, which is why they are one line and not {n}: move or shrink the \
                 boxes, or change the brief's fact and re-derive the region so the change is \
                 visible in the document that owns it.",
                n = boxes_out.len(),
                total = placed.len(),
                list = named_overruns(&boxes_out),
            ),
        ));
    }

    // ---- whole-owned volumes ----
    let mut volumes_out: Vec<Overrun<'_>> = Vec::new();
    for (i, v) in plan.volumes.iter().enumerate() {
        let vmax = v.region.max();
        let mut bad: Vec<(&'static str, i64, i64)> = Vec::new();
        for (axis, name) in [(0usize, "x"), (1, "y"), (2, "z")] {
            if !within((v.region.min[axis], vmax[axis]), spans[axis]) {
                bad.push((name, v.region.min[axis], vmax[axis]));
            }
        }
        if !bad.is_empty() {
            volumes_out.push(Overrun {
                by: String::new(),
                index: i,
                name: v.id.0.as_str(),
                axes: bad,
            });
        }
    }
    if volumes_out.len() == 1 {
        let o = &volumes_out[0];
        d.push(Diagnostic::error(
            DW_BOX_LEAVES_REGION,
            "site-plan",
            format!("/content/volumes/{}", o.index),
            format!(
                "whole-owned volume `{id}` leaves the region: {bad}. The region is the whole's \
                 own extent; mass outside it is the whole growing to fit what was put in it, \
                 which is the direction this stage exists to forbid.",
                id = o.name,
                bad = against_region(&o.axes, &spans),
            ),
        ));
    } else if volumes_out.len() > 1 {
        d.push(Diagnostic::error(
            DW_BOX_LEAVES_REGION,
            "site-plan",
            "/content/volumes",
            format!(
                "{n} of the {total} whole-owned volume(s) leave the region, which is \
                 {region_text}: {list}. The region is the whole's own extent; mass outside it is \
                 the whole growing to fit what was put in it, which is the direction this stage \
                 exists to forbid. One region is the cause of all {n} of these, which is why \
                 they are one line and not {n}.",
                n = volumes_out.len(),
                total = plan.volumes.len(),
                list = named_overruns(&volumes_out),
            ),
        ));
    }
}

/// One offender's overrun, spelled against the region on each axis it leaves —
/// the wording a single finding carries, where the region's own numbers are
/// stated beside the box's because there is only one line to read them in.
fn against_region(bad: &[(&'static str, i64, i64)], spans: &[(i64, i64); 3]) -> String {
    bad.iter()
        .map(|(name, lo, hi)| {
            let axis = match *name {
                "x" => 0,
                "y" => 1,
                _ => 2,
            };
            format!(
                "{name} {lo}..{hi} against the region's {}..{}",
                spans[axis].0, spans[axis].1
            )
        })
        .collect::<Vec<_>>()
        .join("; ")
}

/// One thing the plan places that stands outside the region, and where.
///
/// A named struct rather than a tuple because both arms read it: the single
/// finding addresses its own `index`, the folded one prints `name` and `axes`,
/// and boxes and volumes differ in nothing else.
struct Overrun<'a> {
    /// Position in its own array — the path a single finding is addressed at.
    index: usize,
    /// The id an author reads.
    name: &'a str,
    /// Each axis it leaves, with its own inclusive span on that axis.
    axes: Vec<(&'static str, i64, i64)>,
    /// How its corner was obtained, in the words a refusal uses.
    by: String,
}

/// The offender list a folded finding carries: every name with its own overrun,
/// and no repeat of the region — the folded message states that once.
fn named_overruns(items: &[Overrun<'_>]) -> String {
    items
        .iter()
        .map(|o| {
            format!(
                "`{}` ({})",
                o.name,
                o.axes
                    .iter()
                    .map(|(ax, lo, hi)| format!("{ax} {lo}..{hi}"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        })
        .collect::<Vec<_>>()
        .join(", ")
}

/// `DW0827`: the boxes are disjoint.
///
/// Shared **faces** are the only permitted contact, because a seam needs one —
/// and a shared face is a one-cell gap, not a touch (see [`Placed`]). Two boxes
/// whose play spaces meet are two authorities over one cell, which the
/// derivation would have to arbitrate and must never be asked to.
fn disjoint(placed: &[Placed<'_>], d: &mut Vec<Diagnostic>) {
    for (a_i, a) in placed.iter().enumerate() {
        for b in &placed[a_i + 1..] {
            let (Some(x), Some(z)) = (
                overlap((a.x0(), a.x1()), (b.x0(), b.x1())),
                overlap((a.z0(), a.z1()), (b.z0(), b.z1())),
            ) else {
                continue;
            };
            let y = match (a.y_span(), b.y_span()) {
                (Some(ya), Some(yb)) => match overlap(ya, yb) {
                    Some(y) => y,
                    None => continue,
                },
                // One of them is sky-open with an unresolved class; `DW0812`
                // owns that name, and the footprints alone are enough to say
                // the two places stand in each other.
                _ => (a.floor.min(b.floor), a.floor.max(b.floor)),
            };
            d.push(Diagnostic::error(
                DW_BOXES_OVERLAP,
                "site-plan",
                format!("/content/boxes/{}", b.index),
                format!(
                    "the boxes for `{a_n}` and `{b_n}` overlap, sharing x {x0}..{x1}, y \
                     {y0}..{y1}, z {z0}..{z1}. Two places may share a FACE — that is what a seam \
                     is cut through — but never a cell: overlapping boxes are two owners for one \
                     block, and the derivation would have to pick between them with no rule to \
                     pick by. Boxes that connect sit one cell apart, and the cell between them \
                     is the wall they have in common.",
                    a_n = a.plan.node,
                    b_n = b.plan.node,
                    x0 = x.0,
                    x1 = x.1,
                    y0 = y.0,
                    y1 = y.1,
                    z0 = z.0,
                    z1 = z.1,
                ),
            ));
        }
    }
}

/// `DW0835`: the whole's mass stands beside, under and over places — never
/// inside one.
fn volumes_outside_boxes(plan: &SitePlanContent, placed: &[Placed<'_>], d: &mut Vec<Diagnostic>) {
    for (i, v) in plan.volumes.iter().enumerate() {
        let vmax = v.region.max();
        for p in placed {
            let (Some(x), Some(z)) = (
                overlap((v.region.min[0], vmax[0]), (p.x0(), p.x1())),
                overlap((v.region.min[2], vmax[2]), (p.z0(), p.z1())),
            ) else {
                continue;
            };
            let Some(py) = p.y_span() else { continue };
            let Some(y) = overlap((v.region.min[1], vmax[1]), py) else {
                continue;
            };
            d.push(Diagnostic::error(
                DW_VOLUME_IN_BOX,
                "site-plan",
                format!("/content/volumes/{i}"),
                format!(
                    "whole-owned volume `{id}` ({role}) enters the box for `{node}`, sharing x \
                     {x0}..{x1}, y {y0}..{y1}, z {z0}..{z1}. The whole's mass may stand beside a \
                     place, under it and over it; inside it, the volume and the place are two \
                     authorities writing one cell, and the derivation must never be asked to \
                     arbitrate that. Pull the volume back to the place's face, or move the \
                     place.",
                    id = v.id,
                    role = v.role.as_str(),
                    node = p.plan.node,
                    x0 = x.0,
                    x1 = x.1,
                    y0 = y.0,
                    y1 = y.1,
                    z0 = z.0,
                    z1 = z.1,
                ),
            ));
        }
    }
}

/// `DW0832`: a box is built to its place's class — **either kind** (spec-0053
/// §3).
///
/// # The way branch, and why its third demand is structural
///
/// A size class bounds both horizontal extents and this is the one place that
/// becomes geometry. A way class bounds only the **cross-section**, which is the
/// box's *shorter* horizontal extent — the axis a body feels — and then demands
/// that the **run**, the longer extent, strictly EXCEED the class's
/// `max_width`.
///
/// That third demand is the elongation, and it is deliberately derived from the
/// class's own widest cross-section rather than seeded as a constant, because it
/// is exactly what a room cannot supply. A square box can never satisfy it: its
/// run equals its width, and one number cannot both be `<= max_width` and exceed
/// it. So "declare a room a way to escape the size ladder" is refused **by the
/// object's own shape** rather than by a rule the author could satisfy by
/// choosing differently — the property `CLAUDE.md` demands of an opt-out, since
/// the defect this branch exists to catch is structurally incapable of
/// producing its proof.
///
/// There is no maximum run and there is not going to be one: a route's length is
/// per-campaign geometry, never a standard (spec-0053 §7).
fn size_classes(placed: &[Placed<'_>], d: &mut Vec<Diagnostic>) {
    for p in placed {
        let Some(class) = p.class else {
            continue; // `DW0812` refused the name.
        };
        let (kind, mut bad) = match class {
            PlaceClass::Size(sc) => {
                let mut bad: Vec<String> = Vec::new();
                for (axis, name) in [(0usize, "x"), (1, "z")] {
                    let e = p.plan.extent[axis].get();
                    if e < sc.min_footprint[axis] || e > sc.max_footprint[axis] {
                        bad.push(format!(
                            "{e} blocks on {name}, outside the class's {}..{}",
                            sc.min_footprint[axis], sc.max_footprint[axis]
                        ));
                    }
                }
                ("size", bad)
            }
            PlaceClass::Way(w) => {
                let mut bad: Vec<String> = Vec::new();
                let (dx, dz) = (p.plan.extent[0].get(), p.plan.extent[1].get());
                let (width, run) = (dx.min(dz), dx.max(dz));
                let axis = if dx <= dz { "x" } else { "z" };
                if width < w.min_width || width > w.max_width {
                    bad.push(format!(
                        "a cross-section of {width} blocks (its shorter extent, on {axis}), \
                         outside the class's {}..{}",
                        w.min_width, w.max_width
                    ));
                }
                if run <= w.max_width {
                    bad.push(format!(
                        "a run of {run} blocks, which does not exceed the class's widest \
                         cross-section of {}. A way is a place that is longer than it is wide \
                         by kind and not by margin, so this box is a room — give it a \
                         `size_class` instead, or make it longer",
                        w.max_width
                    ));
                }
                ("way", bad)
            }
        };
        if let Ceiling::Clearance(c) = p.plan.ceiling
            && c.get() < class.min_clearance()
        {
            bad.push(format!(
                "{c} cells of headroom, under the class's minimum of {}",
                class.min_clearance()
            ));
        }
        if bad.is_empty() {
            continue;
        }
        d.push(Diagnostic::error(
            DW_SIZE_CLASS,
            "site-plan",
            format!("/content/boxes/{}", p.index),
            format!(
                "the box for `{node}` is not built to its declared {kind} class: {bad}. The \
                 class is the vocabulary the graph chose this place's scale in, and this is the \
                 one place it becomes geometry — either build the box to it, or declare the \
                 place a different class in the layout graph and say so there.",
                node = p.plan.node,
                bad = bad.join("; "),
            ),
        ));
    }
}

// ---------------------------------------------------------------------------
// Seams: allocated on a face both boxes already have
// ---------------------------------------------------------------------------

/// The rectangle two boxes have in common on one face, in the face's own two
/// in-plane world axes, plus the plane the wall between them stands in.
#[derive(Debug, Clone, Copy)]
struct SharedFace {
    plane: i64,
    u: (i64, i64),
    v: (i64, i64),
    u_axis: &'static str,
    v_axis: &'static str,
}

/// Why two boxes do not share the declared face.
#[derive(Debug, Clone)]
enum NotShared {
    /// They are not neighbours across it: the gap is `gap` cells where the one
    /// wall they would have in common needs exactly 1.
    NotAdjacent { gap: i64 },
    /// They are neighbours, but the face they would share is empty because their
    /// spans miss each other on one of the two in-plane axes.
    NoCommonArea { axis: &'static str },
    /// One of them is sky-open with no stated headroom, so it has no ceiling or
    /// floor plane for a horizontal seam to sit in.
    NoPlane { which: &'static str },
}

/// Do these two boxes share `face` **of `a`**, and where?
///
/// A shared face is a **one-cell gap** — the wall the two places have in common,
/// which the derivation writes once. See [`Placed`] for why the box is the play
/// space rather than the play space plus its shell.
/// The geometry a shared-face question needs of one box: its footprint and its
/// vertical span, when it has one.
///
/// A tiny value rather than `&Placed` so that the **one** implementation of "do
/// these two boxes share this face" serves both readers of the resolved plan:
/// the stage-4 checks, which hold a partially-resolved box, and the derivation
/// and battery in the compiler, which hold a [`PlacedBox`]. A second copy of
/// this arithmetic is how a plan-time green and a byte-time green come to be
/// about different walls.
#[derive(Clone, Copy)]
struct FaceSide {
    foot: [i64; 4],
    y: Option<(i64, i64)>,
}

impl Placed<'_> {
    fn side(&self) -> FaceSide {
        FaceSide {
            foot: self.foot,
            y: self.y_span(),
        }
    }
}

impl PlacedBox {
    fn side(&self) -> FaceSide {
        let (lo, hi) = self.space();
        FaceSide {
            foot: self.foot,
            y: Some((lo[1], hi[1])),
        }
    }
}

/// [`shared_face`] over two fully resolved boxes.
fn shared_face_of(a: &PlacedBox, b: &PlacedBox, face: Face) -> Result<SharedFace, NotShared> {
    shared_face(a.side(), b.side(), face)
}

fn shared_face(a: FaceSide, b: FaceSide, face: Face) -> Result<SharedFace, NotShared> {
    let horizontal_pair = |plane: i64, u: (i64, i64), v: (i64, i64)| -> SharedFace {
        SharedFace {
            plane,
            u,
            v,
            u_axis: "x",
            v_axis: "z",
        }
    };
    match face {
        Face::East | Face::West | Face::South | Face::North => {
            // The axis the face's normal runs along, and the horizontal axis
            // that stays in the plane.
            let (normal, along) = match face {
                Face::East | Face::West => (0usize, 2usize),
                _ => (2usize, 0usize),
            };
            let a_span = span(a.foot, normal);
            let b_span = span(b.foot, normal);
            let positive = matches!(face, Face::East | Face::South);
            let (plane, gap) = if positive {
                (a_span.1 + 1, b_span.0 - a_span.1 - 1)
            } else {
                (a_span.0 - 1, a_span.0 - b_span.1 - 1)
            };
            if gap != SHARED_FACE_GAP_CELLS {
                return Err(NotShared::NotAdjacent { gap });
            }
            let a_along = span(a.foot, along);
            let b_along = span(b.foot, along);
            let u = overlap(a_along, b_along).ok_or(NotShared::NoCommonArea {
                axis: if along == 0 { "x" } else { "z" },
            })?;
            let (ya, yb) = match (a.y, b.y) {
                (Some(ya), Some(yb)) => (ya, yb),
                (None, _) => return Err(NotShared::NoPlane { which: "a" }),
                (_, None) => return Err(NotShared::NoPlane { which: "b" }),
            };
            let v = overlap(ya, yb).ok_or(NotShared::NoCommonArea { axis: "y" })?;
            Ok(SharedFace {
                plane,
                u,
                v,
                u_axis: if along == 0 { "x" } else { "z" },
                v_axis: "y",
            })
        }
        Face::Up | Face::Down => {
            let (Some(ya), Some(yb)) = (a.y, b.y) else {
                return Err(NotShared::NoPlane {
                    which: if a.y.is_none() { "a" } else { "b" },
                });
            };
            let (plane, gap) = if face == Face::Up {
                (ya.1 + 1, yb.0 - ya.1 - 1)
            } else {
                (ya.0 - 1, ya.0 - yb.1 - 1)
            };
            if gap != SHARED_FACE_GAP_CELLS {
                return Err(NotShared::NotAdjacent { gap });
            }
            let u = overlap(span(a.foot, 0), span(b.foot, 0))
                .ok_or(NotShared::NoCommonArea { axis: "x" })?;
            let v = overlap(span(a.foot, 2), span(b.foot, 2))
                .ok_or(NotShared::NoCommonArea { axis: "z" })?;
            Ok(horizontal_pair(plane, u, v))
        }
    }
}

/// One seam and everything already resolved about it: the two places it joins,
/// the connection it allocates, and the face they share. Carried as one value so
/// each rule below takes the seam and its context rather than eight positional
/// arguments — the shape a `clippy::too_many_arguments` allow would otherwise
/// have papered over.
struct SeamCtx<'a> {
    index: usize,
    seam: &'a Seam,
    edge: &'a Edge,
    a: &'a Placed<'a>,
    b: &'a Placed<'a>,
    face: SharedFace,
    /// The crossing's low corner on the face's own two world axes, from the
    /// packing — `[along, sill]` on a wall, `[x, z]` through a floor.
    at: [i64; 2],
}

/// `DW0828`–`DW0831`: every seam sits on a face its two boxes share, at cells
/// that face has, through a standard opening a body can use, and — where the two
/// places are on different planes — by a climb or a fall the standards allow.
fn seams(
    plan: &SitePlanContent,
    graph: &LayoutGraphContent,
    placed: &[Placed<'_>],
    packed: &Packed,
    table: &Metrics,
    reads: &mut Reads,
    d: &mut Vec<Diagnostic>,
) {
    let by_node: BTreeMap<&str, &Placed<'_>> =
        placed.iter().map(|p| (p.plan.node.0.as_str(), p)).collect();
    let edges: BTreeMap<&str, &Edge> = graph.edges.iter().map(|e| (e.id().0.as_str(), e)).collect();

    for (i, s) in plan.seams.iter().enumerate() {
        if packed.refused.contains(&i) {
            continue; // the packing refused this seam by name already.
        }
        let Some(edge) = edges.get(s.edge.0.as_str()) else {
            continue; // `DW0824` refused the reference.
        };
        if matches!(edge, Edge::Vision { .. }) {
            continue; // `DW0824` said this carries a sightline.
        }
        let (Some(a), Some(b)) = (
            by_node.get(edge.a().0.as_str()).copied(),
            by_node.get(edge.b().0.as_str()).copied(),
        ) else {
            continue; // `DW0824` reported the missing box, or nothing placed it.
        };
        let Some(at) = packed.seam_at[i] else {
            continue; // an end has no plane; `DW0112` said so.
        };

        let face = match shared_face(a.side(), b.side(), s.face) {
            Ok(f) => f,
            Err(why) => {
                d.push(not_shared(i, s, edge, a, b, &why));
                continue;
            }
        };

        let ctx = SeamCtx {
            index: i,
            seam: s,
            edge,
            a,
            b,
            face,
            at,
        };

        // `DW0876`, first: a seam that does not state exactly one kind of
        // connection has no crossing for any rule below to judge, and telling
        // an author both that and what the crossing they did not state would
        // have meant prescribes two repairs for one mistake.
        if !contact_declaration(&ctx, table, reads, d) {
            continue;
        }

        let opening = if s.contact.is_some() {
            // A contact has no opening name to resolve and no single sill, so
            // `DW0829` does not run over it. That is stated rather than
            // shoehorned: calling a 55-cell front a door would make every
            // downstream door check wrong (spec-0053 §4).
            None
        } else {
            match table.resolve(
                MetricKind::Opening,
                s.opening.as_deref().unwrap_or_default(),
            ) {
                Ok(e) => match e.value(reads) {
                    MetricValue::Opening(o) => Some(*o),
                    _ => continue,
                },
                Err(unknown) => {
                    d.push(unknown.diagnostic("site-plan", &format!("/content/seams/{i}/opening")));
                    continue;
                }
            }
        };

        if let Some(opening) = opening {
            opening_fits(&ctx, opening, d);
        }
        match edge {
            Edge::Stair { .. } => stair(&ctx, table, reads, d),
            Edge::Drop { falls, .. } => drop_seam(&ctx, *falls, table, reads, d),
            Edge::Walk { .. } | Edge::Barred { .. } => {
                if let Some(opening) = opening {
                    sill(&ctx, opening, d);
                }
            }
            Edge::Vision { .. } => {}
        }
        if matches!(edge, Edge::Stair { .. }) && s.stair_in.is_none() {
            d.push(Diagnostic::error(
                DW_STAIR_PITCH,
                "site-plan",
                format!("/content/seams/{i}"),
                format!(
                    "the seam for stair `{id}` does not say which place hosts its treads. A \
                     stair is massing, and massing stands somewhere: name `{a}` or `{b}` in \
                     `stair_in`, so that the run it costs comes out of a footprint the plan has \
                     already allocated rather than out of whatever space happens to be left.",
                    id = s.edge,
                    a = edge.a(),
                    b = edge.b(),
                ),
            ));
        }
    }
}

/// `DW0828`, with the arithmetic that produced it.
fn not_shared(
    i: usize,
    s: &Seam,
    edge: &Edge,
    a: &Placed<'_>,
    b: &Placed<'_>,
    why: &NotShared,
) -> Diagnostic {
    let detail = match why {
        NotShared::NotAdjacent { gap } if *gap < 0 => format!(
            "they overlap by {} cell(s) across it rather than standing one apart",
            -gap
        ),
        NotShared::NotAdjacent { gap } => format!(
            "there are {gap} cells between them across that face where a shared wall is exactly \
             {SHARED_FACE_GAP_CELLS}"
        ),
        NotShared::NoCommonArea { axis } => format!(
            "they are neighbours across it, but their spans on {axis} miss each other entirely, \
             so the face they share has no area to cut an opening in"
        ),
        NotShared::NoPlane { which } => format!(
            "the `{which}` end is sky-open with no stated headroom, so it has no ceiling or floor \
             plane for a horizontal seam to sit in"
        ),
    };
    Diagnostic::error(
        DW_SEAM_NOT_SHARED,
        "site-plan",
        format!("/content/seams/{i}/face"),
        format!(
            "the seam for `{id}` is declared on the {face} face of `{an}`, and `{an}` and `{bn}` \
             do not share it: {detail}. **A seam is allocated on a face both boxes already \
             have** — that is the whole of why the plan places it while both are still free to \
             move, instead of two finished places discovering later that they cannot mate. \
             `{an}` is x {ax0}..{ax1}, z {az0}..{az1} at floor {af}; `{bn}` is x {bx0}..{bx1}, \
             z {bz0}..{bz1} at floor {bf}. Move one box against the other, or put the seam on \
             the face they really share.",
            id = s.edge,
            face = s.face.as_str(),
            an = edge.a(),
            bn = edge.b(),
            ax0 = a.x0(),
            ax1 = a.x1(),
            az0 = a.z0(),
            az1 = a.z1(),
            af = a.floor,
            bx0 = b.x0(),
            bx1 = b.x1(),
            bz0 = b.z0(),
            bz1 = b.z1(),
            bf = b.floor,
        ),
    )
}

/// **`DW0876`**: this seam states exactly one kind of
/// connection, and if it is a contact, one this engine builds (spec-0053 §4).
///
/// Returns `false` when the seam has no usable crossing, in which case the
/// caller stops: everything below reads the crossing rectangle.
fn contact_declaration(
    ctx: &SeamCtx<'_>,
    table: &Metrics,
    reads: &mut Reads,
    d: &mut Vec<Diagnostic>,
) -> bool {
    let (i, s) = (ctx.index, ctx.seam);
    let mut refuse = |what: String, remedy: String| {
        d.push(Diagnostic::error(
            DW_CONTACT,
            "site-plan",
            format!("/content/seams/{i}"),
            format!(
                "the seam for `{edge}` {what}. To fix it, {remedy}.",
                edge = s.edge,
            ),
        ));
    };

    // ---- Shape 1: exactly one kind.
    match (s.opening.as_ref(), s.contact.as_ref()) {
        (Some(o), Some(_)) => {
            refuse(
                format!(
                    "declares BOTH an `opening` (`{o}`) and a `contact` — a hand-off is one \
                     kind or the other"
                ),
                "delete whichever this is not. A portal allocates the cells a body crosses \
                 at and every one of them must be passable; a contact is a front along which \
                 two places simply meet and needs only one crossable column. The derivation \
                 builds them differently and the byte observer measures them differently, so \
                 there is no world in which a seam is both"
                    .to_string(),
            );
            return false;
        }
        (None, None) => {
            refuse(
                "declares neither an `opening` nor a `contact`, so it states no way across"
                    .to_string(),
                format!(
                    "give it one. A doorway is `\"opening\": \"<name>\"` — defined \
                     standards: {names}. A front where the two places simply meet is \
                     `\"contact\": {{}}`, which spans from `at` to the far edge of the \
                     shared face",
                    names = table.names_of(MetricKind::Opening).join(", "),
                ),
            );
            return false;
        }
        (Some(_), None) => return true,
        (None, Some(_)) => {}
    }

    // ---- Shape 4: the classes a contact may carry.
    //
    // `walk` and `drop` only. A rim falling to a lower court is a genuine broad
    // hand-off, so `drop` is in; `stair`, `barred` and `vision` are excluded
    // until a campaign brief demands one (spec-0053 §4, the falsifier re-armed).
    if !matches!(ctx.edge, Edge::Walk { .. } | Edge::Drop { .. }) {
        refuse(
            format!(
                "is a contact on a `{class}` connection, and a contact carries `walk` or \
                 `drop` only",
                class = ctx.edge.class(),
            ),
            "give the seam a standard `opening`, or declare the connection `walk` or \
             `drop` in the layout graph. A stair needs a run and a pitch, a barred door \
             needs a gate region that seals and clears, and a sightline is not a crossing \
             at all — none of the three is a thing a front can be, and this engine does \
             not have them as contacts until a campaign brief demands one"
                .to_string(),
        );
        return false;
    }

    // ---- Shape 3: wider than the broadest standard opening.
    //
    // The floor is derived from the standard set, so anything at or under it
    // could have been a portal. That is what makes it a demand the defect
    // cannot supply: a door declared a contact is refused by its own width.
    let Some(floor) = table.broadest_opening_width(reads) else {
        return false; // `Metrics::self_check` reports a table with no openings.
    };
    let (u_span, v_span) = (ctx.face.u, ctx.face.v);
    let (u_hi, v_hi) = crossing_hi(ctx);
    let width = u_hi - ctx.at[0] + 1;
    if width <= i64::from(floor) {
        refuse(
            format!(
                "is a contact {width} cell(s) wide, which is not wider than the broadest \
                 standard opening ({floor} cells)"
            ),
            format!(
                "widen the span, or declare it a portal — anything this narrow could have \
                 been one, and a doorway called a contact would dodge the standard set \
                 while every downstream door check went on being wrong about it. Defined \
                 openings: {names}",
                names = table.names_of(MetricKind::Opening).join(", "),
            ),
        );
        return false;
    }

    // ---- Shape 2: the span lies on the shared face.
    let mut off: Vec<String> = Vec::new();
    if ctx.at[0] < u_span.0 || u_hi > u_span.1 {
        off.push(format!(
            "{}..{} on {}, against the face's {}..{}",
            ctx.at[0], u_hi, ctx.face.u_axis, u_span.0, u_span.1
        ));
    }
    if ctx.at[1] < v_span.0 || v_hi > v_span.1 {
        off.push(format!(
            "{}..{} on {}, against the face's {}..{}",
            ctx.at[1], v_hi, ctx.face.v_axis, v_span.0, v_span.1
        ));
    }
    if !off.is_empty() {
        refuse(
            format!(
                "is a contact whose span leaves the face the two boxes share: {}",
                off.join("; ")
            ),
            "move `at` onto the shared face, or shorten `contact.extent` — the span is \
             where the derivation writes no wall, and a span running off the face would \
             ask it to open a wall that is not there. Omitting `contact.extent` runs the \
             span from `at` to the far edge of the face, which never leaves it"
                .to_string(),
        );
        return false;
    }
    true
}

/// The far corner of a seam's crossing rectangle, on the face's own two in-plane
/// axes — [`contact_extent`] resolved against the seam's own anchor, so this
/// rule and the derivation describe one rectangle.
fn crossing_hi(ctx: &SeamCtx<'_>) -> (i64, i64) {
    let e = contact_extent(ctx.seam, ctx.at, &ctx.face);
    (ctx.at[0] + e[0] - 1, ctx.at[1] + e[1] - 1)
}

/// `DW0828`'s anchor half and `DW0829`'s geometric half: the opening's cells are
/// cells the shared face has.
fn opening_fits(ctx: &SeamCtx<'_>, opening: crate::metrics::Opening, d: &mut Vec<Diagnostic>) {
    let (i, s, edge, face, at) = (ctx.index, ctx.seam, ctx.edge, &ctx.face, ctx.at);
    let anchor_in =
        at[0] >= face.u.0 && at[0] <= face.u.1 && at[1] >= face.v.0 && at[1] <= face.v.1;
    if !anchor_in {
        d.push(Diagnostic::error(
            DW_SEAM_NOT_SHARED,
            "site-plan",
            format!("/content/seams/{i}/at"),
            format!(
                "the seam for `{id}` is anchored at {ua} {u}, {va} {v}, which is not on the face \
                 `{an}` and `{bn}` share — that face runs {ua} {u0}..{u1} by {va} {v0}..{v1} in \
                 the plane at {plane}. `at` names the opening's low corner in the face's own two \
                 axes, so a corner off the face allocates the seam nowhere.",
                id = s.edge,
                an = edge.a(),
                bn = edge.b(),
                ua = face.u_axis,
                va = face.v_axis,
                u = at[0],
                v = at[1],
                u0 = face.u.0,
                u1 = face.u.1,
                v0 = face.v.0,
                v1 = face.v.1,
                plane = face.plane,
            ),
        ));
        return;
    }
    let u_hi = at[0] + i64::from(opening.width) - 1;
    let v_hi = at[1] + i64::from(opening.height) - 1;
    if u_hi <= face.u.1 && v_hi <= face.v.1 {
        return;
    }
    d.push(Diagnostic::error(
        DW_SEAM_OPENING,
        "site-plan",
        format!("/content/seams/{i}/opening"),
        format!(
            "the `{name}` opening ({w}x{h}) does not fit on the face `{an}` and `{bn}` share. \
             Anchored at {ua} {u}, {va} {v} it would run to {ua} {u_hi}, {va} {v_hi}, and the \
             shared face ends at {ua} {u1}, {va} {v1}. Move the anchor, choose a narrower \
             standard opening, or grow the overlap between the two boxes — the standard set is \
             the vocabulary, so the opening is never quietly cropped to fit.",
            name = s.opening.as_deref().unwrap_or_default(),
            w = opening.width,
            h = opening.height,
            an = edge.a(),
            bn = edge.b(),
            ua = face.u_axis,
            va = face.v_axis,
            u = at[0],
            v = at[1],
            u1 = face.u.1,
            v1 = face.v.1,
        ),
    ));
}

/// `DW0829`'s step-rule half: a body standing on the floor of a side it enters
/// from can get onto the sill.
fn sill(ctx: &SeamCtx<'_>, opening: crate::metrics::Opening, d: &mut Vec<Diagnostic>) {
    let (i, s, edge, a, b, face) = (ctx.index, ctx.seam, ctx.edge, ctx.a, ctx.b, &ctx.face);
    if face.v_axis != "y" {
        return; // a horizontal seam has no sill; the fall or the treads own it.
    }
    let sources: Vec<(&NodeId, &Placed<'_>)> = match edge.direction() {
        Some(crate::layout::Direction::AToB) => vec![(edge.a(), a)],
        Some(crate::layout::Direction::BToA) => vec![(edge.b(), b)],
        None => vec![(edge.a(), a), (edge.b(), b)],
    };
    let max_rise = MAX_JUMP_RISE_16 / crate::metrics::FULL_16;
    for (name, p) in sources {
        let rise = ctx.at[1] - p.floor;
        if rise <= max_rise {
            continue;
        }
        d.push(Diagnostic::error(
            DW_SEAM_OPENING,
            "site-plan",
            format!("/content/seams/{i}/at"),
            format!(
                "the seam for `{id}` has its sill at y {sill}, {rise} blocks over the floor of \
                 `{name}` at y {floor}, and a body reaches at most {max_rise} block(s) by \
                 jumping ({j}/16 of vanilla's apex). A body entering from `{name}` cannot get \
                 into the opening at all, so the connection the graph declares is not one. The \
                 sill is the higher of the two floors: bring the floors within a step of each \
                 other, or declare the connection a `stair` and let the treads carry the climb. \
                 (The opening is {w}x{h}.)",
                id = s.edge,
                sill = ctx.at[1],
                j = MAX_JUMP_RISE_16,
                floor = p.floor,
                w = opening.width,
                h = opening.height,
            ),
        ));
    }
}

/// `DW0830`: the stair the plan allocated can be built at a standard pitch,
/// inside the box the plan said hosts it.
fn stair(ctx: &SeamCtx<'_>, table: &Metrics, reads: &mut Reads, d: &mut Vec<Diagnostic>) {
    let (i, s, edge, a, b, face) = (ctx.index, ctx.seam, ctx.edge, ctx.a, ctx.b, &ctx.face);
    let rise = b.floor - a.floor;
    if rise == 0 {
        d.push(Diagnostic::error(
            DW_STAIR_PITCH,
            "site-plan",
            format!("/content/seams/{i}"),
            format!(
                "`{id}` is a stair, and `{an}` and `{bn}` are both on plane y {f} — so it climbs \
                 nothing. A stair's rise is not authored here: it is the difference between the \
                 two floors the plan has already chosen, which means a stair between two places \
                 at one level is a walk that has been called a stair. Move one floor, or declare \
                 the connection a `walk`.",
                id = s.edge,
                an = edge.a(),
                bn = edge.b(),
                f = a.floor,
            ),
        ));
        return;
    }
    let Some(host_id) = &s.stair_in else {
        return; // the missing declaration is reported by `seams`.
    };
    // **The treads stand in the LOWER place**, and that is geometry rather than
    // taste: a stair is a stack of courses rising off a walk plane, and the only
    // walk plane it can rise off is the lower of the two. Hosting it in the
    // upper place asks for a stack that starts at that place's floor and has to
    // reach a level *below* it, which is not a stair — it is a hole with treads
    // drawn in the air under it.
    //
    // Found by building. This code checked only that the host affords the RUN,
    // so a plan naming the upper place reached green at stage 4 and the
    // derivation then laid a mound on the wrong side of the opening; the
    // stage-5 observer caught it as a seam whose hole was still solid, which is
    // the right refusal for the wrong defect. `stair_in` stays authored rather
    // than derived because it says WHICH of the two footprints pays for the run
    // when both are candidates — but when only one can be, saying the other is
    // a refusal.
    let (low, high) = if b.floor > a.floor {
        (edge.a(), edge.b())
    } else {
        (edge.b(), edge.a())
    };
    if host_id == high {
        d.push(Diagnostic::error(
            DW_STAIR_PITCH,
            "site-plan",
            format!("/content/seams/{i}/stair_in"),
            format!(
                "the stair for `{id}` hosts its treads in `{high}`, which is the HIGHER of the two \
                 places (`{an}` stands at y {af}, `{bn}` at y {bf}). Treads rise off a walk plane, \
                 and the only plane this stair can rise off is the lower one — massing in the \
                 upper place would have to start at that place's floor and reach a level beneath \
                 it, which is not a stair. Host it in `{low}`, and check that `{low}` affords the \
                 run: a stair costs its footprint, and moving the host moves who pays.",
                id = s.edge,
                an = edge.a(),
                bn = edge.b(),
                af = a.floor,
                bf = b.floor,
            ),
        ));
        return;
    }
    let host = if host_id == edge.a() { a } else { b };
    // **The run is measured the way the derivation lays it**, by the function
    // that lays it — [`stair_run`]. What this check used to measure instead was
    // the seam's rise against the host's whole extent, and neither is what a
    // tread run costs: the courses carry a body to the OPENING, and through a
    // pierced floor they leave along one side of the hole. See [`stair_run`] for
    // the plan that reached green at `needs 8, affords 8` and built no stair.
    let Some((_, extent)) = crossing_rect(s, ctx.at, face, table, reads) else {
        return; // `DW0812` refused the opening; there is no rectangle to measure.
    };
    let Some(run) = stair_run(
        host.floor,
        host.foot,
        normal_axis_of(s.face),
        face.plane,
        crossing_aabb(s, ctx.at, face, extent),
    ) else {
        return; // no run to lay: the higher host is refused above, the stray hole by `DW0828`.
    };
    let run_axis = if run.run_axis == 0 { "x" } else { "z" };
    if gentlest_pitch(table, reads, run.climb, run.available).is_some() {
        return; // some standard pitch fits.
    }
    let Some((name, needed)) = tightest_pitch(table, reads, run.climb) else {
        return; // the table defines no pitch; `Metrics::self_check` owns that.
    };
    let carries = if run.climb == rise.abs() {
        String::new()
    } else {
        format!(
            " The treads carry {climb}, not {rise}: they rise off `{host_id}`'s floor at \
             {hf} and stop at {target}, which is where the opening puts a body.",
            climb = run.climb,
            rise = rise.abs(),
            hf = host.floor,
            target = host.floor + run.climb,
        )
    };
    d.push(Diagnostic::error(
        DW_STAIR_PITCH,
        "site-plan",
        format!("/content/seams/{i}"),
        format!(
            "the stair for `{id}` climbs {rise} block(s) between `{an}` (floor {af}) and `{bn}` \
             (floor {bf}), and no standard pitch fits inside `{host_id}`. The tightest standard \
             is `{name}`, which needs {needed} block(s) of run for a climb of {climb}, and \
             `{host_id}` affords {available} of run on {run_axis}.{carries} Give the host a \
             longer footprint on that axis, move the opening so the run has more room beside it, \
             host the stair in the other place, or bring the two floors closer together — the \
             pitches are standards, so a steeper one is not on offer.",
            id = s.edge,
            an = edge.a(),
            bn = edge.b(),
            af = a.floor,
            bf = b.floor,
            rise = rise.abs(),
            climb = run.climb,
            available = run.available,
        ),
    ));
}

/// `DW0831`: a designed drop falls the way it says it falls, and no further than
/// the policy allows.
fn drop_seam(
    ctx: &SeamCtx<'_>,
    falls: crate::layout::Direction,
    table: &Metrics,
    reads: &mut Reads,
    d: &mut Vec<Diagnostic>,
) {
    let (i, s, edge, a, b) = (ctx.index, ctx.seam, ctx.edge, ctx.a, ctx.b);
    let (from, from_p, to, to_p) = match falls {
        crate::layout::Direction::AToB => (edge.a(), a, edge.b(), b),
        crate::layout::Direction::BToA => (edge.b(), b, edge.a(), a),
    };
    let depth = from_p.floor - to_p.floor;
    if depth <= 0 {
        d.push(Diagnostic::error(
            DW_DROP_POLICY,
            "site-plan",
            format!("/content/seams/{i}"),
            format!(
                "`{id}` falls from `{from}` (floor {ff}) into `{to}` (floor {tf}), which is \
                 {what}. A drop is one-way because a body cannot climb back up the way it came, \
                 and that is only true going down — this one is a mislabelled stair. Swap the \
                 declared direction, move the floors, or declare the connection a `stair`.",
                id = s.edge,
                ff = from_p.floor,
                tf = to_p.floor,
                what = if depth == 0 {
                    "the same plane".to_string()
                } else {
                    format!("{} block(s) HIGHER", -depth)
                },
            ),
        ));
        return;
    }
    let Some(cap) = table.max_designed_drop_blocks(reads) else {
        return;
    };
    if depth <= i64::from(cap) {
        return;
    }
    d.push(Diagnostic::error(
        DW_DROP_POLICY,
        "site-plan",
        format!("/content/seams/{i}"),
        format!(
            "`{id}` drops {depth} blocks from `{from}` into `{to}`, and the designed-drop policy \
             caps a declared fall at {cap}. This is a **policy** cap and it is deliberately far \
             tighter than what a body survives: a drop is a decision about the shape of the map, \
             and it should not also be a decision about the party's health. Bring the two floors \
             closer, or break the fall with a place between them.",
            id = s.edge,
        ),
    ));
}

// ---------------------------------------------------------------------------
// Identities: the plan held to the brief's own numbers
// ---------------------------------------------------------------------------

/// What one measure came out at, or why it could not be taken.
enum Measured {
    Value(f64),
    Unresolved(Diagnostic),
}

/// `DW0833` and `DW0834`: the brief's numbers still hold once the boxes are
/// drawn, and the binding that holds them is not empty.
///
/// `DW0834` is a **warning**, not an error, and the difference is deliberate: a
/// deliberately minimal plan — a fixture, a first sketch — is a legitimate
/// thing to hold, and refusing it would make the smallest useful document
/// uncompilable. What it may not be is *silent*, so the empty side is named on
/// every run and is a finding for the round summary.
///
/// `DW0833` runs here over the plan. **Its second call site is the built
/// world**, where the same rule recomputes the same measures from assembled
/// bytes so that a derivation defect which moved a datum cannot hide behind a
/// plan-time green. That site belongs to the round that builds the blockout;
/// nothing here approximates it.
fn identities(
    c: &Campaign,
    plan: &SitePlanContent,
    placed: &[Placed<'_>],
    d: &mut Vec<Diagnostic>,
) {
    let facts: BTreeMap<&str, &crate::layout::BriefFact> = c
        .geometry_brief
        .as_ref()
        .map(|b| {
            b.content
                .facts
                .iter()
                .map(|f| (f.id.0.as_str(), f))
                .collect()
        })
        .unwrap_or_default();

    if facts.is_empty() || plan.identities.is_empty() {
        let empty = match (facts.is_empty(), plan.identities.is_empty()) {
            (true, true) => "the brief states no fact and the plan declares no identity",
            (true, false) => "the brief states no fact",
            _ => "the plan declares no identity",
        };
        d.push(Diagnostic::warning(
            DW_IDENTITY_EMPTY,
            "site-plan",
            "/content/identities",
            format!(
                "the identity gate binds nothing: {empty}. This is what holds the whole map to \
                 the design somebody wrote down — with either side empty, the plan may say \
                 anything at all and every check above will still pass, because none of them \
                 has an opinion about how big the map was meant to be. It is a warning rather \
                 than a refusal so that a deliberately minimal plan stays compilable; it is \
                 printed every run so that the emptiness is never quietly a pass."
            ),
        ));
    }

    let by_node: BTreeMap<&str, &Placed<'_>> =
        placed.iter().map(|p| (p.plan.node.0.as_str(), p)).collect();
    let datums: BTreeMap<&str, i64> = plan.datums.iter().map(|x| (x.id.0.as_str(), x.y)).collect();

    for (i, id) in plan.identities.iter().enumerate() {
        let Some(fact) = facts.get(id.fact.0.as_str()) else {
            d.push(Diagnostic::error(
                DW_PLAN_AGREEMENT,
                "site-plan",
                format!("/content/identities/{i}/fact"),
                format!(
                    "this identity holds the map to `{f}`, which the geometry brief states no \
                     fact for. An identity binds to a number the brief WROTE DOWN — that is what \
                     makes it a design being kept rather than an assertion the plan makes about \
                     itself.",
                    f = id.fact,
                ),
            ));
            continue;
        };
        let measured = measure(&id.measure, plan, &by_node, &datums, i);
        let value = match measured {
            Measured::Value(v) => v,
            Measured::Unresolved(diag) => {
                d.push(diag);
                continue;
            }
        };
        if id.cmp.holds(value, fact.value) {
            continue;
        }
        d.push(Diagnostic::error(
            DW_IDENTITY_FALSE,
            "site-plan",
            format!("/content/identities/{i}"),
            format!(
                "the plan does not keep `{f}`: {what} measures {value}, and the brief asks for \
                 {cmp} {want}{unit}. The brief's sentence was: \"{note}\". Either move the \
                 geometry until the number is true, or change the brief's fact — in the brief, \
                 where the design is written down, so that the change is a decision somebody \
                 took rather than a plan that drifted.",
                f = id.fact,
                what = describe(&id.measure),
                cmp = id.cmp.as_str(),
                want = fact.value,
                unit = fact
                    .unit
                    .as_ref()
                    .map(|u| format!(" {u}"))
                    .unwrap_or_default(),
                note = fact.note,
            ),
        ));
    }
}

/// Take one measure off the plan.
fn measure(
    m: &Measure,
    plan: &SitePlanContent,
    by_node: &BTreeMap<&str, &Placed<'_>>,
    datums: &BTreeMap<&str, i64>,
    i: usize,
) -> Measured {
    let missing_node = |node: &NodeId| {
        Measured::Unresolved(Diagnostic::error(
            DW_PLAN_AGREEMENT,
            "site-plan",
            format!("/content/identities/{i}/measure"),
            format!(
                "this identity measures `{node}`, which this plan embeds no box for. A measure \
                 is taken off the geometry, so it can only name a place the plan actually put \
                 somewhere."
            ),
        ))
    };
    match m {
        Measure::RegionExtent { axis } => {
            Measured::Value(f64::from(plan.region.extent[axis.index()].get()))
        }
        Measure::BoxExtent { node, axis } => match by_node.get(node.0.as_str()) {
            Some(p) => Measured::Value(f64::from(p.plan.extent[axis.index()].get())),
            None => missing_node(node),
        },
        Measure::BoxHeight { node } => match by_node.get(node.0.as_str()) {
            Some(p) => match p.clearance {
                Some(c) => Measured::Value(f64::from(c)),
                None => Measured::Unresolved(Diagnostic::error(
                    DW_PLAN_AGREEMENT,
                    "site-plan",
                    format!("/content/identities/{i}/measure"),
                    format!(
                        "this identity measures the height of `{node}`, which is sky-open and \
                         whose size class did not resolve — so the plan states no headroom for \
                         it at all. Fix the class name the layout graph declares (`DW0812` names \
                         it) and the height becomes the class's own minimum."
                    ),
                )),
            },
            None => missing_node(node),
        },
        Measure::DistanceXz { from, to } => {
            let (Some(a), Some(b)) = (by_node.get(from.0.as_str()), by_node.get(to.0.as_str()))
            else {
                return missing_node(if by_node.contains_key(from.0.as_str()) {
                    to
                } else {
                    from
                });
            };
            let (ax, az) = a.centre_xz();
            let (bx, bz) = b.centre_xz();
            Measured::Value(((bx - ax).powi(2) + (bz - az).powi(2)).sqrt())
        }
        Measure::DatumY { datum } => match datums.get(datum.0.as_str()) {
            Some(y) => Measured::Value(*y as f64),
            None => Measured::Unresolved(Diagnostic::error(
                crate::codes::DANGLING_REF,
                "site-plan",
                format!("/content/identities/{i}/measure"),
                format!(
                    "this identity measures `{datum}`, which this plan declares no `datums[]` \
                     entry for."
                ),
            )),
        },
    }
}

/// What a measure is, in a refusal's own words.
fn describe(m: &Measure) -> String {
    match m {
        Measure::RegionExtent { axis } => {
            format!("the region's extent on {}", axis.as_str())
        }
        Measure::BoxExtent { node, axis } => {
            format!("`{node}`'s footprint on {}", axis.as_str())
        }
        Measure::BoxHeight { node } => format!("`{node}`'s headroom"),
        Measure::DistanceXz { from, to } => {
            format!("the horizontal distance from `{from}` to `{to}`")
        }
        Measure::DatumY { datum } => format!("the plane `{datum}`"),
    }
}

impl Axis {
    fn index(self) -> usize {
        match self {
            Axis::X => 0,
            Axis::Y => 1,
            Axis::Z => 2,
        }
    }

    fn as_str(self) -> &'static str {
        match self {
            Axis::X => "x",
            Axis::Y => "y",
            Axis::Z => "z",
        }
    }
}

impl PlanAxis {
    fn index(self) -> usize {
        match self {
            PlanAxis::X => 0,
            PlanAxis::Z => 1,
        }
    }

    fn as_str(self) -> &'static str {
        match self {
            PlanAxis::X => "x",
            PlanAxis::Z => "z",
        }
    }
}

impl VolumeRole {
    /// The keyword a refusal prints.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            VolumeRole::Massif => "massif",
            VolumeRole::Ground => "ground",
            VolumeRole::Clearance => "clearance",
        }
    }
}

/// The plan's one lighting setting, range-checked exactly as an area's is — the
/// same code, because it is the same object being asked the same question.
fn lighting(plan: &SitePlanContent, d: &mut Vec<Diagnostic>) {
    let Some(l) = &plan.lighting else { return };
    if (1..=14).contains(&l.min_light) {
        return;
    }
    d.push(Diagnostic::error(
        crate::codes::LIGHTING_RANGE,
        "site-plan",
        "/content/lighting/min_light",
        format!(
            "`lighting.min_light` = {} is out of range — set it to a value in 1..=14 (7 is the \
             default)",
            l.min_light
        ),
    ));
}

/// The floor a designed opening may never be chosen below: the cells a standing
/// body needs to pass at all.
///
/// Not a check of its own — [`Metrics::self_check`] already holds every standard
/// opening over it, and a second refusal here would be this module re-asking a
/// question the table has already answered about itself. It is re-exported so a
/// reader of `DW0829` can see what the standard set is bounded by.
#[must_use]
pub fn passable_opening_cells() -> (u32, u32) {
    (passable_width_cells(), passable_clearance_cells())
}

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

    /// **The run beside a pierced floor is not the host's extent**, and this is
    /// the arithmetic the whole one-authority repair turns on.
    ///
    /// An eight-by-eight host with a three-wide hole cut through the ceiling
    /// above it: the treads leave along ONE side of the hole, so what they have
    /// is the room on the roomier side plus the hole's own width. Centre the
    /// hole and that is 3 + 3 = 6, not 8 — and the courses have to carry the
    /// body to the pierced plane, which is one below the floor of the place
    /// above it.
    ///
    /// The numbers are read off the geometry by hand rather than recomputed
    /// here, so a change to the rule shows up as a failure rather than as two
    /// arithmetics agreeing.
    #[test]
    fn a_run_beside_a_pierced_floor_is_the_room_on_one_side_plus_the_hole() {
        // Host x 4..11, z 4..11, walk plane y 56; the hole is cut at y 63 and
        // spans x 7..9 — three of the eight cells, three to the low side and
        // two to the high.
        let run = stair_run(56, [4, 11, 4, 11], 1, 63, ([7, 63, 6], [9, 63, 8]))
            .expect("the hole is over this host and the plane is above its floor");
        assert_eq!(run.climb, 7, "56 up to the pierced plane at 63");
        assert_eq!(run.run_axis, 0, "the host is square, so the run takes x");
        assert_eq!(
            run.available, 6,
            "three cells of room on the low side, plus the hole's three"
        );
        assert_eq!(
            run.start, 9,
            "course 0 stands under the far edge of the hole"
        );
        assert_eq!(run.step, -1, "and the run walks back into the room");
    }

    /// The same host, the same hole, and the check and the derivation asking the
    /// same question: seven courses do not fit six cells, so no standard pitch
    /// does either. Measured against the host's extent it would — which is the
    /// green a plan used to reach before building nothing.
    #[test]
    fn no_standard_pitch_fits_a_climb_of_seven_in_six_cells_of_run() {
        let table = Metrics::table();
        let mut reads = Reads::default();
        assert!(gentlest_pitch(&table, &mut reads, 7, 6).is_none());
        assert!(gentlest_pitch(&table, &mut reads, 7, 7).is_some());
        assert_eq!(tightest_pitch(&table, &mut reads, 7), Some(("stair", 7)));
    }

    /// Across a vertical face the run walks the whole footprint and the climb is
    /// the seam's own sill — the body stands at the sill and steps through.
    #[test]
    fn a_run_across_a_vertical_face_is_the_whole_footprint() {
        // Host x 4..11, z 4..11, walk plane y 64; the wall is at x 12 and the
        // opening's low corner is at y 72.
        let run = stair_run(64, [4, 11, 4, 11], 0, 12, ([12, 72, 6], [12, 74, 8]))
            .expect("the wall is beyond the host, so the run walks back from it");
        assert_eq!(run.climb, 8, "64 up to the sill at 72");
        assert_eq!(run.run_axis, 0);
        assert_eq!(run.available, 8, "the host's whole extent on x");
        assert_eq!(run.start, 11, "course 0 stands against the wall");
        assert_eq!(run.step, -1);
    }
}