delvewright-dsl 0.35.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
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
//! serde types for the six stage `content` payloads (spec-0001 v0.2).
//!
//! Every struct is `deny_unknown_fields`. Reserved enum values (objective and
//! effect types a campaign's `dsl_version` is too low for) parse successfully
//! and are checked by validation ([`crate::validate`]).

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

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

use crate::celestial::{CelestialTime, Clock, MoonPhase};
use crate::firework::FireworkExplosion;
use crate::layout::StationKind;

use crate::ids::{
    ActorId, AmbushId, AnchorId, AreaId, AssemblyId, AtmosphereId, BranchId, BranchPointId,
    ClassId, DialogueId, EditBatchId, EndingId, FlagId, LethalVolumeId, LoopId, LootId, NpcId,
    ObjectiveId, PoolId, PrefabId, QuestId, RegionId, RigId, ShopId, ShortcutId, StakeId, StateId,
    TimedGateId, TrapId, TriggerId, WaveId,
};

/// serde default helper: `true` (used by DSL v0.4 `trigger.once`).
fn default_true() -> bool {
    true
}

/// serde `skip_serializing_if` helper: skip a `false` bool (DSL v0.4
/// `objective.stealth`), keeping older campaigns byte-identical.
fn is_false(b: &bool) -> bool {
    !*b
}

// ---------------------------------------------------------------------------
// Stage 1 — world
// ---------------------------------------------------------------------------

/// Stage 1 payload: setting, seed and the areas that make up the delve.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WorldContent {
    /// Player-facing delve title.
    pub title: String,
    /// One-line thematic description.
    pub theme: String,
    /// Short narrative premise.
    pub premise: String,
    /// The single downstream randomness source (ADR-0006).
    pub seed: u64,
    /// Informational pacing target in minutes (v0: not enforced).
    pub target_minutes: u32,
    /// The areas the delve is made of; each binds exactly one of `prefab` /
    /// `prefab_pool`.
    ///
    /// **A campaign declares its placement in exactly one document, so this
    /// list is empty on a site-plan campaign** (`DW0839`): where a
    /// `site-plan.json` is present the plan is the placement authority, its one
    /// place is `area/site`, and declaring `areas[]` as well gives every
    /// question about where something is two answers. Empty is therefore a
    /// legitimate and common value, not a campaign that forgot to place
    /// anything.
    pub areas: Vec<Area>,
    /// Additional author-declared translation languages (BCP-47-style codes, e.g.
    /// `["zh-cn"]`). English (`en`) is implicit, always canonical, and is **never**
    /// listed here (spec-0001 i18n addendum). Absent or empty = English-only. Every
    /// declared language must ship a fully-covering `l10n/<code>.json` sidecar
    /// (`DW0180`/`DW0181`). Stage docs themselves stay pure English.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub languages: Vec<String>,
    /// **The hour this delve is played at** (DSL v0.5, spec-0010; required since
    /// spec-0061). Dimension-global; frozen by environment sealing
    /// (`advance_time false`) so the set state persists. Affects sky attenuation
    /// in the compiler's assembled-light model.
    ///
    /// **Required, and it has no default.** "This delve is played at noon" is a
    /// design decision, and a mechanism that supplies one silently when the
    /// author said nothing is exactly what `CLAUDE.md` forbids a primitive from
    /// encoding — the same ruling spec-0060 §4.1 made for `walk_y`. It is also
    /// the world half of the comparison `DW0890` makes against the approved
    /// design's rows, so every campaign has to state it for the comparison to
    /// have two sides. Emission is unchanged: `time set <kw>` was always
    /// emitted, so a campaign that already declared this builds
    /// byte-identically.
    pub time: WorldTime,
    /// **The weather this delve is played in** (DSL v0.5, spec-0010; required
    /// since spec-0061). Dimension-global; frozen by environment sealing
    /// (`advance_weather false`). Rain and thunder attenuate effective sky
    /// brightness in the assembled-light model.
    ///
    /// Required, with no default, for the reason [`WorldContent::time`] gives.
    /// Emission is unchanged: `weather <kw>` is emitted only for a declared
    /// non-`clear` weather, because `clear` is vanilla's own state.
    pub weather: WorldWeather,
    /// Declared combat difficulty (DSL v0.6). Absent =
    /// the compiler's historical derivation — `easy` when the campaign fields any
    /// wave, `peaceful` when it fields none — which is what keeps every campaign
    /// written before this field byte-identical. Declaring it overrides the
    /// derivation for **both** the shipped `server.properties` and a `/difficulty`
    /// in the sealing baseline, so the declaration also holds when the datapack is
    /// dropped into somebody else's world.
    ///
    /// `peaceful` is rejected (`DW0468`). Raising difficulty changes the damage
    /// players take — easy halves it — so combat arithmetic tuned under the old
    /// implicit `easy` must be redone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub difficulty: Option<WorldDifficulty>,
    /// The scenic horizon: the ground and the sky the map stands in
    /// (spec-0026). Absent or `void` is the void world. `ocean` swaps the world
    /// generator for a deterministic superflat sea (bedrock/stone/water, sea
    /// level y=62) and drops the area datum to y=60 so island pieces meet the
    /// sea at their authored waterline. `valley` rings the map in a generated
    /// mountain annulus — the one base that builds terrain rather than picking
    /// a generator. Either a string shorthand or the object form
    /// `{base, …params}`; see [`Horizon`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub horizon: Option<Horizon>,
    /// **The skies a place can stand under** (spec-0080). Each one is declared
    /// once, here, beside `time`, `weather` and `horizon` — the other
    /// statements about the sky the party stands under — and ships as a
    /// datapack biome (`<ns>:atmosphere/<kebab>`) built from the pinned game's
    /// environment attributes. A place carries one from the first tick
    /// ([`Area::atmosphere`], `boxes[].atmosphere`), and a beat repaints a
    /// volume with another ([`Verb::SetAtmosphere`]). Absent or empty: every
    /// cell stands in the horizon's biome. One no place carries and no beat
    /// paints is refused (`DW0930`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub atmospheres: Vec<Atmosphere>,
    /// Playable-region boundary (DSL v0.6, spec-0013). When present, the compiler
    /// derives a region from the placed geometry and a per-second clock returns any
    /// player who leaves it to the last checkpoint. Required when `horizon` is
    /// `ocean` (an infinite swimmable sea with no return rule is `DW0320`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub boundary: Option<Boundary>,
    /// The closing line on the campaign-completion advancement — the last
    /// player-visible sentence of the delve (DSL v0.6). Player-visible, so it is
    /// l10n-inventoried as `world.outro` and sidecars translate it. Absent = the
    /// finale quest's `goal`, which is already both campaign-derived and
    /// inventoried; the description was previously the hardcoded English
    /// "You left the keep." on *every* delve, whatever its theme or language.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outro: Option<String>,
    /// The party size this delve **requires** (DSL v0.6, spec-0018). Absent = 1: a
    /// party of one is always legal and every pre-0.6 campaign keeps that reading.
    /// A design whose beats genuinely need `n` players — two rooms whose switches
    /// are two arms of one AND-join — declares `min_players: n` (max 4), and the
    /// lobby then refuses to start below it: the class-selection dialog stays shut
    /// and the waiting players get a party-count actionbar instead.
    ///
    /// Progression is party state either way (spec-0018), so this is a *declaration
    /// of intent*, not a mechanism: it makes a mandatory-n design first-class
    /// and turns on the analyzer's n-agent division
    /// proof. Out of `1..=4` is `DW0370`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_players: Option<u8>,
    /// **The vanilla textures this delve replaces** (spec-0084). Each row names
    /// one texture the pinned client ships and the campaign's own image for it,
    /// at `textures/<id>.png` in the campaign directory; the build bakes it into
    /// the resource pack at the vanilla path, so it is drawn wherever the client
    /// draws that texture — every mob of that kind, the moon over every area —
    /// for every player who accepted the pack. Absent or empty = vanilla's look.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub textures: Vec<TextureOverride>,
    /// **Whether a player must accept this delve's resource pack to play it**
    /// (spec-0084 §11). `true` is emitted as `require-resource-pack=true`: a
    /// player who declines is disconnected by the server. Absent or `false` =
    /// the pack is offered and may be declined, in which case the player reads
    /// English and sees vanilla's textures. A host may still set the server's own
    /// flip (itzg's `RESOURCE_PACK_ENFORCE`), which is obeyed as given.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub require_resource_pack: bool,
    /// **A fallen player waits before rejoining** (spec-0077). After clicking
    /// *Respawn*, a player whose party still has somebody in play watches a
    /// teammate as a spectator for `seconds`, and counts as down for the party
    /// wipe while they wait. Absent = no wait, and emission is byte-identical to
    /// a campaign that never had the field. Needs a checkpoint or bonfire to come
    /// back to; `seconds` outside `1..=120`, or no checkpoint, is `DW0925`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub respawn_wait: Option<RespawnWait>,
}

/// One vanilla texture a campaign replaces (spec-0084 §3.1). The row is a
/// judgement and nothing more: width, height and frame count are read off the
/// file and the pinned client's census, and the namespace is fixed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TextureOverride {
    /// A bare kebab token, unique among the campaign's textures (`DW0190`). The
    /// image is `textures/<id>.png` in the campaign directory (`DW0309`), and a
    /// `textures/<id>.png.mcmeta` beside it ships with it as the animation.
    pub id: String,
    /// The texture replaced, as a resource location in the `minecraft`
    /// namespace without `textures/` and without `.png` — the path vanilla's own
    /// models and atlases use (e.g. `minecraft:entity/zombie/drowned`,
    /// `minecraft:environment/celestial/moon/full_moon`). It must name a texture
    /// the pinned client ships (`DW0939`).
    pub replaces: String,
    /// Where the image came from and under what licence (ADR-0013): original
    /// work (`spdx` and `source` both `original`), or an allowlisted third-party
    /// image with its `url`, and its `attribution` for CC BY (`DW0741`).
    pub license: crate::license::LicenseEvidence,
}

/// One declared sky (spec-0080 §3.1): what the party sees and hears while it
/// stands in a cell painted with this atmosphere's biome.
///
/// The biome is vanilla's one channel for sky colour, fog, clouds, sky-light
/// tint, stars, ambient particles, music, ambience, grass, foliage and water
/// tint, and precipitation. In the overworld the day cycle stacks over it: it
/// multiplies the colours (a biome's value survives, darkened at night), takes
/// the maximum of `star_brightness`, and replaces the sun, moon and star
/// angles, the sunrise colour and the moon phase outright — which is why those
/// five ids are refused (`DW0928`) and the sun cannot be moved from a place.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Atmosphere {
    /// `atmosphere/<kebab>`, unique.
    pub id: AtmosphereId,
    /// Environment attributes, keyed by id (`visual/sky_color`; the
    /// `minecraft:` prefix is optional). Which ids a campaign may set, the
    /// shape of each value and the range the pinned codec accepts are vendored
    /// data (`crates/delvec/data/environment-attributes-1.21.11.json`), not
    /// DSL surface: a value outside them is `DW0928`. A float attribute may
    /// also be written in vanilla's modifier form, `{"argument": 0.85,
    /// "modifier": "multiply"}`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, serde_json::Value>,
    /// Grass, foliage, dry-foliage and water tint (`#rrggbb`), each optional.
    /// Absent, vanilla derives grass and foliage from the climate and water is
    /// the void biome's `#3f76e4`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tint: Option<AtmosphereTint>,
    /// What falls here when the world's weather is rain or thunder. The
    /// compiler derives the three vanilla fields that must agree from it
    /// (`has_precipitation`, `temperature`, `downfall`), and it is the fact
    /// `DW0496` reads at a cell: `none` under a rainy world means the undead
    /// burn here.
    pub precipitation: Precipitation,
    /// Overrides the derived `temperature` / `downfall`, for vanilla's own
    /// grass colormap at a named point. Must agree with `precipitation`
    /// (`DW0930`): snow below 0.15, rain at or above it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub climate: Option<Climate>,
}

/// An atmosphere's tint (spec-0080 §3.1.3): the biome `effects` colours the
/// pinned data writes, each `#rrggbb`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AtmosphereTint {
    /// `grass_color`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grass: Option<String>,
    /// `foliage_color`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub foliage: Option<String>,
    /// `dry_foliage_color`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dry_foliage: Option<String>,
    /// `water_color`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub water: Option<String>,
}

/// What an atmosphere's biome lets fall (spec-0080 §3.1.4).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Precipitation {
    /// Nothing falls: `has_precipitation: false`.
    None,
    /// Rain falls: `has_precipitation: true`, temperature 0.5.
    Rain,
    /// Snow falls: `has_precipitation: true`, temperature 0.0.
    Snow,
}

/// A biome's climate pair (spec-0080 §3.1.4).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Climate {
    /// `temperature`: vanilla snows below 0.15.
    pub temperature: f64,
    /// `downfall`.
    pub downfall: f64,
}

/// How long a fallen player waits before rejoining the party (spec-0077 §3).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RespawnWait {
    /// Seconds a fallen player waits after clicking *Respawn*, `1..=120`
    /// (`DW0925`). Counted on the server only while the player is online.
    pub seconds: u16,
    /// Whether a player who comes back with nobody else present also waits.
    /// Default `false`: a party of one never waits.
    #[serde(default)]
    pub alone: bool,
}

/// Who a granted item goes to (DSL v0.6, spec-0018).
///
/// Progression is a fact about the party, so the default for every `give-item` and
/// every class-kit entry is **all**: a quest beat that arms the party arms all of
/// it. `one` is the deliberate exception for a single quest prop (the wine-skin,
/// the stake): exactly one copy enters the party, handed to the player whose action
/// earned it, and the party passes it around physically.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Carrier {
    /// Every party member receives the item (the default).
    #[default]
    All,
    /// Exactly one copy, to the player whose action fired the effect.
    One,
}

/// A declared world time state (DSL v0.5, spec-0010; the celestial spelling
/// spec-0081). The sole difference from vanilla is that the daylight cycle is
/// frozen (`advance_time false`), so a set state persists for the whole delve
/// until a `set-time` effect cuts to another.
///
/// **Two spellings of one clock.** A keyword — `day`, `noon`, `dusk`, `night`,
/// `midnight`, `dawn` — states vanilla's word with vanilla's meaning: the hour,
/// on day 0, so a keyword night shows a full moon. A celestial statement
/// ([`CelestialTime`], `{"moon": "just-risen", "phase": "new-moon"}`) names one
/// body, where it stands and, where the moon shows, its phase, and the engine
/// computes the tick count, day included. Both resolve to one [`Clock`]
/// ([`WorldTime::clock`]); two values are equal when their clocks are.
///
/// Vanilla's `/time set` primitive takes **either** one of four keywords or a raw
/// tick count, and the tick form is the general one. `dusk` and `dawn` are the
/// tick form exposed first-class, per the no-hack rule; a celestial statement is
/// the same primitive reached from a designer's sentence. A keyword on day 0
/// still emits its keyword verbatim ([`WorldTime::token`]), so existing
/// campaigns are byte-identical.
///
/// **There is no `Default`** (spec-0061 §4). A default hour is a design decision
/// wearing a mechanism's clothes, and `#[default] Noon` is what let a delve whose
/// whole approved look was night build, light-check and render under a blue noon
/// sky. Removing the impl is what makes that unwritable rather than merely
/// discouraged: `WorldContent::time` is required, and nothing can supply an hour
/// the author did not.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WorldTime {
    /// Morning daylight (`/time set day`, 1000 ticks).
    Day,
    /// Midday, brightest (`/time set noon`, 6000 ticks).
    Noon,
    /// Sunset onset (`/time set 12000`).
    Dusk,
    /// Night, sun fully down (`/time set night`, 13000 ticks).
    Night,
    /// Deep night, darkest (`/time set midnight`, 18000 ticks).
    Midnight,
    /// First light, just before sunrise (`/time set 23000`).
    Dawn,
    /// A sky stated in a designer's words (spec-0081).
    Celestial(CelestialTime),
}

/// The six keyword spellings of a [`WorldTime`] — the wire and schema form of
/// its keyword half.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum TimeKeyword {
    /// Morning daylight (`/time set day`, 1000 ticks).
    Day,
    /// Midday, brightest (`/time set noon`, 6000 ticks).
    Noon,
    /// Sunset — the sky visibly going orange and the day ending
    /// (`/time set 12000`). Deliberately NOT 13000: that is the instant the sun
    /// has finished setting, which is what the `night` keyword already sets, so
    /// 13000 would make `dusk` a synonym rather than its own beat.
    Dusk,
    /// Night, sun fully down (`/time set night`, 13000 ticks).
    Night,
    /// Deep night, darkest (`/time set midnight`, 18000 ticks).
    Midnight,
    /// First light, just before sunrise (`/time set 23000`). Spelled `dawn`;
    /// `sunrise` is accepted as a synonym on input.
    #[serde(alias = "sunrise")]
    Dawn,
}

impl From<TimeKeyword> for WorldTime {
    fn from(k: TimeKeyword) -> WorldTime {
        match k {
            TimeKeyword::Day => WorldTime::Day,
            TimeKeyword::Noon => WorldTime::Noon,
            TimeKeyword::Dusk => WorldTime::Dusk,
            TimeKeyword::Night => WorldTime::Night,
            TimeKeyword::Midnight => WorldTime::Midnight,
            TimeKeyword::Dawn => WorldTime::Dawn,
        }
    }
}

impl Serialize for WorldTime {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        match self {
            WorldTime::Celestial(c) => c.serialize(s),
            kw => s.serialize_str(kw.keyword_str().expect("a keyword")),
        }
    }
}

impl<'de> Deserialize<'de> for WorldTime {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<WorldTime, D::Error> {
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = WorldTime;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str(
                    "a time: a keyword (day, noon, dusk, night, midnight, dawn) or an object \
                     naming one body, where it stands and its phase \
                     ({\"moon\": \"just-risen\", \"phase\": \"new-moon\"})",
                )
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<WorldTime, E> {
                use serde::de::IntoDeserializer;
                TimeKeyword::deserialize(v.into_deserializer()).map(WorldTime::from)
            }
            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                map: A,
            ) -> Result<WorldTime, A::Error> {
                CelestialTime::deserialize(serde::de::value::MapAccessDeserializer::new(map))
                    .map(WorldTime::Celestial)
            }
        }
        de.deserialize_any(V)
    }
}

impl JsonSchema for WorldTime {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "WorldTime".into()
    }

    fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "description": "A time: a keyword, vanilla's hour on day 0 (a keyword night is a full \
                            moon), or a celestial statement naming one body, where it stands and, \
                            where the moon shows, its phase (spec-0081).",
            "anyOf": [g.subschema_for::<TimeKeyword>(), g.subschema_for::<CelestialTime>()],
        })
    }
}

impl WorldTime {
    /// The keyword table: `(the /time set argument, daytime ticks)`, or `None`
    /// for a celestial statement.
    ///
    /// A state vanilla names keeps its keyword — the argument the compiler has
    /// always emitted — so no shipped campaign's bytes move. A state vanilla does
    /// not name emits the equivalent tick count, which is the same primitive.
    const fn spec(self) -> Option<(&'static str, i64)> {
        match self {
            WorldTime::Day => Some(("day", 1000)),
            WorldTime::Noon => Some(("noon", 6000)),
            WorldTime::Dusk => Some(("12000", 12000)),
            WorldTime::Night => Some(("night", 13000)),
            WorldTime::Midnight => Some(("midnight", 18000)),
            WorldTime::Dawn => Some(("23000", 23000)),
            WorldTime::Celestial(_) => None,
        }
    }

    /// Whether this is one of the six keywords.
    pub fn is_keyword(self) -> bool {
        !matches!(self, WorldTime::Celestial(_))
    }

    /// The celestial statement, if this is one.
    pub fn celestial(self) -> Option<CelestialTime> {
        match self {
            WorldTime::Celestial(c) => Some(c),
            _ => None,
        }
    }

    /// The phase this value states, if any.
    pub fn stated_phase(self) -> Option<MoonPhase> {
        self.celestial().and_then(|c| c.phase)
    }

    /// The `daytime` tick value this state sets (the `time query daytime`
    /// read-back). Keywords: day=1000, noon=6000, dusk=12000 (sunset onset),
    /// night=13000, midnight=18000, dawn=23000; a celestial statement its
    /// position's tick ([`crate::celestial::position_tick`]).
    pub fn daytime_ticks(self) -> i64 {
        match self.spec() {
            Some((_, t)) => t,
            None => self.celestial().expect("celestial").daytime(),
        }
    }

    /// The day this value names as **the world's own time**: a keyword is day 0;
    /// a celestial statement the day its `phase` names, or day 0 where it names
    /// none (the moon is below the horizon, so no phase is stated).
    pub fn world_day(self) -> i64 {
        self.stated_phase().map(MoonPhase::index).unwrap_or(0)
    }

    /// **The clock this value sets**, at a site whose world declares `world`
    /// (spec-0081 §3.3).
    ///
    /// - A celestial statement is its position's tick on the day its `phase`
    ///   names, or the world's day where it states none — a cut changes the
    ///   hour, and the moon keeps the phase the world declared.
    /// - A keyword is its table row on day 0 where it states a sky — the
    ///   world's own time, a design row, a camera ([`TimeSite::Sky`]) — and on
    ///   the world's day where it is a `set-time` cut ([`TimeSite::Cut`]), which
    ///   changes the hour and keeps the moon.
    pub fn clock(self, site: TimeSite, world: WorldTime) -> Clock {
        let daytime = self.daytime_ticks();
        let day = match (self, site) {
            (WorldTime::Celestial(c), _) => c
                .phase
                .map(MoonPhase::index)
                .unwrap_or_else(|| world.world_day()),
            (_, TimeSite::Cut) => world.world_day(),
            (_, TimeSite::Sky) => 0,
        };
        Clock { day, daytime }
    }

    /// The world's own clock: [`WorldTime::clock`] at the world's site.
    pub fn world_clock(self) -> Clock {
        self.clock(TimeSite::Sky, self)
    }

    /// **The vanilla `/time set` argument for `clock`**, the one token every
    /// `time set` the engine emits goes through: a keyword on day 0 emits its
    /// table argument verbatim (`night`, `12000`), so no keyword campaign's bytes
    /// move; any other clock emits the integer `day × 24000 + daytime`.
    pub fn token(self, clock: Clock) -> String {
        match self.spec() {
            Some((tok, t)) if clock.day == 0 && clock.daytime == t => tok.to_string(),
            _ => clock.absolute().to_string(),
        }
    }

    /// The keyword spelling, if this is a keyword.
    fn keyword_str(self) -> Option<&'static str> {
        match self {
            WorldTime::Day => Some("day"),
            WorldTime::Noon => Some("noon"),
            WorldTime::Dusk => Some("dusk"),
            WorldTime::Night => Some("night"),
            WorldTime::Midnight => Some("midnight"),
            WorldTime::Dawn => Some("dawn"),
            WorldTime::Celestial(_) => None,
        }
    }

    /// **What an author writes** — this state's spelling in a document: the
    /// keyword, or the canonical JSON of a celestial statement
    /// (`{"moon":"high","phase":"new-moon"}`).
    ///
    /// Not [`WorldTime::token`], which is the `/time set` argument and is a raw
    /// tick count for every state vanilla does not name. A diagnostic that asks
    /// an author to declare an hour has to say `dusk`, not `12000`.
    pub fn keyword(self) -> String {
        match self {
            WorldTime::Celestial(c) => c.spelling(),
            kw => kw.keyword_str().expect("a keyword").to_string(),
        }
    }
}

/// Where a time value is written, which decides the day a keyword names
/// ([`WorldTime::clock`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TimeSite {
    /// A statement of a sky: the world's own time, a design row, a camera.
    Sky,
    /// A `set-time` effect, quest or dialogue.
    Cut,
}

/// A declared weather state (DSL v0.5, spec-0010). Values are the vanilla
/// `/weather` keywords; frozen (`advance_weather false`), so a set state persists.
///
/// **No `Default`**, for the reason [`WorldTime`] gives.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum WorldWeather {
    /// Clear sky (`/weather clear`). Vanilla's own state, so emission writes no
    /// `/weather` command for it.
    Clear,
    /// Rain (`/weather rain`).
    Rain,
    /// Thunderstorm (`/weather thunder`).
    Thunder,
}

impl WorldWeather {
    /// The word an author writes — identical to [`WorldWeather::token`] for
    /// every state, and stated separately so a message that names a document's
    /// vocabulary reads the document's vocabulary. See [`WorldTime::keyword`],
    /// where the two differ.
    pub fn keyword(self) -> &'static str {
        self.token()
    }

    /// The vanilla `/weather` keyword.
    pub fn token(self) -> &'static str {
        match self {
            WorldWeather::Clear => "clear",
            WorldWeather::Rain => "rain",
            WorldWeather::Thunder => "thunder",
        }
    }
}

/// The declared combat difficulty of the delve (DSL v0.6). Values are the
/// vanilla `/difficulty` keywords.
///
/// Difficulty is the single largest lever on how hard a delve *feels*, so the
/// campaign declares it rather than letting the compiler choose. Easy **halves
/// incoming player damage** — `min(dmg / 2 + 1, dmg)` — so a campaign tuned
/// under `easy` is tuned against a halved world. A campaign that
/// raises this must redo that arithmetic.
///
/// [`WorldDifficulty::Peaceful`] parses but is **rejected** by validation
/// (`DW0468`): peaceful makes the engine discard every hostile-category mob on
/// the tick it is ticked, summoned or not, so every wave, actor and ambush in the
/// campaign would silently vanish. It is a variant only so the compiler can say
/// that in a diagnostic instead of a serde "unknown variant" parse error.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum WorldDifficulty {
    /// `/difficulty easy` — the compiler's historical choice for a wave
    /// campaign, and the default reading of an absent field. Incoming player
    /// damage is halved (`min(dmg / 2 + 1, dmg)`).
    #[default]
    Easy,
    /// `/difficulty normal` — vanilla-baseline damage. The souls-style baseline.
    Normal,
    /// `/difficulty hard` — amplified damage, and zombies reinforce.
    Hard,
    /// `/difficulty peaceful` — **always rejected** (`DW0468`). Present only so
    /// the rejection can be a diagnostic with a rationale.
    Peaceful,
}

impl WorldDifficulty {
    /// The vanilla `/difficulty` keyword.
    pub fn token(self) -> &'static str {
        match self {
            WorldDifficulty::Peaceful => "peaceful",
            WorldDifficulty::Easy => "easy",
            WorldDifficulty::Normal => "normal",
            WorldDifficulty::Hard => "hard",
        }
    }

    /// The vanilla `Difficulty#getId()` ordinal, which is also what the bare
    /// `/difficulty` query command returns — the only vanilla read-back path for
    /// the setting, and so what the generated PackTest asserts on.
    pub fn id(self) -> i32 {
        match self {
            WorldDifficulty::Peaceful => 0,
            WorldDifficulty::Easy => 1,
            WorldDifficulty::Normal => 2,
            WorldDifficulty::Hard => 3,
        }
    }
}

/// A scenic horizon (spec-0026). A horizon is a **composition of orthogonal
/// axes**, not an enum of monoliths: a **base** — what surrounds the map — and
/// that base's params. The field accepts a plain string shorthand
/// ([`HorizonName`]) or the object form [`HorizonSpec`] `{base, …params}`.
///
/// Consumers never match this wire enum. [`Horizon::resolved`] desugars both
/// forms into one [`ResolvedHorizon`] with the pinned defaults applied, and
/// [`horizon_base`] answers the one question most callers have.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum Horizon {
    /// A bare base name — `"ocean"` is exactly `{base: "ocean"}`. The two
    /// bases that predate the horizon library were spelled this way and still
    /// are, byte-identically; a base added since is spellable this way too,
    /// because a base with every param at its default has nothing else to say.
    Name(HorizonBase),
    /// The object form `{base, …params}`.
    Spec(HorizonSpec),
}

/// What surrounds the map.
///
/// **One enumeration of bases, reachable two ways.** The shorthand
/// `horizon: "ocean"` and the object form `horizon: {base: "ocean"}` name this
/// same variant, which is what stops a base from existing in one spelling and
/// not the other. A separate list of "names" beside this one would be two
/// enumerations of the same thing, and the second base added would land in
/// whichever of them its author was looking at.
///
/// What is deliberately NOT here is a name that stands for a base plus a set of
/// params. Such a name reads as a thing, and the whole claim of this design is
/// that it is not one — it is a base with params set. A spelling that hides
/// which params it sets makes that claim unverifiable by looking at the
/// document, and buys a few saved keystrokes for it. Each base carries its own params on
/// [`HorizonSpec`], and a param foreign to the declared base is refused rather
/// than ignored.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum HorizonBase {
    /// Void superflat; no surround. The default.
    #[default]
    Void,
    /// Pinned water superflat, sea level 62; no surround.
    Ocean,
    /// A mountain annulus around a flat gap floor, with void ambient below the
    /// tile skirt. The one base that generates terrain.
    Valley,
}

impl HorizonBase {
    /// The kebab wire name.
    pub fn token(self) -> &'static str {
        match self {
            HorizonBase::Void => "void",
            HorizonBase::Ocean => "ocean",
            HorizonBase::Valley => "valley",
        }
    }

    /// Whether this base generates a surround — compiler-built terrain outside
    /// the map's own extent. `void` and `ocean` are pure ambient and build
    /// nothing.
    pub fn has_surround(self) -> bool {
        matches!(self, HorizonBase::Valley)
    }
}

/// The `horizon` object form: a `base` plus that base's params, all optional
/// with pinned defaults ([`horizon_defaults`]).
///
/// The `valley` surround generator carries a second flora and a second surface
/// palette (a cherry grove over `minecraft:cherry_grove`) and **this struct
/// does not expose them.** Every engine surface owes a gallery element in the
/// change that lands it; the element a second flora needs is a valley overlay,
/// and one is writable now that a one-area campaign's single prefab states an
/// extent ([`crate::placement::Extent`], `DW0855`) — the reason recorded here
/// was that no two-file overlay could ring a map, and that reason is spent.
/// What is left is that nothing has written the element, and a surface lands
/// with its element or it does not land. The shape is flat rather than
/// per-base tagged, and a param foreign to the declared base is refused
/// (`DW0853`) — so an `ocean` cannot quietly carry a `rim_height` that nothing
/// reads.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct HorizonSpec {
    /// The base — what surrounds the map.
    pub base: HorizonBase,
    /// `valley`: the surround's total footprint as a multiple of the map's, on
    /// each axis (`2.0..=3.0`, default 2.5).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ratio: Option<f64>,
    /// `valley`: crest height of the rim over the gap floor (`16..=128`,
    /// default 48).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rim_height: Option<i32>,
}

/// Pinned horizon param defaults. One table, so the doc comments, the resolver
/// and the diagnostics cannot drift.
pub mod horizon_defaults {
    /// `valley.ratio`.
    pub const RATIO: f64 = 2.5;
    /// `valley.ratio` lower bound — below 2.0 the annulus has no room for a
    /// gap floor and a slope run both.
    pub const RATIO_MIN: f64 = 2.0;
    /// `valley.ratio` upper bound — above 3.0 the surround is mostly terrain a
    /// body never reaches, at a cost that is all shipped bytes.
    pub const RATIO_MAX: f64 = 3.0;
    /// `valley.rim_height`.
    pub const RIM_HEIGHT: i32 = 48;
    /// `valley.rim_height` lower bound — a rim under 16 does not close the
    /// horizon from a body standing on the gap floor.
    pub const RIM_HEIGHT_MIN: i32 = 16;
    /// `valley.rim_height` upper bound — the build range is 384 blocks tall and
    /// the surround has to fit under whatever the map puts above it.
    pub const RIM_HEIGHT_MAX: i32 = 128;
}

/// A horizon with both wire forms desugared and every default applied — the
/// only view downstream code reads.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ResolvedHorizon {
    /// The base.
    pub base: HorizonBase,
    /// `valley.ratio`.
    pub ratio: f64,
    /// `valley.rim_height`.
    pub rim_height: i32,
}

impl Default for ResolvedHorizon {
    fn default() -> Self {
        ResolvedHorizon {
            base: HorizonBase::Void,
            ratio: horizon_defaults::RATIO,
            rim_height: horizon_defaults::RIM_HEIGHT,
        }
    }
}

impl ResolvedHorizon {
    /// The resolved horizon of `base` with every param at its pinned default.
    pub fn of_base(base: HorizonBase) -> Self {
        ResolvedHorizon {
            base,
            ..Default::default()
        }
    }
}

impl Horizon {
    /// Desugar either wire form to the one resolved view, defaults applied.
    pub fn resolved(&self) -> ResolvedHorizon {
        match self {
            Horizon::Name(base) => ResolvedHorizon::of_base(*base),
            Horizon::Spec(s) => ResolvedHorizon {
                base: s.base,
                ratio: s.ratio.unwrap_or(horizon_defaults::RATIO),
                rim_height: s.rim_height.unwrap_or(horizon_defaults::RIM_HEIGHT),
            },
        }
    }

    /// The resolved base.
    pub fn base(&self) -> HorizonBase {
        self.resolved().base
    }

    /// True when this declaration needs the horizon-library surface: the object
    /// form, or a bare name for a base that did not exist before it.
    ///
    /// The two bases that predate the library stay writable as bare names at
    /// the version that introduced them, and their emission does not move —
    /// which is what makes this a widening rather than a break. What is fenced
    /// is saying something the old surface had no spelling for.
    pub fn needs_horizon_library(&self) -> bool {
        match self {
            Horizon::Spec(_) => true,
            Horizon::Name(base) => match base {
                HorizonBase::Void | HorizonBase::Ocean => false,
                HorizonBase::Valley => true,
            },
        }
    }
}

/// The resolved base of an optional stage-1 `horizon` field — `Void` when
/// absent. The one helper every downstream consumer (placement, the ambient
/// model, emission) goes through, so that a new base cannot be forgotten at one
/// of them.
pub fn horizon_base(horizon: &Option<Horizon>) -> HorizonBase {
    horizon.as_ref().map(|h| h.base()).unwrap_or_default()
}

/// The resolved view of an optional stage-1 `horizon` field, with defaults
/// applied for an absent one.
pub fn resolved_horizon(horizon: &Option<Horizon>) -> ResolvedHorizon {
    horizon.as_ref().map(|h| h.resolved()).unwrap_or_default()
}

/// The default boundary `margin` (blocks of horizontal breathing room added
/// around the derived region). Separate function so `serde(default = …)` and the
/// documented literal cannot drift.
fn default_margin() -> u16 {
    16
}

/// A playable-region boundary declaration (DSL v0.6, spec-0013). The region
/// itself is **derived** by the compiler (union of the final placed-piece AABBs,
/// inflated horizontally by `margin`, unbounded upward, floored at the lowest
/// placed block − 8) — never authored — so "every anchor is inside" is structural.
/// Enforcement is a per-second clock that returns any player outside the region to
/// the last checkpoint (`dw:cp`) with an actionbar message and a soft sound; no
/// damage, no items lost.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Boundary {
    /// Horizontal breathing room in blocks added around the derived region on
    /// every side (default 16). Range-checked to `0..=64` (`DW0321`).
    #[serde(default = "default_margin")]
    pub margin: u16,
    /// Actionbar message shown on return. Absent = the compiler's English default.
    /// When set, it is inventoried under l10n key `world.boundary.message` and is
    /// translated like every other player-facing string.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// A supplemental-lighting fixture the relight pass may place (DSL v0.5,
/// spec-0010 fixture registry v1). The theme choice stays in the DSL layer; the
/// compiler owns the placement rule and block-light emission.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Fixture {
    /// Floor torch (block light 14); `wall_torch` on a wall face as fallback.
    Torch,
    /// Ceiling-hung lantern (block light 15); floor-sitting as fallback.
    Lantern,
    /// Floor campfire (block light 15); never on or adjacent to a required path
    /// cell (it is a damage source).
    Campfire,
    /// Embedded shroomlight (block light 15); replaces a solid wall/ceiling block.
    Shroomlight,
}

impl Fixture {
    /// The kebab id (`torch` / `lantern` / `campfire` / `shroomlight`).
    pub fn token(self) -> &'static str {
        match self {
            Fixture::Torch => "torch",
            Fixture::Lantern => "lantern",
            Fixture::Campfire => "campfire",
            Fixture::Shroomlight => "shroomlight",
        }
    }
}

/// A per-area supplemental-lighting declaration (DSL v0.5, spec-0010). Its
/// presence puts the area on the relight path: the compiler guarantees every
/// reachable walkable cell reaches `min_light` by placing `fixture`s, or fails
/// with `DW0211` if it cannot.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AreaLighting {
    /// The fixture the relight pass places.
    pub fixture: Fixture,
    /// The minimum block+sky light guaranteed on reachable walkable cells
    /// (1..=14, default 7). Range-checked (`DW0196`).
    #[serde(default = "default_min_light")]
    pub min_light: u8,
}

/// Default `min_light` for an [`AreaLighting`] declaration (spec-0010).
fn default_min_light() -> u8 {
    7
}

/// A per-area **darkness mitigation** declaration (DSL v0.6).
///
/// The first-class answer to "this area is meant to be dark, and the players are
/// equipped for it". Declaring it is what makes the compiler *emit* the mitigation
/// (a clocked `effect give … night_vision` scoped to the area's placed bounds) and
/// what satisfies the `DW0210` darkness gate — one declaration, one mechanism, no
/// gap between the check and the feature.
///
/// It replaces the pre-0.6 heuristic that read a class kit item's display *name*
/// for `night vision`: that accepted a renamed water bottle, so the gate passed
/// while nothing in the world granted night vision (owner, island QA).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum AreaMitigation {
    /// Every player inside the area's placed bounds is kept under
    /// `minecraft:night_vision` by a compiler-emitted 1 s clock.
    NightVision,
}

/// One area of the world, bound to a single prefab or a jigsaw prefab pool.
///
/// An area binds **exactly one of** `prefab` (single piece) or `prefab_pool`
/// (+ `pieces`, jigsaw multi-piece assembly, ADR-0004). The exclusivity and
/// pool-existence rules are enforced by validation (`DW0160` / `DW0161`); the
/// full jigsaw layout semantics are spec-0002's.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Area {
    /// Unique area id.
    pub id: AreaId,
    /// Player-facing area name.
    pub name: String,
    /// The single prefab bound to this area (mutually exclusive with
    /// `prefab_pool`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefab: Option<PrefabId>,
    /// The jigsaw prefab pool bound to this area (mutually exclusive with
    /// `prefab`); requires `pieces`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefab_pool: Option<PoolId>,
    /// Jigsaw piece-count bounds (only with `prefab_pool`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pieces: Option<Pieces>,
    /// Optional supplemental-lighting declaration (DSL v0.5, spec-0010). When
    /// present, the compiler's relight pass guarantees `min_light` on every
    /// reachable walkable cell of this area by placing the declared fixture, or
    /// fails with `DW0211`. Absent = no relight (the area is judged as-assembled,
    /// with `DW0210` if a reachable walkable cell is dark and unmitigated).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lighting: Option<AreaLighting>,
    /// Optional darkness-mitigation declaration (DSL v0.6). `night-vision` makes
    /// the compiler emit a clocked `effect give` over this area's placed bounds and
    /// is the (only) declaration that satisfies `DW0210` without `lighting`.
    /// Independent of `lighting`: an area may declare both (fixtures *and* the
    /// effect), either, or neither.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mitigation: Option<AreaMitigation>,
    /// **The sky this place stands under from the first tick** (spec-0080
    /// §3.2): one of `world.atmospheres[]`, painted at world setup over the
    /// area's placed bounds grown up and down as far as the client's biome
    /// blend reads. The volume is the placement's, never typed.
    /// Absent: the horizon's biome.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub atmosphere: Option<AtmosphereId>,
}

/// Inclusive piece-count bounds for a jigsaw `prefab_pool` area.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Pieces {
    /// Minimum number of pieces to assemble.
    pub min: u32,
    /// Maximum number of pieces to assemble.
    pub max: u32,
}

// ---------------------------------------------------------------------------
// Body traversal — the declaration every body that moves carries (DSL v0.11,
// spec-0034)
// ---------------------------------------------------------------------------

/// How a body gets around.
///
/// The compiler DERIVES this from the entity id for every body (spiders climb,
/// ghasts fly, `#minecraft:aquatic` swims, and everything else — including every
/// id the table has never heard of — is [`Locomotion::Ground`], the checked
/// class). [`BodyTraversal`] is the author's side of the same vocabulary: one
/// enum, so a declaration and a derivation can never mean different things.
///
/// The vocabulary lives in this crate rather than in the compiler because it is
/// now DSL surface; the compiler re-exports it and owns the derivation table
/// (`compiler::traversal`).
#[derive(
    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "kebab-case")]
pub enum Locomotion {
    /// Walks, steps and jumps — the default and the CHECKED class.
    Ground,
    /// Climbs sheer vertical surfaces (vanilla's `Spider` class).
    Climber,
    /// Leaves the ground under its own power.
    Flier,
    /// A member of vanilla's `#minecraft:aquatic` tag. A ledger classification
    /// that exempts nothing, which is why it may not be **declared**
    /// (`DW0455`) — see [`BodyTraversal`].
    Aquatic,
}

impl Locomotion {
    /// The stable kebab token this class is written and reported under.
    pub fn token(self) -> &'static str {
        match self {
            Locomotion::Ground => "ground",
            Locomotion::Climber => "climber",
            Locomotion::Flier => "flier",
            Locomotion::Aquatic => "aquatic",
        }
    }

    /// Every class, in ledger order — so a report can never silently drop a row
    /// when a class is added.
    pub const ALL: [Locomotion; 4] = [
        Locomotion::Ground,
        Locomotion::Climber,
        Locomotion::Flier,
        Locomotion::Aquatic,
    ];
}

/// What a body can do when it moves, **declared by the author** (DSL v0.11,
/// spec-0034).
///
/// Carried by every object class in the DSL that has a body and a position and
/// is walked by a compiler-emitted route — the stage-2 [`Npc`] and the stage-5
/// [`Actor`]. It is deliberately one shared type on both rather than a field
/// per consumer: traversal is a property of a body that moves, not of the verb
/// that first needed it (CLAUDE.md), and a second bespoke field would be the
/// defect rather than the fix.
///
/// **A declaration is a claim the build holds you to, never an opt-out.** The
/// compiler compares the verdicts this body earns under the declared class
/// against the ones it earns under its species' derived class; a declaration
/// that changes no verdict is inert and is `DW0454`. So declaring `climber` on
/// a sheep is only accepted where that sheep's route really does go over a
/// barrier line — the exception is authored and proven, instead of happening by
/// accident and merely rendering.
///
/// **What is deliberately NOT here: `opens_gates`.** Passing a closed fence gate
/// is a right-click, a scripted walk is a compiler-emitted `tp` polyline whose
/// puppet performs no interaction at all, and no runtime verb changes a fence
/// gate's block state. Declaring it would not make it true, so the error tier
/// (`DW0452`) has no authorable exemption and a declaration can never reach it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BodyTraversal {
    /// How this body gets around, overriding what its entity id implies.
    pub locomotion: Locomotion,
}

/// One object class that has a **body the compiler stages**: a declared
/// position, a declared species, and a compiler-emitted route.
///
/// A sum type rather than a flattened tuple, so **adding a body class is a
/// compile error at every consumer** until each one says what it does with it.
/// The alternative — each rule walking the classes it happens to remember — is
/// the defect class CLAUDE.md names: a hand-rolled walk that
/// enumerated three of five effect roots.
///
/// **Keyed to the object, not to the verb that first needed it.** This type was
/// introduced for [`BodyTraversal`] and read, for a while, as "one consumer of
/// `BodyTraversal`" — which is why its only enumeration
/// ([`body_traversal_sites`]) was filtered to bodies declaring a traversal, and
/// why the second property a body carries, its [`NpcSkin`], had no enumeration
/// at all: the bake walked the stage-2 npc list by hand, and an actor's skin was
/// emitted into the summon, never baked into the pack, and never refused.
/// A body's properties belong to the body. [`body_sites`] is the unfiltered
/// walk; a per-property enumeration is a *filter* over it, never a second walk.
///
/// Deliberately NOT a member: [`WaveMob`]. A wave mob has a body and a position,
/// but it is driven by **native vanilla AI**, never by a compiler-emitted route,
/// so the compiler makes no claim about the moves it makes and a locomotion
/// declaration on it could change no verdict. It declares no `skin` either — the
/// exclusion holds for both properties, and the schema says so
/// (`crates/dsl/tests/body_skin_sites.rs`). It becomes a member the day the lane
/// proof reasons about how its bodies move — and it joins here, through this
/// same type, rather than through a field of its own.
#[derive(Clone, Copy, Debug)]
pub enum BodyRef<'a> {
    /// A stage-2 NPC, walked by `move-npc`.
    Npc(&'a Npc),
    /// A stage-5 scripted actor, walked by `move-actor`.
    Actor(&'a Actor),
}

impl<'a> BodyRef<'a> {
    /// The declaring stage's wire name (`npcs` / `quests`) — also the stage
    /// whose `dsl_version` fences this body's declaration.
    pub fn stage(self) -> &'static str {
        match self {
            BodyRef::Npc(_) => "npcs",
            BodyRef::Actor(_) => "quests",
        }
    }

    /// The body's declared id.
    pub fn id(self) -> &'a str {
        match self {
            BodyRef::Npc(n) => n.id.as_str(),
            BodyRef::Actor(a) => a.id.as_str(),
        }
    }

    /// The entity id written on the body. **Not necessarily the body that
    /// ships**: a `skin` re-dresses it as a `minecraft:mannequin` — see
    /// [`Self::worn_entity`].
    pub fn declared_entity(self) -> &'a str {
        match self {
            BodyRef::Npc(n) => n.base_entity.as_str(),
            BodyRef::Actor(a) => a.entity.as_str(),
        }
    }

    /// **The entity id the body ships as**: `minecraft:mannequin` when it
    /// declares a `skin`, else the declared entity. The one authority for that
    /// rule — the compiler's geometric proofs (`nav::npc_body_entity`,
    /// `nav::actor_body_entity`) and the equipment fit rule (`DW0898`) all read
    /// it.
    pub fn worn_entity(self) -> &'a str {
        match self.skin() {
            Some(_) => "minecraft:mannequin",
            None => self.declared_entity(),
        }
    }

    /// **The mark this body is placed on** — the anchor and offset the engine
    /// summons it at, for every class alike (spec-0066).
    ///
    /// A body's placement is a property of the body, not of the stage list that
    /// happens to declare it: a mark is a cell, and a cell holds one body. The
    /// rule that reads this ([`crate::compiler`]'s `DW0896`, via
    /// [`body_sites`]) therefore quantifies over npcs and actors in one pass
    /// rather than over `actors[]`, which is where the seven-men-one-anchor
    /// muster came from.
    pub fn mark(self) -> Mark {
        let (anchor, offset) = match self {
            BodyRef::Npc(n) => (&n.anchor, n.offset),
            BodyRef::Actor(a) => (&a.anchor, a.offset),
        };
        Mark {
            anchor: anchor.clone(),
            offset,
        }
    }

    /// The area whose anchor table resolves [`Self::mark`]'s anchor first, when this
    /// class declares one.
    ///
    /// A stage-2 npc names its area and is resolved inside it; a stage-5 actor
    /// names none and is resolved across every placed piece, exactly as an
    /// `open-gate` / `move-actor` destination is. Stated here so the resolution
    /// rule is one rule over both classes and not a per-call-site habit.
    pub fn area(self) -> Option<&'a AreaId> {
        match self {
            BodyRef::Npc(n) => Some(&n.area),
            BodyRef::Actor(_) => None,
        }
    }

    /// Whether this body stands on its mark from **world init**, with no effect
    /// having to fire.
    ///
    /// A stage-2 npc does unless it is `deferred`; a stage-5 actor never does —
    /// a puppet exists only from the `spawn-actor` that summons it, which is why
    /// an actor no `spawn-actor` names never exists at all.
    pub fn at_world_init(self) -> bool {
        match self {
            BodyRef::Npc(n) => !n.deferred,
            BodyRef::Actor(_) => false,
        }
    }

    /// Whether a **player** can end this body's life.
    ///
    /// An npc body is emitted `Invulnerable:1b` unconditionally, so nothing a
    /// player does removes it; an actor's puppet is `Invulnerable` unless it
    /// declares [`Actor::vulnerable`]. A body a player can kill is one whose
    /// lifetime the compiler cannot bound, which is the whole of what this
    /// answers.
    pub fn killable_by_players(self) -> bool {
        match self {
            BodyRef::Npc(_) => false,
            BodyRef::Actor(a) => a.vulnerable,
        }
    }

    /// This body's traversal declaration, if it carries one.
    pub fn traversal(self) -> Option<&'a BodyTraversal> {
        match self {
            BodyRef::Npc(n) => n.traversal.as_ref(),
            BodyRef::Actor(a) => a.traversal.as_ref(),
        }
    }

    /// This body's skin declaration, if it carries one.
    ///
    /// A skinned body of **either** class ships as a `minecraft:mannequin`
    /// whose `profile.texture` resolves to `delvewright:npc/<campaign_id>/<texture_id>`,
    /// so either one owes the same `skins/<texture_id>.png` under the same refusal
    /// (`DW0309`). Answering it here is what stops the bake from being a
    /// property of one class.
    pub fn skin(self) -> Option<&'a NpcSkin> {
        match self {
            BodyRef::Npc(n) => n.skin.as_ref(),
            BodyRef::Actor(a) => a.skin.as_ref(),
        }
    }

    /// This class's name in the JSON Schema export (`delvec schema --stage all`).
    ///
    /// The join between the closed Rust set and the schema, which is the only
    /// authority on *which object classes declare what*. `body_skin_sites.rs`
    /// compares the two.
    pub fn class(self) -> &'static str {
        match self {
            BodyRef::Npc(_) => "Npc",
            BodyRef::Actor(_) => "Actor",
        }
    }

    /// Every body class, by schema name. The closed set, stated once.
    pub const ALL_CLASSES: [&'static str; 2] = ["Npc", "Actor"];
}

/// A staged body declaration, with the JSON pointer at the declaration itself.
///
/// The pointer is at the OBJECT (`/content/npcs/3`), not at any one of its
/// fields: a per-property site appends its own field name. A pointer built per
/// property is how two walks of one population start disagreeing about where a
/// thing was declared.
#[derive(Clone, Debug)]
pub struct BodySite<'a> {
    /// Which object class declared it, and the object itself.
    pub body: BodyRef<'a>,
    /// JSON pointer at the declaration, for a diagnostic path.
    pub path: String,
}

/// **Every** body the campaign declares, in stage order: stage-2 npcs in
/// declaration order, then stage-5 actors in declaration order.
///
/// The one walk of the campaign's bodies. A rule about a property a body carries
/// is a *filter* over this ([`body_traversal_sites`], [`body_skin_sites`]) — never
/// a second traversal, and never a hand-written loop over one stage's list,
/// which is exactly how an actor's skin came to be emitted but never baked.
pub fn body_sites(c: &crate::envelope::Campaign) -> Vec<BodySite<'_>> {
    let mut out: Vec<BodySite<'_>> = Vec::new();
    for (i, n) in c.npcs.content.npcs.iter().enumerate() {
        out.push(BodySite {
            body: BodyRef::Npc(n),
            path: format!("/content/npcs/{i}"),
        });
    }
    for (i, a) in c.quests.content.actors.iter().enumerate() {
        out.push(BodySite {
            body: BodyRef::Actor(a),
            path: format!("/content/actors/{i}"),
        });
    }
    out
}

/// A body that carries a [`BodyTraversal`] declaration, with the JSON pointer at
/// it.
#[derive(Clone, Debug)]
pub struct BodyTraversalSite<'a> {
    /// Which object class declared it, and the object itself.
    pub body: BodyRef<'a>,
    /// JSON pointer at the `traversal` field, for a diagnostic path.
    pub path: String,
    /// The declaration.
    pub traversal: &'a BodyTraversal,
}

/// Every body in the campaign that DECLARES a traversal, in stage order.
///
/// The one enumeration of the declaration's consumers, shared by the DSL's value
/// check (`DW0455`) and by the compiler's proof (`DW0454`), so "which object
/// classes carry this" is answered in exactly one place.
pub fn body_traversal_sites(c: &crate::envelope::Campaign) -> Vec<BodyTraversalSite<'_>> {
    body_sites(c)
        .into_iter()
        .filter_map(|s| {
            s.body.traversal().map(|t| BodyTraversalSite {
                body: s.body,
                path: format!("{}/traversal", s.path),
                traversal: t,
            })
        })
        .collect()
}

/// A body that carries an [`NpcSkin`] declaration, with the JSON pointer at it.
#[derive(Clone, Debug)]
pub struct BodySkinSite<'a> {
    /// Which object class declared it, and the object itself.
    pub body: BodyRef<'a>,
    /// JSON pointer at the `skin` field, for a diagnostic path.
    pub path: String,
    /// The declaration.
    pub skin: &'a NpcSkin,
}

/// Every body in the campaign that DECLARES a skin, in stage order.
///
/// The one enumeration of what the resource-pack bake must serve and what
/// `DW0309` must refuse, for every class alike — a skinned npc and a skinned
/// actor are the same fact about two bodies.
///
/// **Declarations, not textures.** Two bodies may name one `texture_id` (an npc
/// and the puppet that plays it), and the caller decides what that means; the
/// bake reads each file once.
pub fn body_skin_sites(c: &crate::envelope::Campaign) -> Vec<BodySkinSite<'_>> {
    body_sites(c)
        .into_iter()
        .filter_map(|s| {
            s.body.skin().map(|k| BodySkinSite {
                body: s.body,
                path: format!("{}/skin", s.path),
                skin: k,
            })
        })
        .collect()
}

/// The **mutable mirror** of [`body_skin_sites`]: every skin declaration in the
/// campaign, in the identical order, exposed mutably so one pass can rewrite what
/// every emitter will read ([`crate::l10n::namespace_skin_textures`]).
///
/// It carries no [`BodyRef`] and no pointer, because a rewrite needs neither and a
/// borrow of the whole body would forbid the field it is there to change. What it
/// does owe is the **same population**: a body class that declares a skin and is
/// missing here would keep an un-namespaced texture and collide with every other
/// delve, silently. `body_skin_sites_mut_is_the_same_walk`
/// (`crates/dsl/tests/body_skin_sites.rs`) pins that over a campaign carrying one
/// body of every class in [`BodyRef::ALL_CLASSES`] — the closed set the schema
/// export is compared against in the same file, so a new body class turns that
/// coverage red and both walks are visited together.
pub fn body_skins_mut(c: &mut crate::envelope::Campaign) -> Vec<&mut NpcSkin> {
    let mut out: Vec<&mut NpcSkin> = Vec::new();
    out.extend(
        c.npcs
            .content
            .npcs
            .iter_mut()
            .filter_map(|n| n.skin.as_mut()),
    );
    out.extend(
        c.quests
            .content
            .actors
            .iter_mut()
            .filter_map(|a| a.skin.as_mut()),
    );
    out
}

// ---------------------------------------------------------------------------
// Stage 2 — npcs
// ---------------------------------------------------------------------------

/// Stage 2 payload: the campaign's NPCs (casting sheets).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NpcsContent {
    /// All NPCs in the campaign.
    pub npcs: Vec<Npc>,
}

/// A stationary NPC bound to an area anchor (a casting sheet, spec-0001 v0.2).
///
/// Stage 2 carries **no dialogue** — the structured [`Persona`] is the character
/// contract the stage-6 `dialogue` tree must honor.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Npc {
    /// Unique NPC id.
    pub id: NpcId,
    /// Player-facing name.
    pub name: String,
    /// NPC role.
    pub role: Role,
    /// The area this NPC stands in (stage-1 ref).
    pub area: AreaId,
    /// The prefab anchor this NPC stands on.
    pub anchor: AnchorId,
    /// Integer `[x, y, z]` block offset from `anchor` (spec-0066, default
    /// `[0, 0, 0]`): the NPC stands at the [`Mark`] the two fields spell.
    #[serde(default, skip_serializing_if = "is_zero3")]
    pub offset: [i32; 3],
    /// The vanilla entity to re-dress, e.g. `minecraft:villager`.
    pub base_entity: String,
    /// The structured persona (character contract for stage 6).
    pub persona: Persona,
    /// Optional player-model skin (DSL v0.4, spec-0008 §6 / spec-0009). When set,
    /// the compiler emits a `minecraft:mannequin` body carrying this skin profile
    /// instead of re-dressing `base_entity`; the interaction hitbox is unchanged.
    /// Non-skinned NPCs are byte-identical to v0.3.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skin: Option<NpcSkin>,
    /// Deferred entrance (DSL v0.6): when `true` the NPC is **not** summoned at
    /// world init — its body and interaction hitbox only appear when a
    /// [`Verb::SpawnNpc`] fires, at this same `anchor`. The dual of
    /// `despawn-npc`: a character with a scripted entrance must not stand at its
    /// mark as a statue from minute one. A deferred NPC that no `spawn-npc` ever
    /// spawns is unreachable content (`DW0197`). Default `false` = summoned at
    /// init, byte-identical to pre-0.6.
    #[serde(default, skip_serializing_if = "is_false")]
    pub deferred: bool,
    /// What this body can do when it moves (DSL v0.11, spec-0034). Absent = the
    /// class the compiler derives from `base_entity` (or from `minecraft:mannequin`
    /// when `skin` is set — the body that actually ships). See [`BodyTraversal`]:
    /// the declaration must change a verdict or it is `DW0454`, and it can never
    /// reach the error tier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub traversal: Option<BodyTraversal>,
}

/// A mannequin NPC's player-model skin (DSL v0.4). The skin PNG is sourced from
/// the campaign dir's `skins/<texture_id>.png` and ships in the per-delve resource
/// pack at `assets/delvewright/textures/npc/<campaign_id>/<texture_id>.png`, which
/// is what the mannequin's `profile.texture` resolves to. The delve's own
/// directory is stamped on at emission ([`crate::l10n::namespace_skin_textures`])
/// — a client merges every applied pack's textures into ONE space, so two delves
/// that both cast a `keeper` would otherwise wear each other's faces. Nothing a
/// creator writes or names on disk carries it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NpcSkin {
    /// Skin id: the PNG basename under `skins/`, and the last segment of the
    /// resource-pack texture path (a bare kebab token; validated by `DW0190`).
    pub texture_id: String,
    /// Player model. **Required** (spec-0009): an omitted model renders slim, so
    /// a wide skin on a slim model is distorted — the compiler always emits it.
    pub model: SkinModel,
}

/// Player-model shape for a mannequin skin (`wide` = classic/Steve, `slim` =
/// Alex). Emitted verbatim into the mannequin `profile.model`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum SkinModel {
    /// Classic 4-pixel arms (Steve).
    Wide,
    /// Slim 3-pixel arms (Alex).
    Slim,
}

impl SkinModel {
    /// The vanilla `profile.model` token.
    pub fn token(self) -> &'static str {
        match self {
            SkinModel::Wide => "wide",
            SkinModel::Slim => "slim",
        }
    }
}

/// A structured casting sheet. Structure lives in the
/// keys; every value is free text. `archetype`, `speech_style` and `motivation`
/// are required; the rest are optional.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Persona {
    /// One-line character archetype (required).
    pub archetype: String,
    /// How the NPC speaks — register, tics, formality (required).
    pub speech_style: String,
    /// Emotional bearing toward the player (optional).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub demeanor: Option<String>,
    /// What the NPC wants (required).
    pub motivation: String,
    /// Something the NPC hides (optional).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secret: Option<String>,
    /// Backstory colour (optional).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backstory: Option<String>,
    /// Attitudes toward other same-stage NPCs (optional; refs validated).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub relationships: Vec<Relationship>,
}

/// One persona relationship: an attitude toward another same-stage NPC.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Relationship {
    /// The other NPC (stage-2 ref, validated within stage 2).
    pub npc: NpcId,
    /// Free-text attitude toward that NPC.
    pub attitude: String,
}

/// What a speaking part does. A schema enum offers what the engine accepts,
/// so there are two of them: how hard a fight is billed is [`EncounterTier`] on
/// the body that fights (a `waves[]` entry or a stage-5 actor), not a role here.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Role {
    /// Gives and advances quests.
    QuestGiver,
    /// Flavor only.
    Flavor,
}

// ---------------------------------------------------------------------------
// Stage 6 — dialogue
// ---------------------------------------------------------------------------

/// Stage 6 payload: one dialogue tree per stage-2 NPC (spec-0001 v0.2).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DialogueContent {
    /// One tree per NPC (1:1 with stage 2, both directions).
    pub dialogues: Vec<NpcDialogue>,
}

impl DialogueContent {
    /// The dialogue tree for an NPC id, if present.
    pub fn tree_for(&self, npc: &str) -> Option<&NpcDialogue> {
        self.dialogues.iter().find(|t| t.npc.as_str() == npc)
    }
}

/// One NPC's dialogue tree: a root node plus a set of nodes.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NpcDialogue {
    /// The NPC this tree belongs to (stage-2 ref).
    pub npc: NpcId,
    /// The entry node id; every node must be reachable from it.
    pub root: DialogueId,
    /// The dialogue nodes.
    pub nodes: Vec<DialogueNode>,
}

impl NpcDialogue {
    /// The ids of the nodes reachable from `roots` by following option `next`
    /// edges, ignoring every option gate.
    ///
    /// **The one authority for "what can this tree show, entered here".** A
    /// dialogue tree has more than one entry point — the stage-6 `root`, and
    /// every node a quest's `cast` ledger names as a scene — so "reachable" is
    /// always relative to a root SET, and each consumer supplies the set its own
    /// question is about. `DW0120`/`DW0123` ask about every entry point at once;
    /// the cast ledger's `DW0858` asks about the scenes live during one
    /// objective. Gates are ignored on purpose: an option's flag gate is
    /// `DW0191`'s question, not this one's.
    ///
    /// Root ids that name no node of this tree contribute nothing (a dangling
    /// scene root is `DW0464`, and a dangling stage-6 `root` is `DW0121`).
    pub fn reachable_from<'a>(&'a self, roots: &[&str]) -> BTreeSet<&'a str> {
        let by_id: BTreeMap<&'a str, &'a DialogueNode> =
            self.nodes.iter().map(|n| (n.id.as_str(), n)).collect();
        let mut seen: BTreeSet<&'a str> = BTreeSet::new();
        let mut stack: Vec<&'a str> = roots
            .iter()
            .filter_map(|r| by_id.get_key_value(*r).map(|(k, _)| *k))
            .collect();
        while let Some(cur) = stack.pop() {
            if !seen.insert(cur) {
                continue;
            }
            let Some(node) = by_id.get(cur) else { continue };
            for opt in &node.options {
                if let Some(next) = &opt.next
                    && let Some((k, _)) = by_id.get_key_value(next.as_str())
                {
                    stack.push(k);
                }
            }
        }
        seen
    }

    /// The objective ids some option reachable from `roots` completes — what a
    /// player entering this tree at those scenes can actually finish.
    pub fn completes_from<'a>(&'a self, roots: &[&str]) -> BTreeSet<&'a str> {
        let seen = self.reachable_from(roots);
        let mut out: BTreeSet<&'a str> = BTreeSet::new();
        for node in &self.nodes {
            if !seen.contains(node.id.as_str()) {
                continue;
            }
            for opt in &node.options {
                for eff in &opt.effects {
                    if let DialogueEffect::CompleteObjective { objective } = eff {
                        out.insert(objective.as_str());
                    }
                }
            }
        }
        out
    }
}

/// One dialogue node: text plus branching options.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DialogueNode {
    /// Node id (unique within this NPC's dialogue).
    pub id: DialogueId,
    /// The line the NPC speaks.
    pub text: String,
    /// Branching options; empty closes the dialog.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<DialogueOption>,
}

/// One selectable dialogue option.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DialogueOption {
    /// Button label.
    pub label: String,
    /// The full line this button is the caption of (DSL v0.8). Vanilla's dialog button codec
    /// (`CommonButtonData`) carries an optional `tooltip` component beside
    /// `label`, and the client hangs it on the button as a real hover tooltip —
    /// so a caption on the button and the sentence the character actually says
    /// can both exist. **Not** subject to `DW0331`: a tooltip is not drawn on the
    /// 150 px button, it is wrapped at 170 px into its own hover box, so it never
    /// scrolls. Player-visible, so it translates like the label
    /// (`dlg.<npc>.<node>.opt.<i>.tooltip`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tooltip: Option<String>,
    /// Next node; omitted closes the dialog.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next: Option<DialogueId>,
    /// Flags that must be set for this option to be shown (DSL v0.4). Mirrors an
    /// objective's `requires_flags`: an ungated option (empty) is unchanged; a
    /// gated option is hidden until every referenced flag has been set by a
    /// `set-flag` effect (quest or dialogue). Validation guarantees a flag-gated
    /// option cannot make a critical-path node unreachable (`DW0191`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_flags: Vec<FlagId>,
    /// Negative flag gate (DSL v0.6): the option is
    /// **hidden** (and its `/trigger` handler inert) while ANY listed flag is set
    /// for the player — the dual of `requires_flags`. A `forbids_flags`-gated
    /// option counts as *gated* for the `DW0191` deadlock guard: it can be
    /// suppressed at any point, so it cannot be the only completing path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbids_flags: Vec<FlagId>,
    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
    /// hold for this gate to be open. The third field of the one gate, carried by
    /// every gate consumer — never by the verb that first wanted it. Default
    /// empty, so a pre-0.10 campaign is byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_state: Vec<StateCompare>,
    /// Effects fired when this option is chosen.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<DialogueEffect>,
    /// What choosing this option does to the story (spec-0025). Required for a
    /// **story-weight** beat
    /// — an option carrying a `set-flag` effect, which is how a player's choice
    /// forks the world (`DW0481`). An option that only walks the tree or
    /// completes an objective needs none: the objective already declares one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub happening: Option<Happening>,
}

/// Effect fired by a dialogue option. `complete-objective` (v0.2) and, from DSL
/// v0.4, `set-flag` (mirrors the quest effect — sets a campaign flag from a
/// dialogue choice, enabling flag-gated options/objectives/triggers).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
pub enum DialogueEffect {
    /// Marks a stage-5 objective complete.
    CompleteObjective {
        /// The objective to complete (resolved at the stage-5 boundary).
        objective: ObjectiveId,
    },
    /// Sets a campaign flag (DSL v0.4), mirroring [`Verb::SetFlag`].
    SetFlag {
        /// The flag to set.
        flag: FlagId,
    },
    /// Cuts the world time (DSL v0.5), mirroring [`Verb::SetTime`].
    SetTime {
        /// The time state to cut to.
        time: WorldTime,
    },
    /// Cuts the weather (DSL v0.5), mirroring [`Verb::SetWeather`].
    SetWeather {
        /// The weather state to cut to.
        weather: WorldWeather,
    },
    /// Sets the party-wide respawn checkpoint (DSL v0.6, spec-0012), mirroring
    /// [`Verb::SetCheckpoint`] — usable from a dialogue outcome.
    SetCheckpoint {
        /// The prefab checkpoint anchor the party respawns at.
        anchor: AnchorId,
        /// Per-player effects re-run on respawn while this checkpoint is active
        /// (scene reset). Empty = no hook.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        on_respawn: Vec<QuestEffect>,
    },
    /// Summons a `deferred` stage-2 NPC (DSL v0.6), mirroring
    /// [`Verb::SpawnNpc`] — a character who walks in mid-conversation.
    SpawnNpc {
        /// The NPC (stage-2 ref) to summon.
        npc: NpcId,
    },
}

impl DialogueEffect {
    /// The v0.5 effect name if this dialogue effect is one introduced in DSL v0.5
    /// (`set-time`/`set-weather`, spec-0010).
    pub fn v05_effect(&self) -> Option<&'static str> {
        match self {
            DialogueEffect::SetTime { .. } => Some("set-time"),
            DialogueEffect::SetWeather { .. } => Some("set-weather"),
            _ => None,
        }
    }

    /// The v0.6 effect name if this dialogue effect is one introduced in DSL v0.6
    /// (`set-checkpoint`, spec-0012; `spawn-npc`).
    pub fn v06_effect(&self) -> Option<&'static str> {
        match self {
            DialogueEffect::SetCheckpoint { .. } => Some("set-checkpoint"),
            DialogueEffect::SpawnNpc { .. } => Some("spawn-npc"),
            _ => None,
        }
    }

    /// The NPC id if this is a v0.6 `spawn-npc` dialogue effect.
    pub fn spawn_npc(&self) -> Option<&NpcId> {
        match self {
            DialogueEffect::SpawnNpc { npc } => Some(npc),
            _ => None,
        }
    }

    /// **The body this dialogue effect puts into the world**, by id — the
    /// dialogue half of [`QuestEffect::body_entry`].
    ///
    /// A body can enter the world from a conversation as well as from a quest
    /// bundle, and a rule about what is standing where has to enumerate **every**
    /// entry point or it is a gate with a door beside it. This enum carries no
    /// exit at all: nothing a dialogue option does removes a body.
    pub fn body_entry(&self) -> Option<&str> {
        match self {
            DialogueEffect::SpawnNpc { npc } => Some(npc.as_str()),
            _ => None,
        }
    }

    /// `(anchor, on_respawn)` if this is a v0.6 `set-checkpoint` dialogue effect.
    pub fn set_checkpoint(&self) -> Option<(&AnchorId, &[QuestEffect])> {
        match self {
            DialogueEffect::SetCheckpoint { anchor, on_respawn } => {
                Some((anchor, on_respawn.as_slice()))
            }
            _ => None,
        }
    }

    /// The `on_respawn` bundle of a v0.6 `set-checkpoint` dialogue effect —
    /// **effect root 5** ([`crate::effects`]). Named separately from
    /// [`Self::set_checkpoint`] so the root walk and its mutable mirror name the
    /// same accessor modulo mutability, which is what lets one macro body generate
    /// both.
    pub fn set_checkpoint_on_respawn(&self) -> Option<&[QuestEffect]> {
        match self {
            DialogueEffect::SetCheckpoint { on_respawn, .. } => Some(on_respawn.as_slice()),
            _ => None,
        }
    }

    /// The `on_respawn` bundle of a v0.6 `set-checkpoint` dialogue effect, exposed
    /// mutably so the localization pass can rewrite the player-visible strings
    /// nested inside it. Lockstep sibling of [`Self::set_checkpoint`] — the bundle
    /// is a plain `Vec<QuestEffect>` that emission really lowers, so every scan
    /// that reaches it read-only needs a way to reach it writable too.
    pub fn set_checkpoint_on_respawn_mut(&mut self) -> Option<&mut [QuestEffect]> {
        match self {
            DialogueEffect::SetCheckpoint { on_respawn, .. } => Some(on_respawn.as_mut_slice()),
            _ => None,
        }
    }
}

impl DialogueEffect {
    /// The `set-flag` flag id if this is a v0.4 `set-flag` dialogue effect.
    pub fn set_flag(&self) -> Option<&FlagId> {
        match self {
            DialogueEffect::SetFlag { flag } => Some(flag),
            _ => None,
        }
    }

    /// The v0.4 effect name if this dialogue effect is one introduced in DSL v0.4
    /// (`set-flag`).
    pub fn v04_effect(&self) -> Option<&'static str> {
        match self {
            DialogueEffect::SetFlag { .. } => Some("set-flag"),
            _ => None,
        }
    }

    /// The target time if this is a v0.5 `set-time` dialogue effect.
    pub fn set_time(&self) -> Option<WorldTime> {
        match self {
            DialogueEffect::SetTime { time } => Some(*time),
            _ => None,
        }
    }

    /// The target weather if this is a v0.5 `set-weather` dialogue effect.
    pub fn set_weather(&self) -> Option<WorldWeather> {
        match self {
            DialogueEffect::SetWeather { weather } => Some(*weather),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Stage 3 — classes
// ---------------------------------------------------------------------------

/// Stage 3 payload: 1..4 selectable classes.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ClassesContent {
    /// The selectable classes.
    pub classes: Vec<Class>,
}

/// A player class with a starting kit.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Class {
    /// Unique class id.
    pub id: ClassId,
    /// Player-facing name.
    pub name: String,
    /// Selection-screen blurb.
    pub blurb: String,
    /// Granted items.
    pub kit: Vec<KitItem>,
}

/// One item in a class kit.
///
/// Note: `lore`, `enchantments` and `attributes` are reserved for M2/M3
/// (spec-0001). They are intentionally *not* defined as fields in v0, so a
/// document using them is rejected as an unknown field (`DW0100`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KitItem {
    /// Vanilla item id, validated against the pinned 1.21.11 registry.
    pub item: String,
    /// Stack count.
    pub count: u32,
    /// Optional display name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Who gets it (DSL v0.6, spec-0018). Absent = [`Carrier::All`]. A class kit is
    /// per-player gear by construction — every player who picks the class gets the
    /// kit — so `carrier` here marks a **party-unique** kit item: exactly one copy
    /// enters the party, given to the first player to pick this class.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub carrier: Option<Carrier>,
    /// **The flask** (DSL v0.8, spec-0016 §1): this kit
    /// entry is the class's recovery item, and resting at a bonfire replenishes
    /// it to exactly `count`. A campaign that places a `bonfire` and declares no
    /// flask anywhere in its kits is `DW0476` — the estus loop is what makes
    /// dying an investment, so a souls campaign without one is a build error, not
    /// a design choice. Absent on every pre-0.8 kit → emission byte-identical.
    #[serde(default, skip_serializing_if = "is_false")]
    pub flask: bool,
    /// **What is in the bottle** (DSL v0.8, spec-0016 §1): the vanilla
    /// `minecraft:potion_contents` component of a
    /// potion-bearing item ([`POTION_BEARING_ITEMS`]). Without it a
    /// `minecraft:potion` is the *Uncraftable Potion* — a bottle that heals
    /// nothing — which is exactly the placeholder flask this field exists to
    /// abolish, so at `dsl_version` 0.8.0 a potion-bearing kit item that declares
    /// no `contents` is `DW0487`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contents: Option<PotionContents>,
}

/// The items whose vanilla item definition carries a `minecraft:potion_contents`
/// component — the only items a kit `contents` may be declared on (`DW0486`).
///
/// Read off the pinned 1.21.11 `item_components` summary (SHA-256
/// `51b191e13f86813ca02f1498942e5bc235947edb71eb8105a78401670b3665c4`, the same
/// misode/mcmeta ref `crates/delvec/data/PROVENANCE.md` pins): exactly these
/// four items declare the component, and on any other item the game drops the
/// data on the floor.
pub const POTION_BEARING_ITEMS: &[&str] = &[
    "minecraft:lingering_potion",
    "minecraft:potion",
    "minecraft:splash_potion",
    "minecraft:tipped_arrow",
];

/// True if `item_id` (optionally un-namespaced) is one of the four
/// [`POTION_BEARING_ITEMS`].
pub fn is_potion_bearing_item(item_id: &str) -> bool {
    let norm = if item_id.contains(':') {
        item_id.to_string()
    } else {
        format!("minecraft:{item_id}")
    };
    POTION_BEARING_ITEMS.contains(&norm.as_str())
}

/// The two **instantaneous** status effects: they are applied once, on the tick
/// the potion is drunk (`PotionContents.applyToLivingEntity` branches on
/// `isInstantenous` before any effect instance is ever added), so a `duration` on
/// one is a statement the game never reads — `DW0486` says so rather than letting
/// an author believe they wrote a thirty-second heal.
pub const INSTANT_EFFECTS: &[&str] = &["minecraft:instant_health", "minecraft:instant_damage"];

/// A potion-bearing kit item's `minecraft:potion_contents` component (DSL v0.8),
/// modelled field for field on vanilla rather than invented: a **named** potion,
/// a list of **custom effects**, or both, plus the bottle-colour override.
///
/// Vanilla resolves a drink as the named potion's effects followed by the custom
/// ones, and derives the bottle colour from those effects unless `color`
/// overrides it — so `{"potion": "minecraft:strong_healing"}` is literally the
/// Potion of Healing II a player would brew, not an approximation of one.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PotionContents {
    /// A named vanilla potion id (`minecraft:strong_healing`,
    /// `minecraft:long_night_vision`, …), validated against the pinned 1.21.11
    /// `potion` registry (`DW0486`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub potion: Option<String>,
    /// Custom effects applied on top of (or instead of) the named potion — the
    /// escape hatch for a recovery item vanilla has no brew for.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<PotionEffect>,
    /// Bottle-colour override, `#rrggbb` (vanilla `custom_color`). Absent → the
    /// colour vanilla derives from the effects themselves.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
}

/// One entry of a potion's `custom_effects` list.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PotionEffect {
    /// Vanilla status-effect id (e.g. `minecraft:regeneration`), validated
    /// against the pinned registry (`DW0486`).
    pub effect: String,
    /// How long it lasts, in **ticks** (20 = one second). Required for every
    /// effect except the two [`INSTANT_EFFECTS`], which must NOT declare one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration: Option<u32>,
    /// Amplifier, 0 = level I (vanilla's unsigned byte, so 0–255). Absent = 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub amplifier: Option<u32>,
}

impl PotionEffect {
    /// True if this effect is applied once on drinking rather than over time.
    pub fn is_instant(&self) -> bool {
        let norm = crate::registry::namespaced_effect_id(&self.effect);
        INSTANT_EFFECTS.contains(&norm.as_str())
    }
}

/// The largest `duration` a potion effect may declare, in ticks: 1 000 000 ticks
/// ≈ 13.9 hours, past the 10-hour delve ceiling, so nothing a delve can legally
/// need is refused — while a duration typed in *milliseconds*, or one that would
/// overflow vanilla's int, is caught (`DW0486`).
pub const MAX_POTION_DURATION_TICKS: u32 = 1_000_000;

/// The largest `amplifier` a potion effect may declare: vanilla stores it in an
/// unsigned byte, so 255 is not a policy but the end of the field.
pub const MAX_POTION_AMPLIFIER: u32 = 255;

/// The largest `seconds` a [`Verb::GiveEffect`] may declare, derived from
/// [`MAX_POTION_DURATION_TICKS`] rather than chosen again: the two are the same
/// quantity in different units, and a second independently-picked ceiling is how
/// two limits for one fact drift apart. ≈13.9 hours, past the 10-hour delve
/// ceiling, so nothing a delve can legally need is refused — while a duration
/// typed in *ticks* or in milliseconds is caught (`DW0541`).
pub const MAX_EFFECT_SECONDS: u32 = MAX_POTION_DURATION_TICKS / 20;

/// The canonical English title of the bonfire rest dialog. Baked at emit time
/// when the campaign authors no `prompt`, in the
/// `world.boundary.message` tradition: a compiler default is not inventoried, an
/// authored line is — so a delve that wants this sentence in `zh-cn` authors it.
pub const BONFIRE_PROMPT_EN: &str = "Bonfire";
/// The canonical English label of the **rest and save** option.
pub const BONFIRE_REST_LABEL_EN: &str = "Rest and save";
/// The canonical English label of the **save only** option.
pub const BONFIRE_SAVE_LABEL_EN: &str = "Save only";

/// A `bonfire`'s authored rest-dialog strings, each `None` when the campaign
/// leaves the compiler's canonical English in place
/// ([`QuestEffect::bonfire_labels`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BonfireLabels<'a> {
    /// Dialog title; `None` → [`BONFIRE_PROMPT_EN`].
    pub prompt: Option<&'a str>,
    /// **Rest and save** button label; `None` → [`BONFIRE_REST_LABEL_EN`].
    pub rest_label: Option<&'a str>,
    /// **Save only** button label; `None` → [`BONFIRE_SAVE_LABEL_EN`].
    pub save_label: Option<&'a str>,
    /// **Rest and save** button hover tooltip (spec-0078); `None` → none emitted.
    pub rest_tooltip: Option<&'a str>,
    /// **Save only** button hover tooltip (spec-0078); `None` → none emitted.
    pub save_tooltip: Option<&'a str>,
}

impl BonfireLabels<'_> {
    /// The dialog title actually emitted.
    pub fn prompt_or_default(&self) -> &str {
        self.prompt.unwrap_or(BONFIRE_PROMPT_EN)
    }
    /// The **rest and save** label actually emitted.
    pub fn rest_or_default(&self) -> &str {
        self.rest_label.unwrap_or(BONFIRE_REST_LABEL_EN)
    }
    /// The **save only** label actually emitted.
    pub fn save_or_default(&self) -> &str {
        self.save_label.unwrap_or(BONFIRE_SAVE_LABEL_EN)
    }
}

// ---------------------------------------------------------------------------
// Stage 4 — quest-plan
// ---------------------------------------------------------------------------

/// Stage 4 payload: the quest dependency plan.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct QuestPlanContent {
    /// Planned quests (expanded in stage 5).
    pub quests: Vec<PlannedQuest>,
    /// The quest whose completion ends the campaign.
    pub finale: QuestId,
    /// The campaign's declared **story forks** (DSL v0.8, spec-0025). Empty/absent = a campaign that claims to have no
    /// branch — which the compiler then *verifies* rather than assumes: any flag
    /// that gates casts, staging or structure and is set on some playthroughs and
    /// not others belongs to no declared point and is `DW0480`.
    ///
    /// Enumerated branches are the **product of the declared points**, so the
    /// branch set is authored and small — never a combinatorial sweep of every
    /// flag in the campaign.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub branch_points: Vec<BranchPoint>,
}

impl QuestPlanContent {
    /// **The ONE authority on which quests are the spine**: the finale and every
    /// quest its `depends_on` chain transitively demands — the quests a body
    /// cannot reach the finale without.
    ///
    /// The capability belongs here, on the stage-4 document, because the spine is
    /// a fact about the quest plan and about nothing else. It had grown two
    /// derivations of the same closure in two files — one inline in
    /// [`crate::validate`]'s `DW0132` convergence check, one a private
    /// `mandatory_quests` in [`crate::layout`] read by the layout binding and by
    /// the critical-path spine obligation. Both were correct and neither said it
    /// was the authority, which is exactly the shape a later clean merge turns
    /// into two rules that disagree.
    ///
    /// **Why the closure is taken over the raw `depends_on` edges, unfiltered.**
    /// The `validate` copy first dropped every dep naming a quest the plan does
    /// not declare. That filtering is not this function's question: a dangling
    /// `depends_on` is `DW0112`'s finding, and silently pruning it here would
    /// make the set disagree with the document it is derived from. So an id the
    /// plan does not declare is reported in the spine and expands no further —
    /// and the one reader that could care, `DW0132`, only ever asks whether a
    /// **declared** quest is a member, so an undeclared member cannot change its
    /// verdict.
    ///
    /// Cycle-safe by construction (a quest already in the set is not expanded
    /// again), so a plan `DW0130` will refuse still yields a set rather than
    /// hanging.
    ///
    /// **Not the same question as the `mandatory` field**, and the name says so
    /// deliberately. Today the two sets always coincide, because `DW0132` demands
    /// every declared quest be a transitive dependency of the finale and `DW0866`
    /// demands every quest set `mandatory: true`. If `mandatory: false` ever
    /// becomes legal those coincide no longer, and this function keeps answering
    /// the graph question it has always answered.
    #[must_use]
    pub fn spine(&self) -> BTreeSet<&str> {
        let deps: BTreeMap<&str, &[QuestId]> = self
            .quests
            .iter()
            .map(|q| (q.id.as_str(), q.depends_on.as_slice()))
            .collect();
        let mut spine: BTreeSet<&str> = BTreeSet::new();
        let mut stack = vec![self.finale.as_str()];
        while let Some(q) = stack.pop() {
            if !spine.insert(q) {
                continue;
            }
            for dep in deps.get(q).copied().unwrap_or(&[]) {
                stack.push(dep.as_str());
            }
        }
        spine
    }

    /// **The ONE authority on which quests are elective** (spec-0051): the
    /// quests declaring `mandatory: false`.
    ///
    /// The counterpart to [`Self::spine`], and deliberately a *different*
    /// question. `spine` asks what the graph demands; this asks what the author
    /// claims. `DW0866`/`DW0867` are exactly the rules that keep the two
    /// answers honest about each other, and they can only do that while each
    /// side has one derivation — which is the defect the spine function was
    /// created to end, and which a second private `!q.mandatory` filter in the
    /// compiler would re-introduce on the other half.
    #[must_use]
    pub fn optional(&self) -> BTreeSet<&str> {
        self.quests
            .iter()
            .filter(|q| !q.mandatory)
            .map(|q| q.id.as_str())
            .collect()
    }
}

/// One declared story fork (DSL v0.8, spec-0025).
///
/// A branch point names the flag set the story forks on, the quest at which the
/// fork opens, and every branch it offers. Each branch pins the point's whole
/// flag set: the flags it lists are **set**, and every other flag of `forks_on`
/// is **not** — which is what makes exclusive-content leakage (`DW0484`) and
/// per-branch cast resolution (`DW0483`) decidable instead of hopeful.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BranchPoint {
    /// Unique branch-point id.
    pub id: BranchPointId,
    /// The quest at which the fork opens — every branch's divergent content is at
    /// or after it in the stage-4 DAG.
    pub opens_at: QuestId,
    /// The flag set the story forks on. Every branch's `flags` is a subset of
    /// this, and the flags it does not list are pinned **unset** on that branch.
    pub forks_on: Vec<FlagId>,
    /// The alternatives (≥ 2).
    pub branches: Vec<BranchDecl>,
}

/// One alternative of a [`BranchPoint`] (DSL v0.8, spec-0025).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BranchDecl {
    /// Unique branch id (campaign-wide — it names the emitted chronicle file).
    pub id: BranchId,
    /// The subset of the point's `forks_on` that is SET on this branch. The rest
    /// of `forks_on` is pinned unset. An empty list is legal — the "took neither
    /// option" branch — as long as it is genuinely reachable.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub flags: Vec<FlagId>,
    /// Where this branch goes: either the `quest/<kebab>` the branches converge
    /// at, or the `ending/<kebab>` this branch runs to.
    ///
    /// One field, not two mutually exclusive ones, because the **id prefix
    /// already says which it is** — the same convention every cross-stage
    /// reference in the DSL uses. That is what makes "exactly one of them" an
    /// unrepresentable state rather than a rule some diagnostic has to police: a
    /// value that is neither a syntactically valid `quest/…` nor `ending/…` is
    /// the ordinary malformed-id `DW0110`, and one that names nothing is the
    /// ordinary dangling-reference `DW0112`.
    pub leads_to: String,
}

impl BranchDecl {
    /// The convergence quest, if [`Self::leads_to`] names one.
    pub fn converges_at(&self) -> Option<QuestId> {
        let q = QuestId(self.leads_to.clone());
        q.is_valid_syntax().then_some(q)
    }

    /// The ending, if [`Self::leads_to`] names one.
    pub fn ending(&self) -> Option<EndingId> {
        let e = EndingId(self.leads_to.clone());
        e.is_valid_syntax().then_some(e)
    }
}

/// What a story node does to the story (DSL v0.8, spec-0025).
///
/// The generalization of spec-0020's `doing` from NPC presence to event flow: a
/// design that never got written down node by node cannot compile. It is
/// **node-local on purpose** — there is no parallel per-branch script document
/// that could itself drift from the graph.
///
/// `text` is authoring/validation metadata, never shown to a player, so it is
/// deliberately **excluded from the l10n inventory** exactly like `doing`. The
/// compiler reads only `verb` and `subject`; `text` is the flesh the per-branch
/// chronicle is assembled from.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Happening {
    /// The structured event verb — the machine-decidable part.
    pub verb: HappeningVerb,
    /// One line of prose stating what this node does to the story.
    pub text: String,
    /// What the event happens TO: an `npc/`, `actor/`, `wave/` or `anchor/` id
    /// (validated — a dangling one is `DW0112`), or an `item/<kebab>` label for a
    /// story token the campaign tracks by hand. Optional, because not every beat
    /// is about somebody; the hard-contradiction proof (`DW0485`) reasons only
    /// over the beats that name one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
}

/// The subject a beat is about, and whether the document said so (spec-0071 §3).
///
/// Answered by [`QuestEffect::happening_subject`], the one derivation. `derived`
/// is carried rather than dropped because the two readers want different things
/// from it: the namespace check reports on what an author **wrote**, and the
/// chronicle reasons over what the beat **is about**.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HappeningSubject<'a> {
    /// The subject id (`npc/`, `actor/`, `wave/`, `anchor/` or an `item/` label).
    pub id: &'a str,
    /// `true` when the effect's own single object supplied it, `false` when the
    /// `happening` states it.
    pub derived: bool,
}

/// The structured event vocabulary (DSL v0.8, spec-0025).
///
/// Deliberately small and closed. These ten verbs are what make a subset of
/// narrative errors machine-decidable per branch (`DW0485`); everything else a
/// beat means lives in [`Happening::text`], which the compiler never interprets.
/// Extend only when a real campaign cannot state its beat with what is here.
#[derive(
    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "kebab-case")]
pub enum HappeningVerb {
    /// The subject is killed / destroyed. Terminal: nothing the subject does may
    /// follow it on the same branch.
    Dies,
    /// The subject comes through alive — the explicit counterpart of `dies`,
    /// which is what lets a branch state that somebody *did not* die.
    Survives,
    /// The subject leaves the stage (offstage, not dead). Cleared by `arrives`.
    Departs,
    /// The subject enters the stage.
    Arrives,
    /// Somebody learns a fact — the true-information beat.
    Learns,
    /// Somebody comes to believe something (whether or not it is true) — the beat
    /// that carries a wrong belief forward, which is where branch drift shows.
    Believes,
    /// The party (or the subject) gains a thing.
    Gains,
    /// The party (or the subject) loses a thing. A second `loses` with no
    /// intervening `gains` is spending what is already spent (`DW0485`).
    Loses,
    /// A way is opened.
    Opens,
    /// A way is sealed. Cleared by `opens`.
    Seals,
}

/// One planned quest (dependency-graph node).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PlannedQuest {
    /// Unique quest id.
    pub id: QuestId,
    /// Human-readable goal.
    pub goal: String,
    /// Area this quest takes place in (stage-1 ref).
    pub area: AreaId,
    /// NPCs involved (stage-2 refs).
    pub npcs: Vec<NpcId>,
    /// Prerequisite quests; edges must form a DAG.
    pub depends_on: Vec<QuestId>,
    /// `false` declares an optional quest (spec-0051).
    pub mandatory: bool,
    /// Act number (informational).
    pub act: u32,
}

// ---------------------------------------------------------------------------
// Stage 5 — quests
// ---------------------------------------------------------------------------

/// Stage 5 payload: quest expansions.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct QuestsContent {
    /// The expanded quests (1:1 with stage 4).
    pub quests: Vec<Quest>,
    /// Combat waves (DSL v0.3). Each wave is spawned by a `spawn-wave` effect and
    /// slain to complete a `kill` objective. Empty/absent in v0.2 campaigns.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub waves: Vec<Wave>,
    /// Environment triggers (DSL v0.4, spec-0008 §7): "the world answers". Each
    /// watches an anchor for a strike / use / approach event and fires a bundle
    /// of [`QuestEffect`]s. Empty/absent in v0.2/v0.3 campaigns.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub triggers: Vec<EnvTrigger>,
    /// Scripted actors (DSL v0.6, spec-0014): NoAI/Silent/no-loot puppets moved by
    /// compiler-emitted per-tick teleport. Distinct from stage-2 NPCs
    /// (no dialogue, any mob type). Summoned/removed/moved/unleashed by the actor
    /// staging effects. Empty/absent before v0.6.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actors: Vec<Actor>,
    /// Traps (DSL v0.6, spec-0011; command payloads spec-0022): environmental
    /// hazards, each at one point anchor an area's prefab provides. Each says
    /// what springs the trap, what it then does (a command `payload`, a legacy
    /// dispenser `effect`, or both), how dangerous it is, how it is disarmed and
    /// whether it re-arms. Empty/absent in pre-0.6 campaigns, so a v0.5-or-earlier campaign that declares none stays
    /// byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub traps: Vec<Trap>,
    /// Shortcut doors (spec-0016 §2): a gate that is sealed from world-load and
    /// is opened — permanently — from the FAR side. Empty/absent in pre-0.6
    /// campaigns, so a campaign that declares none stays
    /// byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shortcuts: Vec<Shortcut>,
    /// Ambushes (spec-0016 §3): sugar over "deferred actors + a trigger that
    /// springs them". Empty/absent in pre-0.6 campaigns.
    ///
    /// **Never serialized.** [`parse_campaign`](crate::parse_campaign) expands
    /// each ambush into `triggers`, so the canonical form of a campaign is its
    /// **desugared** form. That is what keeps the canonical round-trip idempotent
    /// (re-parsing canonical output finds no `ambushes` and so cannot expand a
    /// second time and duplicate the trigger ids), and it means the sugar exists
    /// at exactly one layer boundary — the authored `.json` — with nothing
    /// downstream needing to know it was ever there. The list itself is kept in
    /// memory so diagnostics can name the ambush the author wrote.
    /// Timed gates (spec-0016 §4): gates on a deterministic open/close clock.
    /// Empty/absent in pre-0.6 campaigns.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub timed_gates: Vec<TimedGate>,
    /// Container fills (spec-0021): pre-placed chests/barrels in the prefabs
    /// given contents at world init. Empty/absent in pre-0.6 campaigns
    ///.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub loot: Vec<Loot>,
    /// Runtime state data (DSL v0.10, spec-0031): named, scoped, integer-valued
    /// counters the campaign sets, adds to and clears at runtime, and compares
    /// against in any gate. A campaign that declares none emits none of it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub state: Vec<StateDecl>,
    /// **The campaign's death beat** (DSL v0.10, spec-0031): effects run at the
    /// moment a player dies, for that player. Effect root **R7**
    /// ([`crate::EffectRootKind::OnDeath`]); a campaign that declares none emits
    /// none of it.
    ///
    /// **Why this is campaign-wide and not a field on a checkpoint.** The engine
    /// already has `on_respawn`, and it hangs off a `set-checkpoint` because
    /// *where you come back* is a property of the checkpoint. *That you died* is
    /// not: it is true at every point of the delve, under every checkpoint, and a
    /// bundle repeated on each checkpoint would be the same content written N
    /// times with N chances to forget one. So death is a moment in the campaign,
    /// and this is the one place it is named. Anything that should only happen in
    /// some phase of the delve is expressed by the ordinary per-effect
    /// `requires_flags` / `forbids_flags` gate every other root already carries —
    /// no second gating surface.
    ///
    /// **Audience is the dying player** (`Audience::Solo`, the audience
    /// `on_respawn` and `on_caught` already use): a death is one player's, and
    /// re-broadcasting it to the party would duplicate their narration and their
    /// kit. A beat the whole party should see is a `narrate` addressed by the
    /// author to the party through the effect's own vocabulary, not a different
    /// default here.
    ///
    /// **Timing.** It fires on the death edge while the player is still a corpse
    /// (`Health: 0.0f`, on the death screen) — see
    /// `emit::emit_checkpoint_functions`. That is the difference between this and
    /// `on_respawn`, which deliberately waits for the player to come back.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub on_death: Vec<QuestEffect>,
    /// Lethal volumes (DSL v0.10, spec-0031): declared boxes that kill whatever
    /// enters them. Empty/absent in pre-0.10 campaigns, so a
    /// campaign that declares none stays byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lethal_volumes: Vec<LethalVolume>,
    /// Shops (DSL v0.10, spec-0032): interaction points that open a list of
    /// gated offers. Empty/absent in pre-0.10 campaigns, so a
    /// campaign that declares none stays byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shops: Vec<Shop>,
    /// Recovery stakes (DSL v0.10, spec-0032): what a death forfeits, where the
    /// marker lands, and how it comes back. Empty/absent in pre-0.10 campaigns
    ///, so a campaign that declares none stays byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stakes: Vec<Stake>,
    /// Assemblies (spec-0082): fixed things built of display entities that
    /// play clips from a library rig, can be struck in melee, and strike back
    /// at a player who stands where they reach. Appear on `spawn-assembly`,
    /// leave on `despawn-assembly`. Empty/absent = nothing emitted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assemblies: Vec<Assembly>,
    /// Loops (spec-0086): slabs whose crossing returns a body by a whole-block
    /// offset to an identical earlier section, held while a party gate is open.
    /// Empty/absent for every campaign that declares none, so such a campaign
    /// stays byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub loops: Vec<Loop>,
    #[serde(default, skip_serializing)]
    pub ambushes: Vec<Ambush>,
    /// Whether [`Self::expand_ambushes`] has already run (never serialized). The
    /// authored `ambushes` are deliberately KEPT after expansion so validation
    /// and the counterplay proof can attribute diagnostics to the ambush the
    /// author actually wrote; this flag is what makes a second expansion a no-op.
    #[serde(skip)]
    pub ambushes_expanded: bool,
}

impl QuestsContent {
    /// Every environment trigger this stage produces: the authored `triggers`
    /// followed by the ones each `ambush` desugars to (spec-0016 §3), in
    /// declared order.
    ///
    /// **This is the single trigger authority.** Validation, the l10n
    /// inventory, the flag/wave producer scans, the nav proofs and emission all
    /// read triggers through it, so an ambush behaves exactly like the trigger
    /// an author would otherwise hand-write — there is no second code path for
    /// the sugar to drift down. Deterministic (declaration order, no hashing).
    pub fn all_triggers(&self) -> Vec<EnvTrigger> {
        let mut out = self.triggers.clone();
        out.extend(self.ambushes.iter().map(Ambush::to_trigger));
        out
    }

    /// **Does the campaign itself answer a right-click at `anchor`?**
    ///
    /// One predicate, read by both consumers of the press-answer rule, so they can
    /// never disagree about what "the campaign answered it" means: the compiler's
    /// synthesis (`plan::collect_press_answers`, which stands down where this is
    /// true) and the obligation on a shortcut door (`DW0429`, which fires where it
    /// is false). Split across the two crates they would drift, and the drift
    /// would read as "the compiler refused a door I answered".
    ///
    /// Deliberately the widest reading — *any* `use` trigger anchored there.
    /// Pressing it already does something the author chose, and the engine does
    /// not adjudicate whether what they chose counts as an answer.
    pub fn answers_press_at(&self, anchor: &str) -> bool {
        self.all_triggers()
            .iter()
            .any(|t| matches!(t.on, TriggerOn::Use) && t.at_anchor() == Some(anchor))
    }

    /// Desugar every `ambush` into a real environment trigger and clear the
    /// ambush list (spec-0016 §3). Called once, by
    /// [`parse_campaign`](crate::parse_campaign); idempotent by construction
    /// (a second call sees no ambushes left to expand).
    pub fn expand_ambushes(&mut self) {
        if self.ambushes_expanded || self.ambushes.is_empty() {
            return;
        }
        self.triggers = self.all_triggers();
        self.ambushes_expanded = true;
    }

    /// The declared datum with this id, if any (DSL v0.10).
    pub fn state_decl(&self, id: &str) -> Option<&StateDecl> {
        self.state.iter().find(|s| s.id.as_str() == id)
    }

    /// The declared stake with this id, if any (DSL v0.10, spec-0032).
    pub fn stake_decl(&self, id: &str) -> Option<&Stake> {
        self.stakes.iter().find(|s| s.id.as_str() == id)
    }

    /// The declared assembly with this id, if any (spec-0082).
    pub fn assembly_decl(&self, id: &str) -> Option<&Assembly> {
        self.assemblies.iter().find(|a| a.id.as_str() == id)
    }
}

// ---------------------------------------------------------------------------
// Stage 5 — runtime state (DSL v0.10, spec-0031)
// ---------------------------------------------------------------------------

/// Who holds a datum's value (DSL v0.10, spec-0031).
///
/// **Declared, never inferred.** A datum's multiplayer semantics is the one
/// thing about it that cannot be recovered from its uses: a purse read on a
/// `talk-to` looks identical whether every player has their own or the party
/// shares one, and the difference decides the whole design. spec-0031 states it
/// as a rule, and the type makes it un-omittable — there is no default.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum StateScope {
    /// Each player holds their own value. Read and written against the acting
    /// player, so a bundle with no acting player (the scheduler) cannot touch one
    /// (`DW0503`).
    Player,
    /// One value the whole party shares — the same holder story flags use
    /// (spec-0018). Readable and writable from every audience, including the
    /// scheduler.
    Party,
}

impl StateScope {
    /// The wire token (`player` / `party`).
    pub fn token(self) -> &'static str {
        match self {
            StateScope::Player => "player",
            StateScope::Party => "party",
        }
    }
}

/// One declared runtime datum (DSL v0.10, spec-0031): a named, scoped,
/// integer-valued counter.
///
/// This is what [`FlagId`] is not. A flag is boolean, party-wide and
/// **monotonic** — no verb clears one — which is exactly right for "this has
/// happened" and useless for a balance, a floor number, or "a ride is in
/// progress". A datum clears, counts down as well as up, and states its scope.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StateDecl {
    /// Unique datum id (`state/<kebab>`).
    pub id: StateId,
    /// Who holds the value. Required — see [`StateScope`].
    pub scope: StateScope,
    /// The value the datum starts at, and the value `clear-state` returns it to.
    /// Defaults to `0`.
    ///
    /// One field rather than a separate `initial` and `cleared`: "the value this
    /// datum has when nothing has happened to it yet" is one fact, and two fields
    /// would let a campaign declare a datum that can never be returned to its own
    /// starting state.
    #[serde(default, skip_serializing_if = "is_zero_i32")]
    pub initial: i32,
    /// Free prose: what this datum means. Never machine-checked, never shown to a
    /// player — the forcing function that makes an author say what the number is,
    /// the same role `cast[].doing` plays.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// The player-visible name of this datum (DSL v0.10, spec-0032).
    ///
    /// **A named datum is a currency.** There is no separate `currencies` section
    /// and there deliberately is not: a purse is a runtime datum that the player
    /// can see, and "the player can see it" is a property of the datum, not a
    /// different object class. A second struct carrying `id` + `scope` +
    /// `initial` + `name` would be a private copy of this one, which is the defect
    /// CLAUDE.md names second.
    ///
    /// Present ⇒ every `set-state` / `add-state` / `clear-state` on this datum
    /// also states the new balance to whoever holds it, on the action bar, as
    /// `<name>: <value>` with the value carried by vanilla's own `score`
    /// component. Absent ⇒ the datum is silent bookkeeping and emission is exactly
    /// what it was.
    ///
    /// Player-visible, so it is inventoried under `state.<id>.name` and
    /// translated like any other authored line.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Where this datum **stands** on screen between changes (spec-0076).
    ///
    /// The announcement `name` buys fades with the action bar; a datum that
    /// declares `display` also occupies a vanilla display slot, so its balance is
    /// on screen at every moment for every player. Declared, never automatic: a
    /// creator may want a named tally that is spoken only when it moves, and the
    /// engine does not decide which of two named datums is the purse.
    ///
    /// Present ⇒ `setup` heads the datum's objective with its translated `name`,
    /// paints the value gold, and puts the objective in the slot. Requires `name`
    /// (the slot's heading is the display name, and without one it would show the
    /// objective's id) and a `player` scope (the sidebar hides `#`-prefixed
    /// holders, which is what a `party` datum's value lives on); one datum per
    /// campaign may stand, because the slot holds one objective — all three are
    /// `DW0919`. Absent ⇒ the datum announces itself and stands nowhere.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display: Option<StateDisplay>,
}

/// The vanilla display slot a named datum stands in (spec-0076).
///
/// One value, because vanilla has one slot that stands for the viewer: `list`
/// shows only while the tab key is held and `below_name` draws under *other*
/// players' name tags, never over the viewer's own body. A second variant is
/// added when the pinned game offers a second standing surface, not before.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum StateDisplay {
    /// The right-hand sidebar: a heading (the datum's `name`) and one line per
    /// player, each showing that player's own balance.
    Sidebar,
}

impl StateDisplay {
    /// The `minecraft:scoreboard_slot` token the slot is addressed by.
    pub fn slot(self) -> &'static str {
        match self {
            StateDisplay::Sidebar => "sidebar",
        }
    }
}

/// serde `skip_serializing_if` helper: skip a zero `i32` (`StateDecl.initial`).
fn is_zero_i32(v: &i32) -> bool {
    *v == 0
}

/// How a [`StateCompare`] relates a datum to its operand (DSL v0.10).
///
/// Four operators, not six: over integers `less-than n` is `at-most n-1` and
/// `greater-than n` is `at-least n+1`, so the extra spellings would add a second
/// way to say one thing and a second emission path to keep honest.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum CompareOp {
    /// The datum is exactly `value`.
    Equals,
    /// The datum is anything but `value`.
    NotEquals,
    /// The datum is `value` or more.
    AtLeast,
    /// The datum is `value` or less.
    AtMost,
}

impl CompareOp {
    /// The wire token (`equals` / `not-equals` / `at-least` / `at-most`).
    pub fn token(self) -> &'static str {
        match self {
            CompareOp::Equals => "equals",
            CompareOp::NotEquals => "not-equals",
            CompareOp::AtLeast => "at-least",
            CompareOp::AtMost => "at-most",
        }
    }
}

/// What one of the DSL v0.10 state verbs does to a datum — the value half of
/// [`QuestEffect::writes_state`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateWrite {
    /// `set-state`: the datum becomes this value.
    Set(i32),
    /// `add-state`: the datum moves by this signed amount.
    Add(i32),
    /// `clear-state`: the datum returns to its declared `initial`.
    Clear,
}

/// One numeric term of a gate (DSL v0.10, spec-0031): *this datum compares thus
/// to this value*.
///
/// It rides [`Gate`](crate::gate::Gate) — the shared gate, carried by every
/// consumer of `requires_flags`/`forbids_flags` — and not any one verb. The
/// comparison's consumers are exactly the gate's consumers ("this door opens at
/// 500", "this line is withheld below 200", "this lever does nothing while the
/// car is moving"), so hanging it off the first verb that asked would leave the
/// second with no surface and make a second bespoke field look like the fix.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StateCompare {
    /// The datum to read. Must be declared in the stage-5 `state` list
    /// (`DW0502`).
    pub state: StateId,
    /// How to compare it.
    pub op: CompareOp,
    /// What to compare it against.
    pub value: i32,
}

/// A stage-5 container fill (DSL v0.6, spec-0021): contents for a chest or
/// barrel the prefab already placed.
///
/// The container is **hardware the prefab authored**, exactly like a trap's
/// dispenser: this declaration gives an already-placed, already-lit, already
/// composed piece of furniture its contents. The compiler never places the
/// container itself — if the anchor's cell does not already hold one, that is a
/// content defect and a build error (`DW0431`), not something to paper over by
/// setblock-ing a chest into a wall.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Loot {
    /// Unique loot id (`loot/<kebab>`).
    pub id: LootId,
    /// The anchor whose cell holds the container to fill.
    pub anchor: AnchorId,
    /// Contents, in declaration order. Slot assignment is positional and
    /// deterministic — the first entry lands in `container.0`, the second in
    /// `container.1`, and so on (ADR-0006: no RNG, no loot tables).
    pub items: Vec<LootItem>,
}

/// One stack inside a [`Loot`] container.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct LootItem {
    /// Item id (e.g. `minecraft:cooked_cod`). Validated against the pinned
    /// 1.21.11 item registry (`DW0143`).
    pub item: String,
    /// Stack size. Defaults to 1.
    #[serde(default = "one_u32")]
    pub count: u32,
    /// Optional custom item name. Enters the l10n string inventory exactly like
    /// a class kit item's name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Enchantments on this stack (`{"minecraft:sharpness": 3}`), emitted as the
    /// 1.21 `minecraft:enchantments` item component — or, on a
    /// `minecraft:enchanted_book`, `minecraft:stored_enchantments`
    /// ([`enchantment_component`]).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub enchantments: BTreeMap<String, u32>,
}

fn one_u32() -> u32 {
    1
}

/// A stage-5 trap (DSL v0.6, spec-0011; command payloads spec-0022): an
/// environmental hazard at one cell of a placed piece.
///
/// **What the prefab has to provide is one point anchor with the trigger block
/// in its cell, and for most traps that is all.** [`Trap::at`] names the
/// trigger/hazard cell; the piece places the plate, tripwire or trapped chest
/// there (`DW0917`); the compiler models it as a hazard for the completability
/// proofs (`DW0342`) and, for a disarmable trap, emits the disarm affordance. A
/// [`payload`](Trap::payload) trap needs nothing else: **the compiler owns the
/// detection**, emitting a per-tick, edge-latched `execute … if entity @a[<cell>]` and running the authored effect
/// bundle from it.
///
/// Two things a piece must pre-wire, each for one case and neither for the
/// common one:
///
/// * the legacy [`effect`](Trap::effect) — a `dispense` payload the prefab's own
///   redstone fires — needs the anchor's `dispenser` socket cell, which the
///   compiler fills. That is the case "harm is redstone-native" (spec-0011) was
///   written about, and the only one in which no detection is emitted.
/// * a **flag-gated** trap ([`requires_flags`](Trap::requires_flags) /
///   [`forbids_flags`](Trap::forbids_flags)) needs the anchor's `trigger_block`,
///   because gating removes the trigger block from the world while the gate is
///   shut and puts it back verbatim (`DW0363`).
///
/// Player-vs-mob distinguishing matters in a sealed box-garden with controlled
/// mobs, so `trapped-chest` (opened by a player) is called out as the only
/// player-distinct trigger.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Trap {
    /// Unique trap id (`trap/<kebab>`).
    pub id: TrapId,
    /// **The point anchor this trap sits on** — any anchor an area's prefab
    /// provides, whatever it is called. Its cell is the trigger/hazard cell the
    /// compiler models, and for a `payload` trap that cell, holding the block
    /// its [`trigger`](Trap::trigger) names, is the whole of what the piece has
    /// to provide: detection is the compiler's, the block is the piece's
    /// (`DW0917`).
    ///
    /// The anchor additionally needs a `dispenser` socket for a legacy
    /// [`effect`](Trap::effect) trap, and a `trigger_block` for a flag-gated one
    /// (`DW0363`). `anchor/trap` is the name the shipped pieces use, and a name
    /// is all it is.
    pub at: AnchorId,
    /// What springs the trap (all redstone-native).
    pub trigger: TrapTrigger,
    /// The **legacy** redstone consequence (spec-0011): a static dispenser
    /// payload the prefab's own wiring fires. Superseded by [`Trap::payload`]
    /// (spec-0022) — redstone now keeps only the trigger — but kept meaningful
    /// so existing campaigns build unchanged. Optional since spec-0022; a trap
    /// must declare `effect`, `payload`, or both (`DW0440`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effect: Option<TrapEffect>,
    /// The **command payload** (spec-0022): an ordered effect list in the same
    /// vocabulary quests use, run when the trigger fires. This is where a trap's
    /// consequence lives now — the compiler owns the detection tick and the
    /// effect vocabulary, so a trap's payload is authored like any other effect
    /// bundle rather than built out of dust and repeaters. Expressiveness moves
    /// from "what dust can carry" to "what the effect vocabulary can say":
    /// `volley` and `collapse` (spec-0022's trap verbs) join `damage-players`,
    /// `play-sound`, `narrate`, `set-flag` and `spawn-wave`.
    ///
    /// Empty = a pure spec-0011 redstone trap, which emits exactly what it
    /// emitted before (byte-identical).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub payload: Vec<QuestEffect>,
    /// How dangerous the trap is. A `lethal` trap on the forced critical path
    /// carries the completability obligation (`DW0342`); `harmful`/`nonlethal`
    /// carry none. Defaults to `harmful`.
    #[serde(default)]
    pub lethality: Lethality,
    /// Optional disarm affordance (quest-coupling): an anchor the player acts on to
    /// turn the trap off — setting a flag and emptying the dispenser — before the
    /// trap cell is forced.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disarm: Option<TrapDisarm>,
    /// Whether the trap re-arms after firing. `once` = single-shot (fires, then
    /// spent — the survivability path); `rearm` = re-fires each trigger (default).
    #[serde(default)]
    pub reset: TrapReset,
    /// Flags that must be set before the trap is considered active (mirrors
    /// [`EnvTrigger::requires_flags`]). Default empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_flags: Vec<FlagId>,
    /// Negative flag gate (DSL v0.6): the trap is considered inactive while ANY
    /// listed flag is set (mirrors [`EnvTrigger::forbids_flags`]). Default empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbids_flags: Vec<FlagId>,
    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
    /// hold for this gate to be open. The third field of the one gate, carried by
    /// every gate consumer — never by the verb that first wanted it. Default
    /// empty, so a pre-0.10 campaign is byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_state: Vec<StateCompare>,
}

impl Trap {
    /// `(item, count)` if this trap declares a legacy `dispense` effect.
    pub fn dispense(&self) -> Option<(&str, u32)> {
        match &self.effect {
            Some(TrapEffect::Dispense { item, count }) => Some((item.as_str(), *count)),
            None => None,
        }
    }

    /// Whether this trap is `lethal` (carries the `DW0342` obligation on the
    /// forced critical path).
    pub fn is_lethal(&self) -> bool {
        matches!(self.lethality, Lethality::Lethal)
    }
}

/// The mechanism that springs a [`Trap`] (DSL v0.6, spec-0011). All three are
/// redstone-native — the hardware fires without any command — so the compiler
/// emits no detection for them; it only models the trigger cell as a hazard and
/// fills the dispenser payload. (`approach`, the compiler-detected v0.4 primitive,
/// is deliberately *not* a trap trigger: it is already fully expressible as an
/// [`EnvTrigger`], so admitting it here would only duplicate that surface.)
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum TrapTrigger {
    /// A pressure plate: any entity stepping on the cell. Auto-rearms on step-off.
    PressurePlate,
    /// A tripwire line: any entity crossing it. Auto-rearms.
    Tripwire,
    /// A trapped chest: a *player opening it* (comparator pulse). The only
    /// player-distinct trigger — a controlled mob cannot spring it.
    TrappedChest,
}

impl TrapTrigger {
    /// The kebab tag (`pressure-plate` / `tripwire` / `trapped-chest`).
    pub fn kind(&self) -> &'static str {
        match self {
            TrapTrigger::PressurePlate => "pressure-plate",
            TrapTrigger::Tripwire => "tripwire",
            TrapTrigger::TrappedChest => "trapped-chest",
        }
    }

    /// Whether `block` (an id, with or without its blockstate) is the hardware
    /// this trigger kind names: the block the party sees and springs. A plate
    /// is any `*_pressure_plate`, a tripwire is the string itself
    /// (`minecraft:tripwire`, not the hook), a trapped chest is
    /// `minecraft:trapped_chest`.
    pub fn is_trigger_block(&self, block: &str) -> bool {
        let id = block.split('[').next().unwrap_or(block);
        match self {
            TrapTrigger::PressurePlate => id.ends_with("_pressure_plate"),
            TrapTrigger::Tripwire => id == "minecraft:tripwire",
            TrapTrigger::TrappedChest => id == "minecraft:trapped_chest",
        }
    }

    /// The block [`TrapTrigger::is_trigger_block`] accepts, as a refusal names it.
    pub fn trigger_block_name(&self) -> &'static str {
        match self {
            TrapTrigger::PressurePlate => "a pressure plate (`minecraft:*_pressure_plate`)",
            TrapTrigger::Tripwire => "a tripwire string (`minecraft:tripwire`)",
            TrapTrigger::TrappedChest => "a trapped chest (`minecraft:trapped_chest`)",
        }
    }
}

/// What a [`Trap`] does when sprung (DSL v0.6, spec-0011). Externally tagged so a
/// future effect adds a variant; a non-`dispense` key (e.g. `tnt`,
/// `release-falling-block`, `crusher`) is an unknown variant → `DW0100`, keeping
/// block-destroying and unmodeled effects out of the schema by construction
/// (spec-0011 non-goals — no hardware the compiler cannot model reaches a world).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum TrapEffect {
    /// Load the prefab's pre-wired dispenser with `count` of `item` (arrows, tipped
    /// arrows, splash potions). The redstone fires it; terrain is untouched
    /// (spec-0011 "primary lethal"). The item is round-tripped into the dispenser
    /// `Items` NBT — a deterministic, static payload.
    Dispense {
        /// Vanilla item id (validated against the pinned 1.21.11 registry, `DW0341`).
        item: String,
        /// How many to load into the dispenser stack.
        count: u32,
    },
}

/// How dangerous a [`Trap`] is (DSL v0.6, spec-0011). Only `lethal` carries the
/// forced-critical-path completability obligation (`DW0342`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Lethality {
    /// Can kill a full-health player — carries the `DW0342` obligation on the path.
    Lethal,
    /// Hurts but is not designed to kill (the default).
    #[default]
    Harmful,
    /// Cosmetic / trivial (a stumble, a scare).
    Nonlethal,
}

/// Whether a [`Trap`] re-arms after firing (DSL v0.6, spec-0011).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum TrapReset {
    /// Fires once, then is spent — the survivability path for a forced lethal trap
    /// (respawn-safe with `keep_inventory`, non-re-triggering on the walk back; no
    /// soft-loop).
    Once,
    /// Re-fires every time the trigger is met (default). A forced lethal `rearm`
    /// trap must be avoidable or disarmable, else `DW0342`.
    #[default]
    Rearm,
}

/// A [`Trap`]'s disarm affordance (DSL v0.6, spec-0011): the player acts on the
/// `via` anchor (an interaction the compiler emits, reusing the v0.4 interaction
/// entity) to turn the trap off — setting `sets_flag` and emptying the dispenser —
/// before the trap cell is forced. Discharges the `DW0342` obligation when the
/// affordance is reachable ahead of the trap without crossing it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TrapDisarm {
    /// The anchor the player interacts with to disarm.
    pub via: AnchorId,
    /// The flag set when the trap is disarmed (a new flag this trap produces; other
    /// objectives/triggers may read it via `requires_flags`).
    pub sets_flag: FlagId,
}

/// A stage-5 **timed gate** (spec-0016 §4): a gate region driven by a
/// deterministic open/close clock, so passage is a timing read rather than a
/// permanent state.
///
/// **The proof is deliberately NOT all-phase passability** — a gate that
/// punishes bad timing is the entire point. What the
/// compiler requires is that the gate is *readable*: the set of entry phases from
/// which a walking player clears the span before it shuts must cover **≥ 20% of
/// the cycle** (`DW0378`). Below that it is a coin flip, not a skill, and no
/// amount of learning the level makes it fair.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TimedGate {
    /// Unique timed-gate id (`timed-gate/<kebab>`).
    pub id: TimedGateId,
    /// The gate anchor the clock drives. Its prefab metadata must declare a fill
    /// `block` (`DW0343`), the same requirement `close-gate` and `shortcut` have.
    pub gate: AnchorId,
    /// Ticks the gate stays OPEN each cycle (> 0).
    pub open_ticks: u32,
    /// Ticks the gate stays CLOSED each cycle (> 0).
    pub closed_ticks: u32,
    /// Ticks after world init before the first open window begins (default 0) —
    /// how two gates in the same room are put out of step with each other. Must
    /// be less than the full cycle.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub phase: u32,
    /// Whether the gate **kills** a player caught inside its region when it
    /// shuts (spec-0016 §4 addendum). A portcullis
    /// that merely shoves you aside teaches nothing; mistiming the crossing is
    /// supposed to be a death you learn from, which is the whole point of §4's
    /// ≥20%-of-cycle window proof — the window is fair, so the penalty can be
    /// absolute.
    ///
    /// This is a real judgement issued by command on the closing tick, not
    /// suffocation: vanilla's in-wall damage is slow, gear-dependent and
    /// escapable, so it would make the portcullis a suggestion. `damage` at the
    /// closing edge is exact and unarguable.
    ///
    /// **Defaults to `false`**, so every campaign authored before this field
    /// existed compiles byte-identically; a delve opts its portcullis in.
    #[serde(default, skip_serializing_if = "is_false")]
    pub crush: bool,
    /// Optional **disarm** affordance (souls dossier §5.2): the third
    /// rung of the hazard ladder — readable, avoidable, and finally *disable-able*.
    /// The real games' best timed hazards can be removed for good (Smouldering
    /// Lake's ballista, the Fringefolk chariot); a clock the party can only ever
    /// dance with is one rung short of the vocabulary.
    ///
    /// Interacting with the affordance suppresses the clock **permanently, with
    /// the gate resting OPEN** — a jammed portcullis stays up. Permanence is
    /// structural exactly as a `shortcut`'s is: no emitted function ever re-arms
    /// the clock, and `DW0389` refuses a campaign that spells a re-seal.
    ///
    /// **Defaults to absent**, so every campaign authored before this field
    /// existed compiles byte-identically; a delve opts its portcullis in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disarm: Option<TimedGateDisarm>,
}

/// A [`TimedGate`]'s disarm affordance (souls dossier §5.2) — the
/// exact shape a trap's [`TrapDisarm`] takes, and deliberately so: one affordance
/// grammar for every mechanism the party can switch off.
///
/// The player acts on the `via` anchor (a compiler-emitted interaction entity
/// plus its visible hardware, `DW0420`) to jam the gate. The clock stops with the
/// span cleared, `sets_flag` is raised party-wide, and nothing in the delve can
/// put the gate back.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct TimedGateDisarm {
    /// The anchor the player interacts with to jam the gate. Must be an anchor
    /// some area's prefab provides, and never the gate anchor itself — the
    /// mechanism belongs beside the doorway, not inside the span that crushes.
    pub via: AnchorId,
    /// The flag set when the gate is disarmed (a new flag this gate produces;
    /// other objectives/triggers may read it via `requires_flags`).
    pub sets_flag: FlagId,
}

/// serde `skip_serializing_if` helper: skip a `0`.
fn is_zero(n: &u32) -> bool {
    *n == 0
}

/// A stage-5 **ambush** (spec-0016 §3) — one declaration for a beat that
/// otherwise takes a deferred actor set plus a hand-wired trigger.
///
/// **`telegraph` is optional, and that is a design ruling, not an oversight.**
/// The un-telegraphed ambush — the shove off the cliff you
/// could not have known about — is core souls vocabulary: 初见杀 is how the level
/// teaches. The engine does not sand that edge off.
///
/// What the engine *does* owe the player is **counterplay on the retry**: having
/// died once, an informed player must have something to do about it. Determinism
/// guarantees the second attempt meets the same ambushers in the same cells; the
/// compiler adds the missing half — `DW0376` proves the trigger cell is not a
/// sealed pocket, i.e. that with every ambusher standing where it will stand,
/// a route out still exists (a retreat, luring ground, a positioning line).
/// Dying uninformed is a lesson; dying with no play available is a broken beat.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Ambush {
    /// Unique ambush id (`ambush/<kebab>`).
    pub id: AmbushId,
    /// The anchor the trigger watches — the corner, doorway or ledge the player
    /// walks into.
    pub at: AnchorId,
    /// The stage-5 actors that spring (1..N). Each is summoned at its own
    /// declared anchor and immediately unleashed to real AI.
    pub actors: Vec<ActorId>,
    /// What springs it (`approach{range}` / `strike` / `use`), exactly the v0.4
    /// environment-trigger vocabulary.
    pub trigger: TriggerOn,
    /// The **optional** tell, fired at the trigger before the ambushers exist:
    /// a sound, a shadow, a line of narration. Empty = un-telegraphed, which is
    /// fully legal.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub telegraph: Vec<QuestEffect>,
    /// What the spring does to the story (DSL v0.8, spec-0025; required at
    /// 0.8.0, `DW0481`).
    ///
    /// **The declaration lives here because this is the object the author
    /// wrote.** An ambush desugars into a `spawn-actor` plus an `unleash-actor`
    /// per listed actor, and every one of those is a story node `DW0481` demands
    /// a `happening` from — on effects the author never wrote and cannot reach.
    /// So for as long as this field did not exist, an `ambushes[]` entry could
    /// not compile at 0.8.0 or above at all: declared in the schema, accepted by
    /// the schema check, and refused at validation with a prescription naming a
    /// field that was not there. Nothing caught it because no campaign and no
    /// fixture had ever written an ambush at a version where the obligation was
    /// live — which is the case spec-0039 exists to make impossible.
    ///
    /// An ambush is **one** beat, not `2N` of them: the ambushers appearing and
    /// coming at you is a single dramatic moment, so one declaration covers the
    /// whole spring. [`Self::to_trigger`] stamps it onto the first generated
    /// `spawn-actor` so the chronicle carries the line at the right position,
    /// and `branch::check_happenings` reads the obligation off the ambush rather
    /// than off the beats derived from it. Repeating it on all `2N` is the
    /// obvious alternative and it is wrong twice over: the chronicle would gain
    /// `N` duplicate lines, and `DW0485` would see one subject act repeatedly
    /// and be right to call it a contradiction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub happening: Option<Happening>,
}

impl Ambush {
    /// The environment trigger this ambush desugars to (spec-0016 §3): a
    /// one-shot trigger at `at` whose effects are the telegraph, then a
    /// `spawn-actor` + `unleash-actor` per listed actor, in declared order.
    ///
    /// This is the **single** expansion authority. Every consumer — validation,
    /// the l10n inventory, the flag/wave producer scans, nav, emission — reads
    /// triggers through [`QuestsContent::all_triggers`], so the sugar cannot
    /// diverge from a hand-written equivalent, and an ambush is exactly as
    /// debuggable as the trigger an author would otherwise type.
    pub fn to_trigger(&self) -> EnvTrigger {
        let mut effects = self.telegraph.clone();
        for (i, a) in self.actors.iter().enumerate() {
            effects.push(QuestEffect {
                when: None,
                // The ambush declaration, on the beat where the spring becomes
                // real. Only the FIRST, for the reason the field documents: one
                // ambush is one beat, and stamping the line on every generated
                // effect would pad the chronicle and trip `DW0485`.
                happening: if i == 0 { self.happening.clone() } else { None },
                audience: None,
                within: None,
                verb: Verb::SpawnActor { actor: a.clone() },
            });
        }
        for a in &self.actors {
            effects.push(Verb::UnleashActor { actor: a.clone() }.into());
        }
        EnvTrigger {
            id: TriggerId(format!(
                "trigger/{}",
                crate::l10n::local_id(self.id.as_str())
            )),
            at: Some(self.at.clone()),
            on: self.trigger.clone(),
            requires_flags: Vec::new(),
            forbids_flags: Vec::new(),
            requires_state: Vec::new(),
            once: true,
            // An ambush is a party beat by construction — it springs actors at
            // the room, not a reply to the one who walked in.
            audience: TriggerAudience::Party,
            effects,
        }
    }
}

/// A stage-5 **shortcut door** (spec-0016 §2) — the souls loop-back.
///
/// The owner's definition of the pattern: between two rest points there are two
/// routes. The **short** one starts sealed and holds nothing; the **long** one is
/// full of enemies and mechanisms. You earn the far side the hard way, pull one
/// mechanism, and the short route opens **forever**. That moment is the design.
///
/// The compiler owns three obligations, none of them optional:
/// 1. the `unlock` affordance is reachable while the gate is still sealed — the
///    long route genuinely exists (`DW0373`);
/// 2. opening the gate genuinely shortens the trip across it — a shortcut that
///    pays nothing is a leak, not a shortcut (`DW0360`);
/// 3. permanence is **structural**: no `close-gate` may target a shortcut gate
///    (`DW0372`). There is no re-sealing verb to reach for.
///
/// `close-gate` on a NON-shortcut gate (the point-of-no-return staging beat) is
/// untouched by this — the two verbs are deliberately disjoint.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Shortcut {
    /// Unique shortcut id (`shortcut/<kebab>`).
    pub id: ShortcutId,
    /// The gate anchor this shortcut opens. Sealed from world-load (the prefab
    /// carries the physical fill), and its metadata must declare the fill `block`
    /// the compiler clears — the same requirement `close-gate` has.
    pub gate: AnchorId,
    /// The FAR-side anchor whose interaction fires the permanent open. The
    /// compiler summons the affordance there and polls it, reusing the v0.4
    /// interaction-entity `use` primitive.
    pub unlock: AnchorId,
    /// Effects fired once, when the shortcut opens — the bar lifting, the
    /// elevator descending, the sound of a door you will never have to earn
    /// again. Emitted server-source-safe (the poll lives on the tick).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub on_unlock: Vec<QuestEffect>,
}

/// A stage-5 environment trigger (DSL v0.4). Emission uses vanilla-intended
/// primitives only (spec-0008 §7): `strike`/`use` read a `minecraft:interaction`
/// entity's attack/interaction records; `approach` is a `distance` selector on
/// the tick. Look-at / break-attempt detection is excluded on principle (no
/// vanilla primitive).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct EnvTrigger {
    /// Unique trigger id (`trigger/<kebab>`).
    pub id: TriggerId,
    /// The anchor this trigger watches. Required for `strike` / `use` /
    /// `approach`, which watch a *place*; **absent** for `strike-npc` (DSL
    /// v0.6), which watches a *character* and names it in `on.npc` instead —
    /// there is no cell for the author to supply and no cell the compiler
    /// would use. Either mismatch is `DW0194`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at: Option<AnchorId>,
    /// The event that fires it.
    pub on: TriggerOn,
    /// Flags that must be set before the trigger can fire (DSL v0.4).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_flags: Vec<FlagId>,
    /// Negative flag gate (DSL v0.6): the trigger is
    /// **suppressed** while ANY listed flag is set (by any player — flags are
    /// campaign state). The dual of `requires_flags`, so an "armed between two
    /// story beats" trigger needs no re-arm plumbing: e.g. a strike-the-giant
    /// retaliation trigger with `requires_flags: [flag/sealed]` and
    /// `forbids_flags: [flag/asleep]` arms when the cave seals and stands down
    /// the moment the wake beat takes over.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbids_flags: Vec<FlagId>,
    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
    /// hold for this gate to be open. The third field of the one gate, carried by
    /// every gate consumer — never by the verb that first wanted it. Default
    /// empty, so a pre-0.10 campaign is byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_state: Vec<StateCompare>,
    /// Fire at most once (default `true`, mirroring objective completion). Set
    /// `false` to allow re-firing every time the condition is met.
    #[serde(default = "default_true")]
    pub once: bool,
    /// **Who the trigger's effects address** (DSL v0.11). Default
    /// [`TriggerAudience::Party`], so every campaign written before this field
    /// existed is byte-identical.
    ///
    /// A trigger is two different things depending on what the author means by
    /// it. A pressure plate that opens a gate and narrates the room is a **party
    /// beat**: everyone should see it, and it does not matter who stepped on the
    /// plate. A barred door that answers *"this cannot be opened from this
    /// side"* is a **reply to one person**: broadcasting it tells four players
    /// about a door three of them are nowhere near.
    ///
    /// Until this field the second was inexpressible, which is why the two verbs
    /// that needed it (`close-gate`'s seal answer, and nothing at all for a
    /// shortcut door) grew their own private reply machinery instead. The
    /// capability belongs to the press, not to the verb.
    #[serde(default, skip_serializing_if = "TriggerAudience::is_party")]
    pub audience: TriggerAudience,
    /// Effects fired when the trigger matches.
    pub effects: Vec<QuestEffect>,
}

impl EnvTrigger {
    /// The anchor this trigger watches, if it watches a place at all. `None`
    /// for `strike-npc`, whose target is a character.
    pub fn at_anchor(&self) -> Option<&str> {
        self.at.as_ref().map(|a| a.as_str())
    }

    /// Whether this trigger's bundle is addressed to the player who pressed it.
    pub fn addresses_presser(&self) -> bool {
        self.audience == TriggerAudience::Presser
    }
}

/// Who an [`EnvTrigger`]'s effects address (DSL v0.11).
///
/// **This is a dispatch decision, not a cosmetic one.** A `party` trigger is
/// polled on the tick with no executor, so `@s` does not exist and every
/// player-facing command addresses `@a`. A `presser` trigger is dispatched by a
/// `minecraft:player_interacted_with_entity` advancement — the one vanilla
/// primitive that runs a function *as the player who clicked* — so `@s` is the
/// presser and the bundle addresses them alone.
///
/// That primitive exists for **right-clicks only**. Vanilla records a left-click
/// on an interaction entity in NBT (which names a UUID no command can become) and
/// offers no criterion for it, so `presser` on a `strike` is refused (`DW0427`)
/// rather than approximated: per CLAUDE.md's no-hack rule, a capability with no
/// vanilla primitive under it is excluded, never faked downstream.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum TriggerAudience {
    /// The whole party (the default, and what every trigger did before v0.11).
    #[default]
    Party,
    /// The one player whose click fired it.
    Presser,
}

impl TriggerAudience {
    /// Serde skip predicate: the default needs no field on the wire, so a
    /// canonical round-trip of a pre-0.11 campaign is byte-identical.
    fn is_party(&self) -> bool {
        *self == TriggerAudience::Party
    }
}

/// The event an [`EnvTrigger`] watches (DSL v0.4).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "on", rename_all = "kebab-case", deny_unknown_fields)]
pub enum TriggerOn {
    /// The player attacks (left-clicks) the interaction entity at the anchor.
    Strike,
    /// The player uses (right-clicks) the interaction entity at the anchor.
    Use,
    /// The player comes within `range` blocks of the anchor.
    Approach {
        /// Approach radius (blocks).
        range: u32,
    },
    /// The player attacks (left-clicks) an **NPC's body** (DSL v0.6).
    ///
    /// The place-based [`TriggerOn::Strike`] cannot express "hit the giant": it
    /// summons its own `minecraft:interaction` at a *cell*, and a large NPC's
    /// body eclipses that cell (`DW0359`), so the click never reaches the
    /// trigger — the owner's island round-7 finding. This form has no cell. It
    /// rides the interaction entity the NPC already owns, which is the entity a
    /// click on that NPC reaches by construction.
    ///
    /// Right-click and left-click stay separate all the way down: a
    /// `minecraft:interaction` records them in two distinct NBT fields
    /// (`interaction` and `attack`), so the NPC's dialogue keeps the right-click
    /// and this trigger takes the left-click, on one shared hitbox.
    StrikeNpc {
        /// The NPC (stage-2 ref) whose body is the target.
        npc: NpcId,
    },
    /// The player attacks (left-clicks) an **assembly's hitbox** (spec-0082).
    ///
    /// The exact shape of [`TriggerOn::StrikeNpc`]: no `at`, because the target
    /// is an object with a hitbox of its own, and the trigger rides it. Melee
    /// only — the hitbox is a `minecraft:interaction`, and an arrow passes
    /// through one without writing its `attack` record (spec-0082 §8 row 5).
    /// `once: false` with an `add-state` is how a hit count is built.
    StrikeAssembly {
        /// The assembly (stage-5 `assemblies` ref) whose hitbox is the target.
        assembly: AssemblyId,
    },
}

impl TriggerOn {
    /// The kebab tag (`strike` / `use` / `approach` / `strike-npc` /
    /// `strike-assembly`).
    pub fn kind(&self) -> &'static str {
        match self {
            TriggerOn::Strike => "strike",
            TriggerOn::Use => "use",
            TriggerOn::Approach { .. } => "approach",
            TriggerOn::StrikeNpc { .. } => "strike-npc",
            TriggerOn::StrikeAssembly { .. } => "strike-assembly",
        }
    }

    /// Whether this event needs an `at` anchor — true for everything that
    /// watches a place, false for `strike-npc` and `strike-assembly`, which
    /// watch an object that carries its own hitbox.
    pub fn needs_anchor(&self) -> bool {
        !matches!(
            self,
            TriggerOn::StrikeNpc { .. } | TriggerOn::StrikeAssembly { .. }
        )
    }

    /// The assembly whose hitbox this event watches (`strike-assembly` only).
    pub fn assembly_target(&self) -> Option<&AssemblyId> {
        match self {
            TriggerOn::StrikeAssembly { assembly } => Some(assembly),
            _ => None,
        }
    }

    /// The NPC whose body this event watches (`strike-npc` only).
    pub fn npc_target(&self) -> Option<&NpcId> {
        match self {
            TriggerOn::StrikeNpc { npc } => Some(npc),
            _ => None,
        }
    }
}

/// A combat wave (DSL v0.3): a bundle of mobs spawned at an anchor and slain to
/// complete a `kill` objective. Emission (spec-0002): a `spawn-wave` effect
/// summons the mobs tagged `dw_wave_<id>` (AI enabled — they fight); a
/// `player_killed_entity` advancement per tag decrements a scoreboard countdown,
/// and the `kill` objective completes when the count reaches zero.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Wave {
    /// Unique wave id.
    pub id: WaveId,
    /// The anchor the wave's mobs spawn at.
    pub anchor: AnchorId,
    /// The mobs that make up the wave (1..N).
    pub mobs: Vec<WaveMob>,
    /// Re-seat this wave every time the party rests at (or respawns from) a
    /// bonfire (spec-0016 §1) — the souls contract: progress is kept, the
    /// enemies come back. The compiler kills any survivor carrying the wave tag
    /// and re-runs the wave's own spawn function, so the room is restored to its
    /// authored composition and spawn cells.
    ///
    /// Inert without a `bonfire` in the campaign, which is a compile error
    /// (`DW0370`) rather than a silent no-op.
    #[serde(default, skip_serializing_if = "is_false")]
    pub respawns_on_rest: bool,
    /// Tower-defense lane routing (spec-0016 §6): march this wave along a
    /// waypoint polyline while distant, hand it to native AI the instant a
    /// player is inside `aggro_radius`. Absent = today's behaviour (spawn and
    /// stand), byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lane: Option<WaveLane>,
    /// Where the wave's mobs materialize (spec-0016 §6). Absent =
    /// [`WaveSummon::Anchor`], the pre-0.6 behaviour: standable cells around the
    /// wave `anchor`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summon: Option<WaveSummon>,
    /// How hard this encounter is *meant* to be (DSL v0.7, spec-0023). Absent =
    /// [`EncounterTier::Ordinary`], byte-identical to every pre-0.7 campaign.
    ///
    /// This is a **declaration, not a knob**: the compiler never scales content
    /// from it (spec-0023 "Out of scope"). It exists because the validation
    /// ladder's inverted floor gate needs to know which fights the content
    /// *claims* are hard — an `elite`/`boss` encounter the unassisted bot beats
    /// on its first attempt is reported as too easy for its billing. Marking it
    /// is how the author opts into that scrutiny; the alternative — inferring
    /// "elite" from how tuned a stack looks — is exactly the downstream folklore
    /// CLAUDE.md's no-hack rule forbids.
    ///
    /// **It does reach emission in exactly one place** (spec-0016 §1): in a
    /// campaign with a `bonfire`, a billed `elite`/
    /// `boss` wave that does not declare `respawns_on_rest` is refreshed by a
    /// rest *while it is still standing* — deleted and re-seated at full count
    /// and full health, so chipping it down one life at a time is never a path.
    /// Beat it and it stays beaten. `DW0499` forbids billing a wave `boss` and
    /// `respawns_on_rest` at once.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tier: Option<EncounterTier>,
    /// A health bar over this wave's bodies (DSL v0.31, spec-0073): a named bar
    /// over their total health, drawn for every player within `range` blocks of a
    /// live one. Absent = no bar, byte-identical. Declared, never derived from
    /// `tier`; a `boss`-billed wave without one is advised (`DW0912`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health_bar: Option<crate::healthbar::HealthBar>,
    /// What happens each time a player is credited with killing one of this
    /// wave's bodies (spec-0074) — effect root R9, the same
    /// [`OnKill`] an actor declares. Absent = no bundle, and the
    /// wave's emission is byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_kill: Option<OnKill>,
}

/// What happens each time a body of this fight is killed (spec-0074): the
/// `on_kill` of a wave or an actor.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct OnKill {
    /// Whether a body that comes back pays again. Required where the fight comes
    /// back after the party has met it — a bonfire re-seats it, or the beat that
    /// seats it can fire more than once (`DW0915`); left off where it does not,
    /// and `every-kill` there is refused as inert (`DW0914`). No default: whether
    /// an economy can be farmed is the creator's judgement.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fires: Option<KillFires>,
    /// The effects, run as the credited player for each credited kill. Every verb
    /// an `on_objective_complete` bundle accepts, each gated by its own `when`.
    #[schemars(length(min = 1))]
    pub effects: Vec<QuestEffect>,
}

/// Whether a body that comes back after a rest pays again (spec-0074 §4).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum KillFires {
    /// Over the whole delve the fight pays at most once per body it seats — the
    /// wave's body count, or once for an actor. A re-seat does not renew it.
    FirstKill,
    /// Every credited kill pays, however many times the fight is re-seated.
    EveryKill,
}

impl KillFires {
    /// The kebab token, as it appears in the DSL.
    pub fn token(self) -> &'static str {
        match self {
            KillFires::FirstKill => "first-kill",
            KillFires::EveryKill => "every-kill",
        }
    }
}

/// What a wave is billed as (DSL v0.7, spec-0023). Consumed by the validation
/// ladder (the run's combat plan) and — since spec-0016 §1's undefeated re-seat
/// — by one emission site: a bonfire refreshes a billed wave that is still
/// standing. Nothing about the encounter itself is scaled from it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum EncounterTier {
    /// Trash / pressure. No floor expectation: a bot that wins it cold proves
    /// nothing either way. The default.
    #[default]
    Ordinary,
    /// A set-piece the content bills as a hard fight (spec-0016's optional-elite
    /// and spawn-and-unleash vocabulary).
    Elite,
    /// A campaign's named fight. Same floor rule as `elite`; the distinction is
    /// for the run report a human reads.
    Boss,
}

impl EncounterTier {
    /// The kebab tag, as it appears in the DSL and in the emitted combat plan.
    pub fn token(self) -> &'static str {
        match self {
            EncounterTier::Ordinary => "ordinary",
            EncounterTier::Elite => "elite",
            EncounterTier::Boss => "boss",
        }
    }

    /// Does the inverted floor gate (spec-0023) apply to this tier? A fight the
    /// content bills as hard carries an expectation the bot can measure; an
    /// ordinary one does not.
    pub fn has_floor_expectation(self) -> bool {
        matches!(self, EncounterTier::Elite | EncounterTier::Boss)
    }
}

/// Where a wave's mobs materialize (spec-0016 §6).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum WaveSummon {
    /// Standable cells around the wave `anchor`, nearest first — the pre-0.6
    /// behaviour and the default.
    Anchor,
    /// **Spirit-summoned at the edge of perception**:
    /// each mob appears on the ring at its own `attributes.follow_range` from
    /// the wave `anchor`, so it acquires a target the instant it exists and
    /// closes under pure native AI. Species without patrol AI never march a
    /// lane; this is what they do instead — never a spawn on top of the party,
    /// never a mob that brushes past.
    ///
    /// With this mode the wave `anchor` is the **defended point** (what the ring
    /// is drawn around), not the spawn point. Each mob stack must declare its
    /// own `attributes.follow_range` (`DW0385`) — the ring radius is authored,
    /// never guessed from a vanilla defaults table the compiler cannot verify.
    AggroEdge,
}

/// Tower-defense lane routing for a wave (spec-0016 §6), built on vanilla's
/// **Raider patrol system** — the intended primitive, live-verified on 1.21.11
/// (`docs/notes/td-routing-spike.md`).
///
/// The squad spawns `Patrolling:1b` with one `PatrolLeader:1b` and a snake_case
/// `patrol_target` int-array; a compiler-emitted clock walks the shared waypoint
/// index forward, and per mob a player-proximity check releases `Patrolling:0b`.
/// From that instant the mob is a plain native hostile. "Combat preempts
/// routing" is engine semantics — vanilla's patrol goal is hard-gated on having
/// no target — so the owner's rule (march while distant, fight with NATIVE AI
/// once aggroed, never brush past) falls out of the primitive unforced.
///
/// Lanes are raider-family only (`DW0382`), squad ≥ 2 (`DW0383`), and a lane
/// pillager must keep its crossbow (`DW0384`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WaveLane {
    /// The lane polyline, in march order: anchors some area's prefab provides.
    /// At least one; consecutive legs (counting the wave `anchor` as the origin)
    /// must be more than 10 blocks apart — vanilla re-rolls a patrol target
    /// within 10 blocks of arrival, so a tighter lane is a lane the engine
    /// quietly stops following (`DW0386`).
    pub waypoints: Vec<AnchorId>,
    /// The release radius, in blocks: the compiler sets every lane mob's
    /// `follow_range` attribute to exactly this and releases `Patrolling:0b`
    /// at the same distance. The two MUST be equal — a patrolling raider that
    /// targets a player it cannot engage holds ground instead of marching, so a
    /// per-mob `attributes.follow_range` that disagrees is `DW0381`.
    pub aggro_radius: u32,
}

/// One mob stack in a [`Wave`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WaveMob {
    /// Vanilla entity id, validated against the pinned 1.21.11 registry.
    pub entity: String,
    /// How many to spawn.
    pub count: u32,
    /// Optional custom name (shown above the mob).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Optional attribute overrides (DSL v0.4), emitted as 1.21.11 attribute
    /// components. Enables e.g. a weakened live warden as a survivable stealth
    /// threat. Omitted = vanilla defaults.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<MobAttributes>,
    /// Optional permanent, ambient status effects (DSL v0.4).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<MobEffect>,
    /// Optional worn/held equipment (DSL v0.6). A helmet is the
    /// sanctioned fix for daylight-burning undead — never
    /// `set-time`. Item ids validate against the pinned 1.21.11 item registry
    /// (`DW0143`, the give-item family); every emitted slot carries drop
    /// chance 0 so players can never farm wave gear (no-grind constitution).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub equipment: Option<MobEquipment>,
    /// What this mob leaves behind when it dies (DSL v0.9). Only an `elite`/`boss` wave may declare it (`DW0491`)
    /// — an ordinary mob's kit is never farmable. Empty = drop chance 0 on
    /// every slot.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub drops: Vec<MobDrop>,
}

/// Worn/held equipment for a wave mob (DSL v0.6). Each field is a vanilla item
/// id for the matching vanilla equipment slot; an unset slot stays empty —
/// except `main_hand`, where the compiler's armed-mob default (skeleton bow,
/// wither-skeleton sword) still applies unless overridden. Emitted as the
/// component-era `equipment`/`drop_chances` summon NBT (1.21.11 silently
/// ignores legacy `ArmorItems`/`HandItems` on `/summon`), all drop chances 0.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MobEquipment {
    /// Head slot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head: Option<EquipItem>,
    /// Chest slot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chest: Option<EquipItem>,
    /// Legs slot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub legs: Option<EquipItem>,
    /// Feet slot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feet: Option<EquipItem>,
    /// Main-hand slot. Overrides the compiler's armed-mob default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub main_hand: Option<EquipItem>,
    /// Off-hand slot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub off_hand: Option<EquipItem>,
    /// Body slot: horse armour, wolf armour, a llama's carpet, a nautilus's
    /// armour, a happy ghast's harness (spec-0067). Shown only on a body whose
    /// entity type draws it (`DW0898`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<EquipItem>,
    /// Saddle slot (spec-0067). Shown only on a body whose entity type draws a
    /// saddle (`DW0898`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub saddle: Option<EquipItem>,
}

impl MobEquipment {
    /// Every slot as `(dsl_field_name, piece)`, in [`EquipSlot::ALL`]'s order —
    /// the single iteration source for validation paths and emission.
    pub fn slots(&self) -> [(&'static str, Option<&EquipItem>); EquipSlot::ALL.len()] {
        EquipSlot::ALL.map(|s| (s.field(), self.filled(s)))
    }

    /// Every slot as `(slot, piece)`, in [`EquipSlot::ALL`]'s order.
    pub fn pieces(&self) -> [(EquipSlot, Option<&EquipItem>); EquipSlot::ALL.len()] {
        EquipSlot::ALL.map(|s| (s, self.filled(s)))
    }

    /// The piece this equipment declaration puts in `slot`, if any. The single
    /// question a `drops[]` `slot` entry asks: a mob can only drop a piece it
    /// actually wears (`DW0490`).
    pub fn filled(&self, slot: EquipSlot) -> Option<&EquipItem> {
        match slot {
            EquipSlot::Head => self.head.as_ref(),
            EquipSlot::Chest => self.chest.as_ref(),
            EquipSlot::Legs => self.legs.as_ref(),
            EquipSlot::Feet => self.feet.as_ref(),
            EquipSlot::MainHand => self.main_hand.as_ref(),
            EquipSlot::OffHand => self.off_hand.as_ref(),
            EquipSlot::Body => self.body.as_ref(),
            EquipSlot::Saddle => self.saddle.as_ref(),
        }
    }
}

/// One vanilla equipment slot, named exactly as the [`MobEquipment`] field that
/// fills it. The DSL name and the summon-NBT key differ (`main_hand` vs
/// `mainhand`), so both live here and nowhere else.
///
/// **The set is the pinned game's equipment-slot set** (spec-0067 §2), a
/// [`crate::metrics::Provenance::VanillaRule`]: the eight values the
/// `minecraft:equippable` component's `slot` field takes, per the Minecraft
/// Wiki page *Data component format/equippable* for Java 1.21.11, which are the
/// serialised names of the client's `EquipmentSlot` enum. The pinned item data
/// is the cross-check, not the source: every `slot` value an item declares is
/// asserted to be one of these, and no item declares `mainhand`, because a hand
/// takes anything.
#[derive(
    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum EquipSlot {
    /// Head slot.
    Head,
    /// Chest slot.
    Chest,
    /// Legs slot.
    Legs,
    /// Feet slot.
    Feet,
    /// Main-hand slot.
    MainHand,
    /// Off-hand slot.
    OffHand,
    /// Body slot (horse armour, wolf armour, carpet, harness).
    Body,
    /// Saddle slot.
    Saddle,
}

impl EquipSlot {
    /// Every slot, in emission order: the two hands, the four armour slots,
    /// then `body` and `saddle`. The one enumeration every slot list derives
    /// from — `MobEquipment::slots()`, the summon `equipment` / `drop_chances`
    /// compounds and the drop-strip line.
    pub const ALL: [EquipSlot; 8] = [
        EquipSlot::MainHand,
        EquipSlot::OffHand,
        EquipSlot::Head,
        EquipSlot::Chest,
        EquipSlot::Legs,
        EquipSlot::Feet,
        EquipSlot::Body,
        EquipSlot::Saddle,
    ];

    /// The DSL field name (`main_hand`), for diagnostics and JSON pointers.
    pub fn field(self) -> &'static str {
        match self {
            EquipSlot::Head => "head",
            EquipSlot::Chest => "chest",
            EquipSlot::Legs => "legs",
            EquipSlot::Feet => "feet",
            EquipSlot::MainHand => "main_hand",
            EquipSlot::OffHand => "off_hand",
            EquipSlot::Body => "body",
            EquipSlot::Saddle => "saddle",
        }
    }

    /// The 1.21.11 `equipment` / `drop_chances` NBT key (`mainhand`) — also the
    /// game's own name for the slot, as an `equippable` component spells it.
    pub fn nbt(self) -> &'static str {
        match self {
            EquipSlot::Head => "head",
            EquipSlot::Chest => "chest",
            EquipSlot::Legs => "legs",
            EquipSlot::Feet => "feet",
            EquipSlot::MainHand => "mainhand",
            EquipSlot::OffHand => "offhand",
            EquipSlot::Body => "body",
            EquipSlot::Saddle => "saddle",
        }
    }

    /// The slot the game names `name` (`mainhand`), if it is one.
    pub fn from_nbt(name: &str) -> Option<EquipSlot> {
        EquipSlot::ALL.into_iter().find(|s| s.nbt() == name)
    }

    /// Whether this is a hand: a hand takes any item, so an item's own declared
    /// slot never contradicts it.
    pub fn is_hand(self) -> bool {
        matches!(self, EquipSlot::MainHand | EquipSlot::OffHand)
    }
}

/// One declared drop of an elite or boss (DSL v0.9).
///
/// A mob may wear many pieces; what it *leaves behind* is a **declared subset**,
/// usually one piece and never automatically everything. Two forms, told apart
/// by which field is present:
///
/// ```json
/// { "slot": "main_hand" }                                  // its axe
/// { "item": "minecraft:tripwire_hook", "name": "Gate Key" } // a quest item
/// ```
///
/// A `slot` entry must name a slot the same entity's `equipment` really fills
/// (`DW0490`) — the drop is the piece the player has been *looking at* through
/// the whole fight, so the two declarations cannot disagree. An `item` entry is
/// a token the fight *yields* rather than wears, and rides the entity's own
/// death loot table.
///
/// Undeclared slots keep drop chance `0.0` — byte-for-byte today's behaviour, and
/// the no-grind constitution's guarantee that an ordinary kit is never farmable.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum MobDrop {
    /// A worn/held piece, named by its equipment slot.
    Slot(SlotDrop),
    /// A quest token the fight yields (not worn).
    Item(ItemDrop),
}

/// The worn-piece form of a [`MobDrop`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SlotDrop {
    /// The equipment slot whose piece drops. Must be filled by the entity's own
    /// `equipment` declaration (`DW0490`).
    pub slot: EquipSlot,
}

/// The quest-token form of a [`MobDrop`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ItemDrop {
    /// Vanilla item id, validated against the pinned 1.21.11 registry
    /// (`DW0143`, the give-item family).
    pub item: String,
    /// Display name the dropped stack carries as a `custom_name` component.
    /// Player-visible, so it enters the l10n string inventory and translates
    /// like any other line.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

impl MobDrop {
    /// The equipment slot this entry names, or `None` for a quest-item drop.
    pub fn slot(&self) -> Option<EquipSlot> {
        match self {
            MobDrop::Slot(s) => Some(s.slot),
            MobDrop::Item(_) => None,
        }
    }

    /// The item id this entry names, or `None` for a worn-piece drop.
    pub fn item(&self) -> Option<&str> {
        match self {
            MobDrop::Slot(_) => None,
            MobDrop::Item(i) => Some(&i.item),
        }
    }

    /// The declared display name of a quest-item drop, when set.
    pub fn name(&self) -> Option<&String> {
        match self {
            MobDrop::Slot(_) => None,
            MobDrop::Item(i) => i.name.as_ref(),
        }
    }

    /// Mutable access to the display name — the l10n traversal's hook.
    pub fn name_mut(&mut self) -> Option<&mut String> {
        match self {
            MobDrop::Slot(_) => None,
            MobDrop::Item(i) => i.name.as_mut(),
        }
    }
}

/// One equipped item: either a bare item id, or an id carrying enchantments.
///
/// The plain form is the common case and stays a plain JSON string, which is
/// what keeps every campaign written before enchantments existed byte-identical
/// on re-serialisation:
///
/// ```json
/// "main_hand": "minecraft:netherite_sword"
/// "head": { "item": "minecraft:netherite_helmet",
///           "enchantments": { "minecraft:protection": 4 } }
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum EquipItem {
    /// A bare item id — no enchantments.
    Plain(String),
    /// An item id plus its enchantments.
    Enchanted(EnchantedItem),
}

impl EquipItem {
    /// The item id, whichever form was authored.
    pub fn item(&self) -> &str {
        match self {
            EquipItem::Plain(s) => s,
            EquipItem::Enchanted(e) => &e.item,
        }
    }

    /// The enchantments on this piece — empty for the plain form. `BTreeMap`
    /// ordered, so emission order is the id order and never hash order
    /// (ADR-0006).
    pub fn enchantments(&self) -> &BTreeMap<String, u32> {
        static EMPTY: std::sync::LazyLock<BTreeMap<String, u32>> =
            std::sync::LazyLock::new(BTreeMap::new);
        match self {
            EquipItem::Plain(_) => &EMPTY,
            EquipItem::Enchanted(e) => &e.enchantments,
        }
    }
}

/// **The item component a stack's enchantments are written to** — vanilla's own
/// rule (`EnchantmentHelper.getComponentType` at 1.21.11): an enchanted book
/// STORES its enchantments (`minecraft:stored_enchantments`, what an anvil
/// applies to the item it is combined with), and every other item CARRIES them
/// (`minecraft:enchantments`). Both are in the pinned 1.21.11
/// `data_component_type` registry.
///
/// A property of the item, not of the surface that writes the stack: a book in
/// a `loot` chest, a book handed over by `give-item` and a book on an equipped
/// piece are one object, so every emitter asks this one function. An
/// enchantment map written to the other component is a book that glints and
/// an anvil ignores, which the game accepts without a word.
pub fn enchantment_component(item: &str) -> &'static str {
    match item.strip_prefix("minecraft:").unwrap_or(item) {
        "enchanted_book" => "minecraft:stored_enchantments",
        _ => "minecraft:enchantments",
    }
}

/// The enchanted form of [`EquipItem`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct EnchantedItem {
    /// Item id (e.g. `minecraft:netherite_chestplate`).
    pub item: String,
    /// Enchantment id → level (e.g. `{"minecraft:protection": 4}`). Emitted as
    /// the 1.21 `minecraft:enchantments` item component.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub enchantments: BTreeMap<String, u32>,
}

/// Attribute overrides for a wave mob (DSL v0.4). Each field maps to a 1.21.11
/// `minecraft:` attribute component; an unset field keeps the vanilla base value.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MobAttributes {
    /// `minecraft:max_health` base value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_health: Option<f64>,
    /// `minecraft:attack_damage` base value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attack_damage: Option<f64>,
    /// `minecraft:movement_speed` base value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub movement_speed: Option<f64>,
    /// `minecraft:follow_range` base value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub follow_range: Option<f64>,
}

/// One permanent status effect on a wave mob (DSL v0.4), emitted as an ambient,
/// non-expiring `effect give`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MobEffect {
    /// Vanilla effect id (e.g. `minecraft:slowness`), validated against the
    /// pinned registry (`DW0192`).
    pub effect: String,
    /// Amplifier (0 = level I).
    pub amplifier: u32,
}

/// One expanded quest.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Quest {
    /// Quest id (matches a stage-4 planned quest).
    pub id: QuestId,
    /// What starts the quest.
    pub trigger: Trigger,
    /// Ordered objectives (intra-quest DAG via `after`).
    pub objectives: Vec<Objective>,
    /// Effects fired when a given objective completes.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub on_objective_complete: BTreeMap<ObjectiveId, Vec<QuestEffect>>,
    /// Effects fired when the whole quest completes.
    pub on_complete: Vec<QuestEffect>,
    /// The **cast ledger** (DSL v0.7, spec-0020): for every stage-2 NPC that is
    /// live during this quest — spawned and not explicitly removed — where it
    /// stands, what it is doing, and what its right-click offers *for this
    /// quest's duration*.
    ///
    /// The ledger exists because an NPC's dialogue used to be one tree for the
    /// whole campaign: after the climactic escape a crew member still offered
    /// "Tell me what he is." — a premise question absurd once the story moved on.
    /// Declaring the scene per quest makes the compiler able to check it
    /// (`DW0460`–`DW0467`) and makes the declaration itself the gate: the
    /// emitted right-click shows the root this quest declares, so a stale root
    /// retires *because the ledger says so*, not because an author remembered a
    /// flag.
    ///
    /// Every NPC live during the quest owes an entry (`DW0460`).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub cast: BTreeMap<NpcId, CastEntry>,
    /// What this quest does to the story (DSL v0.8, spec-0025; required at 0.8.0,
    /// `DW0481`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub happening: Option<Happening>,
}

/// One NPC's entry in a quest's [`cast`](Quest::cast) ledger.
///
/// Three authored shapes, tried in order (untagged): the bare keyword `"dead"` /
/// `"offstage"`, a single flat [`CastPlacement`], or a **list** of placements —
/// per-branch casts, each gated by the flags that select its branch (spec-0020
/// proof 4: where the effect history is branch-dependent, a single flat
/// declaration cannot hold on every reachable branch, and `DW0462` says so).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum CastEntry {
    /// The bare keyword form: `"npc/antiphos": "dead"`. Shorthand for a
    /// placement whose `at` is that keyword and which carries no `doing` or
    /// `dialogue` — a character who is not in the world has no business and
    /// answers no right-click.
    Absent(CastAbsence),
    /// A single placement that must hold on every reachable branch.
    Placement(CastPlacement),
    /// Per-branch placements (spec-0020 proof 4). Each carries the
    /// `requires_flags`/`forbids_flags` that select its branch.
    Branches(Vec<CastPlacement>),
}

impl CastEntry {
    /// Every placement this entry declares, in declared order. The bare-keyword
    /// form yields none — there is no scene to check.
    pub fn placements(&self) -> Vec<&CastPlacement> {
        match self {
            CastEntry::Absent(_) => Vec::new(),
            CastEntry::Placement(p) => vec![p],
            CastEntry::Branches(ps) => ps.iter().collect(),
        }
    }

    /// Every placement this entry declares, mutably (the l10n traversal).
    pub fn placements_mut(&mut self) -> Vec<&mut CastPlacement> {
        match self {
            CastEntry::Absent(_) => Vec::new(),
            CastEntry::Placement(p) => vec![p],
            CastEntry::Branches(ps) => ps.iter_mut().collect(),
        }
    }

    /// The bare-keyword absence this entry declares, if it is that form.
    pub fn absence(&self) -> Option<CastAbsence> {
        match self {
            CastEntry::Absent(a) => Some(*a),
            _ => None,
        }
    }

    /// True if this entry declares the NPC out of the world entirely — the bare
    /// keyword, or every placement's `at` being a keyword.
    pub fn is_absent(&self) -> bool {
        match self {
            CastEntry::Absent(_) => true,
            CastEntry::Placement(p) => p.at.absence().is_some(),
            CastEntry::Branches(ps) => {
                !ps.is_empty() && ps.iter().all(|p| p.at.absence().is_some())
            }
        }
    }
}

/// A declared absence: the NPC is deliberately not in the world.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum CastAbsence {
    /// Removed from the story for good (must match a `despawn-npc` with no later
    /// `spawn-npc`).
    Dead,
    /// Not in the world for this quest, but may return (must match a
    /// `despawn-npc`).
    Offstage,
}

impl CastAbsence {
    /// The authored keyword (`dead` / `offstage`).
    pub fn token(self) -> &'static str {
        match self {
            CastAbsence::Dead => "dead",
            CastAbsence::Offstage => "offstage",
        }
    }
}

/// Where a cast entry puts an NPC: a prefab anchor, a mark, or a declared
/// absence.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum CastPlace {
    /// `"dead"` or `"offstage"` — explicitly not in the world.
    Absent(CastAbsence),
    /// The anchor the NPC stands on for this quest's duration. Must equal the
    /// position the effect history actually produces (`DW0461`): declaring an
    /// anchor does not teleport anybody.
    Anchor(AnchorId),
    /// The mark the NPC stands on for this quest's duration (spec-0066): the
    /// spelling for a body that stands at an offset from its anchor. `DW0461`
    /// compares anchor and offset both.
    Mark(Mark),
}

impl CastPlace {
    /// The anchor this place names, if it names one.
    pub fn anchor(&self) -> Option<&AnchorId> {
        match self {
            CastPlace::Anchor(a) => Some(a),
            CastPlace::Mark(m) => Some(&m.anchor),
            CastPlace::Absent(_) => None,
        }
    }

    /// The mark this place names, if it names one: a bare anchor is the mark at
    /// a zero offset.
    pub fn mark(&self) -> Option<Mark> {
        match self {
            CastPlace::Anchor(a) => Some(Mark::at(a.clone())),
            CastPlace::Mark(m) => Some(m.clone()),
            CastPlace::Absent(_) => None,
        }
    }

    /// The declared absence, if this place is one.
    pub fn absence(&self) -> Option<CastAbsence> {
        match self {
            CastPlace::Absent(a) => Some(*a),
            CastPlace::Anchor(_) | CastPlace::Mark(_) => None,
        }
    }

    /// The authored token, for diagnostics.
    pub fn token(&self) -> String {
        match self {
            CastPlace::Absent(a) => a.token().to_string(),
            CastPlace::Anchor(a) => a.as_str().to_string(),
            CastPlace::Mark(m) => m.display(),
        }
    }
}

/// One declared scene for one NPC in one quest.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CastPlacement {
    /// Where the NPC is: an anchor, or `"offstage"` / `"dead"`.
    pub at: CastPlace,
    /// What the character is *doing* — free prose, never machine-checked.
    ///
    /// This field is the forcing function, which is the whole reason it is
    /// required (`DW0463`) despite being unverifiable: you cannot fill it in
    /// without deciding the character's business in this beat, and stage 6
    /// receives it as the context the NPC's lines are written against.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doing: Option<String>,
    /// What right-click offers during this quest. Required for an on-stage
    /// placement (`DW0463`) — including the explicit `"none"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dialogue: Option<CastDialogue>,
    /// Branch gate (per-branch casts): this placement describes the world only
    /// once every listed flag is set. Mirrors an option's `requires_flags`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_flags: Vec<FlagId>,
    /// Negative branch gate: this placement describes the world only while no
    /// listed flag is set. Mirrors an option's `forbids_flags`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbids_flags: Vec<FlagId>,
    /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison must
    /// hold for this gate to be open. The third field of the one gate, carried by
    /// every gate consumer — never by the verb that first wanted it. Default
    /// empty, so a pre-0.10 campaign is byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_state: Vec<StateCompare>,
}

/// What an NPC's right-click offers for a quest's duration.
///
/// Untagged, tried in order: the keywords `"none"` / `"unchanged"`, a
/// `{"barks": […]}` pool, then a dialogue root id.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum CastDialogue {
    /// A keyword: `"none"` or `"unchanged"`.
    Keyword(CastDialogueKeyword),
    /// A bark pool: right-click yields one inconsequential in-character line —
    /// no tree, no options, no consequences.
    Barks(CastBarks),
    /// A dialogue root id: right-click opens this node of the NPC's stage-6
    /// tree. Must be a node of *that* NPC's tree (`DW0464`).
    Root(DialogueId),
}

/// The keyword forms of [`CastDialogue`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum CastDialogueKeyword {
    /// Genuinely no reaction: the right-click is recorded and consumed, and
    /// nothing opens. Legal, but a last resort — if a body is clickable, the
    /// world should answer; prefer a bark.
    None,
    /// Carry forward whatever this NPC's dialogue was at its **previous**
    /// appearance in the quest-DAG ordering.
    ///
    /// The point is that carrying dialogue forward is a *conscious, declared
    /// act*. It is never an implicit default — an omitted `dialogue` is
    /// `DW0463`, not a carry-forward — and writing `"unchanged"` states the
    /// intent without re-spelling a root id that then drifts out of sync. It
    /// resolves transitively (`unchanged` → `unchanged` → a root), and using it
    /// at an NPC's first appearance is `DW0466`: there is nothing to carry.
    ///
    /// Emission is a **no-op** — no root swap is emitted for that NPC at that
    /// quest — which is what makes the sugar cheap and byte-stable.
    Unchanged,
}

/// A bark pool: inconsequential in-character lines, cycled deterministically.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CastBarks {
    /// The lines, in cycle order. At least one (`DW0464`). Player-visible, so
    /// they enter the l10n inventory like any narrate text.
    pub barks: Vec<String>,
}

/// What triggers a quest.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
pub enum Trigger {
    /// Fires when the campaign starts.
    CampaignStart,
    /// Fires when another quest completes.
    QuestComplete {
        /// The prerequisite quest.
        quest: QuestId,
    },
}

/// A quest objective.
///
/// Every variant may carry `requires_flags`:
/// flag-gated activation, satisfied only once each referenced flag has been set
/// by a `set-flag` effect.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
pub enum Objective {
    /// Completed by a dialogue option's `complete-objective` effect.
    TalkTo {
        /// Objective id.
        id: ObjectiveId,
        /// Short player-facing objective name (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// One-line location/direction hint (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hint: Option<String>,
        /// The NPC to talk to.
        npc: NpcId,
        /// Prerequisite objectives (intra-quest ordering).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        after: Vec<ObjectiveId>,
        /// Flags that must be set before this objective activates (v0.3).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_flags: Vec<FlagId>,
        /// Negative flag gate (DSL v0.6): the
        /// objective is suppressed (cannot activate or complete) while ANY listed
        /// flag is set for the player — the dual of `requires_flags`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        forbids_flags: Vec<FlagId>,
        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
        /// must hold for this gate to be open. The third field of the one gate,
        /// carried by every gate consumer — never by the verb that first wanted
        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_state: Vec<StateCompare>,
        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
        /// bot should traverse sneaking (sprint disabled). Emitted into
        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
        /// hint; no datapack effect.
        #[serde(default, skip_serializing_if = "is_false")]
        stealth: bool,
        /// What this objective does to the story (DSL v0.8, spec-0025; required
        /// at 0.8.0, `DW0481`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        happening: Option<Happening>,
    },
    /// Completed by reaching an anchor once prerequisites are met.
    ReachAnchor {
        /// Objective id.
        id: ObjectiveId,
        /// Short player-facing objective name (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// One-line location/direction hint (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hint: Option<String>,
        /// The anchor to reach.
        anchor: AnchorId,
        /// Completion radius (blocks).
        radius: u32,
        /// Prerequisite objectives (intra-quest ordering).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        after: Vec<ObjectiveId>,
        /// Flags that must be set before this objective activates (v0.3).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_flags: Vec<FlagId>,
        /// Negative flag gate (DSL v0.6): the
        /// objective is suppressed (cannot activate or complete) while ANY listed
        /// flag is set for the player — the dual of `requires_flags`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        forbids_flags: Vec<FlagId>,
        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
        /// must hold for this gate to be open. The third field of the one gate,
        /// carried by every gate consumer — never by the verb that first wanted
        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_state: Vec<StateCompare>,
        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
        /// bot should traverse sneaking (sprint disabled). Emitted into
        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
        /// hint; no datapack effect.
        #[serde(default, skip_serializing_if = "is_false")]
        stealth: bool,
        /// What this objective does to the story (DSL v0.8, spec-0025; required
        /// at 0.8.0, `DW0481`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        happening: Option<Happening>,
    },
    /// Completed when the referenced wave is fully slain (v0.3).
    Kill {
        /// Objective id.
        id: ObjectiveId,
        /// Short player-facing objective name (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// One-line location/direction hint (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hint: Option<String>,
        /// The wave (stage-5 `waves` ref) whose mobs must be slain.
        wave: WaveId,
        /// Prerequisite objectives.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        after: Vec<ObjectiveId>,
        /// Flags that must be set before this objective activates (v0.3).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_flags: Vec<FlagId>,
        /// Negative flag gate (DSL v0.6): the
        /// objective is suppressed (cannot activate or complete) while ANY listed
        /// flag is set for the player — the dual of `requires_flags`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        forbids_flags: Vec<FlagId>,
        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
        /// must hold for this gate to be open. The third field of the one gate,
        /// carried by every gate consumer — never by the verb that first wanted
        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_state: Vec<StateCompare>,
        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
        /// bot should traverse sneaking (sprint disabled). Emitted into
        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
        /// hint; no datapack effect.
        #[serde(default, skip_serializing_if = "is_false")]
        stealth: bool,
        /// What this objective does to the story (DSL v0.8, spec-0025; required
        /// at 0.8.0, `DW0481`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        happening: Option<Happening>,
    },
    /// Completed when `count` of `item` have been collected (v0.3).
    ///
    /// The items are provided in a container: the compiler's own chest at
    /// `anchor` by default, or — since DSL v0.8 — the prefab's existing
    /// chest/barrel at [`Objective::Collect::container`], optionally carrying an
    /// [`Objective::Collect::item_name`] and padded to read full with
    /// [`Objective::Collect::fill_count`].
    Collect {
        /// Objective id.
        id: ObjectiveId,
        /// Short player-facing objective name (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// One-line location/direction hint (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hint: Option<String>,
        /// Vanilla item id to collect (validated against the registry).
        item: String,
        /// How many are required.
        count: u32,
        /// The anchor items are provided at (chest / pickup).
        anchor: AnchorId,
        /// **Adopt the container the prefab already placed**: the anchor whose
        /// assembled-world cell holds
        /// a `chest` / `trapped_chest` / `barrel` this collect fills instead of
        /// conjuring its own chest at [`Objective::Collect::anchor`].
        ///
        /// Same division of labour a `loot` entry and a trap's dispenser already
        /// keep with the prefab: furniture belongs in the piece. A beach camp's
        /// barrel is scenery the player has been walking past since minute one —
        /// having the compiler `setblock` a *second*, floating chest beside it to
        /// hold the quest item is exactly the downstream workaround the no-hack
        /// rule forbids. A `container` whose cell holds no container is a build
        /// error (`DW0438`), never a silent fill into a wall.
        ///
        /// The critical-path step's position follows the container (the bot opens
        /// *this* block), and no chest is placed at `anchor` when it is set.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        container: Option<AnchorId>,
        /// **The item comes off a body, not out of a box**: the wave whose
        /// declared `drops[]` yield
        /// this objective's item. No container is placed — not the compiler's own
        /// chest at `anchor`, not a prefab one — and `container` is therefore
        /// mutually exclusive with it (`DW0100`-adjacent; `DW0492`).
        ///
        /// This is what makes "kill the boss → pick up its key → open the door"
        /// a *proved* chain rather than an authoring intention. The compiler
        /// requires (a) that the named wave really declares an `{item}` drop of
        /// this item (`DW0492`), and (b) that a `kill` objective for that wave
        /// precedes this collect in the objective graph (`DW0493`). The existing
        /// flow machinery then carries the ordering the rest of the way: the
        /// door's `requires_flags` hangs off this collect exactly as it would off
        /// a chest one.
        ///
        /// **Waves only.** An actor's death is not observable by any objective —
        /// there is no vanilla-side signal the flow machinery could consume — so
        /// an actor-gated collect would be an unprovable claim, and per the
        /// no-hack doctrine it is excluded rather than approximated. An actor may
        /// still declare `drops[]`; those drops just cannot gate a quest.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        dropped_by: Option<WaveId>,
        /// Display name for the collected item (DSL v0.8), emitted as the vanilla `custom_name` item component.
        ///
        /// A quest item is a *named thing* in the story ("Cheese", "Tide
        /// Ledger"), and a player who opens the barrel must read that name — an
        /// unnamed `minecraft:pumpkin_pie` says nothing about what the quest asked
        /// for. Player-visible, so it enters the l10n string inventory
        /// (`obj.<quest>.<obj>.item_name`) and translates like any other line.
        ///
        /// Naming changes nothing about adjudication: the completion advancement
        /// and the per-tick held check both match on the ITEM ID, which a named
        /// stack still carries.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        item_name: Option<String>,
        /// Padding stacks that make the container **read full**. Default `0` =
        /// the single required
        /// stack and nothing else.
        ///
        /// A barrel of cheese that opens on one lonely wheel reads as a bug, and
        /// vanilla's notion of "full" is *occupied slots*, not stack size — so
        /// this counts SLOTS: the objective's own stack lands in `container.0` and
        /// each padding stack repeats it in `container.1`, `container.2`, … Slot
        /// assignment is positional and total, the same determinism story `loot`
        /// tells (ADR-0006): no RNG, no loot tables, nothing to reseed.
        ///
        /// The padding is the same item, so taking the whole barrel still
        /// completes the objective and never over- or under-counts it.
        #[serde(default, skip_serializing_if = "is_zero")]
        fill_count: u32,
        /// Prerequisite objectives.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        after: Vec<ObjectiveId>,
        /// Flags that must be set before this objective activates (v0.3).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_flags: Vec<FlagId>,
        /// Negative flag gate (DSL v0.6): the
        /// objective is suppressed (cannot activate or complete) while ANY listed
        /// flag is set for the player — the dual of `requires_flags`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        forbids_flags: Vec<FlagId>,
        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
        /// must hold for this gate to be open. The third field of the one gate,
        /// carried by every gate consumer — never by the verb that first wanted
        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_state: Vec<StateCompare>,
        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
        /// bot should traverse sneaking (sprint disabled). Emitted into
        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
        /// hint; no datapack effect.
        #[serde(default, skip_serializing_if = "is_false")]
        stealth: bool,
        /// What this objective does to the story (DSL v0.8, spec-0025; required
        /// at 0.8.0, `DW0481`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        happening: Option<Happening>,
    },
    /// Completed by interacting with an entity at `anchor`; if `requires_item` is
    /// set, the item must be **held in the main hand** (v0.3; held semantics since
    /// DSL v0.7 — see [`Objective::Interact::requires_item`]).
    Interact {
        /// Objective id.
        id: ObjectiveId,
        /// Short player-facing objective name (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// One-line location/direction hint (v0.3, optional).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hint: Option<String>,
        /// The anchor the interaction entity stands at.
        anchor: AnchorId,
        /// Item the player must be **holding in the main hand** for the
        /// interaction to complete (optional).
        ///
        /// Held, not merely possessed: presenting the
        /// item IS the action — a player who right-clicks a sleeping giant with a
        /// sharpened stake buried in their backpack has not stabbed anything.
        /// Before this ruling the gate read the whole inventory, which made every
        /// `requires_item` interaction fire the moment the item was picked up
        /// anywhere, whatever the player was actually doing with their hands.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        requires_item: Option<String>,
        /// Diegetic feedback for a click that arrives without the required item in
        /// hand (DSL v0.7): narrated to that player in
        /// chat instead of the silence the gate used to answer with. Requires
        /// `requires_item` (`DW0437`).
        ///
        /// Only fires while the objective is genuinely open — same activation gate
        /// as the affordance itself — so a finished or not-yet-active interaction
        /// stays quiet.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        missing_item_hint: Option<String>,
        /// Prop block that IS the interaction affordance (DSL v0.4, spec-0008
        /// §2): the compiler `setblock`s it at the anchor on activation (exactly
        /// as `collect` uses a real chest). Omitted = the glowing-lantern
        /// hologram marker (the v0.3 fallback).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        prop: Option<Prop>,
        /// Prerequisite objectives.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        after: Vec<ObjectiveId>,
        /// Flags that must be set before this objective activates (v0.3).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_flags: Vec<FlagId>,
        /// Negative flag gate (DSL v0.6): the
        /// objective is suppressed (cannot activate or complete) while ANY listed
        /// flag is set for the player — the dual of `requires_flags`.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        forbids_flags: Vec<FlagId>,
        /// Numeric gate terms (DSL v0.10, spec-0031): every listed comparison
        /// must hold for this gate to be open. The third field of the one gate,
        /// carried by every gate consumer — never by the verb that first wanted
        /// it. Default empty, so a pre-0.10 campaign is byte-identical.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        requires_state: Vec<StateCompare>,
        /// Bot stealth hint (DSL v0.4): mark this leg as one the critical-path
        /// bot should traverse sneaking (sprint disabled). Emitted into
        /// `critical-path.json` as `sneak: true` on the step. Purely a harness
        /// hint; no datapack effect.
        #[serde(default, skip_serializing_if = "is_false")]
        stealth: bool,
        /// What this objective does to the story (DSL v0.8, spec-0025; required
        /// at 0.8.0, `DW0481`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        happening: Option<Happening>,
    },
}

/// A prop block for an `interact` objective (DSL v0.4). The block is the
/// affordance the player interacts with; its id is validated against the pinned
/// 1.21.11 block registry (`DW0193`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Prop {
    /// Vanilla block id (e.g. `minecraft:lever`).
    pub block: String,
}

// ---------------------------------------------------------------------------
// Stage 5 — scripted actors (DSL v0.6, spec-0014)
// ---------------------------------------------------------------------------

/// A scripted stage actor (DSL v0.6, spec-0014): a NoAI/Silent/no-loot puppet,
/// distinct from a stage-2 [`Npc`] (no dialogue, any mob type). Emitted with tag
/// `dw_actor_<id>`, `Invulnerable` unless `vulnerable` (a damageable puppet stays
/// knockback-immune — the tower-defense creep). `skin` re-dresses it as a
/// `minecraft:mannequin`, exactly as a stage-2 NPC skin. The puppet is summoned by
/// a `spawn-actor` effect (not at load), moved by `move-actor`, and can be replaced
/// by a real-AI twin with `unleash-actor`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Actor {
    /// Unique actor id (`actor/<kebab>`).
    pub id: ActorId,
    /// The vanilla entity to puppet, e.g. `minecraft:warden`. Validated against the
    /// pinned 1.21.11 entity registry (`DW0173`).
    pub entity: String,
    /// Optional custom name shown above the puppet.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Optional player-model skin (mannequin), as a stage-2 NPC (`DW0190`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skin: Option<NpcSkin>,
    /// The anchor the puppet is summoned on (resolved across areas, like an
    /// `open-gate` / `move-npc` destination).
    pub anchor: AnchorId,
    /// Integer `[x, y, z]` block offset from `anchor` (spec-0066, default
    /// `[0, 0, 0]`): the puppet stands at the [`Mark`] the two fields spell, so
    /// a rank of bodies is one anchor and an offset apiece.
    #[serde(default, skip_serializing_if = "is_zero3")]
    pub offset: [i32; 3],
    /// Initial facing (default `south`). The puppet spawns yawed this way.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub facing: Option<Facing>,
    /// If `true`, the puppet is damageable (a tower-defense creep) but stays
    /// knockback-immune; default `false` (fully `Invulnerable`).
    #[serde(default, skip_serializing_if = "is_false")]
    pub vulnerable: bool,
    /// Gear the actor wears and holds, in the same shape a wave mob uses
    /// ([`MobEquipment`]). Emitted into BOTH the staged puppet and the
    /// unleashed twin, so the dormant elite the player has been circling is
    /// visibly the same armoured thing that stands up. Drop chances are zero —
    /// wave gear and actor gear are never farmable (no-grind constitution).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub equipment: Option<MobEquipment>,
    /// Attribute overrides, in the same shape a wave mob uses ([`MobAttributes`],
    /// the v0.4 surface — one type, one rule set, so the two surfaces cannot
    /// drift). Emitted into BOTH the staged puppet and the unleashed twin, so the
    /// elite the party fights is the elite the author tuned; without it an actor
    /// was stuck at vanilla base values while every wave mob could be tuned,
    /// which is what blocked elite authoring. A `vulnerable` actor's
    /// knockback-immunity is emitted first and is not authorable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<MobAttributes>,
    /// How hard this actor's fight is *meant* to be (DSL v0.8, spec-0023) — the
    /// same [`EncounterTier`] vocabulary a [`Wave`] declares. Absent =
    /// [`EncounterTier::Ordinary`], byte-identical to every pre-0.8 campaign.
    ///
    /// A wave is not the only shape an elite takes. The set-piece souls fight —
    /// the armoured thing kneeling among the graves that stands up when you hit
    /// it — is an **actor**: staged by `spawn-actor`, given AI by
    /// `unleash-actor`, killed by hand rather than by a `kill` objective. Before
    /// this field nothing anywhere stated what such a fight was billed as.
    ///
    /// Like the wave field this is a **declaration, not a knob**: the compiler
    /// never scales an actor from it, and emission is unchanged whichever tier is
    /// declared. Its readers are the health-bar advisory (`DW0912`) and the drop
    /// rule — only a billed fight leaves anything behind.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tier: Option<EncounterTier>,
    /// A health bar over this actor's fight (DSL v0.31, spec-0073) — the same
    /// [`HealthBar`](crate::healthbar::HealthBar) a [`Wave`] declares. It reads the
    /// bodies whose health can move: the unleashed twin, or the puppet itself when
    /// the actor is `vulnerable`. A bar on an actor that is neither is `DW0909`.
    /// Absent = no bar, byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health_bar: Option<crate::healthbar::HealthBar>,
    /// What this actor leaves behind when a player kills it. Only an
    /// `elite`/`boss` actor may
    /// declare it (`DW0491`). Emitted into BOTH the staged puppet and the
    /// unleashed twin, exactly as `equipment` is — the drop belongs to the body,
    /// not to one of its two lifecycles. A `despawn-actor` strips the
    /// declaration off the body before removing it, so re-caging an elite (a
    /// souls re-seat) never scatters its axe.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub drops: Vec<MobDrop>,
    /// What this body can do when it moves (DSL v0.11, spec-0034) — the same
    /// [`BodyTraversal`] a stage-2 [`Npc`] carries, because traversal belongs to
    /// the body and not to the stage that declares it. Absent = the class the
    /// compiler derives from `entity` (or from `minecraft:mannequin` when `skin`
    /// is set).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub traversal: Option<BodyTraversal>,
    /// What happens each time a player is credited with killing this actor's
    /// body (spec-0074) — effect root R9, the same [`OnKill`] a
    /// wave declares. Absent = no bundle, and the actor's emission is
    /// byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_kill: Option<OnKill>,
}

/// A cardinal facing keyword (DSL v0.6). Emitted as the puppet's spawn yaw
/// (MC: yaw 0 = +z/south).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Facing {
    /// Facing +z (yaw 0) — the default.
    South,
    /// Facing -z (yaw 180).
    North,
    /// Facing -x (yaw 90).
    West,
    /// Facing +x (yaw 270).
    East,
}

impl Facing {
    /// The kebab token (`south` / `north` / `west` / `east`).
    pub fn token(self) -> &'static str {
        match self {
            Facing::South => "south",
            Facing::North => "north",
            Facing::West => "west",
            Facing::East => "east",
        }
    }
}

/// How a `despawn-actor` removes its puppet (DSL v0.6).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum DespawnStyle {
    /// The body leaves unseen: no death animation, red flash or death particles
    /// where it stood. It is moved under the world and removed there.
    Vanish,
    /// The body dies where it stands, with the vanilla death animation (a death
    /// the player is meant to watch).
    Kill,
}

impl DespawnStyle {
    /// The kebab token (`vanish` / `kill`).
    pub fn token(self) -> &'static str {
        match self {
            DespawnStyle::Vanish => "vanish",
            DespawnStyle::Kill => "kill",
        }
    }
}

// ---------------------------------------------------------------------------
// Stage 5 — assemblies (spec-0082)
// ---------------------------------------------------------------------------

/// A fixed thing that can be hit and hits back (spec-0082): an object built of
/// display entities standing at a [`Mark`], moving through the clips of a
/// library [`rig`](crate::rig), struck in melee through an optional
/// `minecraft:interaction` hitbox, and striking a player who stands in its
/// arming region.
///
/// It is not a fight class and never dies: no health, equipment, traversal,
/// health bar or kill credit. A hit count is an ordinary `state` datum a
/// `strike-assembly` trigger adds to, and what happens at a count is an effect
/// behind the ordinary gate.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Assembly {
    /// Unique assembly id (`assembly/<kebab>`).
    pub id: AssemblyId,
    /// The library rig (`rig/<name>`, resolved to `rigs/<name>/rig.json`
    /// beside the prefab library) whose parts and clips this assembly is.
    pub rig: RigId,
    /// Where the rig's origin stands: an anchor and an optional offset. The
    /// rig's origin is the mark cell's centre at its floor plane.
    pub at: Mark,
    /// Which way the rig's `+z` front faces (default `south`). Applied by the
    /// compiler to every frame, so the emitted entities stand at yaw 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub facing: Option<Facing>,
    /// The clip playing from spawn. Absent: the parts stand in the rig's rest
    /// pose and no clip plays until a `play-clip`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub initial: Option<String>,
    /// The `minecraft:interaction` a player strikes. Absent: the assembly
    /// cannot be struck, and a `strike-assembly` on it is refused (`DW0936`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hitbox: Option<AssemblyHitbox>,
    /// The blows it deals. Absent: it never strikes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strikes: Option<AssemblyStrikes>,
}

impl Assembly {
    /// The declared facing, `south` when absent.
    pub fn facing(&self) -> Facing {
        self.facing.unwrap_or(Facing::South)
    }
}

/// An assembly's hitbox (spec-0082 §3.2): a `minecraft:interaction` of
/// `width × height` whose bottom centre is the mark's cell centre plus
/// `offset`. Melee only: an arrow passes through an interaction.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AssemblyHitbox {
    /// Width in blocks (`0 < width <= 6`, `DW0936`).
    pub width: f64,
    /// Height in blocks (`0 < height <= 22`, `DW0936`).
    pub height: f64,
    /// Integer `[x, y, z]` block offset of the box's bottom centre from the
    /// mark (default `[0, 0, 0]`).
    #[serde(default, skip_serializing_if = "is_zero3")]
    pub offset: [i32; 3],
}

/// An assembly's strike pattern (spec-0082 §3.2).
///
/// The pattern runs, repeating from its first step, on every tick on which
/// some player's body is in `while_in`, and stops at the end of the step in
/// flight when nobody is.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AssemblyStrikes {
    /// The arming region: an anchor-centred box. Every landing box lies inside
    /// it (`DW0938`), so a player who never entered it is never struck.
    pub while_in: StealthZone,
    /// The steps, in order.
    pub pattern: Vec<StrikeStep>,
    /// Aim (spec-0082 §5.7). Absent: every blow lands where its `on_land`
    /// boxes say. Present: at the start of every wind-up the assembly turns to
    /// the one of its declared facings nearest the bearing of the nearest
    /// player in `while_in`, and every `damage-players` box in `on_land` turns
    /// with it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aim: Option<StrikeAim>,
}

/// An aimed strike pattern's facings (spec-0082 §5.7): `facings` turns
/// evenly spaced round the vertical axis through the mark, the first being the
/// assembly's declared `facing`. Every `on_land` box is written for that first
/// facing; the compiler turns it to each of the others and proves every facing
/// a player in `while_in` can draw (`DW0938`, judged per facing). Which facing
/// a blow takes is chosen at run time among the proven ones; nothing about
/// where it lands is computed there.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StrikeAim {
    /// How many facings, evenly spaced: 4 is a quarter turn apart, 8 an eighth,
    /// 16 a sixteenth. At least 1 (1 is the declared facing alone).
    pub facings: std::num::NonZeroU32,
}

/// One step of a strike pattern: wind up, hold, strike, land.
///
/// How long the wind-up is and how hard the blow lands are the creator's
/// judgement, by spec-0016's standing ruling: no telegraph rule and no
/// one-shot rule.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StrikeStep {
    /// The clip played first.
    pub windup: String,
    /// Ticks the windup's last frame is held before the strike clip starts.
    pub hold: u32,
    /// The clip the blow is.
    pub strike: String,
    /// The step's pace: the keyframe cadence, in ticks per frame (1–20, the
    /// rig's own bounds), its wind-up and strike clips play at. Absent: each
    /// clip's own. The wind-up lasts `1 + (frames - 1) × cadence` ticks, then
    /// `hold`; the blow lands one cadence after the strike's last frame.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ticks_per_frame: Option<u32>,
    /// Effects run, with no acting player, on the tick a client has drawn the
    /// strike clip's last frame whole (one cadence after it is applied). A step
    /// with none is a feint.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub on_land: Vec<QuestEffect>,
}

/// One step of a [`Verb::Sequence`] (DSL v0.6): a group of effects fired at
/// an exact tick offset from the sequence's start.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SequenceStep {
    /// Tick offset from the sequence start at which `effects` fire.
    pub at_ticks: u32,
    /// The effects fired at `at_ticks`. Any stage-5 effect except a nested
    /// `sequence` (rejected with `DW0329`).
    pub effects: Vec<QuestEffect>,
}

impl Objective {
    /// This objective's id.
    pub fn id(&self) -> &ObjectiveId {
        match self {
            Objective::TalkTo { id, .. }
            | Objective::ReachAnchor { id, .. }
            | Objective::Kill { id, .. }
            | Objective::Collect { id, .. }
            | Objective::Interact { id, .. } => id,
        }
    }

    /// This objective's prerequisites.
    pub fn after(&self) -> &[ObjectiveId] {
        match self {
            Objective::TalkTo { after, .. }
            | Objective::ReachAnchor { after, .. }
            | Objective::Kill { after, .. }
            | Objective::Collect { after, .. }
            | Objective::Interact { after, .. } => after,
        }
    }

    /// The short player-facing objective title (v0.3, optional).
    pub fn title(&self) -> Option<&str> {
        match self {
            Objective::TalkTo { title, .. }
            | Objective::ReachAnchor { title, .. }
            | Objective::Kill { title, .. }
            | Objective::Collect { title, .. }
            | Objective::Interact { title, .. } => title.as_deref(),
        }
    }

    /// The one-line location/direction hint (v0.3, optional).
    pub fn hint(&self) -> Option<&str> {
        match self {
            Objective::TalkTo { hint, .. }
            | Objective::ReachAnchor { hint, .. }
            | Objective::Kill { hint, .. }
            | Objective::Collect { hint, .. }
            | Objective::Interact { hint, .. } => hint.as_deref(),
        }
    }

    /// Mutable access to the optional player-facing title (i18n localization).
    pub fn title_mut(&mut self) -> &mut Option<String> {
        match self {
            Objective::TalkTo { title, .. }
            | Objective::ReachAnchor { title, .. }
            | Objective::Kill { title, .. }
            | Objective::Collect { title, .. }
            | Objective::Interact { title, .. } => title,
        }
    }

    /// Mutable access to the optional one-line hint (i18n localization).
    pub fn hint_mut(&mut self) -> &mut Option<String> {
        match self {
            Objective::TalkTo { hint, .. }
            | Objective::ReachAnchor { hint, .. }
            | Objective::Kill { hint, .. }
            | Objective::Collect { hint, .. }
            | Objective::Interact { hint, .. } => hint,
        }
    }

    /// The flags that must be set before this objective activates (v0.3).
    pub fn requires_flags(&self) -> &[FlagId] {
        match self {
            Objective::TalkTo { requires_flags, .. }
            | Objective::ReachAnchor { requires_flags, .. }
            | Objective::Kill { requires_flags, .. }
            | Objective::Collect { requires_flags, .. }
            | Objective::Interact { requires_flags, .. } => requires_flags,
        }
    }

    /// The negative flag gate (DSL v0.6): flags whose being set **suppresses**
    /// this objective. The dual of [`Objective::requires_flags`].
    pub fn forbids_flags(&self) -> &[FlagId] {
        match self {
            Objective::TalkTo { forbids_flags, .. }
            | Objective::ReachAnchor { forbids_flags, .. }
            | Objective::Kill { forbids_flags, .. }
            | Objective::Collect { forbids_flags, .. }
            | Objective::Interact { forbids_flags, .. } => forbids_flags,
        }
    }

    /// The numeric gate terms (DSL v0.10, spec-0031): comparisons that must hold
    /// before this objective activates. See [`StateCompare`].
    pub fn requires_state(&self) -> &[StateCompare] {
        match self {
            Objective::TalkTo { requires_state, .. }
            | Objective::ReachAnchor { requires_state, .. }
            | Objective::Kill { requires_state, .. }
            | Objective::Collect { requires_state, .. }
            | Objective::Interact { requires_state, .. } => requires_state,
        }
    }

    /// What this objective does to the story (DSL v0.8, spec-0025).
    pub fn happening(&self) -> Option<&Happening> {
        match self {
            Objective::TalkTo { happening, .. }
            | Objective::ReachAnchor { happening, .. }
            | Objective::Kill { happening, .. }
            | Objective::Collect { happening, .. }
            | Objective::Interact { happening, .. } => happening.as_ref(),
        }
    }

    /// The bot stealth hint (DSL v0.4): traverse this leg sneaking.
    pub fn stealth(&self) -> bool {
        match self {
            Objective::TalkTo { stealth, .. }
            | Objective::ReachAnchor { stealth, .. }
            | Objective::Kill { stealth, .. }
            | Objective::Collect { stealth, .. }
            | Objective::Interact { stealth, .. } => *stealth,
        }
    }

    /// The container this objective ADOPTS (DSL v0.8), if it is a `collect` that
    /// declares one: the anchor whose prefab-placed chest/barrel it fills instead
    /// of conjuring its own chest. `None` on every other objective and on a
    /// `collect` that keeps the compiler-placed chest.
    pub fn collect_container(&self) -> Option<&AnchorId> {
        match self {
            Objective::Collect { container, .. } => container.as_ref(),
            _ => None,
        }
    }

    /// The wave whose declared drops provide this objective's item (DSL v0.9),
    /// if it is a `collect` that declares one. `None` on every other objective
    /// and on a `collect` fed by a container.
    pub fn collect_dropped_by(&self) -> Option<&WaveId> {
        match self {
            Objective::Collect { dropped_by, .. } => dropped_by.as_ref(),
            _ => None,
        }
    }

    /// The padding-stack count of a `collect` (DSL v0.8); `0` for every other
    /// objective and for a `collect` that fills the single required stack only.
    pub fn collect_fill_count(&self) -> u32 {
        match self {
            Objective::Collect { fill_count, .. } => *fill_count,
            _ => 0,
        }
    }

    /// The `interact` prop block (DSL v0.4), if this is an `interact` with a prop.
    pub fn prop(&self) -> Option<&Prop> {
        match self {
            Objective::Interact { prop, .. } => prop.as_ref(),
            _ => None,
        }
    }

    /// The kebab type tag.
    pub fn kind(&self) -> &'static str {
        match self {
            Objective::TalkTo { .. } => "talk-to",
            Objective::ReachAnchor { .. } => "reach-anchor",
            Objective::Kill { .. } => "kill",
            Objective::Collect { .. } => "collect",
            Objective::Interact { .. } => "interact",
        }
    }

    /// The v0.3 verb name if this objective is one of the verbs introduced in
    /// DSL v0.3 (`kill`/`collect`/`interact`). These validate in v0.3 campaigns
    ///.
    pub fn v03_verb(&self) -> Option<&'static str> {
        match self {
            Objective::Kill { .. } => Some("kill"),
            Objective::Collect { .. } => Some("collect"),
            Objective::Interact { .. } => Some("interact"),
            Objective::TalkTo { .. } | Objective::ReachAnchor { .. } => None,
        }
    }
}

/// The condition under which an effect fires, as one object.
///
/// The three axes of [`crate::gate::Gate`] in their declared form: the flags that
/// must be set, the flags that must not be, and the numeric comparisons that must
/// hold. Declared once and carried by [`QuestEffect::when`], so every verb is
/// gatable on exactly the same terms and a fourth axis is one field here.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Guard {
    /// Flags that must ALL be set (per party) for the effect to fire. Emission
    /// wraps the effect's commands in `execute if score #party dw.f_<flag> matches 1`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_flags: Vec<FlagId>,
    /// Flags whose being set SUPPRESSES the effect — the dual of `requires_flags`,
    /// emitted as `execute unless score #party dw.f_<flag> matches 1`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbids_flags: Vec<FlagId>,
    /// Numeric comparisons that must ALL hold (spec-0031), emitted as
    /// `execute if score <holder> dw.s_<state> matches <range>`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_state: Vec<StateCompare>,
}

/// An effect fired by quest progress: **one guard, one story note, one verb.**
///
/// The guard is a property of an effect, not of the verb that first wanted one, so
/// it is declared once in [`Guard`] and every verb carries it — including the
/// staging and souls vocabulary (`spawn-actor`, `move-actor`, `set-checkpoint`,
/// `bonfire`, `begin-stealth`, `sequence`, …) that could not be branch-gated while
/// the fields lived on the variants. A gate that can never open on a
/// `campaign-complete` is caught where it belongs, by the completability proof.
///
/// `verb` is `#[serde(flatten)]`, so the JSON is unchanged in shape apart from the
/// guard moving under `when`: `{"type": "open-gate", "anchor": "…", "when":
/// {"requires_flags": ["…"]}}`. [`Verb`] keeps `deny_unknown_fields`, which is what
/// the flattened deserializer applies to everything the outer struct did not claim
/// — an author's typo is still `DW0100`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct QuestEffect {
    /// When this effect fires. `None` is the always-open gate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<Guard>,
    /// What this beat does to the story (spec-0025) — validation metadata with no
    /// emission of its own.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub happening: Option<Happening>,
    /// **Who a player-facing effect addresses** (spec-0085 §3.2): `party` or
    /// `actor`, the one player whose act fired the root. Absent = the root's own
    /// answer — a quest completion addresses the party, a death, a respawn, a
    /// purchase, a credited kill and a `presser` trigger address their actor, a
    /// polled trigger, a trap and a shortcut address the party — so a campaign
    /// that never writes the field emits exactly what it emitted before it
    /// existed.
    ///
    /// A property of the envelope rather than of any verb: it reaches every
    /// verb the emitter addresses to players ([`Verb::addresses_players`]), and
    /// on any other verb it is refused (`DW0942`). `actor` where emission has no
    /// acting player is `DW0503`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audience: Option<EffectAudience>,
    /// **Narrows the audience to players inside an anchor-centred box**
    /// (`anchor ± extent`, spec-0085 §3.2) at the moment the effect fires — the
    /// same [`StealthZone`] a `begin-stealth` zone and a `lethal_volumes[]`
    /// region take, resolved through the one `Plan::zone_box`. Composes with
    /// [`Self::audience`]: `actor` + `in` is the actor, if they stand in the box.
    ///
    /// One field on the envelope, reaching every player-facing verb; refused on
    /// any other (`DW0942`) — a box narrows an audience, and a world fact has
    /// none.
    #[serde(default, rename = "in", skip_serializing_if = "Option::is_none")]
    pub within: Option<StealthZone>,
    /// What the effect does.
    #[serde(flatten)]
    pub verb: Verb,
}

/// **Who a player-facing effect addresses** (spec-0085 §3.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum EffectAudience {
    /// Every player — `@a`.
    Party,
    /// The one player whose act fired the root — the completing player, the
    /// presser, the dying or respawning player, the buyer, the credited killer.
    /// Emitted `@s`, so it exists only where emission has an acting player
    /// (`DW0503`).
    Actor,
}

impl EffectAudience {
    /// The token the document spells.
    pub fn token(self) -> &'static str {
        match self {
            EffectAudience::Party => "party",
            EffectAudience::Actor => "actor",
        }
    }
}

impl From<Verb> for QuestEffect {
    /// An unguarded effect with no story note and the root's own audience — the
    /// shape a compiler-synthesized beat and most tests want.
    fn from(verb: Verb) -> Self {
        QuestEffect {
            when: None,
            happening: None,
            audience: None,
            within: None,
            verb,
        }
    }
}

/// What an effect does, without the guard: the closed set of verbs.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "kebab-case", deny_unknown_fields)]
pub enum Verb {
    /// Opens a prefab-declared gate (one-way).
    OpenGate {
        /// The gate anchor to open.
        anchor: AnchorId,
    },
    /// Seals a prefab-declared gate — the physical dual of `open-gate` (DSL v0.6):
    /// fills the gate anchor's region with the block the anchor declares (e.g. the
    /// boulder's `minecraft:basalt`), turning an opened threshold back into a wall.
    /// The declared fill block is prefab metadata; a gate anchor with no `block` is
    /// rejected (`DW0343`). The completability model treats the region as **solid**
    /// from the point in the quest DAG where this fires (mirroring how `open-gate`'s
    /// clearing is modelled) — a critical path that must cross a gate after it seals
    /// fails the DW0311 reachability proof.
    CloseGate {
        /// The gate anchor to seal.
        anchor: AnchorId,
        /// What the seal *says* when a player right-clicks it (DSL v0.8). A sealed gate is a wall the party will walk back to
        /// and press: the compiler answers that press on the actionbar. Absent, the
        /// compiler's canonical English is baked in (`The way is sealed.`) exactly
        /// as `world.boundary.message` does; authored, the line is l10n-inventoried
        /// under `<effect-key>.sealed_hint` and translates like every other
        /// player-visible string.
        ///
        /// Unlike `happening`, this **does** print in the hand-written `Debug`
        /// below when present — it changes emission, so two otherwise-identical
        /// sequences that differ only in their seal's answer are different content.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sealed_hint: Option<String>,
    },
    /// Marks the campaign complete (final advancement + credits). Terminal — not
    /// flag-gatable (gating the campaign's own completion is a deadlock footgun),
    /// so this variant carries no `requires_flags`.
    CampaignComplete {
        /// Which ENDING this is (DSL v0.8, spec-0025).
        /// A campaign with more than one `campaign-complete` has more than one
        /// ending, and a branch that runs to an ending names it here — so the
        /// terminality proof (`DW0482`) can state *which* ending a branch reached
        /// instead of merely that something ended. There is no separate `endings`
        /// section: the set of endings is exactly the set named here, the same
        /// rule flags follow.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ending: Option<EndingId>,
    },
    /// Gives the party an item (v0.3; party-wide since v0.6/spec-0018).
    GiveItem {
        /// Vanilla item id to give (validated against the registry).
        item: String,
        /// How many to give.
        count: u32,
        /// Optional display name (DSL v0.4), matching [`KitItem::name`].
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name: Option<String>,
        /// Who receives it (DSL v0.6, spec-0018). Absent = [`Carrier::All`] — every
        /// party member. `one` hands a single copy to the player whose action fired
        /// the effect; it is rejected in a scheduler-only bundle (`DW0371`), which
        /// has no acting player.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        carrier: Option<Carrier>,
        /// Enchantments on the given stack (`{"minecraft:sharpness": 2}`) —
        /// the field a `loot` stack and an equipped piece carry, under the same
        /// checks (`DW0433`/`DW0434`) and written by the same rule
        /// ([`enchantment_component`]): on a `minecraft:enchanted_book` they are
        /// the book's stored enchantments, the ones an anvil applies.
        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
        enchantments: BTreeMap<String, u32>,
    },
    /// Sets a campaign flag, enabling flag-gated objectives (v0.3).
    SetFlag {
        /// The flag to set.
        flag: FlagId,
    },
    /// Writes a declared datum to an absolute value (DSL v0.10, spec-0031).
    SetState {
        /// The datum to write (stage-5 `state` ref).
        state: StateId,
        /// The value to write.
        value: i32,
    },
    /// Moves a declared datum by a signed amount (DSL v0.10, spec-0031).
    ///
    /// **Signed on purpose.** A purse that a shop debits and a stake that a death
    /// forfeits are the same operation with the sign flipped; a separate
    /// `subtract-state` would be a second verb for one mechanism, and the first
    /// campaign to need "add a negative" would have to choose between them.
    AddState {
        /// The datum to move (stage-5 `state` ref).
        state: StateId,
        /// How far to move it. Negative counts down.
        amount: i32,
    },
    /// Leaves a declared [`Stake`] behind for the acting player (DSL v0.10,
    /// spec-0032): forfeit the declared share of its datum, and place a
    /// collectable marker at the compile-time anchor for where they are.
    ///
    /// **Nothing about this verb says "death".** It is written in `on_death`
    /// because that is where a souls-shaped delve wants it, but the mechanism is
    /// "leave a recoverable cache where the acting player stands", and the effect
    /// carries the ordinary gate so any root may run it. What *is* death-specific
    /// — that the corpse stands on the death position, so the placement lookup has
    /// a position to key on — is a property of the `on_death` root, not of this
    /// verb.
    DropStake {
        /// The stake (stage-5 `stakes` ref) to leave.
        stake: StakeId,
    },
    /// Returns a declared datum to its declared `initial` (DSL v0.10,
    /// spec-0031) — the verb `FlagId` has never had.
    ClearState {
        /// The datum to clear (stage-5 `state` ref).
        state: StateId,
    },
    /// Spawns a stage-5 wave's mobs at its anchor (v0.3).
    SpawnWave {
        /// The wave (stage-5 `waves` ref) to spawn.
        wave: WaveId,
    },
    /// Narrates a player-visible line (DSL v0.4, spec-0008 §3). `text` enters the
    /// l10n key inventory like any player-visible string.
    Narrate {
        /// The line shown to the player.
        text: String,
        /// Presentation channel (default `chat`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        style: Option<NarrateStyle>,
        /// Optional sound id played alongside the line.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sound: Option<String>,
    },
    /// Sets a block at an anchor (DSL v0.4, spec-0008 §2). General form of a prop
    /// placement. Block id validated against the pinned 1.21.11 block registry;
    /// a vanilla blockstate suffix (`minecraft:grindstone[face=floor]`) is
    /// accepted and passed through verbatim (DSL v0.6).
    SetBlock {
        /// The anchor to place the block at.
        anchor: AnchorId,
        /// Vanilla block id to place.
        block: String,
    },
    /// **Fill a declared region with a block** at runtime (DSL v0.10, spec-0031).
    ///
    /// The general spelling of the capability `open-gate` / `close-gate` carried
    /// privately: a region, filled or cleared, from a point in the quest DAG.
    /// `close-gate` is this verb with the region and the block read off a prefab
    /// gate anchor instead of authored; `set-block` is the one-cell case at a
    /// point anchor. All three lower through one emission
    /// (`emit::fill_region_command`) and are modelled by one completability rule
    /// (`plan::RegionEvent`), so a third consumer inherits the proof instead of
    /// re-deriving it.
    ///
    /// From the DAG point at which this fires, the completability model treats the
    /// filled cells as whatever the **block** makes them. A full-cube block leaves
    /// them **solid**, exactly as a `close-gate` seal is: a critical path that must
    /// cross the region afterwards fails `DW0311`. `minecraft:water` /
    /// `minecraft:lava` leave them **flooded** — impassable and never floor, because
    /// nothing stands on a fluid — and because a fill carries no `replace` filter it
    /// takes away whatever floor was in the box, so a forced leg that needed that
    /// footing fails `DW0544`.
    FillRegion {
        /// The volume to fill, as an anchor-centred box (`anchor ± extent`).
        ///
        /// Deliberately the existing [`StealthZone`] — the engine's one
        /// anchor-centred box object class, already shared by `damage-players`'s
        /// `in` filter, `collapse`'s `region_anchor`, a `volley` kill zone and a
        /// `lethal_volumes[]` region, and resolved through the single
        /// `Plan::zone_box`. A private twin with the same two fields would be
        /// `tools/ci/check-capability-ownership.py` check C by construction.
        ///
        /// An anchor-centred box rather than a prefab `region` anchor for the
        /// reason `collapse` states: the assembled model deletes every gate-region
        /// anchor's cells, so a slab declared that way would already be gone.
        region: StealthZone,
        /// The block the region is filled with (validated against the pinned
        /// 1.21.11 block registry, `DW0193`).
        block: String,
    },
    /// **Clear a declared region to air** at runtime (DSL v0.10, spec-0031) — the
    /// physical dual of [`Verb::FillRegion`], and the general spelling of
    /// what `open-gate` does to a gate anchor's region.
    ///
    /// The completability model treats the cleared cells as **passable** from the
    /// DAG point at which this fires, with one exception it states out loud: a
    /// cleared cell the model already floods stays impassable, because clearing a
    /// block does not remove water (`nav::World::with_cleared`).
    ClearRegion {
        /// The volume to clear, as an anchor-centred box (`anchor ± extent`) —
        /// the same object class [`Verb::FillRegion`] fills.
        region: StealthZone,
    },
    /// **Repaint a volume's sky** (spec-0080 §3.3): `/fillbiome` over the
    /// volume with the named atmosphere's biome, while the party stands in it.
    ///
    /// A runtime edit of the world keyed to a volume, so it is a verb of the
    /// physical-edit family [`Verb::FillRegion`] / [`Verb::ClearRegion`] form.
    /// Exactly one of `region` / `place` (`DW0929`): a volume inside a place is
    /// the creator's judgement, a whole place's bounds are a derivation the
    /// creator never types. Painting back is this verb naming the place's own
    /// atmosphere, or `atmosphere: null` for the horizon's biome.
    ///
    /// A hard cut: the client blends fog over its biome-blend radius and grass
    /// not at all, and biome cells are 4×4×4, so the painted volume is the
    /// enclosing 4-aligned box, up to three blocks past each face.
    SetAtmosphere {
        /// One of `world.atmospheres[]`, or `null` for the horizon's biome.
        #[serde(default)]
        atmosphere: Option<AtmosphereId>,
        /// The volume, as an anchor-centred box (`anchor ± extent`) — the same
        /// object class [`Verb::FillRegion`] fills, resolved through the same
        /// `Plan::zone_box`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        region: Option<StealthZone>,
        /// A whole place: an `area/…` id, or a site-plan box's `node/…`. Its
        /// volume is the cells the place's own `atmosphere` paints at setup:
        /// its bounds, grown as far as the client's biome blend reads.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        place: Option<String>,
    },
    /// **Opens a placed piece's contingent way** (DSL v0.12, spec-0042 §2.4): the
    /// broken flight a beat repairs, the bridge a beat lowers, the rubble a beat
    /// clears.
    ///
    /// A piece's spatial contract may declare a traversal edge whose crossability
    /// depends on a named region — `laid` (empty as built, opening fills it) or
    /// `cleared` (built solid, opening voids it). The prefab checker proves the
    /// piece is severed as shipped and joined once that region is opened; this is
    /// the verb that opens it, and it is the only one, because a way is the object
    /// and opening it is the operation.
    ///
    /// **There is no region, no block and no sign on this effect, and that is the
    /// design rather than an omission.** All three are read from the piece's own
    /// exported metadata (`spatial_contract.edges[].way`), so the effect and the
    /// building cannot disagree about what a way is — two authorities plus an
    /// equality check is the defect this shape avoids, not a variant of the fix
    /// (spec-0042 AC8). What the campaign decides is *when*.
    ///
    /// Completability: the way is **shut until this fires**, and from the DAG
    /// point at which it fires the region is solid-and-footing (`laid`) or
    /// passable (`cleared`) — the same [`Verb::FillRegion`] /
    /// [`Verb::ClearRegion`] model, fed from metadata instead of from an
    /// authored box, so this verb inherits the forced-footing rule (`DW0546`)
    /// rather than restating it. Required content standing beyond a way that no
    /// forced opening precedes is `DW0548`, which names the way, the effect and
    /// the element.
    OpenWay {
        /// The placed piece whose way this opens (`prefab/<name>`).
        ///
        /// A piece, not an anchor: the way's cells are the contract's, not a gate
        /// anchor's, and a piece placed twice has two ways. The reference must
        /// name exactly one placement; naming none or several is `DW0547`.
        piece: PrefabId,
        /// The way's region name, as the piece's contract exports it
        /// (`spatial_contract.edges[].way.region`).
        way: String,
    },
    /// Despawns an NPC and its interaction hitbox (DSL v0.4, spec-0008 §5). The
    /// NPC leaves unseen: no death animation, red flash or death particles.
    DespawnNpc {
        /// The NPC (stage-2 ref) to remove.
        npc: NpcId,
    },
    /// Moves an NPC (and its interaction hitbox in lockstep) to an anchor (DSL
    /// v0.4, spec-0008 §5 + addendum). The compiler plans a **collision-safe walked
    /// path** by A* over the solved voxel grid and emits per-tick teleport
    /// waypoints along it, so the NPC never clips a wall and walks up to (not into)
    /// a solid affordance. An unroutable move is a compile error (`DW0307`).
    MoveNpc {
        /// The NPC (stage-2 ref) to move.
        npc: NpcId,
        /// The destination mark: an anchor and an optional offset (spec-0066).
        to: Mark,
        /// Optional travel speed in blocks/tick (defaults to ~0.15).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        speed: Option<f64>,
        /// Effects fired once the NPC arrives at the destination cell — exact
        /// parity with [`Verb::MoveActor`]
        /// `on_arrive`: same arrival detection (the walk driver's final tick), same
        /// execution context, and every deep effect walker recurses into it via
        /// [`QuestEffect::nested_effect_lists`]. This is what lets content gate a
        /// beat on walk *completion* instead of fire-and-forgetting the walk (e.g.
        /// `on_arrive: [set-flag]` so a cutscene waits for the NPC to reach its
        /// mark).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        on_arrive: Vec<QuestEffect>,
    },
    /// Plays a scripted camera cutscene (DSL v0.4 addendum). Per player: save
    /// gamemode+position, spectator, then dolly two co-located cameras along a
    /// straight-line lerp between waypoints and alternate `spectate` between them
    /// each tick (the two-camera bounce; the same-entity re-`spectate` is a server
    /// no-op and is never emitted), and restore on completion. The compiler
    /// validates the dolly path passes only through non-solid blocks — cameras
    /// fly but must not clip a solid (`DW0308`).
    ///
    /// Camera **aim** (DSL v0.6): with `look_at`, every dolly camera is rotated at
    /// emission to face that world point from its own position, so the shot keeps
    /// its subject framed for the whole move; without it, the camera faces along
    /// the direction of travel (the segment it is currently traversing).
    ///
    /// **Shape** — a cutscene is a list of [`CameraShot`]s played back-to-back
    /// inside one save/restore bracket (hard cut between shots). Two accepted,
    /// mutually exclusive spellings, both normalized by
    /// [`QuestEffect::cutscene_shots`]:
    /// - multi-shot (DSL v0.6): `{"shots": [{path, seconds, look_at?}, …]}`;
    /// - single-shot (DSL v0.4): `{"path": […], "seconds": n, "look_at"?: …}` —
    ///   exactly equivalent to a one-entry `shots` list.
    ///
    /// Mixing or omitting both is `DW0199`.
    Cutscene {
        /// Multi-shot form (DSL v0.6): the ordered shot list. Mutually exclusive
        /// with the single-shot `path`/`seconds` fields (`DW0199`).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        shots: Vec<CameraShot>,
        /// Single-shot form (DSL v0.4): ordered camera waypoints (straight-line
        /// lerp between them).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        path: Vec<Mark>,
        /// Single-shot form (DSL v0.4): shot duration in seconds.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        seconds: Option<u32>,
        /// Single-shot form (DSL v0.6): the subject the camera keeps framed.
        /// Absent = face along the direction of travel.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        look_at: Option<Mark>,
    },
    /// Cuts the dimension-global world time to a new state (DSL v0.5, spec-0010).
    /// Instantaneous (vanilla has no gradual transition); the state persists
    /// because the daylight cycle is frozen by sealing.
    SetTime {
        /// The time state to cut to.
        time: WorldTime,
    },
    /// Cuts the dimension-global weather to a new state (DSL v0.5, spec-0010).
    /// Instantaneous; persists because the weather cycle is frozen by sealing.
    SetWeather {
        /// The weather state to cut to.
        weather: WorldWeather,
    },
    /// Plays a vanilla sound event, positionally or per-player (DSL v0.6,
    /// spec-0014). `sound` is validated against the vendored pinned-1.21.11
    /// sound-event registry (`DW0326` unknown). `at` selects where the sound
    /// originates (default: each player's own position); `volume`/`pitch` map to
    /// the `playsound` command's trailing args (pitch clamps to 0.0..=2.0 in
    /// vanilla).
    PlaySound {
        /// The vanilla sound-event id (`minecraft:` prefix optional).
        sound: String,
        /// Where the sound plays from (default: `players`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        at: Option<SoundAt>,
        /// Playback volume (vanilla default 1.0; > 1.0 only extends audible range).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        volume: Option<f64>,
        /// Playback pitch (vanilla 0.0..=2.0; default 1.0).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pitch: Option<f64>,
    },
    /// Deals damage to the acting player(s) (DSL v0.6): the real consequence a
    /// stealth `on_caught` or a souls-style beat needs — vanilla's `/damage`
    /// primitive. Runs in the effect's `as @a` / `as @s` context, so `@s` is each
    /// acting player: at top level it damages every player once; inside a stealth
    /// `on_caught` it damages the caught player (the "caught → death → respawn at
    /// checkpoint" beat). `amount` is in **half-hearts** (1 HP each); an amount ≥ 40
    /// is lethal through golden apples / absorption. The envelope's `in`
    /// ([`QuestEffect::within`]) narrows to acting players standing inside an
    /// anchor-centred box, keeping the per-`@s` semantics. `damage_type` is the damage
    /// type — a curated set of vanilla types that all respect `keepInventory` and do
    /// **not** bypass totems (no `out_of_world`/`generic_kill`); default `generic`.
    /// (The field is `damage_type`, not `type`, because the effect enum is
    /// internally tagged on `type`.)
    DamagePlayers {
        /// Damage dealt, in half-hearts (1 = 1 HP; ≥ 40 is effectively lethal).
        amount: u32,
        /// The damage type (default [`DamageKind::Generic`]).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        damage_type: Option<DamageKind>,
    },
    /// Sets the party-wide respawn checkpoint (DSL v0.6, spec-0012). Emits
    /// `spawnpoint @a` at the anchor cell and mirrors the coords into
    /// `storage dw:cp pos`. Party-wide and monotonic by quest order (a later
    /// `set-checkpoint` always replaces an earlier one). The compiler proves the
    /// cell is standable (`DW0316`) and that the remaining critical path stays
    /// reachable from it (`DW0315`).
    SetCheckpoint {
        /// The prefab checkpoint anchor the party respawns at.
        anchor: AnchorId,
        /// Per-player effects re-run each time a player respawns while this
        /// checkpoint is the active one — scene reset (e.g. re-caging an
        /// unleashed actor). Emitted idempotently in declared order; empty = no
        /// hook. Respawn is detected via the vanilla `deathCount` criterion.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        on_respawn: Vec<QuestEffect>,
    },
    /// Places a **bonfire** rest point (DSL v0.6, spec-0016 §1) — the sibling of
    /// [`Verb::SetCheckpoint`] for souls-mode pacing. The effect *arms*
    /// the rest affordance (a `minecraft:interaction` the player right-clicks at
    /// the anchor, the campfire prop being prefab dressing); the checkpoint moves
    /// only **when the party actually rests**. Resting fires `on_rest` — the
    /// scene reset that makes retry cheap: re-arming traps, re-seating waves
    /// declared `respawns_on_rest`, restoring actor postures. Death respawns the
    /// party at the last-rested bonfire and runs the **same** `on_rest` bundle,
    /// so the world's answer to a death and to a rest is identical (spec-0016:
    /// death is an investment, never a tax).
    ///
    /// Proofs are inherited from the checkpoint machinery: the anchor must be
    /// standable (`DW0316`) and must not strand the party (`DW0315`), rooted at
    /// the beat that arms the bonfire (the earliest moment a rest can happen).
    Bonfire {
        /// The prefab anchor the rest affordance stands at, and the cell the
        /// party respawns at once rested.
        anchor: AnchorId,
        /// Effects re-run on every rest **and** on every respawn at this bonfire
        /// — the scene reset. Emitted in declared order and expected to be
        /// idempotent (the same contract as `set-checkpoint`'s `on_respawn`).
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        on_rest: Vec<QuestEffect>,
        /// Title of the two-option rest dialog (DSL v0.8).
        /// Absent = the compiler's canonical English `Bonfire`,
        /// baked at emit time (the `world.boundary.message` precedent): an
        /// authored line is inventoried and translates like every other
        /// player-visible string.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        prompt: Option<String>,
        /// Label of the **rest and save** button. Absent = `Rest and save`.
        /// A dialog button is a fixed-width caption, so keep it to ~20 Latin /
        /// ~12 Han characters (skill *Writing craft* §C) — a wider label scrolls.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        rest_label: Option<String>,
        /// Label of the **save only** button. Absent = `Save only`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        save_label: Option<String>,
        /// Hover tooltip of the **rest and save** button (spec-0078) — the same
        /// optional `tooltip` every dialog button carries, beside the label it
        /// explains. Absent = no tooltip. Not subject to `DW0331`: a tooltip
        /// wraps in its own hover box. Inventoried as `fx.….rest_tooltip`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        rest_tooltip: Option<String>,
        /// Hover tooltip of the **save only** button (spec-0078). Absent = no
        /// tooltip. Inventoried as `fx.….save_tooltip`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        save_tooltip: Option<String>,
    },
    /// Begins a stealth beat (DSL v0.6, spec-0014):
    /// zone presence alone = hidden — no sneak requirement, which collides with
    /// the spectator cutscene camera. While active, every player must be
    /// inside some `zone` each tick; a player outside every zone for
    /// `grace_ticks` fires `on_caught` (typically a kill → checkpoint respawn).
    /// Zone membership is read from the player's position. The compiler proves
    /// each zone is standable and reachable from the activating beat (`DW0327`).
    BeginStealth {
        /// The "shadow" regions, each an anchor-centred box (see [`StealthZone`]).
        zones: Vec<StealthZone>,
        /// Per-player effects fired when a player is caught (out of every zone
        /// for `grace_ticks`). Empty = no consequence.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        on_caught: Vec<QuestEffect>,
        /// Ticks a player may be exposed before `on_caught` fires (default 20).
        #[serde(default = "default_grace_ticks")]
        grace_ticks: u32,
    },
    /// Ends the active stealth beat (DSL v0.6, spec-0014). No-op if none active.
    EndStealth,
    /// Summons a `deferred` stage-2 NPC (body + interaction hitbox + name display)
    /// at its declared anchor (DSL v0.6) — the dual of `despawn-npc`, and the
    /// scripted entrance a staged character needs. Idempotent: spawning an NPC
    /// already in the world is a no-op. Only meaningful for an NPC declared
    /// `deferred: true`; a non-deferred NPC is already in the world from init.
    SpawnNpc {
        /// The NPC (stage-2 ref) to summon.
        npc: NpcId,
    },
    // --- DSL v0.6 actor staging effects (spec-0014) ---
    /// Summons a stage-5 actor's puppet at its anchor (DSL v0.6). Idempotent: a
    /// spawn of an already-present actor is a no-op (re-caging after `unleash`).
    SpawnActor {
        /// The actor (stage-5 `actors` ref) to summon.
        actor: ActorId,
    },
    /// Removes an actor's puppet (DSL v0.6). `kill` plays the vanilla death
    /// animation (cutscene deaths); `vanish` is silent removal.
    DespawnActor {
        /// The actor (stage-5 `actors` ref) to remove.
        actor: ActorId,
        /// How the puppet is removed.
        style: DespawnStyle,
    },
    /// Walks an actor's puppet to an anchor by A*-planned per-tick teleport over
    /// the assembled model, using the actor's hitbox footprint, yawed along the
    /// path tangent (DSL v0.6). Concurrent movers are allowed (a herded
    /// flock is N synchronized `move-actor`s). Unroutable → `DW0325`. `on_arrive`
    /// effects fire once the puppet reaches the destination cell.
    MoveActor {
        /// The actor (stage-5 `actors` ref) to move.
        actor: ActorId,
        /// The destination mark: an anchor and an optional offset (spec-0066).
        to: Mark,
        /// Optional travel speed in blocks/tick (defaults to ~0.15).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        speed: Option<f64>,
        /// Effects fired once the puppet arrives at the destination cell.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        on_arrive: Vec<QuestEffect>,
    },
    /// Replaces an actor's puppet with a real-AI twin of the same type / position /
    /// name / attributes / tag (DSL v0.6) — the "attack the idle giant → real
    /// fight" beat. Re-caging is `despawn-actor` + `spawn-actor` (idempotent), not a
    /// special verb.
    UnleashActor {
        /// The actor (stage-5 `actors` ref) to unleash.
        actor: ActorId,
    },
    // --- spec-0082 assembly verbs ---
    /// Summons an assembly (spec-0082): its root, one display per rig part
    /// riding the root, and its hitbox when declared, at its mark, playing its
    /// `initial` clip. Idempotent: a spawn of a present assembly is a no-op.
    SpawnAssembly {
        /// The assembly (stage-5 `assemblies` ref) to summon.
        assembly: AssemblyId,
    },
    /// Removes an assembly's root, parts and hitbox (spec-0082). They leave
    /// unseen: a display entity has no death, so there is no `style`.
    DespawnAssembly {
        /// The assembly (stage-5 `assemblies` ref) to remove.
        assembly: AssemblyId,
    },
    /// Switches the clip an assembly plays (spec-0082); its first frame is
    /// applied on the next tick. While a strike step is in flight the switch
    /// waits for the step to end, so a story beat never cuts a strike at the
    /// frame before it lands.
    PlayClip {
        /// The assembly (stage-5 `assemblies` ref).
        assembly: AssemblyId,
        /// A clip the assembly's rig declares.
        clip: String,
    },
    /// A deterministic timeline (DSL v0.6): one schedule chain firing effect groups
    /// at exact tick offsets. Effects are any in the stage-5 set except a nested
    /// `sequence` (rejected with `DW0329`).
    Sequence {
        /// Timeline steps; each fires its `effects` at `at_ticks` from the start.
        steps: Vec<SequenceStep>,
    },
    /// **Saturating projectile volley** (DSL v0.6, spec-0022): command-summoned
    /// projectiles with real velocity vectors, fired from a gallery slot into a
    /// declared kill zone.
    ///
    /// The contract is **saturation, not sniping**.
    /// Every salvo puts one projectile on the trajectory to **every standable
    /// cell of `kill_zone`**, plus one aimed at the triggering player's
    /// fire-time position (which punishes standing still). A player therefore
    /// cannot dodge a volley by strafing — escaping means *leaving the zone*, a
    /// decision rather than a lucky step. Coverage is proven at compile time:
    /// `from_anchor` must have clear line of fire to every standable kill-zone
    /// cell (`DW0442`), so "the gallery slot can actually hit a player anywhere
    /// on the stairs" is a build-time fact, not a hope.
    ///
    /// Projectiles are summoned `NoGravity` so the flown path is exactly the
    /// straight segment the coverage proof checks — proof and runtime share one
    /// geometry. Drag scales speed but not direction, so the line is preserved.
    Volley {
        /// Projectile entity id (default `minecraft:arrow`; validated against
        /// the pinned 1.21.11 registry, `DW0441`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        projectile: Option<String>,
        /// The gallery slot the volley is fired FROM — a point anchor. Its cell
        /// must be clear (a projectile spawned inside a wall never leaves it).
        from_anchor: AnchorId,
        /// The zone the volley must blanket, as an anchor-centred box
        /// (`anchor ± extent`) — the same shape `damage-players`'s `in` and
        /// `begin-stealth`'s `zones` use. Every standable cell in it receives
        /// fire each salvo.
        ///
        /// Deliberately NOT a bare prefab `region` anchor: the assembled model
        /// clears every gate-region anchor's cells unconditionally, so
        /// describing a zone that way would delete the geometry it names.
        kill_zone: StealthZone,
        /// How many rounds the pattern repeats (default 3, `DW0443` bounds it).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        salvos: Option<u32>,
        /// Ticks between salvos (default 10, `DW0443` bounds it).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        interval: Option<u32>,
    },
    /// **Ceiling collapse** (DSL v0.6, spec-0022): delete a region's blocks and
    /// drop them as `falling_block` entities — the buried-alive trap redstone
    /// cannot express at all.
    ///
    /// The post-collapse world is **modeled, not guessed**: the compiler clears
    /// the region, settles every dropped column through the existing gravity
    /// model (spec-0010), optionally paves the landing surface with
    /// `then_floor`, and re-runs the critical-path completability proof against
    /// that mutated world (`DW0445`). A collapse that buries the only route is a
    /// build error, exactly as a `shortcut` seal that strands the party is.
    Collapse {
        /// The volume whose blocks fall, as an anchor-centred box
        /// (`anchor ± extent`). Must hold blocks and sit above standable footing
        /// (`DW0444`) — a collapse over nothing is scenery, not a trap.
        ///
        /// An anchor-centred box rather than a prefab `region` anchor for a
        /// load-bearing reason: the assembled model deletes every gate-region
        /// anchor's cells, so a ceiling slab declared that way would already be
        /// gone before the trap ever fired.
        region_anchor: StealthZone,
        /// The block the falling entities are made of (default
        /// `minecraft:gravel`; validated against the pinned registry, `DW0441`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        falling_block: Option<String>,
        /// Optional block the landing surface is paved with once the debris
        /// settles — the authored post-collapse floor the completability proof
        /// reasons over.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        then_floor: Option<String>,
    },
    /// Grants a vanilla **status effect** for a stated duration (DSL v0.10,
    /// spec-0031). The engine has emitted status effects since v0.6 — the
    /// night-vision area mitigation is a self-rescheduling, region-scoped
    /// `effect give` — and exposed none, so an author who wanted blindness for a
    /// lift ride, slowness in deep water or regeneration at a shrine had no
    /// surface at all. This is that surface, over the whole pinned 1.21.11
    /// `mob_effect` registry (`DW0192` rejects an id outside it).
    ///
    /// **A grant carries a duration, and there is no way to spell one that does
    /// not.** Vanilla's `infinite` keyword is deliberately absent from this
    /// surface: an effect whose only removal is a later command is an effect the
    /// player keeps forever whenever that command does not run — a logout, a
    /// crash, a chain interrupted by a death. A duration expires on its own, with
    /// no cooperation from anything. `seconds` is therefore required and bounded
    /// (1..=[`MAX_EFFECT_SECONDS`], `DW0541`), and the *pattern* that reintroduces
    /// the same hazard — pairing a grant with a `clear-effect` that removes it
    /// while it is still live — is `DW0540`.
    ///
    /// The envelope's `in` ([`QuestEffect::within`]) narrows to players inside an
    /// anchor-centred box. It is what makes "blind whoever is riding the car"
    /// expressible without blinding the whole party. A blinding grant owes the
    /// blind-reach proof wherever it is written (`DW0943`, spec-0085 §6).
    GiveEffect {
        /// Vanilla status-effect id (e.g. `minecraft:blindness`), validated
        /// against the pinned 1.21.11 registry (`DW0192`).
        effect: String,
        /// Duration in seconds. Required, `1..=`[`MAX_EFFECT_SECONDS`]
        /// (`DW0541`) — see the variant docs for why there is no infinite form.
        seconds: u32,
        /// Amplifier (0 = level I), `0..=`[`MAX_POTION_AMPLIFIER`] (`DW0541`).
        /// Absent = 0.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        amplifier: Option<u32>,
        /// Suppress the swirling particles (vanilla's `hideParticles`). Absent =
        /// `false`, vanilla's own default.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hide_particles: Option<bool>,
    },
    /// Removes a status effect (DSL v0.10, spec-0031) — vanilla's `effect clear`.
    ///
    /// This is **not** how a `give-effect` is supposed to end: a duration is. It
    /// exists for the effects the engine did not grant — a potion the player
    /// drank, a `wither` a mob applied, the whole set at a bonfire — which is why
    /// `effect` is optional (absent = clear everything, exactly as vanilla's
    /// `effect clear <targets>` does). Pairing it with a live grant of the same
    /// effect in the same bundle is `DW0540`.
    ClearEffect {
        /// The status-effect id to remove (`DW0192`). **Absent clears every
        /// effect**, matching `effect clear <targets>` with no id.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        effect: Option<String>,
    },
    /// Teleports **everything inside a declared volume** to an anchor (DSL v0.10,
    /// spec-0031).
    ///
    /// **The selector is a region, never a block.** "Whoever is standing on this
    /// block" has three different answers for a player half a foot over the edge,
    /// a player mid-jump and a player sneaking on the lip; a volume has one, and
    /// it is the same one every tick. `from` is the anchor-centred
    /// [`StealthZone`] box the rest of the engine already uses.
    ///
    /// **The selection is total over bodies.** Emission is a single `tp
    /// @e[<box>,tag=!dw_fixture] <cell>` with no `type=`, no `limit=` and no
    /// `sort=` — every body in the volume moves, and
    /// `crates/delvec/tests/v10_teleport.rs` asserts that from the emitted
    /// selector rather than from anyone's memory. A machinery-**type** exemption
    /// of the kind a `lethal_volumes[]` entry must carry was considered and
    /// **rejected**: an NPC is a body plus a co-located `minecraft:interaction`
    /// hitbox, so exempting `minecraft:interaction` — as the lethal volume does —
    /// would teleport the speaker and leave its dialogue box behind. Everyone on
    /// the car travels, players and entities
    /// alike; totality over bodies is how that is true.
    ///
    /// The one narrowing is a **class the engine's own furniture declares about
    /// itself**: `dw_fixture` means *my position IS engine state*. A bonfire's
    /// hitbox, a shortcut lever and a recovery stake's marker are places, not
    /// passengers, and carrying one does not move a thing — it rewrites a fact
    /// (for a stake, the ledger holds the marker's coordinates, and the next tick
    /// retires a marker nobody has a wager at). Places whose cell is known at
    /// compile time are refused outright instead, because the author can move
    /// them (`DW0542`); places the runtime puts down are excluded by the selector,
    /// because nobody can (`DW0545`). Nothing an author writes carries either tag,
    /// and no campaign JSON can turn either off.
    ///
    /// **A teleport is not a rescue.** Accumulated fall distance carries across
    /// one unchanged and is charged in full at the destination — measured Δ
    /// exactly `0.0000` in 46/46 trials on the pinned 1.21.11, including
    /// teleports 143 and 157 blocks straight *up*, with landing damage
    /// `floor(fall_distance) − 3` (`docs/notes/death-and-teleport-spike.md` §3).
    /// A platform that arrives under a falling player past ~20 blocks of fall is
    /// the surface they die on. The compiler does not try to reset the counter:
    /// what *does* reset it was explicitly not measured, and inventing a
    /// mechanism from recall is the folklore this project forbids.
    Teleport {
        /// The volume whose contents are moved, as an anchor-centred box
        /// (`anchor ± extent`) — the same shape a `begin-stealth` zone, a
        /// `damage-players` `in` filter and a `lethal_volumes[]` region take.
        ///
        /// Deliberately NOT a bare prefab `region` anchor, for the reason
        /// [`Verb::Collapse`] records: the assembled model clears every
        /// gate-region anchor's cells, so a volume described that way would
        /// delete the geometry it names.
        from: StealthZone,
        /// The destination mark (spec-0066). Resolved to a literal cell at build
        /// time, so the emitted `tp` carries absolute coordinates and no runtime
        /// search.
        to: Mark,
    },
    /// Fires a **firework rocket** from a mark (DSL v0.29, spec-0068).
    ///
    /// One effect at a point, the member of the same class as [`Verb::PlaySound`]
    /// — a one-shot thing that happens where the campaign says, beside the sound
    /// that goes with it. A display of many rockets is a [`Verb::Sequence`] of
    /// these, not a verb with timing of its own.
    ///
    /// # The burst height is a stated number, not a roll
    ///
    /// The emitter writes the entity's `LifeTime`
    /// ([`crate::firework::lifetime_ticks`]) rather than leaving it to the game,
    /// which randomises it at launch: two runs of one datapack would otherwise
    /// burst at two heights and nothing could be proven about where the burst is.
    /// Fixed at the floor of the game's range, the burst stands
    /// [`crate::firework::burst_height`] blocks over the mark.
    ///
    /// # A burst hurts, so the compiler asks where it is
    ///
    /// A build refuses a rocket whose column to that height is roofed, and one
    /// whose burst lies within [`crate::firework::BLAST_RADIUS`] blocks of a
    /// place the campaign posts a body (`DW0899`). Players are **not** posted:
    /// a player standing level with a burst takes up to
    /// [`crate::firework::worst_damage_hp`] HP, under a full body's twenty, and
    /// that is a hazard a player can see coming.
    Firework {
        /// The mark the rocket is launched from — the cell's centre, at the
        /// mark's own plane.
        at: Mark,
        /// Flight duration, 1–3 (the three the game crafts). Absent =
        /// [`crate::firework::MIN_FLIGHT`].
        #[serde(default, skip_serializing_if = "Option::is_none")]
        #[schemars(range(min = 1, max = 3))]
        flight: Option<u8>,
        /// One to seven bursts, in the order the component carries them.
        #[schemars(length(min = 1, max = 7))]
        explosions: Vec<FireworkExplosion>,
    },
    /// Spawns **particles** (spec-0085 §4.3) — the next one-shot point effect
    /// after [`Verb::Firework`], at a mark or at each addressed player.
    ///
    /// `particle` is a vanilla particle type id validated against the pinned
    /// registry `crates/dsl/data/particles-1.21.11.json`; an unknown id, or one
    /// whose type **takes options** (`dust`, `block`, `item`, …), is `DW0941`.
    ///
    /// Emitted as one vanilla `particle` command, always in **`force`** mode,
    /// whose viewers are the effect's audience: a particle a creator writes is
    /// meant to be seen, and `force` is the mode the game sends 512 blocks out
    /// and draws even at the client's Minimal particle setting. A
    /// `minecraft:elder_guardian` at `players` is the full-screen face.
    Particle {
        /// The particle type id (`minecraft:` prefix optional).
        particle: String,
        /// Where the particles spawn: a [`Mark`], or `players` — at each
        /// addressed player's own position.
        at: ParticleAt,
        /// How many (vanilla `<count>`, default 1). Zero is vanilla's spelling of
        /// a different thing — one particle with a velocity — and is refused.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        #[schemars(range(min = 1))]
        count: Option<u32>,
        /// Standard deviations `[x, y, z]` of the spawn spread, in blocks
        /// (vanilla `<delta>`, default `[0, 0, 0]`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        spread: Option<[f64; 3]>,
        /// Vanilla `<speed>` (default 0).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        speed: Option<f64>,
    },
}

/// Where a [`Verb::Particle`] spawns (spec-0085 §4.3): a mark, or the literal
/// `players`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum ParticleAt {
    /// `"players"` — at each addressed player's own position.
    Players(PlayersKeyword),
    /// A mark — the cell's centre at the mark's plane.
    Mark(Mark),
}

/// The literal `players`, the one keyword [`ParticleAt`] admits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum PlayersKeyword {
    /// At each addressed player.
    Players,
}

/// Default `grace_ticks` for [`Verb::BeginStealth`] (spec-0014).
fn default_grace_ticks() -> u32 {
    20
}

/// Default projectile for [`Verb::Volley`] (spec-0022).
pub const DEFAULT_VOLLEY_PROJECTILE: &str = "minecraft:arrow";
/// Default salvo count for [`Verb::Volley`] (spec-0022).
pub const DEFAULT_VOLLEY_SALVOS: u32 = 3;
/// Default ticks between salvos for [`Verb::Volley`] (spec-0022).
pub const DEFAULT_VOLLEY_INTERVAL: u32 = 10;
/// Largest admissible `salvos` — beyond this a volley is an entity-count
/// hazard rather than a trap (`DW0443`).
pub const MAX_VOLLEY_SALVOS: u32 = 16;
/// Largest admissible `interval` in ticks (`DW0443`): 10 seconds. A volley
/// slower than this is no longer one event the player reads as a trap.
pub const MAX_VOLLEY_INTERVAL: u32 = 200;
/// Default falling block for [`Verb::Collapse`] (spec-0022).
pub const DEFAULT_COLLAPSE_FALLING_BLOCK: &str = "minecraft:gravel";

/// A stealth "shadow" region (DSL v0.6, spec-0014): an axis-aligned box centred
/// on `anchor`, extending `extent` blocks along each axis (so the box spans
/// `anchor ± extent`). Presented in-world via dark cells but judged purely by
/// region membership, so the check is deterministic and provable.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct StealthZone {
    /// The prefab anchor at the centre of the zone box.
    pub anchor: AnchorId,
    /// Half-extents `[x, y, z]` in blocks from the anchor (each component ≥ 0);
    /// the zone AABB is `[anchor - extent, anchor + extent]`.
    pub extent: [u32; 3],
}

/// Where a [`Verb::PlaySound`] originates (DSL v0.6, spec-0014). A sound
/// plays at fixed coordinates or at each listener's own position; the compiler
/// resolves no position for a live actor, so the `actor` variant is accepted by
/// the schema and rejected with `DW0335`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "at", rename_all = "kebab-case", deny_unknown_fields)]
pub enum SoundAt {
    /// Play the sound positioned at a resolved anchor, audible to all players.
    Anchor {
        /// The anchor the sound plays from.
        anchor: AnchorId,
        /// Integer `[x, y, z]` block offset from `anchor` (spec-0066, default
        /// `[0, 0, 0]`): the sound plays at the [`Mark`] the two fields spell.
        #[serde(default, skip_serializing_if = "is_zero3")]
        offset: [i32; 3],
    },
    /// Play the sound at each player's own position (the default), or at
    /// `offset` in **the listener's own frame** (spec-0085 §4.4): `+x` to the
    /// listener's left, `+y` up, `+z` the way the listener faces, with the pitch
    /// flattened so *behind* stays at ear height. `[0, 0, -3]` is three blocks
    /// behind. Integer blocks, as a [`Mark`]'s offset is.
    Players {
        /// Integer `[x, y, z]` offset in the listener's local frame (default
        /// `[0, 0, 0]`).
        #[serde(default, skip_serializing_if = "is_zero3")]
        offset: [i32; 3],
    },
    /// Play the sound at a scripted actor's position (rejected — `DW0335`; no
    /// actor position resolves at emission).
    Actor {
        /// The actor id (stage-5 `actors[]`).
        actor: String,
    },
}

/// The damage type of a [`Verb::DamagePlayers`] effect (DSL v0.6). A
/// **curated** subset of the vanilla 1.21.11 damage-type registry: every variant
/// respects the `keepInventory` death flow (a gamerule, so all deaths do) and does
/// **not** bypass a totem of undying — the totem-bypassing `out_of_world` /
/// `generic_kill` types are deliberately excluded, so a scripted consequence can
/// never silently void a player's held totem. Modelled as an enum (not a free
/// string) so an unknown type is a schema rejection (`DW0100`) and needs no separate
/// registry / diagnostic. `generic` is the default: command damage that respects
/// totems + absorption but ignores armor, so a scripted hit lands regardless of gear.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum DamageKind {
    /// `minecraft:generic` — armor-ignoring command damage (default).
    Generic,
    /// `minecraft:magic` — magical damage.
    Magic,
    /// `minecraft:wither` — the wither/withering effect's damage type.
    Wither,
    /// `minecraft:on_fire` — burning damage.
    Fire,
    /// `minecraft:drown` — drowning damage.
    Drown,
    /// `minecraft:freeze` — powder-snow freezing damage.
    Freeze,
    /// `minecraft:fall` — fall damage.
    Fall,
    /// `minecraft:lightning_bolt` — a lightning strike's damage type.
    LightningBolt,
    /// `minecraft:explosion` — a (non-player) explosion's damage type.
    Explosion,
}

impl DamageKind {
    /// The vanilla `minecraft:` damage-type id emitted to `/damage`.
    pub fn id(self) -> &'static str {
        match self {
            DamageKind::Generic => "minecraft:generic",
            DamageKind::Magic => "minecraft:magic",
            DamageKind::Wither => "minecraft:wither",
            DamageKind::Fire => "minecraft:on_fire",
            DamageKind::Drown => "minecraft:drown",
            DamageKind::Freeze => "minecraft:freeze",
            DamageKind::Fall => "minecraft:fall",
            DamageKind::LightningBolt => "minecraft:lightning_bolt",
            DamageKind::Explosion => "minecraft:explosion",
        }
    }
}

/// A stage-5 **lethal volume** (DSL v0.10, spec-0031): a declared box that kills
/// whatever enters it, and states — in the campaign's own words — what killed it.
///
/// # A mechanism, not a fiction
///
/// The commissioning case was a cliff whose fall must be fatal, but nothing here
/// knows what a cliff is: a lava pit, an acid pool, an out-of-bounds plane and the
/// bottom of a lift shaft are the same declaration, differently dressed and
/// differently worded. The alternative considered and **rejected** for the cliff
/// was making the world's horizon void so the fall kills anyway — that changes
/// approved art to obtain a behaviour, and it serves exactly one fiction.
///
/// # It is geometry, so the completability proof owns it
///
/// A volume that kills is, for a route, a volume that cannot be crossed. The
/// compiler models its cells as impassable in the same navigation world every
/// other reachability proof runs on, exactly as a `close-gate`'s sealed region is
/// modelled solid — so a forced path that has no way to an objective except
/// through a lethal volume is a build failure (`DW0510`) naming the volume, never
/// a shipped delve that kills the player on the critical path. A respawn seat
/// inside one is the death loop that failure mode ends in, and is its own
/// error (`DW0511`).
///
/// # It rides the death edge that already exists
///
/// The kill is a `/damage`, exactly like `damage-players`, a trap payload or a
/// timed gate's crush. Everything downstream — the vanilla `deathCount` edge
/// (`dw.deaths` / `dw.death_ack`), the checkpoint re-seat (`cp_respawn_check`),
/// `keep_inventory` — sees an ordinary death and needs no second detector.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct LethalVolume {
    /// Unique lethal-volume id (`lethal/<kebab>`).
    pub id: LethalVolumeId,
    /// The volume: an anchor-centred box (`anchor ± extent`).
    ///
    /// **Deliberately the existing zone type**, not a second struct with the same
    /// two fields. `StealthZone` is already the engine's anchor-centred box object
    /// class — `damage-players`'s `in` filter reuses it, and the compiler resolves
    /// every one of them through the single `Plan::zone_box`. A private twin here
    /// would be `tools/ci/check-capability-ownership.py` check C by construction, and
    /// would fork the resolution the very next time a box grew a capability.
    pub region: StealthZone,
    /// What this volume says when it kills — a player-visible line, inventoried
    /// under `lethal.<id>.message` and translated like every other one.
    ///
    /// Required, and deliberately so: a volume with no words is a player who dies
    /// with no idea why, and there is no compiler-owned default that could be
    /// right for a cliff, a lava pit and an acid pool at once.
    pub message: String,
    /// The damage type the kill is dealt with (default [`DamageKind::Generic`]).
    ///
    /// This is what words vanilla's own broadcast — `fall` says the party member
    /// fell from a high place, `on_fire` that they burnt to a crisp — while
    /// [`Self::message`] says what the *place* was. The curated enum is shared
    /// with `damage-players`, so a lethal volume can no more void a held totem
    /// than a scripted hit can.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub damage_type: Option<DamageKind>,
    /// **The blocks that show a player this floor kills** (spec-0062 §3).
    ///
    /// A lava surface, a magma floor, a bed of spikes, a burning strip: the
    /// danger is level with the footing because the block *is* the signal. This
    /// is where a volume says so, and it is a claim about the assembled bytes
    /// rather than a word that switches a rule off — `DW0891` checks it per
    /// caught cell against the block under or in that cell, refuses a listed
    /// block no caught cell bears out, and refuses at validation any id vanilla
    /// does not hurt a body with.
    ///
    /// Empty is the ordinary case and means the ordinary thing: this volume
    /// catches no floor the party walks, because it sits at the bottom of a pit
    /// or a course under a lake's surface. It does **not** exempt a cell from
    /// the walk graph — a visible hazard is still a hazard, and the router
    /// refuses every cell of the keep-out either way.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shown_by: Vec<String>,
    /// **When this volume kills** (spec-0088): the one [`Guard`] every other
    /// gated object carries, verbatim. Absent, the volume is live from
    /// world-load to the end. Present, it is live while its gate holds —
    /// `requires_flags` is a pit that kills from a beat on, `forbids_flags` a
    /// shaft that kills until one, `requires_state` a chamber that kills while
    /// a party datum stands in range.
    ///
    /// A volume's liveness is a fact about the place, so the gate is a fact
    /// about the party: `when: {}` (a stage with no term) and a term on a
    /// `player`-scoped datum are refused at the document (`DW0953`). The
    /// navigation world holds the volume per quest configuration, and `DW0891`
    /// judges what shows it in every configuration a body can meet it in,
    /// including the last one before it goes live.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when: Option<Guard>,
}

/// A stage-5 **loop** (spec-0086): a slab a body crosses and is returned from,
/// by a whole-block offset, to an earlier section that looks exactly the same —
/// its position inside the cell, its facing and its velocity all kept.
///
/// # It is a region with a standing property
///
/// A loop acts on whatever body enters a volume, every tick, the way a
/// [`LethalVolume`] does; nothing completes and nobody is addressed. So it is
/// declared beside the lethal volume, with the same region type
/// ([`StealthZone`], resolved through the one `Plan::zone_box`), and not as a
/// trigger with a relative teleport in it: the seamlessness proof is a property
/// of the region-plus-offset pair, which a compiler would otherwise have to
/// recognise by pattern-matching a trigger's effect list.
///
/// # The offset is derived, never typed
///
/// `to` is a [`Mark`] naming where the slab's own anchor cell lands, so the
/// offset is `cell(to) − cell(region.anchor)` — a whole-block vector by
/// construction, and a judgement about the world (*the fourth bay's anchor lands
/// on the second's*) rather than a vector the compiler could compute.
///
/// # The gate is the release
///
/// The loop **holds** while its gate is open and stands down while it is shut,
/// read against the party: flags are campaign state, and a `requires_state` term
/// must name a `party` datum (`DW0949`). A loop with no gate term holds forever
/// and is refused at the document (`DW0949`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Loop {
    /// Unique loop id (`loop/<kebab>`).
    pub id: LoopId,
    /// The slab a body crosses: an anchor-centred box (`anchor ± extent`), one
    /// axis of which is the crossing axis. The existing zone type, for the reason
    /// [`LethalVolume::region`] gives.
    pub region: StealthZone,
    /// Where the slab's own anchor cell lands: the loop's offset is
    /// `cell(to) − cell(region.anchor)`. Lies inside its anchor's piece
    /// (`DW0897`).
    pub to: Mark,
    /// Flags that must all be set for the loop to hold.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_flags: Vec<FlagId>,
    /// Flags any one of which stands the loop down — `forbids_flags:
    /// [flag/the-bell-found]` is a loop that ends the moment the bell is found.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbids_flags: Vec<FlagId>,
    /// Numeric gate terms: every comparison must hold for the loop to hold. Each
    /// names a `party`-scoped datum (`DW0949`). The third field of the one gate,
    /// carried by every gate consumer.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_state: Vec<StateCompare>,
    /// A `party`-scoped datum the loop raises by one on every move, before
    /// `on_cross` runs — the counter a crossing-counted release reads.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub counts: Option<StateId>,
    /// The dungeon's answer to a move: effects run on every move, after the body
    /// is moved and the count raised, from the server command source (no acting
    /// player). Each effect's own `when` keys a write to a count. A `teleport`
    /// here is refused (`DW0949`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub on_cross: Vec<QuestEffect>,
}

// ---------------------------------------------------------------------------
// Stage 5 — trade and the recovery stake (DSL v0.10, spec-0032)
// ---------------------------------------------------------------------------

/// A stage-5 **shop** (DSL v0.10, spec-0032): an interaction point that opens a
/// list of offers, each of which is a gate and a bundle of effects.
///
/// # It is the rest flow with different buttons, and that is the whole design
///
/// A bonfire is already an interaction entity, a player-interaction advancement
/// that supplies the acting player, a `minecraft:multi_action` dialog, buttons
/// that run `/trigger`, and tick dispatch. A shop is that same hardware with an
/// authored button list, so nothing here is new machinery — it is the machinery
/// spec-0016 §1 shipped, made author-visible.
///
/// # There is no price field, and that is deliberate
///
/// A price is *"may this happen yet?"*, which is the question
/// [`Gate`](crate::gate::Gate) answers for six other object classes. An offer is
/// therefore the **seventh gate consumer**: it carries `requires_flags`,
/// `forbids_flags` and `requires_state`, and the numeric comparison it needs is
/// the one spec-0031 put in the gate rather than in the verb that first asked.
/// A `price` field would be a second comparison surface for one meaning, which is
/// the defect CLAUDE.md names first.
///
/// # Villager `Offers` is excluded
///
/// Three independent reasons, any one sufficient (spec-0032): a vanilla trade
/// cost can only ever be an item, never a scoreboard value; right-click on a
/// villager body is already allocated to dialogue; and the data-driven trade
/// registry post-dates the pinned 1.21.11.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Shop {
    /// Unique shop id (`shop/<kebab>`).
    pub id: ShopId,
    /// The prefab anchor the shop's interaction point stands on.
    pub anchor: AnchorId,
    /// The dialog's title line. Player-visible, inventoried under
    /// `shop.<id>.title`.
    pub title: String,
    /// The item the visible marker renders as (default `minecraft:emerald`).
    /// Cosmetic only: the marker is a `minecraft:item_display`, so it never
    /// occupies the cell or obstructs the hitbox.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub marker_item: Option<String>,
    /// The offers, in declaration order — which is button order, and the order
    /// the `/trigger` routing values are assigned in.
    pub offers: Vec<ShopOffer>,
}

/// One button in a [`Shop`]: a gate, a label, and the effects choosing it runs.
///
/// **Effect root R8.** The bundle hangs off an object with runtime machinery of
/// its own (an advancement, a dialog, a trigger objective and a tick dispatch),
/// which is spec-0031's stated rule for adding a root rather than desugaring.
///
/// **Refusal is authored, not a field.** An offer whose own gate is closed is not
/// shown at all; an offer that should be *shown and refuse* leaves its own gate
/// open and gates its effects instead — the purchase behind `at-least <price>`,
/// the apology behind `at-most <price − 1>`. Both are the ordinary per-effect
/// gate every effect already carries, so the engine adds no `refused` field and
/// no second way to say one thing.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ShopOffer {
    /// The button's caption. Player-visible, inventoried under
    /// `shop.<id>.offer.<i>.label`, and width-checked like any dialog button.
    pub label: String,
    /// The button's hover tooltip — the natural home for a price in words.
    /// Player-visible, inventoried under `shop.<id>.offer.<i>.tooltip`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tooltip: Option<String>,
    /// Flags that must all be set for this offer to be shown (the one gate).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_flags: Vec<FlagId>,
    /// Flags whose being set hides this offer (the one gate).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub forbids_flags: Vec<FlagId>,
    /// Numeric gate terms (the one gate) — **this is where a price lives**.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_state: Vec<StateCompare>,
    /// What choosing this offer does. Effect root R8; runs with the choosing
    /// player as the acting player, so a `player`-scoped datum is writable here.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub effects: Vec<QuestEffect>,
}

impl ShopOffer {
    /// This offer's whole gate, as one value (DSL v0.10) — see
    /// [`crate::gate::Gate`].
    pub fn gate(&self) -> crate::gate::Gate<'_> {
        crate::gate::Gate::of(
            &self.requires_flags,
            &self.forbids_flags,
            &self.requires_state,
        )
    }
}

/// How much of a datum a death forfeits into a [`Stake`] (DSL v0.10, spec-0032).
///
/// A creator who wants **no death cost at all** picks [`Forfeit::None`]; the
/// stake then still marks where they fell, which is the memorial case.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum Forfeit {
    /// The whole balance.
    All,
    /// A percentage of the balance, rounded toward zero (integer arithmetic —
    /// ADR-0006 forbids anything a second implementation could round differently).
    Proportion {
        /// 0–100.
        percent: u32,
    },
    /// A fixed amount, capped at the balance so a purse can never go negative.
    Fixed {
        /// The amount.
        amount: i32,
    },
    /// Nothing is taken. The stake is a marker, not a wager.
    None,
}

/// What a death does when the player already holds the maximum number of live
/// stakes (DSL v0.10, spec-0032).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum OnFull {
    /// Retire the player's oldest live stake — its contents are lost — and place a
    /// new one. With `max_live: 1` this is the souls behaviour.
    Replace,
    /// Leave the existing stakes alone: the new death places nothing and forfeits
    /// nothing. One wager at a time.
    Keep,
}

impl OnFull {
    /// The wire token (`replace` / `keep`).
    pub fn token(self) -> &'static str {
        match self {
            OnFull::Replace => "replace",
            OnFull::Keep => "keep",
        }
    }
}

/// Who may collect a stake that is not theirs (DSL v0.10, spec-0032).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum CollectBy {
    /// Only the player who left it. The default.
    Owner,
    /// Anyone standing at it. The whole of every live stake at that place is
    /// transferred to the collector.
    Anyone,
}

impl CollectBy {
    /// The wire token (`owner` / `anyone`).
    pub fn token(self) -> &'static str {
        match self {
            CollectBy::Owner => "owner",
            CollectBy::Anyone => "anyone",
        }
    }
}

/// A stage-5 **recovery stake** (DSL v0.10, spec-0032): what a death leaves
/// behind, and the one chance to get it back.
///
/// # A mechanism, not a genre
///
/// "Souls" is one setting of this declaration and nothing here knows the word.
/// The mechanism is *a death forfeits some of a declared datum into a collectable
/// marker at a computed place, and collecting it returns exactly what was taken*.
/// A campaign with no death cost, a campaign with a permanent memorial at every
/// death site, and a campaign with the souls loop are three configurations, not
/// three engines.
///
/// # Where it lands is a compile-time answer
///
/// The owner's rule: *the anchor is the point, on the walkable path
/// from the respawn point in force at the moment of death to the death point
/// under the quest state in force at that moment, that minimises distance to the
/// death point.* Every term already has an owner in the compiler — walkability is
/// the navigation world the completability proof runs on, quest-state passability
/// is the DAG-indexed sealing `close-gate` established, and the respawn point in
/// force is engine state. So it is a table computed at build time and a lookup at
/// run time: **no runtime search, no nondeterminism.**
///
/// # It is hardware, so it inherits the hardware rules
///
/// The marker is an invisible `minecraft:interaction` for the hitbox plus a
/// glowing `minecraft:item_display` for the rendering — the same pair every other
/// affordance in the engine uses, and therefore the same invisible-affordance
/// (`DW0420`) and hardware-erasure (`DW0421`) proofs. It is deliberately **not**
/// a dropped item entity: an item despawns after 6000 ticks, burns in lava, sinks
/// in the void, and can be picked up by anyone.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Stake {
    /// Unique stake id (`stake/<kebab>`).
    pub id: StakeId,
    /// The datum a death forfeits into this stake, and a collection returns.
    /// Must be declared in the stage-5 `state` list, and must be `player`-scoped:
    /// a stake is a personal wager, and a party-shared purse would turn one
    /// player's death into everyone's penalty.
    pub state: StateId,
    /// How much of [`Self::state`] a death takes. Default: the whole balance.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub forfeit: Option<Forfeit>,
    /// How many live stakes one player may hold at once. Default 1; `0` means a
    /// death never places one (and never forfeits anything), which is the
    /// "no death cost" configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_live: Option<u32>,
    /// What a death does when the player is already at [`Self::max_live`].
    /// Default [`OnFull::Replace`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_full: Option<OnFull>,
    /// Who may collect. Default [`CollectBy::Owner`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collect_by: Option<CollectBy>,
    /// The line a collection says, on the action bar. Player-visible, inventoried
    /// under `stake.<id>.collected`.
    pub collected_message: String,
    /// The item the glowing marker renders as (default `minecraft:soul_lantern`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub marker_item: Option<String>,
}

impl Stake {
    /// The forfeit rule, with the documented default applied.
    pub fn forfeit(&self) -> Forfeit {
        self.forfeit.unwrap_or(Forfeit::All)
    }

    /// How many live stakes one player may hold, with the documented default.
    pub fn max_live(&self) -> u32 {
        self.max_live.unwrap_or(1)
    }

    /// The at-capacity rule, with the documented default.
    pub fn on_full(&self) -> OnFull {
        self.on_full.unwrap_or(OnFull::Replace)
    }

    /// The collection rule, with the documented default.
    pub fn collect_by(&self) -> CollectBy {
        self.collect_by.unwrap_or(CollectBy::Owner)
    }

    /// The item the marker renders as, with the documented default.
    pub fn marker_item(&self) -> &str {
        self.marker_item
            .as_deref()
            .unwrap_or("minecraft:soul_lantern")
    }
}

/// The presentation channel for a [`Verb::Narrate`] (DSL v0.4).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum NarrateStyle {
    /// A chat line (default).
    Chat,
    /// A large on-screen title.
    Title,
    /// An on-screen subtitle.
    Subtitle,
    /// An "art" title rendered through the delve's custom resource-pack pixel-banner
    /// font (`delve:art`) so endings can flash blocky all-caps text (DSL v0.6,
    /// spec-0014). Text is checked at compile time against the font's glyph inventory
    /// (`DW0328`); characters outside it (e.g. non-Latin script) are rejected. It
    /// renders in the vanilla title slot, so it is width-checked like any title
    /// (`DW0330`) — roughly 15 glyphs fit on screen.
    Art,
    /// The **actionbar** — the one-line strip above the hotbar (DSL v0.11).
    ///
    /// This is the channel a *reply* uses: it does not interrupt, it does not
    /// stack, and it is overwritten by the next one. Every reply the compiler
    /// itself writes has always used it — a sealed gate's answer, a checkpoint
    /// return, the lobby's party count — but `narrate` could not reach it, which
    /// is the mechanical reason `close-gate.sealed_hint` could not have been an
    /// ordinary `narrate` even had someone tried (capability-ownership audit
    /// finding 3b). A channel is a property of the message, not of the verb that
    /// first wanted it.
    ///
    /// Unlike a title it is never width-checked: vanilla truncates nothing and
    /// draws it at GUI width, and a reply is a fragment rather than a banner.
    Actionbar,
}

impl NarrateStyle {
    /// The kebab tag (`chat` / `title` / `subtitle` / `art` / `actionbar`).
    pub fn token(self) -> &'static str {
        match self {
            NarrateStyle::Chat => "chat",
            NarrateStyle::Title => "title",
            NarrateStyle::Subtitle => "subtitle",
            NarrateStyle::Art => "art",
            NarrateStyle::Actionbar => "actionbar",
        }
    }
}

/// **A mark** (spec-0066): an anchor and an integer block offset from it, the
/// one declaration of a point the campaign places relative to a piece.
///
/// Its cell is the anchor's resolved cell plus `offset`, in world axes after
/// the piece's placement. It is what a body stands on ([`Npc::offset`],
/// [`Actor::offset`]), where a walk ends ([`Verb::MoveNpc`], [`Verb::MoveActor`],
/// [`Verb::Teleport`]), where the cast ledger says a body is
/// ([`CastPlace::Mark`]), where a sound plays ([`SoundAt::Anchor`]), and every
/// camera position in a shot: a dolly waypoint (`path`), an aim target
/// (`look_at`) and an anchor subject (`subject`). The roles are fields; the
/// type is one.
///
/// A mark's cell lies inside the placed piece its anchor belongs to (`DW0897`):
/// an offset says *where beside this place*, never *which place*.
#[derive(
    Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
)]
#[serde(deny_unknown_fields)]
pub struct Mark {
    /// The anchor the mark is relative to.
    pub anchor: AnchorId,
    /// Integer `[x, y, z]` block offset from the anchor (default `[0, 0, 0]`).
    #[serde(default, skip_serializing_if = "is_zero3")]
    pub offset: [i32; 3],
}

impl Mark {
    /// A mark at `anchor` with no offset.
    pub fn at(anchor: AnchorId) -> Self {
        Mark {
            anchor,
            offset: [0, 0, 0],
        }
    }

    /// Whether the offset is non-zero.
    pub fn is_offset(&self) -> bool {
        !is_zero3(&self.offset)
    }

    /// The mark's cell, given the cell its anchor resolved to.
    pub fn cell(&self, anchor_cell: [i32; 3]) -> [i32; 3] {
        offset_cell(anchor_cell, self.offset)
    }

    /// The mark as a diagnostic spells it: the anchor alone at a zero offset,
    /// else `anchor + [x, y, z]`.
    pub fn display(&self) -> String {
        if self.is_offset() {
            format!(
                "{} + [{}, {}, {}]",
                self.anchor, self.offset[0], self.offset[1], self.offset[2]
            )
        } else {
            self.anchor.as_str().to_string()
        }
    }
}

/// `cell + offset`, componentwise: the one arithmetic a [`Mark`] adds.
pub fn offset_cell(cell: [i32; 3], offset: [i32; 3]) -> [i32; 3] {
    [
        cell[0] + offset[0],
        cell[1] + offset[1],
        cell[2] + offset[2],
    ]
}

/// One shot of a [`Verb::Cutscene`] (DSL v0.6): a camera dolly with its
/// own duration and optional subject. A cutscene plays its shots back-to-back —
/// a hard cut between them — inside a single gamemode/position save-restore
/// bracket, so a wide establishing move can be followed by an interior close-up
/// without the players ever leaving the cinematic.
#[derive(Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CameraShot {
    /// Ordered camera waypoints (straight-line lerp between them). A one-waypoint
    /// path is a static shot. Required without `shot_style`; with one, optional —
    /// an explicit `path` always overrides the style's expanded dolly.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub path: Vec<Mark>,
    /// This shot's duration in seconds. Required without `shot_style`; with one,
    /// optional — the style's default duration applies (see
    /// [`ShotStyle::default_seconds`]), and an explicit value always overrides.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seconds: Option<u32>,
    /// Optional subject the camera keeps framed for this shot. Absent = face
    /// along the direction of travel (or, under a `shot_style`, the style's own
    /// aim at its `subject`). An explicit `look_at` always overrides a style's
    /// aim.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub look_at: Option<Mark>,
    /// Shot-style preset (DSL v0.6, spec-0015 shot-grammar library): the
    /// compiler expands the style deterministically into a camera dolly +
    /// per-keyframe aim from the `subject`'s resolved geometry. Requires
    /// `subject`; `path`/`look_at`/`seconds` remain legal and always override
    /// the corresponding expanded part (`DW0348` polices the combinations).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shot_style: Option<ShotStyle>,
    /// The styled shot's subject — what the shot is *about*. Required with
    /// `shot_style`, rejected without one (`DW0348`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject: Option<CameraSubject>,
    /// `two-shot` only: the second framed subject (`DW0348` elsewhere).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subject_b: Option<CameraSubject>,
    /// Styled shots only: the style's characteristic camera distance in blocks
    /// (its *start* distance for the dolly styles). Default per style — see the
    /// `shot_style` table in `docs/reference/compiler.md`. Clamped range 1..=48
    /// (`DW0348`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dist: Option<f64>,
    /// `orbit-arc` only: the sweep in degrees, 45..=120 (dossier range),
    /// default 90 (`DW0348` elsewhere or out of range).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub degrees: Option<f64>,
    /// Styled shots only: placement bearing in degrees — where the camera sits
    /// (or starts) relative to the subject, measured like a Minecraft yaw
    /// *from* the subject: `0` puts the camera south of the subject (+Z), `90`
    /// west (−X), `-90` east (+X), `180` north (−Z). Default `0`. For
    /// `side-track` the bearing picks which side of the subject's travel the
    /// camera runs abeam (`0` = right of travel, `180` = left).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bearing: Option<f64>,
}

/// A `shot_style` preset (DSL v0.6): the dossier's 9-template library
/// (`docs/notes/camera-dossier.md` §2), each expanded deterministically by the
/// compiler into a dolly + aim from the subject's geometry. Camera "lens feel"
/// is **distance only** — vanilla has no in-game FOV control.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum ShotStyle {
    /// Fully static close framing of a prop/detail. The beat that always looks
    /// right.
    Insert,
    /// Static position; only the aim turns as the subject (ideally moving)
    /// passes. Rockstar's roadside "ground view".
    LockedOff,
    /// Straight dolly toward the subject along the view axis; medium → close.
    PushIn,
    /// Reverse of `push-in`: close → wide, revealing context.
    PullBackReveal,
    /// High and far, descending and closing on the subject. First sight of an
    /// area.
    EstablishingCrane,
    /// Constant-radius, constant-height arc around the subject.
    OrbitArc,
    /// Parallel dolly abeam a **moving** subject at constant offset — needs a
    /// compiler-known subject path (`DW0349`).
    SideTrack,
    /// Static placement solved so **both** subjects land on opposite thirds
    /// (Toric-space construction). Needs `subject_b`.
    TwoShot,
    /// Low, close, trailing a **moving** subject near ground level — needs a
    /// compiler-known subject path (`DW0349`).
    LowFollow,
}

impl ShotStyle {
    /// The kebab token (diagnostics, digests).
    pub fn token(self) -> &'static str {
        match self {
            ShotStyle::Insert => "insert",
            ShotStyle::LockedOff => "locked-off",
            ShotStyle::PushIn => "push-in",
            ShotStyle::PullBackReveal => "pull-back-reveal",
            ShotStyle::EstablishingCrane => "establishing-crane",
            ShotStyle::OrbitArc => "orbit-arc",
            ShotStyle::SideTrack => "side-track",
            ShotStyle::TwoShot => "two-shot",
            ShotStyle::LowFollow => "low-follow",
        }
    }

    /// Default shot duration in seconds, from the dossier's per-style duration
    /// ranges (§2, anchored on the film-editing ASL literature) — the value an
    /// omitted `seconds` resolves to.
    pub fn default_seconds(self) -> u32 {
        match self {
            ShotStyle::Insert => 2,
            ShotStyle::LockedOff => 6,
            ShotStyle::PushIn => 4,
            ShotStyle::PullBackReveal => 6,
            ShotStyle::EstablishingCrane => 8,
            ShotStyle::OrbitArc => 8,
            ShotStyle::SideTrack => 8,
            ShotStyle::TwoShot => 5,
            ShotStyle::LowFollow => 5,
        }
    }

    /// `true` for the styles whose subject must be *moving* on a compiler-known
    /// path (`move-npc` / `move-actor` in the same effect group or sequence) —
    /// `side-track` and `low-follow` (`DW0349` otherwise).
    pub fn needs_moving_subject(self) -> bool {
        matches!(self, ShotStyle::SideTrack | ShotStyle::LowFollow)
    }
}

/// A styled shot's subject (DSL v0.6): the world thing the shot frames — a
/// prefab anchor point, a stage-2 NPC, or a stage-5 actor — plus an integer
/// block offset. For `npc`/`actor` subjects the aim point is the entity's cell
/// **plus one block up** (torso height, so a close shot does not frame feet)
/// before `offset` is applied; an `anchor` subject aims at the block centre
/// exactly like a [`CameraTarget`].
/// Each variant's payload is a **named struct** carrying `deny_unknown_fields`
/// — serde has no variant-level `deny_unknown_fields`, so an untagged
/// enum with inline struct variants silently *ignores* any key it does not
/// recognise: `{"npc": …, "ofset": [0,1,0]}` would deserialize happily with the
/// offset dropped, and `{"anchor": …, "npc": …}` would quietly match `Anchor`
/// and discard the NPC. Lifting each variant into its own type keeps the repo-wide
/// deny-unknown rule for both serde and the published JSON Schema
/// (`additionalProperties: false`): a mistyped shot subject fails the schema
/// instead of rendering a shot pointed somewhere the author never asked for.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum CameraSubject {
    /// A fixed world point: prefab anchor + offset.
    Anchor(Mark),
    /// A stage-2 NPC — moving if a `move-npc` for it runs in the same effect
    /// group / sequence, else static at its declared (or spawn) anchor.
    Npc(NpcSubject),
    /// A stage-5 actor — moving if a `move-actor` for it runs in the same
    /// effect group / sequence, else static at its declared anchor.
    Actor(ActorSubject),
}

/// A [`CameraSubject::Npc`] payload: a stage-2 NPC.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NpcSubject {
    /// The NPC (stage-2 ref).
    pub npc: NpcId,
    /// Integer `[x, y, z]` block offset (default `[0, 0, 0]`).
    #[serde(default, skip_serializing_if = "is_zero3")]
    pub offset: [i32; 3],
}

/// A [`CameraSubject::Actor`] payload: a stage-5 actor.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ActorSubject {
    /// The actor (stage-5 `actors` ref).
    pub actor: ActorId,
    /// Integer `[x, y, z]` block offset (default `[0, 0, 0]`).
    #[serde(default, skip_serializing_if = "is_zero3")]
    pub offset: [i32; 3],
}

impl CameraSubject {
    /// The subject's integer offset, whichever variant.
    pub fn offset(&self) -> [i32; 3] {
        match self {
            CameraSubject::Anchor(s) => s.offset,
            CameraSubject::Npc(s) => s.offset,
            CameraSubject::Actor(s) => s.offset,
        }
    }

    /// A short canonical rendering for digests/diagnostics.
    pub fn canon(&self) -> String {
        let (kind, id, o) = match self {
            CameraSubject::Anchor(s) => ("a", s.anchor.as_str(), &s.offset),
            CameraSubject::Npc(s) => ("n", s.npc.as_str(), &s.offset),
            CameraSubject::Actor(s) => ("c", s.actor.as_str(), &s.offset),
        };
        format!("{kind}:{id}@{},{},{}", o[0], o[1], o[2])
    }
}

/// `Debug` is hand-written because it is a **stable content-key rendering**:
/// the compiler's `payload_verb_key` (FNV over a verb's own `{:?}`) names the
/// generated `volley_`, `collapse_` and `teleport_` functions from it, so a shot
/// that uses none of the v0.6 style fields must render byte-identically to the
/// pre-style struct (`seconds` prints its inner value; absent style fields print
/// nothing) — otherwise a purely additive schema change would silently churn the
/// content key of every payload that carries a cutscene.
impl std::fmt::Debug for CameraShot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("CameraShot");
        d.field("path", &self.path);
        match self.seconds {
            Some(v) => d.field("seconds", &v),
            None => d.field("seconds", &self.seconds),
        };
        d.field("look_at", &self.look_at);
        if self.shot_style.is_some() {
            d.field("shot_style", &self.shot_style);
        }
        if self.subject.is_some() {
            d.field("subject", &self.subject);
        }
        if self.subject_b.is_some() {
            d.field("subject_b", &self.subject_b);
        }
        if self.dist.is_some() {
            d.field("dist", &self.dist);
        }
        if self.degrees.is_some() {
            d.field("degrees", &self.degrees);
        }
        if self.bearing.is_some() {
            d.field("bearing", &self.bearing);
        }
        d.finish()
    }
}

impl CameraShot {
    /// The shot's resolved duration in seconds: explicit `seconds`, else the
    /// style default, else `1` (a shape-invalid shot — `DW0199` reports it; the
    /// fallback only keeps downstream passes total).
    pub fn resolved_seconds(&self) -> u32 {
        self.seconds
            .or(self.shot_style.map(ShotStyle::default_seconds))
            .unwrap_or(1)
    }
}

/// serde `skip_serializing_if` helper: skip a `[0, 0, 0]` offset.
fn is_zero3(v: &[i32; 3]) -> bool {
    *v == [0, 0, 0]
}

impl Verb {
    /// The kebab-case `type` tag this verb serializes as — the verb a
    /// diagnostic should name so the author can find it in the JSON.
    pub fn tag(&self) -> &'static str {
        match self {
            Verb::OpenGate { .. } => "open-gate",
            Verb::CloseGate { .. } => "close-gate",
            Verb::CampaignComplete { .. } => "campaign-complete",
            Verb::GiveItem { .. } => "give-item",
            Verb::SetFlag { .. } => "set-flag",
            Verb::SetState { .. } => "set-state",
            Verb::AddState { .. } => "add-state",
            Verb::ClearState { .. } => "clear-state",
            Verb::DropStake { .. } => "drop-stake",
            Verb::SpawnWave { .. } => "spawn-wave",
            Verb::Narrate { .. } => "narrate",
            Verb::SetBlock { .. } => "set-block",
            Verb::FillRegion { .. } => "fill-region",
            Verb::ClearRegion { .. } => "clear-region",
            Verb::SetAtmosphere { .. } => "set-atmosphere",
            Verb::OpenWay { .. } => "open-way",
            Verb::DespawnNpc { .. } => "despawn-npc",
            Verb::MoveNpc { .. } => "move-npc",
            Verb::Cutscene { .. } => "cutscene",
            Verb::SetTime { .. } => "set-time",
            Verb::SetWeather { .. } => "set-weather",
            Verb::PlaySound { .. } => "play-sound",
            Verb::DamagePlayers { .. } => "damage-players",
            Verb::SetCheckpoint { .. } => "set-checkpoint",
            Verb::Bonfire { .. } => "bonfire",
            Verb::BeginStealth { .. } => "begin-stealth",
            Verb::EndStealth => "end-stealth",
            Verb::SpawnNpc { .. } => "spawn-npc",
            Verb::SpawnActor { .. } => "spawn-actor",
            Verb::DespawnActor { .. } => "despawn-actor",
            Verb::MoveActor { .. } => "move-actor",
            Verb::UnleashActor { .. } => "unleash-actor",
            Verb::Sequence { .. } => "sequence",
            Verb::Volley { .. } => "volley",
            Verb::Collapse { .. } => "collapse",
            Verb::GiveEffect { .. } => "give-effect",
            Verb::ClearEffect { .. } => "clear-effect",
            Verb::Teleport { .. } => "teleport",
            Verb::Firework { .. } => "firework",
            Verb::SpawnAssembly { .. } => "spawn-assembly",
            Verb::DespawnAssembly { .. } => "despawn-assembly",
            Verb::PlayClip { .. } => "play-clip",
            Verb::Particle { .. } => "particle",
        }
    }

    /// **Whether the emitter addresses this verb to players** (spec-0085 §3.3) —
    /// whether its emitted commands name the effect's audience selector at all.
    ///
    /// A verb that answers `false` is a **party fact**: it fires once for the
    /// world (a flag, a gate, a block, a region, a wave, an actor, an NPC, a
    /// camera, the time, a checkpoint, a stealth beat, a timeline, a teleported
    /// volume, a rocket), so the envelope's `audience` and `in` have nothing to
    /// narrow and are refused on it (`DW0942`). A `player`-scoped state write
    /// answers `false` too: its holder is the acting player by declaration, never
    /// the audience.
    ///
    /// Exhaustive, so a new verb cannot be added without answering it; and
    /// `emit`'s own test binds this answer to the emitted bytes in both
    /// directions — every verb is emitted under two audiences, and its commands
    /// differ exactly when this says `true`.
    pub fn addresses_players(&self) -> bool {
        match self {
            Verb::GiveItem { .. }
            | Verb::Narrate { .. }
            | Verb::PlaySound { .. }
            | Verb::DamagePlayers { .. }
            | Verb::GiveEffect { .. }
            | Verb::ClearEffect { .. }
            | Verb::Particle { .. } => true,
            Verb::OpenGate { .. }
            | Verb::CloseGate { .. }
            | Verb::CampaignComplete { .. }
            | Verb::SetFlag { .. }
            | Verb::SetState { .. }
            | Verb::AddState { .. }
            | Verb::ClearState { .. }
            | Verb::DropStake { .. }
            | Verb::SpawnWave { .. }
            | Verb::SetBlock { .. }
            | Verb::FillRegion { .. }
            | Verb::ClearRegion { .. }
            | Verb::OpenWay { .. }
            | Verb::DespawnNpc { .. }
            | Verb::MoveNpc { .. }
            | Verb::Cutscene { .. }
            | Verb::SetTime { .. }
            | Verb::SetWeather { .. }
            | Verb::SetCheckpoint { .. }
            | Verb::Bonfire { .. }
            | Verb::BeginStealth { .. }
            | Verb::EndStealth
            | Verb::SpawnActor { .. }
            | Verb::DespawnActor { .. }
            | Verb::MoveActor { .. }
            | Verb::UnleashActor { .. }
            | Verb::SpawnNpc { .. }
            | Verb::Sequence { .. }
            | Verb::Volley { .. }
            | Verb::Collapse { .. }
            | Verb::Teleport { .. }
            | Verb::Firework { .. }
            // spec-0080: a biome repaint is a world fact (`fillbiome`).
            | Verb::SetAtmosphere { .. }
            // spec-0082: an assembly is a world object.
            | Verb::SpawnAssembly { .. }
            | Verb::DespawnAssembly { .. }
            | Verb::PlayClip { .. } => false,
        }
    }
}

/// **How a nested effect list is dispatched, relative to the bundle it sits in**
/// (spec-0085 §3.2) — the one statement of which command source each nesting
/// site runs under, read by `DW0357`/`DW0503` and by the emitter's timeline
/// keying alike.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NestedDispatch {
    /// Under the parent's own source: a `sequence` step. A timeline started
    /// where there is an acting player carries that player across its
    /// `schedule`s by a compiler-owned tag, and a timeline started from the
    /// server source has nobody to carry.
    Inherit,
    /// As one player, whatever the parent was: a `set-checkpoint`'s
    /// `on_respawn` (the respawning player) and a `begin-stealth`'s `on_caught`
    /// (the spotted player).
    Player,
    /// From the server command source, whatever the parent was: a
    /// `move-npc`/`move-actor` `on_arrive` (the driver's scheduled tick) and a
    /// `bonfire`'s `on_rest` (the party-wide rest, dispatched from the tick).
    Server,
}

impl NestedDispatch {
    /// Whether a list dispatched this way, inside a bundle that does (or does
    /// not) have an acting player, has one.
    pub fn has_actor(self, parent_has_actor: bool) -> bool {
        match self {
            NestedDispatch::Inherit => parent_has_actor,
            NestedDispatch::Player => true,
            NestedDispatch::Server => false,
        }
    }
}

impl QuestEffect {
    /// Each nested effect list with how it is dispatched ([`NestedDispatch`]) —
    /// the same lists, in the same order, as [`Self::nested_effect_lists`].
    pub fn nested_effect_dispatch(&self) -> Vec<(&[QuestEffect], NestedDispatch)> {
        match &self.verb {
            Verb::Sequence { steps } => steps
                .iter()
                .map(|s| (s.effects.as_slice(), NestedDispatch::Inherit))
                .collect(),
            Verb::SetCheckpoint { on_respawn, .. } => {
                vec![(on_respawn.as_slice(), NestedDispatch::Player)]
            }
            Verb::Bonfire { on_rest, .. } => vec![(on_rest.as_slice(), NestedDispatch::Server)],
            Verb::BeginStealth { on_caught, .. } => {
                vec![(on_caught.as_slice(), NestedDispatch::Player)]
            }
            Verb::MoveActor { on_arrive, .. } | Verb::MoveNpc { on_arrive, .. } => {
                vec![(on_arrive.as_slice(), NestedDispatch::Server)]
            }
            _ => Vec::new(),
        }
    }

    /// Whether this effect addresses players at all — [`Verb::addresses_players`].
    pub fn addresses_players(&self) -> bool {
        self.verb.addresses_players()
    }
    /// The gate anchor if this is `open-gate`.
    pub fn open_gate_anchor(&self) -> Option<&AnchorId> {
        match &self.verb {
            Verb::OpenGate { anchor, .. } => Some(anchor),
            _ => None,
        }
    }

    /// The gate anchor if this is `close-gate` (DSL v0.6).
    pub fn close_gate_anchor(&self) -> Option<&AnchorId> {
        match &self.verb {
            Verb::CloseGate { anchor, .. } => Some(anchor),
            _ => None,
        }
    }

    /// The authored `sealed_hint` if this is a `close-gate` that declares one (DSL
    /// v0.8). `None` for every other effect **and** for a `close-gate` that takes
    /// the compiler's canonical English seal line.
    pub fn close_gate_sealed_hint(&self) -> Option<&str> {
        match &self.verb {
            Verb::CloseGate { sealed_hint, .. } => sealed_hint.as_deref(),
            _ => None,
        }
    }

    /// The wave id if this is `spawn-wave` (v0.3).
    pub fn spawn_wave(&self) -> Option<&WaveId> {
        match &self.verb {
            Verb::SpawnWave { wave, .. } => Some(wave),
            _ => None,
        }
    }

    /// The flag id if this is `set-flag` (v0.3).
    pub fn set_flag(&self) -> Option<&FlagId> {
        match &self.verb {
            Verb::SetFlag { flag, .. } => Some(flag),
            _ => None,
        }
    }

    /// The item id if this is `give-item` (v0.3).
    pub fn give_item(&self) -> Option<&str> {
        match &self.verb {
            Verb::GiveItem { item, .. } => Some(item),
            _ => None,
        }
    }

    /// `true` if this is a `give-item` carrying a v0.4 display `name`.
    pub fn give_item_named(&self) -> bool {
        matches!(self.verb, Verb::GiveItem { name: Some(_), .. })
    }

    /// The declared `carrier` if this is a `give-item` that states one (v0.6,
    /// spec-0018). `None` for any other effect **and** for a `give-item` that
    /// leaves it absent — absent reads as [`Carrier::All`], and the distinction
    /// matters only for the pre-0.6 reserved-field gate.
    pub fn give_carrier(&self) -> Option<Carrier> {
        match &self.verb {
            Verb::GiveItem { carrier, .. } => *carrier,
            _ => None,
        }
    }

    /// Does this `give-item` hand a single copy to the acting player (v0.6,
    /// spec-0018)? `false` for every other effect and for the party-wide default.
    pub fn gives_to_one(&self) -> bool {
        matches!(self.give_carrier(), Some(Carrier::One))
    }

    /// The `set-block` block id if this is a v0.4 `set-block` effect.
    pub fn set_block(&self) -> Option<(&AnchorId, &str)> {
        match &self.verb {
            Verb::SetBlock { anchor, block, .. } => Some((anchor, block.as_str())),
            _ => None,
        }
    }

    /// The NPC id if this is a v0.4 `despawn-npc` effect.
    pub fn despawn_npc(&self) -> Option<&NpcId> {
        match &self.verb {
            Verb::DespawnNpc { npc, .. } => Some(npc),
            _ => None,
        }
    }

    /// `(npc, to)` if this is a v0.4 `move-npc` effect.
    pub fn move_npc(&self) -> Option<(&NpcId, &Mark)> {
        match &self.verb {
            Verb::MoveNpc { npc, to, .. } => Some((npc, to)),
            _ => None,
        }
    }

    /// The v0.3 effect name if this effect is one introduced in DSL v0.3
    /// (`give-item`/`set-flag`/`spawn-wave`). These validate in v0.3 campaigns
    ///.
    pub fn v03_effect(&self) -> Option<&'static str> {
        match &self.verb {
            Verb::GiveItem { .. } => Some("give-item"),
            Verb::SetFlag { .. } => Some("set-flag"),
            Verb::SpawnWave { .. } => Some("spawn-wave"),
            Verb::OpenGate { .. }
            | Verb::CloseGate { .. }
            | Verb::CampaignComplete { .. } => None,
            // v0.4 effects report via `v04_effect`; v0.5 via `v05_effect`; they
            // are not v0.3 verbs.
            Verb::Narrate { .. }
            | Verb::SetBlock { .. }
            | Verb::DespawnNpc { .. }
            | Verb::MoveNpc { .. }
            | Verb::Cutscene { .. }
            | Verb::SetTime { .. }
            | Verb::SetWeather { .. }
            | Verb::PlaySound { .. }
            | Verb::DamagePlayers { .. }
            | Verb::SetCheckpoint { .. }
            | Verb::Bonfire { .. }
            | Verb::BeginStealth { .. }
            | Verb::EndStealth
            | Verb::SpawnActor { .. }
            | Verb::DespawnActor { .. }
            | Verb::MoveActor { .. }
            | Verb::UnleashActor { .. }
            | Verb::SpawnNpc { .. }
            | Verb::Sequence { .. }
            // spec-0022 trap-payload verbs are v0.6 — they report via `v06_effect`.
            | Verb::Volley { .. }
            | Verb::Collapse { .. }
            // spec-0031's state verbs, region writes, status effects and teleport,
            // and spec-0032's `drop-stake`, are all v0.10 — they report via
            // `v10_effect`.
            | Verb::SetState { .. }
            | Verb::AddState { .. }
            | Verb::ClearState { .. }
            | Verb::FillRegion { .. }
            | Verb::ClearRegion { .. }
            | Verb::SetAtmosphere { .. }
            // spec-0042's `open-way` is v0.12 — it reports via `v12_effect`.
            | Verb::OpenWay { .. }
            | Verb::GiveEffect { .. }
            | Verb::ClearEffect { .. }
            | Verb::Teleport { .. }
            // spec-0068's `firework` is v0.29.
            | Verb::Firework { .. }
            // spec-0082's assembly verbs.
            | Verb::SpawnAssembly { .. }
            | Verb::DespawnAssembly { .. }
            | Verb::PlayClip { .. }
            // spec-0085's `particle`.
            | Verb::Particle { .. }
            | Verb::DropStake { .. } => None,
        }
    }

    /// The v0.4 effect name if this effect is one introduced in DSL v0.4
    /// (`narrate`/`set-block`/`despawn-npc`/`move-npc`/`cutscene`). These validate
    /// in v0.4 campaigns.
    pub fn v04_effect(&self) -> Option<&'static str> {
        match &self.verb {
            Verb::Narrate { .. } => Some("narrate"),
            Verb::SetBlock { .. } => Some("set-block"),
            Verb::DespawnNpc { .. } => Some("despawn-npc"),
            Verb::MoveNpc { .. } => Some("move-npc"),
            Verb::Cutscene { .. } => Some("cutscene"),
            _ => None,
        }
    }

    /// The v0.5 effect name if this effect is one introduced in DSL v0.5
    /// (`set-time`/`set-weather`, spec-0010).
    pub fn v05_effect(&self) -> Option<&'static str> {
        match &self.verb {
            Verb::SetTime { .. } => Some("set-time"),
            Verb::SetWeather { .. } => Some("set-weather"),
            _ => None,
        }
    }

    /// The v0.6 effect name if this effect is one introduced in DSL v0.6
    /// (`set-checkpoint`, spec-0012; `begin-stealth`/`end-stealth`, spec-0014;
    /// `play-sound`, spec-0014; the scripted-actor staging verbs
    /// `spawn-actor`/`despawn-actor`/`move-actor`/`unleash-actor`/`sequence`,
    /// spec-0014). These validate in v0.6 campaigns
    /// earlier. (The `narrate` `art` style is a v0.6 addition to an existing verb
    /// — see [`QuestEffect::narrate_art`] — not a new effect.)
    pub fn v06_effect(&self) -> Option<&'static str> {
        match &self.verb {
            Verb::CloseGate { .. } => Some("close-gate"),
            Verb::SetCheckpoint { .. } => Some("set-checkpoint"),
            Verb::Bonfire { .. } => Some("bonfire"),
            Verb::BeginStealth { .. } => Some("begin-stealth"),
            Verb::EndStealth => Some("end-stealth"),
            Verb::PlaySound { .. } => Some("play-sound"),
            Verb::DamagePlayers { .. } => Some("damage-players"),
            Verb::SpawnActor { .. } => Some("spawn-actor"),
            Verb::DespawnActor { .. } => Some("despawn-actor"),
            Verb::MoveActor { .. } => Some("move-actor"),
            Verb::UnleashActor { .. } => Some("unleash-actor"),
            Verb::Sequence { .. } => Some("sequence"),
            Verb::SpawnNpc { .. } => Some("spawn-npc"),
            // spec-0022 trap-payload verbs — v0.6 surface, reserved earlier.
            Verb::Volley { .. } => Some("volley"),
            Verb::Collapse { .. } => Some("collapse"),
            _ => None,
        }
    }

    /// The v0.10 effect name if this effect is one introduced in DSL v0.10
    /// (`set-state`/`add-state`/`clear-state` and the region writes
    /// `fill-region`/`clear-region`, spec-0031). These validate in v0.10
    /// campaigns.
    pub fn v10_effect(&self) -> Option<&'static str> {
        match &self.verb {
            Verb::SetState { .. } => Some("set-state"),
            Verb::AddState { .. } => Some("add-state"),
            Verb::ClearState { .. } => Some("clear-state"),
            Verb::FillRegion { .. } => Some("fill-region"),
            Verb::ClearRegion { .. } => Some("clear-region"),
            Verb::GiveEffect { .. } => Some("give-effect"),
            Verb::ClearEffect { .. } => Some("clear-effect"),
            Verb::Teleport { .. } => Some("teleport"),
            Verb::DropStake { .. } => Some("drop-stake"),
            _ => None,
        }
    }

    /// The v0.12 effect name if this effect is one introduced in DSL v0.12
    /// (`open-way`, spec-0042).
    pub fn v12_effect(&self) -> Option<&'static str> {
        match &self.verb {
            Verb::OpenWay { .. } => Some("open-way"),
            _ => None,
        }
    }

    /// **The way this effect opens** (DSL v0.12, spec-0042): the placed piece and
    /// the name of one way that piece's spatial contract exports.
    ///
    /// The third spelling of the one region write, beside
    /// [`QuestEffect::region_write`] (the author's own box) and
    /// [`QuestEffect::gate_region_write`] (a gate anchor's box). It answers with a
    /// *reference* and never with geometry, because the geometry is not the
    /// campaign's to state: the cells, the block and the direction all live in the
    /// piece's metadata, and the compiler resolves them there
    /// (`compiler::ways`). A region-shaped accessor here would be the second
    /// authority this surface exists to avoid.
    pub fn way_write(&self) -> Option<(&PrefabId, &str)> {
        match &self.verb {
            Verb::OpenWay { piece, way, .. } => Some((piece, way.as_str())),
            _ => None,
        }
    }

    /// **The one region write**, whichever verb spelled it (DSL v0.10,
    /// spec-0031): the box to write and the block to write it with — `None` for
    /// the block meaning *clear to air*.
    ///
    /// This is the accessor the capability belongs to. It answers for
    /// `fill-region` / `clear-region`, which name their own box; `open-gate` /
    /// `close-gate` are the same operation over a box a prefab gate anchor
    /// declares, so they answer through
    /// [`QuestEffect::gate_region_write`](Self::gate_region_write) — the anchor
    /// is theirs, the *operation* is shared.
    pub fn region_write(&self) -> Option<(&StealthZone, Option<&str>)> {
        match &self.verb {
            Verb::FillRegion { region, block, .. } => Some((region, Some(block.as_str()))),
            Verb::ClearRegion { region, .. } => Some((region, None)),
            _ => None,
        }
    }

    /// The gate anchor this effect writes, and whether the write **fills** it:
    /// `Some((anchor, true))` for `close-gate`, `Some((anchor, false))` for
    /// `open-gate`, `None` for everything else.
    ///
    /// The gate half of [`QuestEffect::region_write`]: same operation, but the box
    /// and the fill block come from the prefab's gate anchor rather than from the
    /// author. Everything that reasons about runtime region writes reads both
    /// accessors and nothing else.
    pub fn gate_region_write(&self) -> Option<(&AnchorId, bool)> {
        match &self.verb {
            Verb::CloseGate { anchor, .. } => Some((anchor, true)),
            Verb::OpenGate { anchor, .. } => Some((anchor, false)),
            _ => None,
        }
    }

    /// `(projectile, from_anchor, kill_zone, salvos, interval)` if this is a
    /// `volley` (spec-0022), with the documented defaults already applied.
    pub fn volley(&self) -> Option<(&str, &AnchorId, &StealthZone, u32, u32)> {
        match &self.verb {
            Verb::Volley {
                projectile,
                from_anchor,
                kill_zone,
                salvos,
                interval,
                ..
            } => Some((
                projectile.as_deref().unwrap_or(DEFAULT_VOLLEY_PROJECTILE),
                from_anchor,
                kill_zone,
                salvos.unwrap_or(DEFAULT_VOLLEY_SALVOS),
                interval.unwrap_or(DEFAULT_VOLLEY_INTERVAL),
            )),
            _ => None,
        }
    }

    /// `(region_anchor, falling_block, then_floor)` if this is a `collapse`
    /// (spec-0022), with the documented default already applied.
    pub fn collapse(&self) -> Option<(&StealthZone, &str, Option<&str>)> {
        match &self.verb {
            Verb::Collapse {
                region_anchor,
                falling_block,
                then_floor,
                ..
            } => Some((
                region_anchor,
                falling_block
                    .as_deref()
                    .unwrap_or(DEFAULT_COLLAPSE_FALLING_BLOCK),
                then_floor.as_deref(),
            )),
            _ => None,
        }
    }

    /// The NPC id if this is a v0.6 `spawn-npc` effect (the dual of
    /// [`QuestEffect::despawn_npc`]).
    pub fn spawn_npc(&self) -> Option<&NpcId> {
        match &self.verb {
            Verb::SpawnNpc { npc, .. } => Some(npc),
            _ => None,
        }
    }

    /// **The body this effect puts into the world**, by id, for every body class
    /// alike ([`BodyRef`]).
    ///
    /// `spawn-npc` and `spawn-actor` are the two, and they are answered in one
    /// place so a rule about a body's lifetime quantifies over bodies rather
    /// than over the verb that first needed it. A body's OTHER entry — standing
    /// on its mark from world init — is not an effect at all and is
    /// [`BodyRef::at_world_init`].
    ///
    /// `unleash-actor` is deliberately not an entry: it puts no new body on the
    /// mark, it replaces the one already standing there (see [`Self::body_exit`]).
    pub fn body_entry(&self) -> Option<&str> {
        match &self.verb {
            Verb::SpawnNpc { npc, .. } => Some(npc.as_str()),
            Verb::SpawnActor { actor, .. } => Some(actor.as_str()),
            _ => None,
        }
    }

    /// **The body this effect takes out of the world**, by id, for every body
    /// class alike.
    ///
    /// `despawn-npc` and `despawn-actor` remove the body outright.
    /// `unleash-actor` is the third: it kills the staged puppet and stands a
    /// real-AI twin in its place, and from that moment the compiler makes no
    /// claim about where that body is or whether it is still alive — the twin
    /// walks, fights and dies under vanilla AI. Answering all three here is what
    /// keeps "can this body still be standing?" from being decided one verb at a
    /// time.
    ///
    /// Deliberately NOT an exit: `move-npc` / `move-actor`. A walked body is
    /// still in the world, and its declared mark is still the cell the engine
    /// summoned it onto — a mark two live bodies share is shared whether or not
    /// one of them has since walked off it.
    pub fn body_exit(&self) -> Option<&str> {
        match &self.verb {
            Verb::DespawnNpc { npc, .. } => Some(npc.as_str()),
            Verb::DespawnActor { actor, .. } | Verb::UnleashActor { actor, .. } => {
                Some(actor.as_str())
            }
            _ => None,
        }
    }

    /// `(anchor, on_respawn)` if this is a v0.6 `set-checkpoint` effect.
    pub fn set_checkpoint(&self) -> Option<(&AnchorId, &[QuestEffect])> {
        match &self.verb {
            Verb::SetCheckpoint { anchor, on_respawn } => Some((anchor, on_respawn.as_slice())),
            _ => None,
        }
    }

    /// `(anchor, on_rest)` if this is a `bonfire` effect (spec-0016 §1).
    pub fn bonfire(&self) -> Option<(&AnchorId, &[QuestEffect])> {
        match &self.verb {
            Verb::Bonfire {
                anchor, on_rest, ..
            } => Some((anchor, on_rest.as_slice())),
            _ => None,
        }
    }

    /// The bonfire's authored rest-dialog strings, each `None` when unauthored
    /// (the compiler then bakes its canonical English). `None` for every other
    /// effect (spec-0016 §1).
    pub fn bonfire_labels(&self) -> Option<BonfireLabels<'_>> {
        match &self.verb {
            Verb::Bonfire {
                prompt,
                rest_label,
                save_label,
                rest_tooltip,
                save_tooltip,
                ..
            } => Some(BonfireLabels {
                prompt: prompt.as_deref(),
                rest_label: rest_label.as_deref(),
                save_label: save_label.as_deref(),
                rest_tooltip: rest_tooltip.as_deref(),
                save_tooltip: save_tooltip.as_deref(),
            }),
            _ => None,
        }
    }

    /// The `within` filter zone if this is a v0.6 `damage-players` effect that
    /// declares one (the `in` spatial scope). `None` for an unscoped
    /// `damage-players` and for every other effect.
    pub fn damage_within(&self) -> Option<&StealthZone> {
        match &self.verb {
            Verb::DamagePlayers { .. } => self.within.as_ref(),
            _ => None,
        }
    }

    /// `(zones, on_caught, grace_ticks)` if this is a v0.6 `begin-stealth` effect.
    pub fn begin_stealth(&self) -> Option<(&[StealthZone], &[QuestEffect], u32)> {
        match &self.verb {
            Verb::BeginStealth {
                zones,
                on_caught,
                grace_ticks,
            } => Some((zones.as_slice(), on_caught.as_slice(), *grace_ticks)),
            _ => None,
        }
    }

    /// The target time if this is a v0.5 `set-time` effect.
    pub fn set_time(&self) -> Option<WorldTime> {
        match &self.verb {
            Verb::SetTime { time, .. } => Some(*time),
            _ => None,
        }
    }

    /// The target weather if this is a v0.5 `set-weather` effect.
    pub fn set_weather(&self) -> Option<WorldWeather> {
        match &self.verb {
            Verb::SetWeather { weather, .. } => Some(*weather),
            _ => None,
        }
    }

    /// The effect lists nested one level inside this effect (DSL v0.6): a
    /// `sequence`'s per-step effects (in step order), a `set-checkpoint`'s
    /// `on_respawn`, a `begin-stealth`'s `on_caught`, and a `move-actor`'s /
    /// `move-npc`'s `on_arrive`. Empty for a leaf effect.
    ///
    /// This is the **single authority** on effect nesting. Every deep traversal —
    /// the flag/wave producer scans, the checkpoint/stealth collector, the l10n
    /// string inventory, and emission — walks the tree through it (see
    /// [`Self::visit_deep`]), so a new nesting site is picked up everywhere at
    /// once and no walker can silently miss a list (the class of bug where a
    /// `set-flag`/`set-checkpoint` nested in a `sequence` was skipped).
    pub fn nested_effect_lists(&self) -> Vec<&[QuestEffect]> {
        match &self.verb {
            Verb::Sequence { steps } => steps.iter().map(|s| s.effects.as_slice()).collect(),
            Verb::SetCheckpoint { on_respawn, .. } => vec![on_respawn.as_slice()],
            Verb::Bonfire { on_rest, .. } => vec![on_rest.as_slice()],
            Verb::BeginStealth { on_caught, .. } => vec![on_caught.as_slice()],
            Verb::MoveActor { on_arrive, .. } | Verb::MoveNpc { on_arrive, .. } => {
                vec![on_arrive.as_slice()]
            }
            _ => Vec::new(),
        }
    }

    /// Visit `self` and every transitively nested effect (depth-first, pre-order),
    /// descending through [`Self::nested_effect_lists`].
    pub fn visit_deep<'a>(&'a self, f: &mut dyn FnMut(&'a QuestEffect)) {
        f(self);
        for list in self.nested_effect_lists() {
            for e in list {
                e.visit_deep(f);
            }
        }
    }

    /// Each nested effect list ([`Self::nested_effect_lists`]) paired with the
    /// **stable key segment** used to derive child l10n keys / diagnostic paths, and
    /// exposed mutably so the localization pass can rewrite nested player-visible
    /// strings in place. Segments: `seq.<step>` for each sequence step (step index),
    /// `respawn` for `set-checkpoint.on_respawn`, `caught` for
    /// `begin-stealth.on_caught`, `arrive` for `move-actor.on_arrive`. Kept in
    /// lockstep with `nested_effect_lists` (same lists, same order) — the position-
    /// derived segments make every derived key deterministic and stable across
    /// builds (ADR-0006 byte-identity).
    pub fn nested_effect_lists_keyed_mut(&mut self) -> Vec<(String, &mut [QuestEffect])> {
        match &mut self.verb {
            Verb::Sequence { steps } => steps
                .iter_mut()
                .enumerate()
                .map(|(s, st)| (format!("seq.{s}"), st.effects.as_mut_slice()))
                .collect(),
            Verb::SetCheckpoint { on_respawn, .. } => {
                vec![("respawn".to_string(), on_respawn.as_mut_slice())]
            }
            Verb::Bonfire { on_rest, .. } => {
                vec![("rest".to_string(), on_rest.as_mut_slice())]
            }
            Verb::BeginStealth { on_caught, .. } => {
                vec![("caught".to_string(), on_caught.as_mut_slice())]
            }
            Verb::MoveActor { on_arrive, .. } | Verb::MoveNpc { on_arrive, .. } => {
                vec![("arrive".to_string(), on_arrive.as_mut_slice())]
            }
            _ => Vec::new(),
        }
    }

    /// Immutable sibling of [`Self::nested_effect_lists_keyed_mut`] that additionally
    /// exposes the **JSON-pointer path segment** for each nested list, so a deep
    /// consumer scan (sound/art/give/wave refs) can report a precise diagnostic path
    /// *and* the matching l10n key. Each entry is `(path_seg, key_seg, list)`; the
    /// caller appends the per-effect index — `/{j}` to the path, `.{j}` to the key.
    /// Kept in lockstep with `nested_effect_lists` / `nested_effect_lists_keyed_mut`
    /// (same lists, same order): the l10n key segments match
    /// `nested_effect_lists_keyed_mut` exactly (`seq.<step>`/`respawn`/`caught`/
    /// `arrive`), and the path segments name the real fields
    /// (`steps/<step>/effects`, `on_respawn`, `on_caught`, `on_arrive`).
    pub fn nested_effect_lists_labeled(&self) -> Vec<(String, String, &[QuestEffect])> {
        match &self.verb {
            Verb::Sequence { steps } => steps
                .iter()
                .enumerate()
                .map(|(s, st)| {
                    (
                        format!("steps/{s}/effects"),
                        format!("seq.{s}"),
                        st.effects.as_slice(),
                    )
                })
                .collect(),
            Verb::SetCheckpoint { on_respawn, .. } => vec![(
                "on_respawn".to_string(),
                "respawn".to_string(),
                on_respawn.as_slice(),
            )],
            Verb::Bonfire { on_rest, .. } => vec![(
                "on_rest".to_string(),
                "rest".to_string(),
                on_rest.as_slice(),
            )],
            Verb::BeginStealth { on_caught, .. } => vec![(
                "on_caught".to_string(),
                "caught".to_string(),
                on_caught.as_slice(),
            )],
            Verb::MoveActor { on_arrive, .. } | Verb::MoveNpc { on_arrive, .. } => {
                vec![(
                    "on_arrive".to_string(),
                    "arrive".to_string(),
                    on_arrive.as_slice(),
                )]
            }
            _ => Vec::new(),
        }
    }

    /// Every world anchor this effect names **at this node** — the single
    /// authority on the anchor-bearing effect surface, the referential sibling of
    /// [`Self::nested_effect_lists`]. Each entry is `(json_path_suffix, anchor)`,
    /// where the suffix is appended to the effect's own JSON pointer
    /// (`anchor`, `to/anchor`, `in/anchor`, `zones/<i>/anchor`, `at/anchor`,
    /// `shots/<i>/path/<j>/anchor`, …).
    ///
    /// Not recursive: pair it with [`Self::visit_deep`] to sweep a whole effect
    /// tree. Every consumer that must resolve an anchor — the DSL's `DW0142`
    /// reference scan, the compiler's build-time resolution seal (`DW0360`) —
    /// goes through here, so a new anchor-bearing variant (or a new anchor field
    /// on an existing one) is picked up by all of them at once. That closes the
    /// silent-drop class of bug: an anchor-bearing effect whose anchor is typo'd
    /// used to emit *nothing* (the emitter's `for … if name == anchor` loop simply
    /// found no match) while every shallow validator looked straight past it.
    ///
    /// # The third element is the SHAPE the site demands
    ///
    /// A reference is not only a name: `close-gate` fills and clears a region and
    /// `bonfire` seats a body, and until spec-0052 those two sat in one match arm
    /// with nothing recording the difference. The demand rides with the reference
    /// so that a new anchor-bearing variant cannot be added without stating what
    /// it does with the anchor — the same reason this is one authority and not
    /// three walks.
    ///
    /// **A demand is stated only where the shape is structurally required**, and
    /// the line is drawn where this engine's own `DW0845` already draws it — *a
    /// region is not a place to stand*:
    ///
    /// * [`StationKind::Gate`] where the verb cannot function without a region
    ///   that seals and clears: the two gate verbs. A point is not a gate, and
    ///   `gate_region_block_any` finds nothing for one.
    /// * [`StationKind::Point`] where a **body is put**: a checkpoint seat, a
    ///   bonfire, a `move-npc`/`move-actor` destination, a `teleport`
    ///   destination. A body cannot stand inside bars.
    /// * `None` wherever a reference merely names a **location** — every
    ///   anchor-centred volume's centre, every camera field, a `set-block`, a
    ///   `play-sound`. A gate region's own corner is a perfectly good answer
    ///   there, and refusing it would refuse correct content.
    ///
    /// That last case is not a gap left for later. An earlier draft of this rule
    /// demanded a point at every non-gate site, and the gallery refused to
    /// compile: `trigger/east-door-wrong-side` is a `use` trigger sitting on the
    /// very `anchor/seam-…` of a barred door so that it can say "the east door
    /// does not open from this side". A check that resolves against a smaller
    /// world than the campaign has refuses CONTENT, which is the lesson `DW0343`
    /// carries three files away.
    pub fn anchor_refs(&self) -> Vec<(String, &AnchorId, Option<StationKind>)> {
        // The envelope's `in` box (spec-0085 §3.2) is one capability of every
        // player-facing verb, so it registers once, here, before the verb's own.
        let mut out: Vec<(String, &AnchorId, Option<StationKind>)> = Vec::new();
        if let Some(zone) = &self.within {
            out.push(("in/anchor".to_string(), &zone.anchor, None));
        }
        out.extend(self.verb_anchor_refs());
        out
    }

    /// The anchors the VERB names at this node — [`Self::anchor_refs`] without the
    /// envelope.
    fn verb_anchor_refs(&self) -> Vec<(String, &AnchorId, Option<StationKind>)> {
        // Every camera field is a point: a shot flies through cells and looks at
        // one.
        /// `(suffix, anchor, kind)` for a shot's own anchor-bearing fields, under `base`.
        fn shot_refs<'a>(
            base: &str,
            shot: &'a CameraShot,
        ) -> Vec<(String, &'a AnchorId, Option<StationKind>)> {
            let mut out: Vec<(String, &AnchorId, Option<StationKind>)> = shot
                .path
                .iter()
                .enumerate()
                .map(|(j, w)| (format!("{base}path/{j}/anchor"), &w.anchor, None))
                .collect();
            if let Some(t) = &shot.look_at {
                out.push((format!("{base}look_at/anchor"), &t.anchor, None));
            }
            for (field, subject) in [("subject", &shot.subject), ("subject_b", &shot.subject_b)] {
                if let Some(CameraSubject::Anchor(s)) = subject {
                    out.push((format!("{base}{field}/anchor"), &s.anchor, None));
                }
            }
            out
        }
        match &self.verb {
            // The two gate verbs address a REGION that seals and clears; the
            // three below them seat or write at a cell. They shared an arm until
            // the demand had somewhere to be written down.
            Verb::OpenGate { anchor, .. } | Verb::CloseGate { anchor, .. } => {
                vec![("anchor".to_string(), anchor, Some(StationKind::Gate))]
            }
            // A checkpoint and a bonfire are **respawn seats** — a body is put
            // there, so a region is not one. `set-block` writes a block at a
            // cell, which names a location and seats nothing.
            Verb::SetCheckpoint { anchor, .. } | Verb::Bonfire { anchor, .. } => {
                vec![("anchor".to_string(), anchor, Some(StationKind::Point))]
            }
            Verb::SetBlock { anchor, .. } => {
                vec![("anchor".to_string(), anchor, None)]
            }
            Verb::MoveNpc { to, .. } | Verb::MoveActor { to, .. } => {
                vec![(
                    "to/anchor".to_string(),
                    &to.anchor,
                    Some(StationKind::Point),
                )]
            }
            // Both of a `teleport`'s anchors are load-bearing — the source volume
            // decides WHAT moves and the destination decides WHERE — so a typo in
            // either is a dangling reference (`DW0142`), never a silently
            // zero-cell volume or a dropped command.
            Verb::Teleport { from, to, .. } => vec![
                ("from/anchor".to_string(), &from.anchor, None),
                (
                    "to/anchor".to_string(),
                    &to.anchor,
                    Some(StationKind::Point),
                ),
            ],
            Verb::BeginStealth { zones, .. } => zones
                .iter()
                .enumerate()
                .map(|(i, z)| (format!("zones/{i}/anchor"), &z.anchor, None))
                .collect(),
            Verb::PlaySound {
                at: Some(SoundAt::Anchor { anchor, .. }),
                ..
            } => vec![("at/anchor".to_string(), anchor, None)],
            // A firework is launched from a point and seats nothing, so it names
            // a location in the same shape `play-sound` does.
            Verb::Firework { at, .. } => vec![("at/anchor".to_string(), &at.anchor, None)],
            // A particle at a mark names a location the same way; at `players`
            // it names none.
            Verb::Particle {
                at: ParticleAt::Mark(m),
                ..
            } => vec![("at/anchor".to_string(), &m.anchor, None)],
            // spec-0022 trap-payload verbs. Both anchors of a `volley` are
            // load-bearing for the coverage proof, so both register here — a
            // typo'd `kill_zone` must be a dangling-reference error, never a
            // silently zero-cell (and therefore vacuously "covered") volley.
            Verb::Volley {
                from_anchor,
                kill_zone,
                ..
            } => vec![
                ("from_anchor".to_string(), from_anchor, None),
                ("kill_zone/anchor".to_string(), &kill_zone.anchor, None),
            ],
            Verb::Collapse { region_anchor, .. } => {
                vec![(
                    "region_anchor/anchor".to_string(),
                    &region_anchor.anchor,
                    None,
                )]
            }
            // The v0.10 region writes: the box's anchor is load-bearing for both
            // the emission and the completability model, so a typo'd one must be a
            // dangling-reference error (`DW0142`/`DW0360`), never a silently
            // unwritten — and therefore vacuously proven — region.
            Verb::FillRegion { region, .. } | Verb::ClearRegion { region, .. } => {
                vec![("region/anchor".to_string(), &region.anchor, None)]
            }
            // A repaint's box centre names a location, exactly as a region
            // write's does.
            Verb::SetAtmosphere {
                region: Some(region),
                ..
            } => vec![("region/anchor".to_string(), &region.anchor, None)],
            // Both cutscene spellings (`DW0199` polices mixing them): the v0.6
            // multi-shot list, or the v0.4 single-shot fields flattened at the
            // effect's own level.
            Verb::Cutscene {
                shots,
                path,
                look_at,
                ..
            } => {
                let mut out: Vec<(String, &AnchorId, Option<StationKind>)> = shots
                    .iter()
                    .enumerate()
                    .flat_map(|(i, s)| shot_refs(&format!("shots/{i}/"), s))
                    .collect();
                out.extend(
                    path.iter()
                        .enumerate()
                        .map(|(j, w)| (format!("path/{j}/anchor"), &w.anchor, None)),
                );
                if let Some(t) = look_at {
                    out.push(("look_at/anchor".to_string(), &t.anchor, None));
                }
                out
            }
            _ => Vec::new(),
        }
    }

    /// **Every object of a subject kind this effect names at this node** — the
    /// `npc/`, `actor/`, `wave/` and `anchor/` ids [`Happening::subject`] may
    /// name, in a fixed order, deduplicated (spec-0071 §3).
    ///
    /// The bodies come from [`Self::body_entry`] / [`Self::body_exit`] and the
    /// move verbs; the anchors come from [`Self::anchor_refs`], the single
    /// authority on the anchor-bearing surface, so a verb that gains an anchor
    /// gains it here too. Not recursive: a `sequence`'s steps each answer for
    /// themselves.
    ///
    /// This is a question about the **object class** a beat can be about, not
    /// about a list of verbs somebody maintains — which is why `unleash-actor`
    /// (one actor), `set-block` (one anchor) and `fill-region` (one anchor)
    /// answer it without being named anywhere, and why `move-actor` (an actor
    /// AND a destination anchor) and `teleport` (two anchors) answer with two.
    pub fn subject_objects(&self) -> Vec<&str> {
        fn add<'a>(id: &'a str, out: &mut Vec<&'a str>) {
            if !out.contains(&id) {
                out.push(id);
            }
        }
        let mut out: Vec<&str> = Vec::new();
        match &self.verb {
            Verb::SpawnNpc { npc, .. }
            | Verb::DespawnNpc { npc, .. }
            | Verb::MoveNpc { npc, .. } => add(npc.as_str(), &mut out),
            Verb::SpawnWave { wave, .. } => add(wave.as_str(), &mut out),
            _ => {}
        }
        if let Some(actor) = self.actor_ref() {
            add(actor.as_str(), &mut out);
        }
        for (_, anchor, _) in self.anchor_refs() {
            add(anchor.as_str(), &mut out);
        }
        out
    }

    /// **What this effect's `happening` is about**: the subject the branch
    /// chronicle records and the contradiction proof (`DW0485`) reasons over
    /// (spec-0071 §3).
    ///
    /// A stated [`Happening::subject`] always wins — the caller knows more. An
    /// absent one resolves to the effect's own object when it has exactly one
    /// ([`Self::subject_objects`]), because the beat that opens a gate is about
    /// that gate and the id is otherwise typed twice, two keys apart. An effect
    /// with several objects, or none, resolves nothing: naming one of them would
    /// be the compiler guessing which.
    ///
    /// **The one derivation.** The namespace check (`dsl::validate`) and the
    /// chronicle writer (`delvec::compiler::branch`) both read the subject
    /// through here, so a beat cannot be about one thing for the proof and
    /// another for the account a reader is handed.
    pub fn happening_subject(&self) -> Option<HappeningSubject<'_>> {
        let h = self.happening.as_ref()?;
        if let Some(stated) = h.subject.as_deref() {
            return Some(HappeningSubject {
                id: stated,
                derived: false,
            });
        }
        let objects = self.subject_objects();
        match objects.as_slice() {
            [only] => Some(HappeningSubject {
                id: only,
                derived: true,
            }),
            _ => None,
        }
    }

    /// The `cutscene` camera subject if this is a single-shot `cutscene` carrying
    /// the v0.6 `look_at` field.
    pub fn cutscene_look_at(&self) -> Option<&Mark> {
        match &self.verb {
            Verb::Cutscene { look_at, .. } => look_at.as_ref(),
            _ => None,
        }
    }

    /// `true` if this is a `cutscene` written in the v0.6 multi-shot form
    ///.
    pub fn cutscene_multi_shot(&self) -> bool {
        matches!(&self.verb, Verb::Cutscene { shots, .. } if !shots.is_empty())
    }

    /// The normalized shot list of a `cutscene`, whichever spelling was used: the
    /// v0.6 `shots` list as-is, or the v0.4 `path`/`seconds`/`look_at` fields as a
    /// single shot. `None` for a non-cutscene effect; an empty list for a cutscene
    /// whose shape is invalid (`DW0199` reports that).
    pub fn cutscene_shots(&self) -> Option<Vec<CameraShot>> {
        match &self.verb {
            Verb::Cutscene {
                shots,
                path,
                seconds,
                look_at,
                ..
            } => {
                if !shots.is_empty() {
                    return Some(shots.clone());
                }
                match seconds {
                    Some(secs) => Some(vec![CameraShot {
                        path: path.clone(),
                        seconds: Some(*secs),
                        look_at: look_at.clone(),
                        shot_style: None,
                        subject: None,
                        subject_b: None,
                        dist: None,
                        degrees: None,
                        bearing: None,
                    }]),
                    None => Some(Vec::new()),
                }
            }
            _ => None,
        }
    }

    /// `true` if this is a `narrate` carrying the `art` style (glyph-checked
    /// `DW0328`).
    pub fn narrate_art(&self) -> bool {
        matches!(
            &self.verb,
            Verb::Narrate {
                style: Some(NarrateStyle::Art),
                ..
            }
        )
    }

    /// The `narrate` line's text if this is a `narrate` with the `art` style.
    pub fn narrate_art_text(&self) -> Option<&str> {
        match &self.verb {
            Verb::Narrate {
                text,
                style: Some(NarrateStyle::Art),
                ..
            } => Some(text.as_str()),
            _ => None,
        }
    }

    /// The `narrate` line's style and text if this is a `narrate` rendered **on
    /// screen** — `title`, `subtitle` or `art` — rather than in chat. These are the
    /// styles vanilla draws centred and unwrapped, so their rendered width is
    /// length-checked against the screen (`DW0330`); `chat` scrolls and wraps, so it
    /// is exempt.
    pub fn narrate_on_screen(&self) -> Option<(NarrateStyle, &str)> {
        match &self.verb {
            Verb::Narrate {
                text,
                style: Some(s),
                ..
            } if matches!(
                s,
                NarrateStyle::Title | NarrateStyle::Subtitle | NarrateStyle::Art
            ) =>
            {
                Some((*s, text.as_str()))
            }
            _ => None,
        }
    }

    /// Every vanilla sound-event id this effect references, for registry
    /// validation (`DW0326`): a `play-sound`'s `sound`, and a `narrate`'s optional
    /// `sound`. Returns `(subpath, id)` pairs where `subpath` locates the field
    /// within the effect (e.g. `sound`).
    pub fn sound_refs(&self) -> Vec<(&'static str, &str)> {
        match &self.verb {
            Verb::PlaySound { sound, .. } => vec![("sound", sound.as_str())],
            Verb::Narrate { sound: Some(s), .. } => vec![("sound", s.as_str())],
            _ => Vec::new(),
        }
    }

    /// The `play-sound` `at: actor` id, if this effect is a `play-sound`
    /// targeting an actor (rejected `DW0335`).
    pub fn play_sound_actor(&self) -> Option<&str> {
        match &self.verb {
            Verb::PlaySound {
                at: Some(SoundAt::Actor { actor }),
                ..
            } => Some(actor.as_str()),
            _ => None,
        }
    }

    /// The per-effect flag gate: flags that must ALL be set (per party) for this
    /// effect to fire. Empty for an ungated effect. Read off the one [`Guard`], so
    /// **every** verb answers it — the staging and souls vocabulary included.
    pub fn requires_flags(&self) -> &[FlagId] {
        self.when.as_ref().map_or(&[][..], |g| &g.requires_flags)
    }

    /// The per-effect **negative** flag gate: flags whose being set suppresses this
    /// effect — the dual of [`QuestEffect::requires_flags`], on the same guard.
    pub fn forbids_flags(&self) -> &[FlagId] {
        self.when.as_ref().map_or(&[][..], |g| &g.forbids_flags)
    }

    /// The numeric gate terms (spec-0031) — the third axis of the same guard, so
    /// "which verbs are gatable" has exactly one answer.
    pub fn requires_state(&self) -> &[StateCompare] {
        self.when.as_ref().map_or(&[][..], |g| &g.requires_state)
    }

    /// The datum this effect writes and how, if it is one of the DSL v0.10 state
    /// verbs (`set-state` / `add-state` / `clear-state`).
    pub fn writes_state(&self) -> Option<(&StateId, StateWrite)> {
        match &self.verb {
            Verb::SetState { state, value, .. } => Some((state, StateWrite::Set(*value))),
            Verb::AddState { state, amount, .. } => Some((state, StateWrite::Add(*amount))),
            Verb::ClearState { state, .. } => Some((state, StateWrite::Clear)),
            _ => None,
        }
    }

    /// The `on_arrive` bundle if this is a `move-npc` carrying one (DSL v0.6;
    /// parity with `move-actor`). `None` for a bare `move-npc` and every other
    /// effect.
    pub fn move_npc_on_arrive(&self) -> Option<&[QuestEffect]> {
        match &self.verb {
            Verb::MoveNpc { on_arrive, .. } if !on_arrive.is_empty() => Some(on_arrive.as_slice()),
            _ => None,
        }
    }

    /// The actor id this effect targets, if it is one of the actor staging effects
    /// (`spawn-actor`/`despawn-actor`/`move-actor`/`unleash-actor`). `sequence` has
    /// no single actor (its nested effects each carry their own).
    pub fn actor_ref(&self) -> Option<&ActorId> {
        match &self.verb {
            Verb::SpawnActor { actor, .. }
            | Verb::DespawnActor { actor, .. }
            | Verb::MoveActor { actor, .. }
            | Verb::UnleashActor { actor, .. } => Some(actor),
            _ => None,
        }
    }

    /// Every vanilla **status-effect** id this effect names, for registry
    /// validation (`DW0192`) — the sibling of [`Self::sound_refs`] and the single
    /// authority on the status-effect-bearing verb surface. `(subpath, id)`
    /// pairs; empty for a `clear-effect` that names none (which clears all).
    pub fn status_effect_refs(&self) -> Vec<(&'static str, &str)> {
        match &self.verb {
            Verb::GiveEffect { effect, .. } => vec![("effect", effect.as_str())],
            Verb::ClearEffect {
                effect: Some(e), ..
            } => vec![("effect", e.as_str())],
            _ => Vec::new(),
        }
    }

    /// `(effect, seconds, amplifier, hide_particles, in)` if this is a
    /// `give-effect` (DSL v0.10), with the documented defaults already applied.
    pub fn give_effect(&self) -> Option<(&str, u32, u32, bool, Option<&StealthZone>)> {
        match &self.verb {
            Verb::GiveEffect {
                effect,
                seconds,
                amplifier,
                hide_particles,
                ..
            } => Some((
                effect.as_str(),
                *seconds,
                amplifier.unwrap_or(0),
                hide_particles.unwrap_or(false),
                self.within.as_ref(),
            )),
            _ => None,
        }
    }

    /// `(effect, in)` if this is a `clear-effect` (DSL v0.10). The effect is
    /// `None` for the clear-everything form, exactly as vanilla spells it.
    pub fn clear_effect(&self) -> Option<(Option<&str>, Option<&StealthZone>)> {
        match &self.verb {
            Verb::ClearEffect { effect, .. } => Some((effect.as_deref(), self.within.as_ref())),
            _ => None,
        }
    }

    /// `(from, to)` if this is a `teleport` (DSL v0.10): the source volume and
    /// the destination mark.
    pub fn teleport(&self) -> Option<(&StealthZone, &Mark)> {
        match &self.verb {
            Verb::Teleport { from, to, .. } => Some((from, to)),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Stage 7 — world-edits (the map editor edit script, DSL v0.6, spec-0017)
// ---------------------------------------------------------------------------

/// Stage 7 payload (optional; DSL v0.6, spec-0017): the map-editor edit script.
///
/// The artifact of record for L3 world detailing: an ordered list of edit
/// batches the compiler replays deterministically **after** world assembly.
/// The world files are never truth — same DSL + same edits + same seed →
/// byte-identical world (ADR-0006). A campaign without a `world-edits.json`
/// builds byte-identically to one from before this stage existed.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WorldEditsContent {
    /// Ordered edit batches, replayed in order. After every batch the post-edit
    /// invariants re-prove (walkability, sealing + relight, boundary safety),
    /// so each batch is a valid, snapshot-reviewable world state.
    pub batches: Vec<EditBatch>,
}

/// One edit batch: an ordered group of edit verbs applied to a single area,
/// checked and snapshot-rendered as a unit.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct EditBatch {
    /// Batch id (`batch/<kebab>`), unique in the script. Also the batch's
    /// snapshot name and seed-stream label — renaming a batch deliberately
    /// reseeds its noise.
    pub id: EditBatchId,
    /// The stage-1 area this batch edits. Frames and regions resolve against
    /// this area's placed pieces and anchors.
    pub area: AreaId,
    /// Authoring context (why this batch exists). Machine-ignored; **excluded**
    /// from l10n like `theme`/`premise`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// Ordered edit verbs. `select` defines named regions; later verbs in the
    /// same batch refer back to them (strictly backward, like every DSL ref).
    pub edits: Vec<WorldEdit>,
}

/// One edit verb (spec-0017 L3). Every verb operates on named regions and every
/// seeded verb derives its noise stream from the campaign seed + its script
/// position (`edits/<batch>/<index>`) — no wall clock, no unseeded RNG.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "verb", rename_all = "kebab-case", deny_unknown_fields)]
pub enum WorldEdit {
    /// Define a named region (`region/<kebab>`) for later verbs in this batch.
    Select {
        /// The region name being defined (unique within the batch).
        name: RegionId,
        /// The region's shape (box, surface band, palette match, or a
        /// composition of earlier regions).
        shape: RegionShape,
    },
    /// Fill every cell of a region from a seeded palette recipe (value-noise
    /// keyed, so picks cluster into patches — never a uniform fill).
    Fill {
        /// The region (an earlier `select` in this batch) to fill.
        region: RegionId,
        /// The palette recipe to fill with.
        recipe: PaletteRecipe,
    },
    /// Like `fill`, but only rewrites cells whose current block matches one of
    /// `matching` (base ids; blockstate suffixes are ignored when matching).
    Replace {
        /// The region (an earlier `select` in this batch) to edit.
        region: RegionId,
        /// Base block ids to rewrite (e.g. `["minecraft:stone"]`).
        matching: Vec<String>,
        /// The palette recipe to rewrite them with.
        recipe: PaletteRecipe,
    },
    /// Clear a region to air. Sealing-aware: the carved region re-enters the
    /// sealing + relight passes and every walkability invariant re-proves.
    Carve {
        /// The region (an earlier `select` in this batch) to clear.
        region: RegionId,
    },
    /// Reshape terrain surface within a region (raise / lower / smooth).
    Morph {
        /// The region (an earlier `select` in this batch) whose columns to
        /// reshape. The region defines the footprint and where each column's
        /// surface is read (the highest occupied cell in the region's y-range);
        /// `raise`/`smooth` may add cells above the region's top — reshaping
        /// upward is the point — while removal only touches region cells.
        region: RegionId,
        /// The surface operation.
        op: MorphOp,
    },
    /// Seeded dressing scatter (spec-0017): drop weighted single-block
    /// dressing (flora, rocks, props) onto standable cells of a region —
    /// air cells with an occupied cell directly below — honoring keep-clear
    /// envelopes (`avoid`). Per-cell white-noise density gate (dressing wants
    /// speckle, not the fill verbs' clustered patches), deterministic from the
    /// campaign seed + script position.
    Scatter {
        /// The region (an earlier `select` in this batch) to dress.
        region: RegionId,
        /// Weighted dressing blocks (blockstate suffixes allowed).
        items: Vec<PaletteBlock>,
        /// Per-candidate placement probability in `(0, 1]`.
        density: f64,
        /// Keep-clear envelopes: earlier regions whose cells (and columns —
        /// matched by `(x, z)`) never receive dressing.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        avoid: Vec<RegionId>,
        /// Optional minimum spacing: when set, candidates are taken in
        /// descending noise order and one is rejected while another accepted
        /// candidate is closer than this on **both** horizontal axes (the
        /// generators' spread rule).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        spacing: Option<u32>,
        /// Optional cap on how many items are placed (highest-noise first).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        limit: Option<u32>,
    },
    /// Structural flora (spec-0017): plant hand-shaped trees via the
    /// lean-or-grow canopy rules — a canopy that would reach a
    /// keep-clear (`avoid`) column first leans one block away from it; if that
    /// still covers the corridor the tree grows tall instead, arching its
    /// whole canopy 3 blocks above the trunk's floor. No leaf is ever sliced.
    Plant {
        /// The region (an earlier `select` in this batch) to plant in. Trunk
        /// cells are standable region cells (air over an occupied cell).
        region: RegionId,
        /// The tree species (canopy shape rules are per-species).
        tree: TreeKind,
        /// How many trees to plant (≥ 1; highest-noise candidates first).
        count: u32,
        /// Keep-clear envelopes: trunks never stand in these columns and
        /// canopies lean/grow to clear them.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        avoid: Vec<RegionId>,
        /// Minimum trunk spacing (reject when closer on BOTH axes; default 4).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        spacing: Option<u32>,
    },
    /// Stamp a prefab fragment (spec-0017): copy a library prefab's
    /// non-air cells into the world at a frame-resolved position. The fragment
    /// is a first-class library prefab — its provenance/license metadata is
    /// recorded and validated exactly like any placed prefab (ADR-0013);
    /// nothing outside the library can be stamped.
    Fragment {
        /// The library prefab to stamp.
        prefab: PrefabId,
        /// The frame `at` resolves in.
        frame: EditFrame,
        /// Where the fragment's local `(0, 0, 0)` lands (frame coordinates).
        at: [i32; 3],
        /// Placement rotation (default `none`), the same quarter-turn set as
        /// `/place template`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        rotation: Option<FragmentRotation>,
    },
    /// Explicit region relight (spec-0017, spec-0010 machinery): run the
    /// deterministic fixture-placement pass over ONE region and bake the
    /// resulting fixtures into the edit script's writes — authorial control of
    /// where fixtures land, instead of the whole-area pass's greedy siting.
    /// (The whole-area relight still re-proves after every batch either way.)
    Relight {
        /// The region (an earlier `select` in this batch) to relight: its
        /// reachable walkable cells are brought to `min_light`.
        region: RegionId,
        /// Fixture override; default = the area's declared `lighting.fixture`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        fixture: Option<Fixture>,
        /// Target light override (1..=14); default = the area's declared
        /// `lighting.min_light`. Required (with `fixture`) when the area
        /// declares no `lighting`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        min_light: Option<u8>,
    },
    /// L2 massing (spec-0017): replace a placed piece with another
    /// library prefab that re-mates every currently-mated socket at its exact
    /// world pose (any rotation; overlap-checked). Applied at **plan** time —
    /// the whole downstream ladder (anchors, gate reachability, assembly,
    /// relight, nav, L3 detailing) re-runs over the massaged layout. Massing
    /// verbs live in massing-only batches, ordered before every detailing
    /// batch.
    SwapPiece {
        /// The piece's placement index in its area's solved layout (0-based,
        /// entry first).
        piece: u32,
        /// The prefab the indexed piece must currently be (drift guard).
        prefab: PrefabId,
        /// The library prefab to swap in.
        with: PrefabId,
    },
    /// L2 massing (spec-0017): attach a new piece at a specific **open**
    /// (unmated) socket of an existing piece — the targeted form of the
    /// solver's frontier attach. The socket opens (its seal becomes a
    /// passage); the new piece's other sockets seal.
    InsertPiece {
        /// The host piece's placement index.
        at_piece: u32,
        /// The prefab the host piece must currently be (drift guard).
        prefab: PrefabId,
        /// The host's connector index (prefab metadata `connectors` order).
        socket: u32,
        /// The library prefab to attach.
        insert: PrefabId,
    },
    /// L2 massing (spec-0017): remove a **leaf** piece (exactly one
    /// mated socket; never the entry piece). The neighbour's socket unmates
    /// and re-seals. Removal shifts later placement indices — order removals
    /// before other index-referencing massing verbs.
    RemovePiece {
        /// The piece's placement index.
        piece: u32,
        /// The prefab the indexed piece must currently be (drift guard).
        prefab: PrefabId,
    },
    /// L2 massing (spec-0017): override one socket's seal — `open`
    /// clears the opening to a passage, `sealed` walls it up — independent of
    /// its mated state (sealing a mated doorway makes a wall between joined
    /// pieces; opening an unmated exterior socket exposes the outside, which
    /// the boundary-safety proof then judges).
    RewireSocket {
        /// The piece's placement index.
        piece: u32,
        /// The prefab the indexed piece must currently be (drift guard).
        prefab: PrefabId,
        /// The connector index (prefab metadata `connectors` order).
        socket: u32,
        /// The socket's new state.
        state: SocketState,
    },
    /// L2 massing (spec-0017): re-pick this piece from its area pool's
    /// compatible members (weighted, seeded from the campaign seed + this
    /// verb's script position — moving the verb deliberately re-rolls). The
    /// current prefab is excluded, so a reseed always changes the piece or
    /// errors loudly.
    ReseedPiece {
        /// The piece's placement index.
        piece: u32,
        /// The prefab the indexed piece must currently be (drift guard).
        prefab: PrefabId,
    },
}

/// A socket seal state for `rewire-socket` (spec-0017).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum SocketState {
    /// The opening is cleared to a passage.
    Open,
    /// The opening is walled up.
    Sealed,
}

/// A tree species for the `plant` verb (spec-0017). One species per
/// canopy-rule implementation; the shipped rule set is the lean-or-grow oak.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum TreeKind {
    /// Small hand-shaped oak (3–4 logs, 5-wide leaf ball) with the
    /// lean-or-grow corridor rules.
    Oak,
}

/// A `fragment` stamp rotation (spec-0017) — the `/place template`
/// quarter-turn set.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum FragmentRotation {
    /// No rotation.
    None,
    /// 90° clockwise.
    Clockwise90,
    /// 180°.
    Clockwise180,
    /// 90° counterclockwise.
    Counterclockwise90,
}

/// A `select` verb's shape (spec-0017): primitive shapes resolve in a declared
/// frame; compositions combine earlier regions of the same batch.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum RegionShape {
    /// An inclusive axis-aligned box, `min`/`max` in the declared frame.
    Box {
        /// The coordinate frame `min`/`max` resolve in.
        frame: EditFrame,
        /// Inclusive minimum corner (frame coordinates).
        min: [i32; 3],
        /// Inclusive maximum corner (frame coordinates; each axis ≥ `min`).
        max: [i32; 3],
    },
    /// The band of cells at `from..=to` blocks relative to each column's
    /// terrain surface (the highest non-air cell of the column) within an
    /// earlier region. `from: 1, to: 3` is the 3 cells of air-space above the
    /// surface; `from: 0, to: 0` is the surface cells themselves; negative
    /// offsets reach below the surface.
    SurfaceBand {
        /// The earlier region whose columns are scanned.
        over: RegionId,
        /// Inclusive band start, relative to each column's surface y.
        from: i32,
        /// Inclusive band end (≥ `from`), relative to each column's surface y.
        to: i32,
    },
    /// The cells of an earlier region whose current block matches one of
    /// `blocks` (base ids; blockstate suffixes ignored when matching).
    PaletteMatch {
        /// The earlier region to filter.
        within: RegionId,
        /// Base block ids to match (e.g. `["minecraft:grass_block"]`).
        blocks: Vec<String>,
    },
    /// The union of earlier regions.
    Union {
        /// The earlier regions to unite (≥ 2).
        of: Vec<RegionId>,
    },
    /// The intersection of earlier regions.
    Intersect {
        /// The earlier regions to intersect (≥ 2).
        of: Vec<RegionId>,
    },
    /// An earlier region minus other earlier regions.
    Subtract {
        /// The earlier region to start from.
        base: RegionId,
        /// The earlier regions to remove from it (≥ 1).
        remove: Vec<RegionId>,
    },
}

/// The coordinate frame a primitive [`RegionShape`] resolves in (spec-0017):
/// piece-local or anchor-relative — never raw world coordinates, so an edit
/// script survives a layout's world placement moving.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum EditFrame {
    /// The local frame of a placed piece of the batch's area: `[0, 0, 0]` is
    /// the piece's structure origin, axes as authored (the compiler applies
    /// the piece's placed rotation).
    PieceLocal {
        /// The piece's placement index in the area's solved layout (0-based,
        /// entry piece first — the order `delvec snapshot`'s manifest lists).
        piece: u32,
        /// The prefab the indexed piece must be (a drift guard: if a re-solve
        /// changed the layout, the mismatch is a loud compile error, never a
        /// silently misplaced edit).
        prefab: PrefabId,
    },
    /// Relative to a resolved anchor of the batch's area: `[0, 0, 0]` is the
    /// anchor cell, axes world-aligned.
    AnchorRelative {
        /// The anchor (prefab metadata, resolved by the compiler).
        anchor: AnchorId,
    },
}

/// A surface operation for the `morph` verb (spec-0017).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum MorphOp {
    /// Raise each column's surface by up to `by` blocks, drawing the added
    /// cells from `recipe` (value-noise keyed per cell, so a raised band reads
    /// as natural strata, not an extruded slab).
    Raise {
        /// How many blocks to raise each column (≥ 1).
        by: u32,
        /// The palette recipe for the added cells.
        recipe: PaletteRecipe,
    },
    /// Lower each column's surface by up to `by` blocks (carving the topmost
    /// solid cells to air).
    Lower {
        /// How many blocks to lower each column (≥ 1).
        by: u32,
    },
    /// Relax each column's surface toward the mean of its cardinal neighbours
    /// (one block per pass), turning steps into slopes. Added cells draw from
    /// `recipe`; removed cells carve to air. Deterministic double-buffered
    /// passes in fixed scan order.
    Smooth {
        /// Relaxation passes (≥ 1).
        passes: u32,
        /// The palette recipe for cells a pass adds.
        recipe: PaletteRecipe,
    },
}

/// A seeded palette recipe (spec-0017): weighted blocks picked per cell by a
/// smooth value-noise sample, the island/cave generators' proven primitive —
/// picks cluster into strata/patches instead of per-cell speckle, and a
/// single-entry recipe is the degenerate (discouraged) uniform case.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PaletteRecipe {
    /// Weighted palette entries (≥ 1; ≥ 2 for any visible surface).
    pub blocks: Vec<PaletteBlock>,
    /// Noise frequency in blocks⁻¹ (default `0.35` — patches a few blocks
    /// across). Larger = smaller patches. Must be finite and > 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scale: Option<f64>,
}

/// One weighted entry of a [`PaletteRecipe`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PaletteBlock {
    /// Vanilla block id (validated against the pinned 1.21.11 registry), with
    /// an optional verbatim blockstate suffix (`minecraft:oak_leaves[persistent=true]`).
    pub block: String,
    /// Relative weight (finite, > 0).
    pub weight: f64,
}

/// Where in the campaign one effect sits — the attribution every per-branch
/// proof and the branch chronicle need (spec-0025).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EffectSite {
    /// A quest's `on_objective_complete[<objective>]` bundle.
    Objective {
        /// The owning quest.
        quest: String,
        /// The objective whose completion fires the bundle.
        objective: String,
    },
    /// A quest's `on_complete` bundle.
    QuestComplete {
        /// The owning quest.
        quest: String,
    },
    /// An environment trigger's `effects` bundle — ambient, no DAG position.
    Trigger {
        /// The trigger id.
        trigger: String,
    },
    /// A trap's spec-0022 `payload` bundle — ambient, no DAG position.
    Trap {
        /// The trap id.
        trap: String,
    },
    /// A **dialogue option's** `set-checkpoint` `on_respawn` bundle — ambient, no
    /// DAG position, and the only site that does not live in the quests stage.
    ///
    /// This variant did not exist until the effect-root sweep, and its absence was
    /// load-bearing: `EffectSite` had no way to *represent* a dialogue-hosted
    /// bundle, so the four proofs that walk [`for_each_campaign_effect`]
    /// (`combat::actor_beats`, `validate::difficulty_checks`,
    /// `daylight::fightable_actor`, `nav::actor_fights`) could not have seen root 5
    /// even if their authors had thought of it. Widening the type is what let the
    /// walk widen.
    DialogueRespawn {
        /// The NPC whose dialogue tree hosts the option.
        npc: String,
        /// The node the option sits under.
        node: String,
    },
    /// A `shortcuts[].on_unlock` bundle (spec-0016 §2) — ambient, no DAG
    /// position, and the sixth root: representable here only since spec-0031, for
    /// exactly the reason [`EffectSite::DialogueRespawn`] records above.
    ShortcutUnlock {
        /// The shortcut id.
        shortcut: String,
    },
    /// A `shops[].offers[].effects` bundle (DSL v0.10, spec-0032) — ambient, no
    /// DAG position: nobody is forced to buy anything.
    ShopOffer {
        /// The shop id.
        shop: String,
        /// The offer's index within that shop, which is also its button order.
        offer: usize,
    },
    /// The campaign's `on_death` bundle (spec-0031) — ambient, no DAG position,
    /// and no owning object: there is one per campaign.
    OnDeath,
    /// A wave's or an actor's `on_kill` bundle (spec-0074) — ambient, no DAG
    /// position: nobody is forced to be credited with a kill.
    OnKill {
        /// The fight's id (`wave/<kebab>` or `actor/<kebab>`).
        fight: String,
    },
    /// An assembly strike step's `on_land` bundle (spec-0082) — ambient, no
    /// DAG position: nobody is forced to stand where a blow lands.
    AssemblyLand {
        /// The assembly id.
        assembly: String,
        /// The step's index within the pattern.
        step: usize,
    },
    /// A loop's `on_cross` bundle (spec-0086) — no DAG position of its own: it
    /// runs when a body crosses the holding slab.
    LoopCross {
        /// The loop id (`loop/<kebab>`).
        r#loop: String,
    },
}

impl EffectSite {
    /// The quest this site belongs to, if it has a DAG position at all.
    ///
    /// **This `Option` is the capability, and it is on the enum rather than on the
    /// variants that happen to have a quest.** Only two of the eight sites name a
    /// quest, because only two of the eight roots HAVE a DAG position: an ambient
    /// root — a trigger, a trap payload, a dialogue `on_respawn`, a shortcut's
    /// `on_unlock`, the campaign's `on_death`, a shop offer — fires at a moment no
    /// static model can order, and inventing a quest for one would be exactly the
    /// over-attribution the completability model must not make. Asking the question
    /// of every variant and getting an honest `None` is the lift;
    /// `tools/ci/check-capability-ownership.py` check D asked for it while the field
    /// was still cross-cutting, and spec-0032's eighth site took it below that
    /// threshold, so the reasoning lives here now rather than in an exemption.
    pub fn quest(&self) -> Option<&str> {
        match self {
            EffectSite::Objective { quest, .. } | EffectSite::QuestComplete { quest } => {
                Some(quest)
            }
            EffectSite::Trigger { .. }
            | EffectSite::Trap { .. }
            | EffectSite::DialogueRespawn { .. }
            | EffectSite::ShortcutUnlock { .. }
            | EffectSite::ShopOffer { .. }
            | EffectSite::OnDeath
            | EffectSite::OnKill { .. }
            | EffectSite::AssemblyLand { .. }
            | EffectSite::LoopCross { .. } => None,
        }
    }
}

/// Visit **every** effect the compiler can lower — at every one of the five
/// effect roots, top-level and transitively nested — in a fixed deterministic
/// order, invoking `f(json_pointer, site, effect)`.
///
/// The roots come from [`crate::effects::for_each_effect_root`], the single
/// enumeration; nesting is descended through the single
/// [`QuestEffect::nested_effect_lists_labeled`] authority. Neither axis is
/// enumerated here, which is the point: this walk used to hand-list four of the
/// five roots (it had no `EffectSite` variant for the fifth), so every proof
/// defined in terms of it inherited that blind spot.
pub fn for_each_campaign_effect<'a>(
    c: &'a crate::envelope::Campaign,
    f: &mut dyn FnMut(&str, &EffectSite, &'a QuestEffect),
) {
    crate::effects::for_each_effect_root(c, &mut |root, list| {
        let site = match root.owner {
            crate::effects::EffectRootOwner::ObjectiveComplete { quest, objective } => {
                EffectSite::Objective {
                    quest: quest.id.as_str().to_string(),
                    objective: objective.to_string(),
                }
            }
            crate::effects::EffectRootOwner::QuestComplete { quest } => EffectSite::QuestComplete {
                quest: quest.id.as_str().to_string(),
            },
            crate::effects::EffectRootOwner::Trigger(t) => EffectSite::Trigger {
                trigger: t.id.as_str().to_string(),
            },
            crate::effects::EffectRootOwner::TrapPayload(t) => EffectSite::Trap {
                trap: t.id.as_str().to_string(),
            },
            crate::effects::EffectRootOwner::DialogueRespawn => {
                // The npc and node are in the root's path; parse them back rather
                // than widening the root walk's owner for one consumer.
                let seg = |n: usize| -> String {
                    root.path.split('/').nth(n).unwrap_or_default().to_string()
                };
                EffectSite::DialogueRespawn {
                    npc: seg(3),
                    node: seg(5),
                }
            }
            crate::effects::EffectRootOwner::ShortcutUnlock(s) => EffectSite::ShortcutUnlock {
                shortcut: s.id.as_str().to_string(),
            },
            crate::effects::EffectRootOwner::OnDeath => EffectSite::OnDeath,
            crate::effects::EffectRootOwner::ShopOffer(h) => EffectSite::ShopOffer {
                shop: h.id.as_str().to_string(),
                // The offer index is in the root's path
                // (`/content/shops/<h>/offers/<i>/effects`), parsed back rather
                // than widening the owner for one consumer — the same call the
                // dialogue arm above makes. Segment 5 is the index: segment 4 is
                // the literal `offers`, which parses as nothing and reported
                // every offer as the shop's first.
                offer: root
                    .path
                    .split('/')
                    .nth(5)
                    .and_then(|n| n.parse().ok())
                    .unwrap_or(0),
            },
            crate::effects::EffectRootOwner::OnKill(f) => EffectSite::OnKill {
                fight: f.id().to_string(),
            },
            crate::effects::EffectRootOwner::AssemblyLand(m) => EffectSite::AssemblyLand {
                assembly: m.id.as_str().to_string(),
                // `/content/assemblies/<m>/strikes/pattern/<s>/on_land`: segment
                // 6 is the step index, parsed back as the shop arm does.
                step: root
                    .path
                    .split('/')
                    .nth(6)
                    .and_then(|n| n.parse().ok())
                    .unwrap_or(0),
            },
            crate::effects::EffectRootOwner::LoopCross(l) => EffectSite::LoopCross {
                r#loop: l.id.as_str().to_string(),
            },
        };
        for (i, eff) in list.iter().enumerate() {
            campaign_effect_deep(eff, &format!("{}/{i}", root.path), &site, f);
        }
    });
}

fn campaign_effect_deep<'a>(
    eff: &'a QuestEffect,
    path: &str,
    site: &EffectSite,
    f: &mut dyn FnMut(&str, &EffectSite, &'a QuestEffect),
) {
    f(path, site, eff);
    for (pseg, _kseg, list) in eff.nested_effect_lists_labeled() {
        for (j, inner) in list.iter().enumerate() {
            campaign_effect_deep(inner, &format!("{path}/{pseg}/{j}"), site, f);
        }
    }
}

// ---------------------------------------------------------------------------
// The spine authority (`QuestPlanContent::spine`)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod spine_tests {
    use super::QuestPlanContent;

    /// Build a plan from `(id, deps)` pairs plus a finale. JSON rather than a
    /// struct literal on purpose: a field added to `PlannedQuest` later must not
    /// red these tests for a reason that has nothing to do with the spine.
    fn plan(finale: &str, quests: &[(&str, &[&str])]) -> QuestPlanContent {
        let quests: Vec<serde_json::Value> = quests
            .iter()
            .map(|(id, deps)| {
                serde_json::json!({
                    "id": id,
                    "goal": "g",
                    "area": "area/keep",
                    "npcs": [],
                    "depends_on": deps,
                    "mandatory": true,
                    "act": 1,
                })
            })
            .collect();
        serde_json::from_value(serde_json::json!({
            "finale": finale,
            "quests": quests,
        }))
        .expect("plan fixture parses")
    }

    fn sorted(p: &QuestPlanContent) -> Vec<String> {
        p.spine().into_iter().map(str::to_owned).collect()
    }

    #[test]
    fn a_chain_is_wholly_spine() {
        let p = plan(
            "quest/c",
            &[
                ("quest/a", &[]),
                ("quest/b", &["quest/a"]),
                ("quest/c", &["quest/b"]),
            ],
        );
        assert_eq!(sorted(&p), ["quest/a", "quest/b", "quest/c"]);
    }

    #[test]
    fn a_quest_the_finale_does_not_depend_on_is_off_the_spine() {
        // Exactly the `DW0132` shape: the plan does not converge, and the spine
        // is the half that does. The authority answers, it does not refuse — the
        // refusal is `validate`'s, built on this answer.
        let p = plan("quest/end", &[("quest/end", &[]), ("quest/side-trip", &[])]);
        assert_eq!(sorted(&p), ["quest/end"]);
    }

    #[test]
    fn a_diamond_counts_the_join_once() {
        let p = plan(
            "quest/d",
            &[
                ("quest/a", &[]),
                ("quest/b", &["quest/a"]),
                ("quest/c", &["quest/a"]),
                ("quest/d", &["quest/b", "quest/c"]),
            ],
        );
        assert_eq!(sorted(&p), ["quest/a", "quest/b", "quest/c", "quest/d"]);
    }

    #[test]
    fn a_cycle_terminates_and_yields_a_set() {
        // `DW0130` refuses this plan, but the authority is asked before that
        // verdict is known (the layout binding prints on an erroring campaign),
        // so it must terminate rather than hang.
        let p = plan(
            "quest/b",
            &[("quest/a", &["quest/b"]), ("quest/b", &["quest/a"])],
        );
        assert_eq!(sorted(&p), ["quest/a", "quest/b"]);
    }

    #[test]
    fn a_dangling_dependency_is_reported_and_expands_no_further() {
        // The deliberate difference between the two derivations this function
        // replaced. `validate` pruned undeclared ids before walking; the
        // authority does not, because pruning them would make the set disagree
        // with the document, and naming an id the plan does not declare is
        // `DW0112`'s finding rather than the spine's.
        let p = plan("quest/end", &[("quest/end", &["quest/ghost"])]);
        assert_eq!(sorted(&p), ["quest/end", "quest/ghost"]);
    }

    #[test]
    fn an_undeclared_finale_is_the_whole_spine() {
        // `DW0131`'s shape. The answer is honest about the document: nothing the
        // plan declares is on the spine of a finale it never declared.
        let p = plan(
            "quest/ghost",
            &[("quest/a", &[]), ("quest/b", &["quest/a"])],
        );
        assert_eq!(sorted(&p), ["quest/ghost"]);
    }
}

// ---------------------------------------------------------------------------
// The derived happening subject (spec-0071 §3)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod happening_subject_tests {
    use super::QuestEffect;

    /// An effect with a `happening` that states no subject.
    fn beat(verb: serde_json::Value) -> QuestEffect {
        let mut v = verb;
        v["happening"] = serde_json::json!({ "verb": "opens", "text": "It gives." });
        serde_json::from_value(v).expect("effect fixture parses")
    }

    fn subject(v: serde_json::Value) -> Option<String> {
        beat(v).happening_subject().map(|s| {
            assert!(s.derived, "the fixture states no subject");
            s.id.to_string()
        })
    }

    /// **The census, over every verb the DSL declares.** Which verbs resolve a
    /// subject is a fact about the objects an effect names, so the answer is
    /// computed here rather than listed anywhere: the table below is held to the
    /// variant set of the exported schema, and a thirty-ninth verb reds this
    /// test until somebody answers for it.
    ///
    /// Run with `--nocapture` to print the census a document quotes.
    #[test]
    fn every_verb_answers_the_census() {
        // One minimal instance per verb, in the schema's own order.
        let table: Vec<(&str, serde_json::Value, Option<&str>)> = vec![
            (
                "open-gate",
                serde_json::json!({"type":"open-gate","anchor":"anchor/door"}),
                Some("anchor/door"),
            ),
            (
                "close-gate",
                serde_json::json!({"type":"close-gate","anchor":"anchor/door"}),
                Some("anchor/door"),
            ),
            (
                "campaign-complete",
                serde_json::json!({"type":"campaign-complete"}),
                None,
            ),
            (
                "give-item",
                serde_json::json!({"type":"give-item","item":"minecraft:bread","count":1}),
                None,
            ),
            (
                "set-flag",
                serde_json::json!({"type":"set-flag","flag":"flag/heard"}),
                None,
            ),
            (
                "set-state",
                serde_json::json!({"type":"set-state","state":"state/purse","value":1}),
                None,
            ),
            (
                "add-state",
                serde_json::json!({"type":"add-state","state":"state/purse","amount":-1}),
                None,
            ),
            (
                "drop-stake",
                serde_json::json!({"type":"drop-stake","stake":"stake/purse"}),
                None,
            ),
            (
                "clear-state",
                serde_json::json!({"type":"clear-state","state":"state/purse"}),
                None,
            ),
            (
                "spawn-wave",
                serde_json::json!({"type":"spawn-wave","wave":"wave/muster"}),
                Some("wave/muster"),
            ),
            (
                "narrate",
                serde_json::json!({"type":"narrate","text":"The hall answers."}),
                None,
            ),
            (
                "set-block",
                serde_json::json!({"type":"set-block","anchor":"anchor/altar","block":"minecraft:stone"}),
                Some("anchor/altar"),
            ),
            (
                "fill-region",
                serde_json::json!({"type":"fill-region","region":{"anchor":"anchor/pit","extent":[2,2,2]},"block":"minecraft:water"}),
                Some("anchor/pit"),
            ),
            (
                "set-atmosphere",
                serde_json::json!({"type":"set-atmosphere","atmosphere":"atmosphere/wrong","region":{"anchor":"anchor/hall","extent":[4,2,4]}}),
                Some("anchor/hall"),
            ),
            (
                "clear-region",
                serde_json::json!({"type":"clear-region","region":{"anchor":"anchor/pit","extent":[2,2,2]}}),
                Some("anchor/pit"),
            ),
            (
                "open-way",
                serde_json::json!({"type":"open-way","piece":"prefab/span","way":"gap"}),
                None,
            ),
            (
                "despawn-npc",
                serde_json::json!({"type":"despawn-npc","npc":"npc/keeper"}),
                Some("npc/keeper"),
            ),
            (
                "move-npc",
                serde_json::json!({"type":"move-npc","npc":"npc/keeper","to":{"anchor":"anchor/door"}}),
                None,
            ),
            (
                "cutscene",
                serde_json::json!({"type":"cutscene","path":[{"anchor":"anchor/hall"},{"anchor":"anchor/door"}],"seconds":4}),
                None,
            ),
            (
                "set-time",
                serde_json::json!({"type":"set-time","time":"noon"}),
                None,
            ),
            (
                "set-weather",
                serde_json::json!({"type":"set-weather","weather":"clear"}),
                None,
            ),
            (
                "play-sound",
                serde_json::json!({"type":"play-sound","sound":"minecraft:block.bell.use","at":{"at":"anchor","anchor":"anchor/bell"}}),
                Some("anchor/bell"),
            ),
            (
                "damage-players",
                serde_json::json!({"type":"damage-players","amount":2}),
                None,
            ),
            (
                "set-checkpoint",
                serde_json::json!({"type":"set-checkpoint","anchor":"anchor/seat"}),
                Some("anchor/seat"),
            ),
            (
                "bonfire",
                serde_json::json!({"type":"bonfire","anchor":"anchor/seat"}),
                Some("anchor/seat"),
            ),
            (
                "begin-stealth",
                serde_json::json!({"type":"begin-stealth","zones":[{"anchor":"anchor/yard","extent":[4,2,4]}]}),
                Some("anchor/yard"),
            ),
            (
                "end-stealth",
                serde_json::json!({"type":"end-stealth"}),
                None,
            ),
            (
                "spawn-npc",
                serde_json::json!({"type":"spawn-npc","npc":"npc/keeper"}),
                Some("npc/keeper"),
            ),
            (
                "spawn-actor",
                serde_json::json!({"type":"spawn-actor","actor":"actor/giant"}),
                Some("actor/giant"),
            ),
            (
                "despawn-actor",
                serde_json::json!({"type":"despawn-actor","actor":"actor/giant","style":"vanish"}),
                Some("actor/giant"),
            ),
            (
                "move-actor",
                serde_json::json!({"type":"move-actor","actor":"actor/giant","to":{"anchor":"anchor/door"}}),
                None,
            ),
            (
                "unleash-actor",
                serde_json::json!({"type":"unleash-actor","actor":"actor/giant"}),
                Some("actor/giant"),
            ),
            (
                "sequence",
                serde_json::json!({"type":"sequence","steps":[]}),
                None,
            ),
            (
                "volley",
                serde_json::json!({"type":"volley","from_anchor":"anchor/slot","kill_zone":{"anchor":"anchor/lane","extent":[3,2,3]}}),
                None,
            ),
            (
                "collapse",
                serde_json::json!({"type":"collapse","region_anchor":{"anchor":"anchor/roof","extent":[3,1,3]}}),
                Some("anchor/roof"),
            ),
            (
                "give-effect",
                serde_json::json!({"type":"give-effect","effect":"minecraft:speed","seconds":10}),
                None,
            ),
            (
                "clear-effect",
                serde_json::json!({"type":"clear-effect"}),
                None,
            ),
            (
                "teleport",
                serde_json::json!({"type":"teleport","from":{"anchor":"anchor/hall","extent":[4,2,4]},"to":{"anchor":"anchor/door"}}),
                None,
            ),
            (
                "firework",
                serde_json::json!({"type":"firework","at":{"anchor":"anchor/court"},"explosions":[{"shape":"star","colors":["#ffd700"]}]}),
                Some("anchor/court"),
            ),
            // spec-0082: an assembly is not a story subject (no `happening` is
            // demanded of its verbs), so none of the three resolves one.
            (
                "spawn-assembly",
                serde_json::json!({"type":"spawn-assembly","assembly":"assembly/limb"}),
                None,
            ),
            (
                "despawn-assembly",
                serde_json::json!({"type":"despawn-assembly","assembly":"assembly/limb"}),
                None,
            ),
            (
                "play-clip",
                serde_json::json!({"type":"play-clip","assembly":"assembly/limb","clip":"idle"}),
                None,
            ),
            (
                "particle",
                serde_json::json!({"type":"particle","particle":"minecraft:soul","at":{"anchor":"anchor/well"}}),
                Some("anchor/well"),
            ),
        ];
        // The binding: the table answers for every verb the schema declares, and
        // for no name the schema does not.
        let schema = crate::schema::stage_schema(crate::envelope::Stage::Quests);
        let declared: std::collections::BTreeSet<String> = schema["$defs"]["QuestEffect"]["oneOf"]
            .as_array()
            .expect("QuestEffect is a tagged union")
            .iter()
            .map(|b| {
                b["properties"]["type"]["const"]
                    .as_str()
                    .expect("a tag")
                    .to_string()
            })
            .collect();
        let answered: std::collections::BTreeSet<String> =
            table.iter().map(|(t, _, _)| (*t).to_string()).collect();
        assert_eq!(
            answered, declared,
            "the census answers for exactly the verbs the DSL declares"
        );
        for (tag, effect, want) in &table {
            let got = subject(effect.clone());
            assert_eq!(
                got.as_deref(),
                *want,
                "`{tag}` resolves {want:?}; it names {:?}",
                beat(effect.clone()).subject_objects()
            );
            println!(
                "| `{tag}` | {} | {} |",
                want.unwrap_or("—"),
                beat(effect.clone()).subject_objects().join(", ")
            );
        }
    }

    /// **Some verbs answer per instance, not per verb**, because the object is
    /// in an optional field: an `in` filter, a second stealth zone, a camera
    /// path of one waypoint. The rule is over the objects an effect names, so
    /// the same verb resolves in one document and not in another — and that is
    /// the answer, not a gap in it.
    #[test]
    fn a_verb_whose_object_is_optional_answers_per_instance() {
        for (what, effect, want) in [
            (
                "damage-players with an `in` filter",
                serde_json::json!({"type":"damage-players","amount":2,"in":{"anchor":"anchor/lane","extent":[3,2,3]}}),
                Some("anchor/lane"),
            ),
            (
                "give-effect with an `in` filter",
                serde_json::json!({"type":"give-effect","effect":"minecraft:speed","seconds":10,"in":{"anchor":"anchor/lane","extent":[3,2,3]}}),
                Some("anchor/lane"),
            ),
            (
                "clear-effect with an `in` filter",
                serde_json::json!({"type":"clear-effect","in":{"anchor":"anchor/lane","extent":[3,2,3]}}),
                Some("anchor/lane"),
            ),
            (
                "play-sound with no `at`",
                serde_json::json!({"type":"play-sound","sound":"minecraft:block.bell.use"}),
                None,
            ),
            (
                "begin-stealth over two zones",
                serde_json::json!({"type":"begin-stealth","zones":[
                    {"anchor":"anchor/yard","extent":[4,2,4]},
                    {"anchor":"anchor/lane","extent":[4,2,4]}]}),
                None,
            ),
            (
                "a cutscene whose path names one cell",
                serde_json::json!({"type":"cutscene","path":[{"anchor":"anchor/hall"}],"seconds":4}),
                Some("anchor/hall"),
            ),
        ] {
            assert_eq!(subject(effect.clone()).as_deref(), want, "{what}");
        }
    }

    /// The four the spec illustrates, beside the ones the rule covers without
    /// naming them.
    #[test]
    fn an_effect_with_one_object_is_about_that_object() {
        for (effect, want) in [
            (
                serde_json::json!({ "type": "open-gate", "anchor": "anchor/door" }),
                "anchor/door",
            ),
            (
                serde_json::json!({ "type": "close-gate", "anchor": "anchor/door" }),
                "anchor/door",
            ),
            (
                serde_json::json!({ "type": "spawn-actor", "actor": "actor/giant" }),
                "actor/giant",
            ),
            (
                serde_json::json!({ "type": "despawn-actor", "actor": "actor/giant", "style": "vanish" }),
                "actor/giant",
            ),
            (
                serde_json::json!({ "type": "unleash-actor", "actor": "actor/giant" }),
                "actor/giant",
            ),
            (
                serde_json::json!({ "type": "spawn-wave", "wave": "wave/muster" }),
                "wave/muster",
            ),
            (
                serde_json::json!({ "type": "spawn-npc", "npc": "npc/keeper" }),
                "npc/keeper",
            ),
            (
                serde_json::json!({ "type": "despawn-npc", "npc": "npc/keeper" }),
                "npc/keeper",
            ),
            (
                serde_json::json!({ "type": "set-block", "anchor": "anchor/altar", "block": "minecraft:stone" }),
                "anchor/altar",
            ),
        ] {
            assert_eq!(subject(effect.clone()).as_deref(), Some(want), "{effect}");
        }
    }

    /// Several objects, or none, resolve nothing: naming one of them would be
    /// the compiler guessing which the beat is about. A `move-actor` walks an
    /// actor to an anchor and names both.
    #[test]
    fn an_effect_with_no_single_object_resolves_nothing() {
        for effect in [
            serde_json::json!({ "type": "move-actor", "actor": "actor/giant", "to": { "anchor": "anchor/door" } }),
            serde_json::json!({ "type": "move-npc", "npc": "npc/keeper", "to": { "anchor": "anchor/door" } }),
            serde_json::json!({ "type": "teleport", "from": { "anchor": "anchor/hall", "extent": [2, 2, 2] }, "to": { "anchor": "anchor/door" } }),
            serde_json::json!({ "type": "narrate", "text": "The hall answers." }),
            serde_json::json!({ "type": "set-flag", "flag": "flag/heard" }),
        ] {
            assert_eq!(subject(effect.clone()), None, "{effect}");
        }
    }

    /// A stated subject wins, and says so.
    #[test]
    fn a_stated_subject_is_not_derived() {
        let e: QuestEffect = serde_json::from_value(serde_json::json!({
            "type": "open-gate",
            "anchor": "anchor/door",
            "happening": { "verb": "opens", "text": "He lifts it.", "subject": "npc/keeper" }
        }))
        .unwrap();
        let s = e.happening_subject().expect("a stated subject");
        assert_eq!((s.id, s.derived), ("npc/keeper", false));
    }

    /// No `happening`, no subject: the derivation is about a beat, not about an
    /// effect.
    #[test]
    fn an_effect_with_no_happening_has_no_subject() {
        let e: QuestEffect = serde_json::from_value(
            serde_json::json!({ "type": "open-gate", "anchor": "anchor/door" }),
        )
        .unwrap();
        assert!(e.happening_subject().is_none());
        assert_eq!(e.subject_objects(), vec!["anchor/door"]);
    }
}