tatara-lisp 0.3.11

Homoiconic S-expression reader + macroexpander — the pleme-io Lisp authoring surface, hermetic-build standalone
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
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
//! Macro expander — rewrites `defmacro` / `defpoint-template` calls into
//! their quasi-quoted templates.
//!
//! Semantics (v0, no evaluator):
//!
//! ```lisp
//! (defmacro wrap (x) `(list ,x ,x))      ; or defpoint-template
//! (wrap hello)                            ; expands to (list hello hello)
//! ```
//!
//! Supported:
//!   - Required params:      `(name a b c)`
//!   - Optional params:      `(name a &optional b c)` — unsupplied bind to `()`
//!   - Rest param:           `(name a &rest rest)`
//!   - Quasi-quote body:     `` `(…) ``
//!   - Unquote substitution: `,x`
//!   - Splice substitution:  `,@x` (splices a bound list into the outer list)
//!   - Recursive expansion: macro bodies may call other macros.
//!
//! Not yet supported (no evaluator):
//!   - Arbitrary expressions under `,` — only bound symbol lookups.
//!   - Nested quasi-quotes.
//!   - Hygiene / gensym — param names capture aggressively.

use std::cmp::Ordering;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};

use crate::ast::Sexp;
use crate::error::{LispError, MacroDefHead, Result, TemplateInvariantKind, UnquoteForm};

/// Default ceiling on `Expander::expand`'s recursive re-entry into a
/// macro-call form. A macro whose expansion contains another call to
/// itself — the canonical runaway `(defmacro loop (x) `(loop ,x))` —
/// pre-lift stack-overflowed the process (a below-floor abort with no
/// `Result` witness). The ceiling turns that abort into a
/// [`LispError::ExpansionDepthExceeded`] rejection at the expander
/// boundary. `256` is large enough that no lawful hand-authored
/// expansion nesting hits it (nested `when` / `let` / template
/// compositions cap out in single digits in practice) and small
/// enough that a runaway is rejected in microseconds instead of
/// consuming a process stack. Consumers that need a tighter or looser
/// ceiling call [`Expander::set_max_expansion_depth`].
pub const DEFAULT_MAX_EXPANSION_DEPTH: usize = 256;

/// Default ceiling on the expansion cache's entry count. Peer to
/// [`DEFAULT_MAX_EXPANSION_DEPTH`] one RESOURCE axis over on the
/// expander surface — where the depth ceiling bounds RECURSION (a
/// runaway macro's stack), this ceiling bounds MEMORY (the memoized
/// `apply(macro, args)` result table). Pre-lift the cache was an
/// unbounded [`HashMap`] shared across [`Expander`] clones via
/// [`std::sync::Arc`]; a long-running host (REPL, LSP,
/// `tatara-check`, MCP server) that expanded many distinct
/// `(macro, args)` pairs would accrete cache entries without bound —
/// the same below-floor resource-drift the depth ceiling closed on
/// the recursion axis. Post-lift the [`Expander::apply`] insert path
/// consults this ceiling before growing the cache; once the entry
/// count reaches the ceiling, new expansions still succeed (the
/// cache remains a pure PERFORMANCE optimization — never a
/// CORRECTNESS gate) but skip cache insertion until the operator
/// clears the cache via [`Expander::clear_cache`]. Consumers that
/// need a tighter ceiling (embedded / test harnesses) call
/// [`Expander::set_max_cache_entries`] with a lower cap; consumers
/// that want unbounded caching (batch compilation runs where memory
/// is not the concern) call it with [`usize::MAX`].
///
/// `8192` is large enough that lawful macro authoring — a small
/// closed set of macros, each expanded against a bounded set of
/// argument shapes — never brushes the ceiling on a session-length
/// workload (a typescape with 20 macros × 32 distinct arg-shapes ×
/// several call sites still sits under 1K entries), and small
/// enough that a pathological expansion loop (a macro emitting
/// unique arg-shapes on every call) is rejected before it exhausts
/// process memory. The default is deliberately generous — the
/// ceiling exists to prevent unbounded drift, not to force operators
/// to tune it. Consumers that want a tighter policy configure it
/// explicitly.
pub const DEFAULT_MAX_CACHE_ENTRIES: usize = 8192;

/// Default ceiling on a single macro-expansion output's structural
/// node count. Peer to [`DEFAULT_MAX_EXPANSION_DEPTH`] and
/// [`DEFAULT_MAX_CACHE_ENTRIES`] one RESOURCE-DIMENSION axis over on
/// the expander surface — where the depth ceiling bounds RECURSION
/// LENGTH (a runaway macro's stack) and the cache ceiling bounds
/// MEMOIZATION WIDTH (the memoized `apply(macro, args)` table's
/// entry count), this ceiling bounds OUTPUT SIZE (the "expansion
/// bomb" axis: a well-defined macro whose depth stays small while
/// the produced tree grows past any reasonable working-set budget).
/// Pre-lift the canonical
/// `(defmacro bomb (x) `(list ,x ,x ,x ,x ,x ,x ,x ,x))` composed
/// under itself a handful of times exhausted the process heap while
/// the depth counter was still at low single digits and the cache
/// entry count sat under any reasonable ceiling — a below-floor
/// resource-drift the depth AND cache ceilings both admitted through.
/// Post-lift the [`Expander::expand_with_depth`] site consults this
/// ceiling on every freshly-applied macro output via
/// [`crate::ast::Sexp::node_count`]; once an `apply` result exceeds
/// the ceiling the expander returns
/// [`crate::error::LispError::ExpansionSizeExceeded`] with
/// `macro_name`, `size`, and `limit` populated. Consumers that need
/// a tighter or looser ceiling call
/// [`Expander::set_max_expansion_size`].
///
/// `65_536` is large enough that lawful macro-authored output — a
/// domain-language body composed from a few dozen typed primitives,
/// each expanded against a bounded set of arg-shapes — never brushes
/// the ceiling on a session-length workload (a typical `defpoint` /
/// `defmonitor` expansion sits under 100 nodes, and even a
/// hand-authored `defcheck` cascade tops out in the low thousands),
/// and small enough that a pathological "output bomb" (a macro
/// producing a 2^N-node blob from a small input) is rejected in
/// milliseconds instead of consuming multiple gigabytes of process
/// memory in the worst case. The default is deliberately generous —
/// the ceiling exists to prevent unbounded drift, not to force
/// operators to tune it. Consumers that want a tighter policy
/// configure it explicitly.
pub const DEFAULT_MAX_EXPANSION_SIZE: usize = 65_536;

/// Default ceiling on a registered macro's BODY structural node count.
/// Peer to [`DEFAULT_MAX_EXPANSION_DEPTH`], [`DEFAULT_MAX_CACHE_ENTRIES`],
/// and [`DEFAULT_MAX_EXPANSION_SIZE`] one PIPELINE-STAGE axis over on
/// the expander surface — the three prior guards close the RESOURCE
/// surface at EXPAND time (recursion length, memoization width,
/// single-`apply` output size); this ceiling closes it at REGISTER time
/// (the SIZE the body itself contributes to storage in
/// [`Expander::macros`], to [`compile_template`]'s pre-expansion walk,
/// and to every subsequent [`substitute`] walk that recurses through
/// the body-shaped template). Pre-lift a pathological
/// `(defmacro huge (x) `<template-of-N-million-nodes>)` would land the
/// body in the macros table before any `apply` ran and inflate the
/// per-registration cost proportional to `N` — a below-floor
/// resource-drift the three expand-time ceilings all admitted through
/// because none of them fires at the registration boundary. Post-lift
/// the [`Expander::register_macro_def`] site consults this ceiling
/// against `def.body.node_count()`; once the observed size exceeds
/// the ceiling the expander returns
/// [`crate::error::LispError::MacroBodySizeExceeded`] with
/// `macro_name`, `size`, and `limit` populated, and BOTH the
/// [`Expander::macros`] AND [`Expander::templates`] tables stay
/// exactly as they were — no partial-write window in which the
/// registration succeeded halfway.
///
/// `16_384` is large enough that lawful hand-authored macro bodies
/// (an outer quasi-quote wrapping a few dozen nested lists with a
/// handful of substitution slots) never brush the ceiling on any
/// realistic authoring workload — even a heavily-composed
/// `defalertpolicy` template with multi-page cascades tops out in the
/// low thousands — and small enough that a pathological "authoring
/// bomb" (a code-generator that unrolls a `Vec<TypedEntity>` into a
/// giant literal body) is rejected at the registration boundary in
/// microseconds instead of leaking a multi-megabyte template into the
/// live macros table. The default is deliberately generous — the
/// ceiling exists to prevent unbounded drift, not to force operators
/// to tune it. Consumers that want a tighter or looser ceiling call
/// [`Expander::set_max_macro_body_size`].
pub const DEFAULT_MAX_MACRO_BODY_SIZE: usize = 16_384;

/// Default ceiling on the [`Expander::macros`] table's entry count.
/// Peer to [`DEFAULT_MAX_MACRO_BODY_SIZE`] one RESOURCE-DIMENSION axis
/// over on the REGISTER-time surface — where the body-size ceiling
/// bounds a single macro's BODY SIZE (the per-registration authoring
/// bomb), this ceiling bounds TABLE ENTRY COUNT (the cumulative
/// registration bomb: a code-generator emitting unbounded fresh
/// `(defmacro N (x) `(list ,x))` heads whose bodies each sit
/// comfortably under [`DEFAULT_MAX_MACRO_BODY_SIZE`] yet collectively
/// saturate process memory). Also peer to [`DEFAULT_MAX_CACHE_ENTRIES`]
/// one PIPELINE-STAGE axis over — where the cache-entries ceiling
/// bounds EXPAND-time memoization width, this ceiling bounds
/// REGISTER-time macro-table width. The two entry-count guards close
/// the two pipeline stages symmetrically. Pre-lift the macros table
/// was an unbounded [`HashMap`]; a long-running host (REPL, LSP,
/// `tatara-check`, MCP server) that ingested a source stream of
/// distinct `(defmacro …)` heads would accrete entries without
/// bound — a below-floor resource-drift the four prior guards (depth,
/// cache-entries, expansion-size, body-size) all admitted through
/// because none of them fires against the CUMULATIVE registration
/// count.
///
/// Overwrites (a re-registration of an already-registered key) do not
/// grow the table and never trigger this ceiling — operators can
/// redefine a macro at capacity without hitting the gate. Only FRESH
/// keys are counted against the ceiling.
///
/// `4096` is large enough that lawful hand-authored typescapes never
/// brush the ceiling on any realistic authoring workload — a
/// typescape with 20-100 macros × several call sites sits well under
/// 1K entries, and even a library-heavy project composing hundreds of
/// domain macros stays under a fraction of the default — and small
/// enough that a pathological registration bomb (a code-generator
/// unrolling a `Vec<TypedEntity>` into a giant `(defmacro fresh-N …)`
/// stream) is rejected at the registration boundary in microseconds
/// instead of leaking a multi-megabyte macros table into the live
/// expander. The default is deliberately generous — the ceiling
/// exists to prevent unbounded drift, not to force operators to tune
/// it. Consumers that want a tighter or looser ceiling call
/// [`Expander::set_max_registered_macros`].
pub const DEFAULT_MAX_REGISTERED_MACROS: usize = 4096;

/// Default ceiling on a registered macro's lambda-list ARITY — the
/// count of parameter slots (`required` + `optional` + `rest?`) the
/// [`MacroDef`] declares. Peer to [`DEFAULT_MAX_MACRO_BODY_SIZE`] one
/// RESOURCE-DIMENSION axis over on the REGISTER-time surface — where
/// body-size bounds a per-registration BODY node count (the AST-nodes
/// of the template a macro rewrites INTO), this ceiling bounds a
/// per-registration PARAM slot count (the fresh symbols
/// [`compile_template`]'s `,name`-index resolution AND
/// [`MacroParams::bind`]'s per-index binder walk have to thread through
/// on every call). Peer to [`DEFAULT_MAX_REGISTERED_MACROS`] one
/// RESOURCE-DIMENSION axis over on the REGISTER-time surface — where
/// the registered-macros ceiling bounds cumulative registration COUNT
/// (the table-scoped resource), this ceiling bounds a per-registration
/// PARAM-LIST WIDTH (the per-entry resource). Together the three
/// REGISTER-time ceilings close the (per-body SIZE, per-body ARITY,
/// per-table COUNT) three-corner surface — a `Vec<TypedEntity>`
/// arity-bomb code-generator emitting a
/// `(defmacro huge (a-1 a-2 … a-N-million) `,a-1)` head with a
/// single-node body slips past `max_macro_body_size` and past
/// `max_registered_macros` (one fresh key), yet each subsequent call
/// pays O(N) walking the required-run binder — a below-floor
/// resource-drift the two prior REGISTER-time guards admit through
/// because neither of them fires against the PER-REGISTRATION
/// PARAM-LIST WIDTH.
///
/// The default is deliberately generous — lawful hand-authored macros
/// carry a handful of required params + a small optional run + at
/// most a single `&rest` slot (`observability-stack`'s `defalertpolicy`
/// carries under 8 slots; even keyword-heavy authoring surfaces sit
/// well under 32 slots). `128` sits an order of magnitude past any
/// realistic authoring workload yet an order of magnitude BELOW a
/// pathological code-generator's arity-bomb output, so the ceiling
/// gates the drift without brushing lawful traffic. Consumers that
/// want a tighter or looser ceiling call
/// [`Expander::set_max_macro_arity`].
///
/// Frontier inspiration: Common Lisp's `LAMBDA-PARAMETERS-LIMIT`
/// standard variable (CLHS §3.4.1) — the runtime-reflectable
/// "upper exclusive bound on the number of parameters that may
/// appear in a lambda list" every conforming implementation carries.
/// SBCL's is `4611686018427387903`, ECL's is `4096`, CLisp's is `4096`.
/// `DEFAULT_MAX_MACRO_ARITY` is the substrate's typed-Rust peer at
/// compile time, translated through pleme-io primitives: a
/// `pub const usize` on the typed macro-expander algebra rather than
/// a runtime-mutable global, wired into the substrate's typed
/// [`crate::error::LispError`] Result algebra at
/// [`Expander::register_macro_def`] rather than raised as an
/// implementation-defined condition.
pub const DEFAULT_MAX_MACRO_ARITY: usize = 128;

/// Typed snapshot of the six `Expander` resource ceilings — the
/// bundled peer of the six [`Expander::max_expansion_depth`] /
/// [`Expander::max_cache_entries`] / [`Expander::max_expansion_size`] /
/// [`Expander::max_macro_body_size`] / [`Expander::max_registered_macros`] /
/// [`Expander::max_macro_arity`] individual getters. The six knobs form
/// ONE resource surface (the (PIPELINE-STAGE × RESOURCE-DIMENSION)
/// grid the last six commits closed corner-by-corner) yet the
/// pre-lift `Expander` surface exposed them only as SIX independent
/// projections — inspecting the full posture required six calls, and
/// bulk-configuring the expander (a preset for CI, a preset for the
/// REPL, a preset for a test harness) required six independent
/// setter invocations whose ordering the type system did not gate.
///
/// Post-lift the typed bundle binds the six knobs at ONE typed value
/// on the `Expander` surface. A `#[derive(Clone, Copy, Debug,
/// PartialEq, Eq)]` posture — every ceiling is a `Copy` scalar —
/// gives callers a cheap snapshot they can serialize, compare, or
/// pass around; the `Copy` implementation guarantees the bundle
/// never carries a hidden allocation. Adding a SEVENTH ceiling
/// extends this struct AND [`DEFAULT_RESOURCE_LIMITS`] in lockstep
/// via rustc's field-exhaustiveness on the `..Default::default()`-free
/// literal construction — no independent-field-drift window.
///
/// Peer of the six `DEFAULT_MAX_*` module constants one AGGREGATION
/// axis over: where each constant carries ONE ceiling, this struct
/// carries the SIX-fold cross-product. [`DEFAULT_RESOURCE_LIMITS`]
/// pins the (defaults × aggregation) corner so a consumer that wants
/// the shipped posture in one value does not re-derive the six
/// individual constants at its call site.
///
/// Theory grounding: THEORY.md §II.1 — typed entry / typed exit for
/// the resource-limit configuration surface. The pre-lift six
/// independent knobs were a set of typed scalars but their
/// composition into an "Expander resource posture" was untyped —
/// callers assembled the posture at their call site with no
/// compile-time exhaustiveness check that all six were considered.
/// Frontier inspiration: `tokio::runtime::Builder`'s bundled knob
/// struct — a runtime's ceiling posture is ONE typed value rather
/// than a chain of independent method calls; translation through
/// pleme-io primitives is the plain `Copy` snapshot below, no
/// builder-pattern indirection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ResourceLimits {
    /// See [`Expander::max_expansion_depth`].
    pub max_expansion_depth: usize,
    /// See [`Expander::max_cache_entries`].
    pub max_cache_entries: usize,
    /// See [`Expander::max_expansion_size`].
    pub max_expansion_size: usize,
    /// See [`Expander::max_macro_body_size`].
    pub max_macro_body_size: usize,
    /// See [`Expander::max_registered_macros`].
    pub max_registered_macros: usize,
    /// See [`Expander::max_macro_arity`].
    pub max_macro_arity: usize,
}

impl Default for ResourceLimits {
    /// The shipped posture — every field seeded from its matching
    /// `DEFAULT_MAX_*` module constant. Pinned equal to
    /// [`DEFAULT_RESOURCE_LIMITS`] as a compile-time identity so a
    /// future re-tuning of ONE default lands in ONE place and both
    /// projections pick it up mechanically.
    fn default() -> Self {
        DEFAULT_RESOURCE_LIMITS
    }
}

/// The shipped [`ResourceLimits`] posture — every field bound to its
/// matching `DEFAULT_MAX_*` module constant at ONE typed value. This
/// is the `const` peer of [`ResourceLimits::default`]; the two are
/// pinned equal so a call-site that wants the shipped posture as a
/// compile-time value binds through the `const` and a call-site that
/// wants it as a runtime `Default::default()` value binds through the
/// trait impl — both routes reach the SAME six numbers.
///
/// Adding a SEVENTH ceiling extends this constant AND the struct AND
/// [`Expander`]'s constructors in lockstep — rustc's
/// field-exhaustiveness on this `..Default::default()`-free literal
/// forces the new field to appear here, and the trait impl above
/// reuses this constant so no independent-default-drift window opens
/// between the two projections.
pub const DEFAULT_RESOURCE_LIMITS: ResourceLimits = ResourceLimits {
    max_expansion_depth: DEFAULT_MAX_EXPANSION_DEPTH,
    max_cache_entries: DEFAULT_MAX_CACHE_ENTRIES,
    max_expansion_size: DEFAULT_MAX_EXPANSION_SIZE,
    max_macro_body_size: DEFAULT_MAX_MACRO_BODY_SIZE,
    max_registered_macros: DEFAULT_MAX_REGISTERED_MACROS,
    max_macro_arity: DEFAULT_MAX_MACRO_ARITY,
};

/// The unbounded [`ResourceLimits`] posture — every ceiling seeded to
/// [`usize::MAX`] at ONE typed value. This is the CEILING-LIFTED peer of
/// [`DEFAULT_RESOURCE_LIMITS`] one PRESET-POSTURE axis over on the
/// named-preset surface: where the default constant binds each field to
/// the shipped `DEFAULT_MAX_*` module constant, this constant binds
/// each field to the raw `usize::MAX` sentinel that every
/// [`Expander::set_max_expansion_depth`] / [`Expander::set_max_cache_entries`] /
/// [`Expander::set_max_expansion_size`] / [`Expander::set_max_macro_body_size`] /
/// [`Expander::set_max_registered_macros`] / [`Expander::set_max_macro_arity`]
/// setter's doc names as "the ceiling is effectively lifted" —
/// admitting any lawful value the type system supports.
///
/// A test-harness fixture that wants "exercise the raw expander with no
/// ceiling gating anything" pre-lift composed the posture at its call
/// site as six independent [`usize::MAX`] literals (or six independent
/// setter invocations post-`Expander::new`) whose exhaustiveness the
/// type system did NOT gate — a copy-paste that dropped one of the six
/// lifts left THAT ceiling at its default and gated the fixture
/// silently. Post-lift the posture is ONE named typed constant every
/// such fixture routes through, AND rustc's field-exhaustiveness on
/// the `..Default::default()`-free literal here forces a SEVENTH
/// ceiling extension to appear at this site in lockstep with
/// [`DEFAULT_RESOURCE_LIMITS`] and the [`ResourceLimits`] struct
/// itself — no independent-preset-drift window.
///
/// Peer to [`DEFAULT_RESOURCE_LIMITS`] on the (posture × aggregation)
/// grid: both constants live at the AGGREGATION corner (six ceilings
/// as ONE typed value); the posture axis distinguishes the SHIPPED
/// default from the CEILING-LIFTED unbounded preset. Disagrees with
/// [`DEFAULT_RESOURCE_LIMITS`] on every field (every default is a
/// concrete non-[`usize::MAX`] positive constant, so the six-way
/// disagreement is structurally exhaustive) — pinned as a typed
/// theorem in the [`ResourceLimits`] test cohort.
///
/// Frontier inspiration: `tokio::runtime::Builder`'s pattern of
/// exposing named preset thunks (`multi_thread`, `current_thread`)
/// alongside the field-level configurators, so a caller that wants a
/// standard posture binds through ONE named entry rather than
/// composing the field literals at the call site. Translation
/// through pleme-io primitives is the plain `const` snapshot below,
/// no builder-pattern indirection — the `Copy` posture on
/// [`ResourceLimits`] already gives callers the struct-update
/// literal (`ResourceLimits { max_expansion_depth: 4,
/// ..UNBOUNDED_RESOURCE_LIMITS }`) that isolates the ONE ceiling
/// still gating from the five lifted.
pub const UNBOUNDED_RESOURCE_LIMITS: ResourceLimits = ResourceLimits {
    max_expansion_depth: usize::MAX,
    max_cache_entries: usize::MAX,
    max_expansion_size: usize::MAX,
    max_macro_body_size: usize::MAX,
    max_registered_macros: usize::MAX,
    max_macro_arity: usize::MAX,
};

/// The zero [`ResourceLimits`] posture — every ceiling seeded to `0` at
/// ONE typed value. This is the BOTTOM peer of
/// [`UNBOUNDED_RESOURCE_LIMITS`] one LATTICE-POLE axis over on the
/// (bottom, top) bounded-lattice preset-pair surface: where the
/// ceiling-lifted preset carries every gate at [`usize::MAX`]
/// (admitting every lawful `usize`-indexed value the type system
/// supports), this preset carries every gate at `0` (rejecting every
/// non-empty input past the first depth step, cache slot, macro-body
/// node, macro registration, or arity slot). Together the two close
/// the (BOTTOM, TOP) preset-posture pair on the bounded-lattice
/// diagonal, and [`DEFAULT_RESOURCE_LIMITS`] sits strictly between
/// them (`EMPTY.leq(DEFAULT) && DEFAULT.leq(UNBOUNDED)`).
///
/// **Bounded-lattice identity elements**: [`ResourceLimits`] under the
/// pointwise `min` / `max` operations forms a BOUNDED lattice; each
/// operation acquires its identity element from the OPPOSITE pole of
/// the preset-pair diagonal, and its ANNIHILATOR from the SAME pole.
///   * [`Self::strictest`] (meet, pointwise `min`) —
///     [`UNBOUNDED_RESOURCE_LIMITS`] is the identity
///     (`a.strictest(UNBOUNDED) == a` for every posture, since pointwise
///     `min` against [`usize::MAX`] returns `a`); this constant is the
///     ANNIHILATOR (`a.strictest(EMPTY) == EMPTY` for every posture,
///     since pointwise `min` against `0` returns `0`).
///   * [`Self::most_permissive`] (join, pointwise `max`) — this
///     constant is the identity (`a.most_permissive(EMPTY) == a` for
///     every posture, since pointwise `max` against `0` returns `a`);
///     [`UNBOUNDED_RESOURCE_LIMITS`] is the ANNIHILATOR
///     (`a.most_permissive(UNBOUNDED) == UNBOUNDED`).
///   * [`Self::leq`] (partial order) — this constant is the MINIMUM
///     (`EMPTY.leq(a) == true` for every posture, since `0 <= x` holds
///     for every `usize x`); [`UNBOUNDED_RESOURCE_LIMITS`] is the
///     MAXIMUM (`a.leq(UNBOUNDED) == true` for every posture, since
///     `x <= usize::MAX` holds for every `usize x`).
///
/// **Fold-identity use case**: a caller aggregating a slice of
/// postures through [`Self::most_permissive`] (computing the pointwise
/// least upper bound across the slice) seeds the fold from this
/// constant — the join-identity property guarantees the seed does not
/// distort the fold's result:
///
/// ```rust,ignore
/// let joined = postures.iter().copied()
///     .fold(EMPTY_RESOURCE_LIMITS, ResourceLimits::most_permissive);
/// ```
///
/// The dual pattern (folding through [`Self::strictest`] to compute
/// the pointwise greatest lower bound) seeds from
/// [`UNBOUNDED_RESOURCE_LIMITS`] — the meet-identity from the OPPOSITE
/// pole. Pre-lift, an aggregator either (a) picked ONE arbitrary
/// element of the slice as the seed and folded through the tail — a
/// non-total fixup that panicked on an empty slice — or (b) seeded
/// from `Some(first)`-style option wrapper — a runtime `Option` that
/// carried a type-level admission the aggregate might be absent even
/// though the algebra defines it exhaustively via its identity. Post-
/// lift the fold takes ONE typed identity element and handles empty
/// slices as the algebraic identity value — a boundary case which the
/// bounded-lattice structure resolves at TYPE level rather than the
/// caller resolving at CALL SITE with a wrapper type.
///
/// Adding a SEVENTH ceiling extends this constant AND the struct AND
/// [`DEFAULT_RESOURCE_LIMITS`] AND [`UNBOUNDED_RESOURCE_LIMITS`] in
/// lockstep — rustc's field-exhaustiveness on this
/// `..Default::default()`-free literal forces the new field to appear
/// at this site, and the identity-law tests pin `0` as the seventh
/// field's value at compile time via the const-fn peer of the
/// existing lattice-law const-fn pins.
///
/// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
/// proofs; the identity element of a lattice operation is itself a
/// typed named entry whose composition with any other element is the
/// element (join) or the identity (meet). THEORY.md §V.1 — knowable
/// platform; the bounded-lattice bottom binds at ONE typed constant
/// rather than a six-primitive inline literal every consumer that
/// needs the fold identity carries at its call site. Frontier
/// inspiration: the algebraic-datatypes tradition of a `Monoid` typeclass
/// (Haskell's `mempty`, Scala's `Monoid.empty`, Rust's various
/// `Default::default` for `Sum`/`Product` newtypes) — a caller
/// aggregating values through a binary combinator binds its identity
/// element at ONE named entry rather than composing the identity
/// literal at every fold site. Translation through pleme-io primitives
/// is the plain `const` snapshot below, no typeclass indirection — the
/// `Copy` posture on [`ResourceLimits`] already gives callers the
/// struct-update literal (`ResourceLimits { max_macro_arity: 3,
/// ..EMPTY_RESOURCE_LIMITS }`) that isolates the ONE ceiling admitting
/// non-zero input from the five sealed at `0`.
pub const EMPTY_RESOURCE_LIMITS: ResourceLimits = ResourceLimits {
    max_expansion_depth: 0,
    max_cache_entries: 0,
    max_expansion_size: 0,
    max_macro_body_size: 0,
    max_registered_macros: 0,
    max_macro_arity: 0,
};

/// Pointwise `min` / `max` primitives the [`ResourceLimits`] lattice binds
/// its meet ([`ResourceLimits::strictest`]) and join
/// ([`ResourceLimits::most_permissive`]) operations to. Named at module
/// scope as `const fn` so both operations are themselves `const fn` on
/// stable — composing two postures at compile time (a caller stitching a
/// new `pub const` preset from two shipped presets) needs no runtime
/// evaluation. Ternary form rather than [`usize::min`] / [`usize::max`]
/// so the two `const fn` remain valid on any tatara MSRV whose stability
/// on the primitive const-fn methods has not been established.
const fn min_usize(a: usize, b: usize) -> usize {
    if a <= b {
        a
    } else {
        b
    }
}

const fn max_usize(a: usize, b: usize) -> usize {
    if a >= b {
        a
    } else {
        b
    }
}

impl ResourceLimits {
    /// Pointwise-`min` across the six ceilings — the STRICTEST posture
    /// whose admissible input set is the intersection of `self`'s and
    /// `other`'s admissible input sets. `a.strictest(b)` admits an
    /// input iff BOTH `a` AND `b` admit it: on every field the
    /// per-axis ceiling is the smaller of the two, so a value that
    /// clears the meet clears BOTH postures, and a value that any
    /// posture rejects the meet also rejects.
    ///
    /// The meet of the `ResourceLimits` lattice under the pointwise
    /// partial order `a ≤ b iff every field of a ≤ every field of b`
    /// (tighter-first — a POSTURE admits FEWER inputs on that field's
    /// axis when the ceiling is smaller). Peer of
    /// [`Self::most_permissive`] one COMBINATOR axis over on the
    /// lattice-algebra surface: where `most_permissive` is the join
    /// (pointwise-`max`, LUB), this is the meet (pointwise-`min`, GLB).
    /// Together the two operations close the (meet, join) lattice
    /// operator pair on the [`ResourceLimits`] posture algebra.
    ///
    /// The concrete identity on the shipped preset pair holds
    /// structurally: [`DEFAULT_RESOURCE_LIMITS`]`.strictest(`
    /// [`UNBOUNDED_RESOURCE_LIMITS`]`) == `[`DEFAULT_RESOURCE_LIMITS`].
    /// Every `DEFAULT_MAX_*` module constant is a concrete positive
    /// value strictly less than [`usize::MAX`], so on every axis the
    /// pointwise-`min` picks the DEFAULT side; the six-axis pin holds
    /// as a typed theorem in the test cohort.
    ///
    /// Idempotent (`a.strictest(a) == a`), commutative
    /// (`a.strictest(b) == b.strictest(a)`), associative
    /// (`(a.strictest(b)).strictest(c) == a.strictest(b.strictest(c))`),
    /// and satisfies the absorption identity with the join
    /// (`a.strictest(a.most_permissive(b)) == a`) — all pinned as
    /// typed theorems in the test cohort. Distributive over the join
    /// (`a.strictest(b.most_permissive(c)) ==
    /// a.strictest(b).most_permissive(a.strictest(c))`) because
    /// pointwise-`min` and pointwise-`max` on [`usize`] each
    /// distribute over the other on every axis.
    ///
    /// `const fn` so a caller can compose two named presets into a
    /// third at compile time (`pub const CI_RESOURCE_LIMITS:
    /// ResourceLimits = SOME_OPERATOR_PRESET.strictest(
    /// SOME_CI_PRESET);`) rather than deferring the composition to
    /// a runtime `Default::default()` chain.
    ///
    /// Pre-lift, a caller wanting the tightest common posture across
    /// two shipped presets composed the intersection at its call site
    /// as six independent `usize::min(a.max_X, b.max_X)` invocations
    /// stitched into a fresh `ResourceLimits { ... }` literal — the
    /// same six-inline-primitive shape the pre-`ResourceLimits`
    /// bundled `Expander` posture required its callers to carry, and
    /// the same exhaustiveness gap the `..Default::default()`-free
    /// literal on the bundled struct exists to close: a copy-paste
    /// that dropped ONE of the six `min` invocations left THAT
    /// ceiling at whichever posture the caller happened to seed the
    /// literal with, and the type system did not gate the drop.
    /// Post-lift the composition binds at ONE typed method on the
    /// posture algebra — a caller writes
    /// `operator_preset.strictest(ci_preset)` and rustc's
    /// field-exhaustiveness at the const's construction guarantees
    /// every ceiling is threaded through the `min` primitive.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the tightest posture of two preset-carried
    /// resource proofs is itself a `ResourceLimits` whose proof
    /// content is the intersection of the two, and this method is
    /// the typed named entry composing them. THEORY.md §V.1 —
    /// knowable platform; the pointwise-`min` combinator becomes a
    /// TYPE-level operation on the posture algebra rather than an
    /// inline six-primitive cascade at every consumer that composes
    /// two presets. `tatara-lattice`'s `meet` / `join` operators on
    /// `Classification` (see `pleme-io/tatara` workspace crate
    /// docstring: "Lattice algebra over Classification — `meet` /
    /// `join` / `leq` / `Baseline`") close the SAME shape one layer
    /// down: an entity's classification is a lattice; a resource
    /// posture is a lattice; both algebras carry the (meet, join)
    /// operator pair as their fundamental composition primitives.
    #[must_use]
    pub const fn strictest(self, other: Self) -> Self {
        Self {
            max_expansion_depth: min_usize(self.max_expansion_depth, other.max_expansion_depth),
            max_cache_entries: min_usize(self.max_cache_entries, other.max_cache_entries),
            max_expansion_size: min_usize(self.max_expansion_size, other.max_expansion_size),
            max_macro_body_size: min_usize(self.max_macro_body_size, other.max_macro_body_size),
            max_registered_macros: min_usize(
                self.max_registered_macros,
                other.max_registered_macros,
            ),
            max_macro_arity: min_usize(self.max_macro_arity, other.max_macro_arity),
        }
    }

    /// Pointwise-`max` across the six ceilings — the MOST-PERMISSIVE
    /// posture whose admissible input set is the union of `self`'s
    /// and `other`'s admissible input sets. `a.most_permissive(b)`
    /// admits an input iff EITHER `a` OR `b` admits it: on every
    /// field the per-axis ceiling is the larger of the two, so a
    /// value that either posture accepts the join accepts, and a
    /// value the join rejects both postures reject.
    ///
    /// The join of the `ResourceLimits` lattice under the pointwise
    /// partial order `a ≤ b iff every field of a ≤ every field of b`
    /// (tighter-first). Peer of [`Self::strictest`] one COMBINATOR
    /// axis over on the lattice-algebra surface: where `strictest` is
    /// the meet (pointwise-`min`, GLB), this is the join
    /// (pointwise-`max`, LUB). Together the two operations close the
    /// (meet, join) lattice operator pair on the [`ResourceLimits`]
    /// posture algebra.
    ///
    /// The concrete identity on the shipped preset pair holds
    /// structurally: [`DEFAULT_RESOURCE_LIMITS`]`.most_permissive(`
    /// [`UNBOUNDED_RESOURCE_LIMITS`]`) == `[`UNBOUNDED_RESOURCE_LIMITS`].
    /// Every `DEFAULT_MAX_*` module constant is a concrete positive
    /// value strictly less than [`usize::MAX`], so on every axis the
    /// pointwise-`max` picks the UNBOUNDED side; the six-axis pin
    /// holds as a typed theorem in the test cohort.
    ///
    /// Idempotent, commutative, associative, and satisfies the
    /// absorption identity with the meet
    /// (`a.most_permissive(a.strictest(b)) == a`) — all pinned as
    /// typed theorems in the test cohort. Distributive over the meet
    /// (`a.most_permissive(b.strictest(c)) ==
    /// a.most_permissive(b).strictest(a.most_permissive(c))`).
    ///
    /// `const fn` so a caller can compose two named presets into a
    /// third at compile time rather than deferring the composition
    /// to a runtime `Default::default()` chain.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the most-permissive posture of two preset-
    /// carried resource proofs is itself a `ResourceLimits` whose
    /// proof content is the union of the two, and this method is the
    /// typed named entry composing them. THEORY.md §V.1 — knowable
    /// platform; the pointwise-`max` combinator becomes a TYPE-level
    /// operation on the posture algebra rather than an inline
    /// six-primitive cascade at every consumer that composes two
    /// presets.
    #[must_use]
    pub const fn most_permissive(self, other: Self) -> Self {
        Self {
            max_expansion_depth: max_usize(self.max_expansion_depth, other.max_expansion_depth),
            max_cache_entries: max_usize(self.max_cache_entries, other.max_cache_entries),
            max_expansion_size: max_usize(self.max_expansion_size, other.max_expansion_size),
            max_macro_body_size: max_usize(self.max_macro_body_size, other.max_macro_body_size),
            max_registered_macros: max_usize(
                self.max_registered_macros,
                other.max_registered_macros,
            ),
            max_macro_arity: max_usize(self.max_macro_arity, other.max_macro_arity),
        }
    }

    /// Pointwise partial-order relation across the six ceilings — `self`
    /// is at least as tight as `other` iff every field of `self` is at
    /// most the matching field of `other`. `a.leq(b)` holds iff every
    /// input the `a` posture admits the `b` posture also admits: `a`'s
    /// per-axis ceilings all sit at or below `b`'s per-axis ceilings, so
    /// any value that clears `a`'s tighter gates also clears `b`'s
    /// looser gates.
    ///
    /// The partial order underneath the [`ResourceLimits`] lattice.
    /// Peer of [`Self::strictest`] (meet, GLB) and [`Self::most_permissive`]
    /// (join, LUB) one PRIMITIVE-KIND axis over on the lattice-algebra
    /// surface: where those two are the (meet, join) COMBINATORS, this
    /// is the RELATION they are defined against. Together the three
    /// close the (meet, join, leq) primitive triple on the
    /// [`ResourceLimits`] posture algebra — the same triple
    /// `tatara-lattice`'s [`Lattice`] trait exposes as its three
    /// required methods for every classification lattice one crate over
    /// (see `tatara-lattice/src/lib.rs`).
    ///
    /// **Meet-agreement** (`a.leq(b) ⇔ a.strictest(b) == a`): if `a` is
    /// tighter on every axis than `b`, then the pointwise `min` picks
    /// `a` on every axis, so `a.strictest(b) == a`; conversely, if
    /// `a.strictest(b) == a`, every field's `min` picked `a`, so every
    /// field of `a` is at most the matching field of `b`. Pinned as
    /// `resource_limits_leq_agrees_with_meet` in the test cohort.
    ///
    /// **Join-agreement** (`a.leq(b) ⇔ a.most_permissive(b) == b`):
    /// symmetric statement on the LUB side; pinned as
    /// `resource_limits_leq_agrees_with_join`. Together the two
    /// agreements are the canonical lattice cross-check axiom
    /// `a ≤ b ⇔ a ⊓ b = a ⇔ a ⊔ b = b` documented in
    /// `tatara-lattice/src/lib.rs`'s preamble.
    ///
    /// Reflexive (`a.leq(a) == true`), antisymmetric (`a.leq(b) &&
    /// b.leq(a) → a == b`), transitive (`a.leq(b) && b.leq(c) →
    /// a.leq(c)`) — all pinned as typed theorems in the test cohort.
    /// NOT total: two postures with reversed per-axis orderings (some
    /// axes where `a` is tighter, some where `b` is tighter) are
    /// incomparable — `!a.leq(b) && !b.leq(a)` — pinned by
    /// `resource_limits_leq_is_not_total_on_asymmetric_postures`.
    ///
    /// **Bounds pins in terms of leq**:
    ///   * `a.strictest(b).leq(a) && a.strictest(b).leq(b)` (meet is
    ///     the greatest lower bound) — pinned by
    ///     `resource_limits_strictest_is_leq_both_operands`, the typed
    ///     lattice-relation companion to the per-axis
    ///     `resource_limits_strictest_is_dominated_by_both_operands_pointwise`.
    ///   * `a.leq(a.most_permissive(b)) && b.leq(a.most_permissive(b))`
    ///     (join is the least upper bound) — pinned by
    ///     `resource_limits_most_permissive_is_geq_both_operands`, the
    ///     typed lattice-relation companion to the per-axis
    ///     `resource_limits_most_permissive_dominates_both_operands_pointwise`.
    ///
    /// **Concrete-preset pin**: [`DEFAULT_RESOURCE_LIMITS`]`.leq(`
    /// [`UNBOUNDED_RESOURCE_LIMITS`]`) == true` (every
    /// `DEFAULT_MAX_*` module constant is a concrete positive value at
    /// most [`usize::MAX`]) AND
    /// `!UNBOUNDED_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS)` (every
    /// `DEFAULT_MAX_*` is strictly less than [`usize::MAX`], so on
    /// every axis [`usize::MAX`] exceeds the matching default) — the
    /// partial order is a STRICT order on the shipped preset pair.
    /// Pinned by `resource_limits_leq_of_default_and_unbounded_is_a_strict_order`.
    ///
    /// `const fn` so a caller can pin a preset-relation identity at
    /// compile time (`const _: () = assert!(DEFAULT_RESOURCE_LIMITS
    /// .leq(UNBOUNDED_RESOURCE_LIMITS));`) — the typed lattice-relation
    /// peer of the `const fn` composition ability on
    /// [`Self::strictest`] / [`Self::most_permissive`].
    ///
    /// Pre-lift, a caller wanting to decide whether one posture was
    /// tighter than another either (a) composed six independent
    /// per-axis `<=` comparisons at the call site stitched into a
    /// six-fold `&&` — the same six-inline-primitive shape the
    /// pre-`ResourceLimits` bundled Expander posture required its
    /// callers to carry, and the same exhaustiveness gap the
    /// `..Default::default()`-free literal on the bundled struct exists
    /// to close: a copy-paste that dropped ONE of the six comparisons
    /// silently admitted a posture that violated tightness on THAT
    /// axis — or (b) invoked [`Self::strictest`] and compared the result
    /// to `self` — a correct but roundabout composition of the partial-
    /// order primitive against its lattice-companion. Post-lift the
    /// relation binds at ONE typed method on the posture algebra; a
    /// caller writes `tighter.leq(looser)` and rustc's exhaustiveness
    /// on the six-field conjunction below guarantees every ceiling is
    /// threaded through the `<=` primitive.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the partial-order relation on two preset-
    /// carried resource proofs is itself a typed named entry composing
    /// their tightness ordering. THEORY.md §V.1 — knowable platform;
    /// the pointwise `<=` combinator becomes a TYPE-level operation on
    /// the posture algebra rather than an inline six-primitive
    /// conjunction at every consumer that compares two presets.
    /// `tatara-lattice`'s [`Lattice::leq`] method on `Classification`
    /// closes the SAME shape one layer down — an entity's
    /// classification is a lattice with a `leq` partial order; a
    /// resource posture is a lattice with a `leq` partial order; both
    /// algebras carry the (meet, join, leq) primitive triple as their
    /// fundamental relation-and-combinator surface.
    #[must_use]
    pub const fn leq(self, other: Self) -> bool {
        self.max_expansion_depth <= other.max_expansion_depth
            && self.max_cache_entries <= other.max_cache_entries
            && self.max_expansion_size <= other.max_expansion_size
            && self.max_macro_body_size <= other.max_macro_body_size
            && self.max_registered_macros <= other.max_registered_macros
            && self.max_macro_arity <= other.max_macro_arity
    }

    /// Pointwise-`min` fold across a slice of postures — the STRICTEST
    /// posture whose admissible input set is the intersection of every
    /// operand's admissible input sets. `ResourceLimits::strictest_of(&[a,
    /// b, c])` admits an input iff EVERY operand admits it: on every
    /// field the per-axis ceiling is the smallest across the whole slice,
    /// so a value that clears the aggregated meet clears EVERY operand,
    /// and a value that ANY operand rejects the aggregated meet also
    /// rejects.
    ///
    /// The N-ary MEET aggregation on the [`ResourceLimits`] lattice —
    /// the extension of [`Self::strictest`] from a 2-input pairwise
    /// combinator to an N-input fold across a slice. Seeded from
    /// [`UNBOUNDED_RESOURCE_LIMITS`] (the meet-identity — its per-axis
    /// [`usize::MAX`] never wins the pointwise `min` against a concrete
    /// positive value, so the seed contributes nothing to the fold's
    /// result), which makes the empty-slice case aggregate to the
    /// identity element rather than requiring an `Option<Self>` wrapper
    /// the caller inspects at every consumption site. Peer of
    /// [`Self::most_permissive_of`] one COMBINATOR axis over on the
    /// N-ary aggregation surface: where `most_permissive_of` is the
    /// N-ary JOIN (LUB across the slice, seeded from the join-identity
    /// [`EMPTY_RESOURCE_LIMITS`]), this is the N-ary MEET (GLB across
    /// the slice, seeded from the meet-identity). Together the two
    /// close the (N-ary meet, N-ary join) aggregation pair the pairwise
    /// combinators [`Self::strictest`] / [`Self::most_permissive`]
    /// extend from 2 to N.
    ///
    /// **Empty-slice identity**: `strictest_of(&[]) ==
    /// UNBOUNDED_RESOURCE_LIMITS` — the null aggregate binds structurally
    /// to the meet-identity element. Pre-lift a caller composing "the
    /// tightest posture across THIS SLICE" from the pairwise `strictest`
    /// primitive either (a) seeded the fold from a non-empty first
    /// element and panicked on empty input, or (b) wrapped the aggregate
    /// in `Option<Self>` — a runtime type-level admission the aggregate
    /// might be absent even though the algebra's bounded-lattice
    /// structure defines the null aggregate exhaustively via its
    /// identity element. Post-lift the null aggregate is
    /// [`UNBOUNDED_RESOURCE_LIMITS`] at the TYPE level, not a wrapper
    /// the consumer inspects.
    ///
    /// **Single-element identity**: `strictest_of(&[a]) == a` — the
    /// 1-input aggregate is the input verbatim, since
    /// `UNBOUNDED.strictest(a) == a` for every posture `a` by the
    /// meet-identity law.
    ///
    /// **Two-element identity**: `strictest_of(&[a, b]) ==
    /// a.strictest(b)` — the 2-input aggregate reduces to the pairwise
    /// combinator, since `UNBOUNDED.strictest(a).strictest(b) ==
    /// a.strictest(b)`.
    ///
    /// **Order-independent**: `strictest_of(&[a, b, c]) ==
    /// strictest_of(&[c, b, a])` — the fold inherits the commutativity
    /// AND associativity of the pairwise `strictest`, so any permutation
    /// of the slice yields the same aggregate.
    ///
    /// `const fn` so a caller can compose an arbitrary-length preset
    /// slice into a third preset at compile time (`pub const
    /// COMBINED_PRESET: ResourceLimits = ResourceLimits::strictest_of(
    /// &[SOME_OPERATOR_PRESET, SOME_CI_PRESET, SOME_HOSTILE_PRESET]);`)
    /// rather than deferring the composition to a runtime chain — the
    /// N-ary const-fn peer of the pairwise const-fn on
    /// [`Self::strictest`]. `Copy` on [`ResourceLimits`] lets the const-
    /// fn loop index the slice by value without an explicit `.clone()`
    /// (which const-fn would not permit anyway).
    ///
    /// Pre-lift, the SAME `.iter().copied().fold(UNBOUNDED, strictest)`
    /// three-primitive cascade appeared verbatim in
    /// `unbounded_resource_limits_seeds_strictest_fold_over_slice` AND at
    /// every future consumer that would compose "the tightest across
    /// this set of presets" — a PRIME DIRECTIVE ≥2 trigger, since the
    /// fold docstring on [`UNBOUNDED_RESOURCE_LIMITS`] explicitly names
    /// this pattern as the constant's fold-identity use case. Post-lift
    /// the N-ary aggregation binds at ONE typed method the algebra
    /// exposes, and every future consumer routes through ONE name whose
    /// signature carries the identity-element choice INTO the method
    /// (rather than the consumer having to remember which seed pairs
    /// with which combinator at each call site).
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the N-ary aggregation of N preset-carried
    /// resource proofs is itself a `ResourceLimits` whose proof content
    /// is the intersection of every operand's, and this method is the
    /// typed named entry composing them. THEORY.md §V.1 — knowable
    /// platform; the N-ary meet becomes a TYPE-level operation on the
    /// posture algebra rather than an inline fold cascade at every
    /// consumer that aggregates a slice of presets — with the
    /// meet-identity seed baked in so the consumer cannot pair the join-
    /// identity (`EMPTY`) with the meet combinator (a silent
    /// distortion that would collapse every axis to `0`). Frontier
    /// inspiration: the algebraic-datatypes tradition of a `Monoid`
    /// typeclass exposing `mconcat` / `Monoid.combineAll` alongside the
    /// pairwise `mappend` — the N-ary aggregation of a collection
    /// through a binary combinator is a first-class named method the
    /// typeclass carries. Translation through pleme-io primitives is
    /// the plain `const fn` slice-fold below, no typeclass indirection
    /// — the meet-identity element already exists as a named `pub const`
    /// on the algebra so the fold picks it up structurally.
    #[must_use]
    pub const fn strictest_of(postures: &[Self]) -> Self {
        let mut acc = UNBOUNDED_RESOURCE_LIMITS;
        let mut i = 0;
        while i < postures.len() {
            acc = acc.strictest(postures[i]);
            i += 1;
        }
        acc
    }

    /// Pointwise-`max` fold across a slice of postures — the MOST-
    /// PERMISSIVE posture whose admissible input set is the union of
    /// every operand's admissible input sets.
    /// `ResourceLimits::most_permissive_of(&[a, b, c])` admits an input
    /// iff ANY operand admits it: on every field the per-axis ceiling
    /// is the largest across the whole slice.
    ///
    /// The N-ary JOIN aggregation on the [`ResourceLimits`] lattice —
    /// the extension of [`Self::most_permissive`] from a 2-input
    /// pairwise combinator to an N-input fold across a slice. Seeded
    /// from [`EMPTY_RESOURCE_LIMITS`] (the join-identity — every field
    /// at `0`, which never wins the pointwise `max` against any
    /// non-zero value, so the seed contributes nothing to the fold's
    /// result), which makes the empty-slice case aggregate to the
    /// identity element. Peer of [`Self::strictest_of`] one COMBINATOR
    /// axis over on the N-ary aggregation surface: where `strictest_of`
    /// is the N-ary MEET (seeded from the meet-identity
    /// [`UNBOUNDED_RESOURCE_LIMITS`]), this is the N-ary JOIN (seeded
    /// from the join-identity). Together the two close the (N-ary meet,
    /// N-ary join) aggregation pair.
    ///
    /// **Empty-slice identity**: `most_permissive_of(&[]) ==
    /// EMPTY_RESOURCE_LIMITS` — the null aggregate binds structurally
    /// to the join-identity element.
    ///
    /// **Single-element identity**: `most_permissive_of(&[a]) == a` —
    /// the 1-input aggregate is the input verbatim, since
    /// `EMPTY.most_permissive(a) == a` for every posture `a` by the
    /// join-identity law.
    ///
    /// **Two-element identity**: `most_permissive_of(&[a, b]) ==
    /// a.most_permissive(b)` — the 2-input aggregate reduces to the
    /// pairwise combinator.
    ///
    /// **Order-independent**: `most_permissive_of(&[a, b, c]) ==
    /// most_permissive_of(&[c, b, a])` — the fold inherits the
    /// commutativity AND associativity of the pairwise
    /// `most_permissive`.
    ///
    /// `const fn` so a caller can compose an arbitrary-length preset
    /// slice at compile time — the N-ary const-fn peer of the pairwise
    /// const-fn on [`Self::most_permissive`].
    ///
    /// Pre-lift, the SAME `.iter().copied().fold(EMPTY,
    /// most_permissive)` three-primitive cascade appeared verbatim in
    /// `empty_resource_limits_seeds_most_permissive_fold_over_slice`
    /// AND at every future consumer that would compose "the loosest
    /// across this set of presets" — a PRIME DIRECTIVE ≥2 trigger.
    /// Post-lift the N-ary aggregation binds at ONE typed method with
    /// the join-identity seed baked in so the consumer cannot pair the
    /// meet-identity (`UNBOUNDED`) with the join combinator (a silent
    /// distortion that would inflate every axis to [`usize::MAX`]).
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the N-ary join of N preset-carried resource
    /// proofs is itself a `ResourceLimits`. THEORY.md §V.1 — knowable
    /// platform; the N-ary join becomes a TYPE-level operation on the
    /// posture algebra rather than an inline fold cascade at every
    /// consumer that aggregates a slice of presets.
    #[must_use]
    pub const fn most_permissive_of(postures: &[Self]) -> Self {
        let mut acc = EMPTY_RESOURCE_LIMITS;
        let mut i = 0;
        while i < postures.len() {
            acc = acc.most_permissive(postures[i]);
            i += 1;
        }
        acc
    }

    /// Pointwise projection of `self` into the closed range `[lower, upper]`
    /// — the bounded-lattice bracket combinator. `a.clamp(lower, upper)`
    /// returns the posture whose per-axis ceiling is the input's own
    /// ceiling raised to at least `lower`'s and then lowered to at most
    /// `upper`'s: on every field the result is `min(max(a, lower), upper)`.
    ///
    /// The BRACKET operation on the [`ResourceLimits`] lattice — the
    /// composition of [`Self::most_permissive`] with `lower` followed by
    /// [`Self::strictest`] with `upper`. Peer of the (meet, join) pairwise
    /// combinators one ARITY axis over (2 → 3 inputs) on the lattice-
    /// algebra surface: where those two combine a `self` with ONE bound,
    /// this combines a `self` with TWO bounds and closes the (unbounded-
    /// side, bounded) row on the combinator-arity face. The bounded-lattice
    /// analog of [`Ord::clamp`] on total orders, and the natural typed
    /// entry a caller enforces "this posture must sit within the
    /// `[ORG_MIN, ORG_MAX]` operator bracket" through.
    ///
    /// **In-range identity**: if `lower.leq(self) && self.leq(upper)` (the
    /// input already sits within the bracket), then `a.clamp(lower, upper)
    /// == a` — the pointwise `max(a, lower)` picks `a` on every axis (since
    /// `lower ≤ a` per-axis), then pointwise `min(..., upper)` picks `a`
    /// again (since `a ≤ upper` per-axis). Pinned as
    /// `resource_limits_clamp_of_posture_already_in_range_returns_the_posture`.
    ///
    /// **Below-lower floor**: if `self.leq(lower)` and `lower.leq(upper)`
    /// (input tighter than the bracket floor, and floor within ceiling),
    /// then `a.clamp(lower, upper) == lower` — the pointwise `max` lifts
    /// every axis to `lower`, then the pointwise `min` keeps `lower` (since
    /// `lower ≤ upper` per-axis). Pinned as
    /// `resource_limits_clamp_of_posture_below_lower_returns_lower`.
    ///
    /// **Above-upper ceiling**: if `upper.leq(self)` and `lower.leq(upper)`
    /// (input looser than the bracket ceiling), then `a.clamp(lower, upper)
    /// == upper` — the pointwise `max` keeps `self` on every axis (since
    /// `lower ≤ self` per-axis via transitivity through `upper`), then the
    /// pointwise `min` lowers every axis to `upper`. Pinned as
    /// `resource_limits_clamp_of_posture_above_upper_returns_upper`.
    ///
    /// **Bracket-membership** (`lower.leq(a.clamp(lower, upper)) &&
    /// a.clamp(lower, upper).leq(upper)` for every `a` when `lower.leq(upper)`):
    /// the result always sits within the `[lower, upper]` bracket
    /// regardless of the input's position relative to the bracket. This is
    /// the DEFINING contract of the clamp primitive — every consumer that
    /// invokes it does so precisely to guarantee the result sits within
    /// the bracket, and the type system now carries that guarantee at ONE
    /// named entry. Pinned as
    /// `resource_limits_clamp_result_sits_within_the_bracket`.
    ///
    /// **Extrema-bracket identity**: `a.clamp(EMPTY_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS) == a` — clamping against the bounded-
    /// lattice extrema is the identity function, since every posture
    /// already sits within the widest possible bracket. This is the
    /// bounded-lattice cross-check with the identity elements previously
    /// lifted (`EMPTY_RESOURCE_LIMITS` as the leq-minimum and
    /// `UNBOUNDED_RESOURCE_LIMITS` as the leq-maximum). Pinned as
    /// `resource_limits_clamp_with_lattice_extrema_returns_the_input`.
    ///
    /// **Degenerate-bracket collapse**: `a.clamp(x, x) == x` for every `a,
    /// x` — a zero-width bracket collapses every input to the single point
    /// `x`. Pinned as
    /// `resource_limits_clamp_with_equal_bounds_returns_the_bound`.
    ///
    /// **Idempotence**: `a.clamp(lower, upper).clamp(lower, upper) ==
    /// a.clamp(lower, upper)` — re-applying the same bracket to an
    /// already-clamped posture returns the same result, since the clamped
    /// value already sits within the bracket. Pinned as
    /// `resource_limits_clamp_is_idempotent`.
    ///
    /// `const fn` so a caller can pre-clamp a shipped preset against an
    /// operator-supplied policy bracket at compile time (`pub const
    /// POLICY_CLAMPED: ResourceLimits = SOME_PRESET.clamp(
    /// ORG_MIN_PRESET, ORG_MAX_PRESET);`) — the typed bracket-combinator
    /// peer of the const-fn composition ability on [`Self::strictest`] /
    /// [`Self::most_permissive`].
    ///
    /// Pre-lift, a caller wanting to bracket a posture within a
    /// `[lower, upper]` range composed the two-step cascade at its call
    /// site as `self.most_permissive(lower).strictest(upper)` — the same
    /// PRIME DIRECTIVE ≥2 pattern the pairwise combinators already lifted
    /// one arity down from the six-inline-primitive per-axis cascade.
    /// The `resource_limits_clamp_agrees_with_direct_two_step_cascade`
    /// pin below composes the pre-lift cascade at ONE explicit assertion
    /// site (its sole purpose is to pin the method-vs-cascade equivalence)
    /// — every future consumer that enforces a
    /// policy bracket (an operator-supplied `[ORG_MIN, ORG_MAX]`, a
    /// hostile-input `[EMPTY, HOSTILE_MAX]`, a CI-time `[TEST_MIN,
    /// TEST_MAX]`) would compose the same cascade at its call site with
    /// no exhaustiveness gate on the composition order. Post-lift the
    /// bracket binds at ONE typed method whose signature carries the
    /// bounds' roles (`lower` first, `upper` second) into the method
    /// rather than the consumer having to remember which side pairs with
    /// which combinator at each call site — a copy-paste that swapped the
    /// two combinators would clip the input to `min(max(a, upper), lower)`
    /// (the WRONG bracket order that returns `lower` for every input
    /// looser than `lower` regardless of `upper`'s position), a silent
    /// distortion the type system did not gate pre-lift and now does
    /// through the method's parameter order.
    ///
    /// **Non-lattice-bracket behaviour** (`!lower.leq(upper)`): the four
    /// documented invariants above are stated for the well-formed bracket
    /// case where `lower.leq(upper)`. When the two bounds are pointwise-
    /// incomparable OR strictly reversed (`upper.leq(lower) && lower !=
    /// upper`), the result is pointwise `min(max(a, lower), upper)` which
    /// is well-defined but no longer sits within a "bracket" in the
    /// intuitive sense — for a reversed bound the pointwise `max` pushes
    /// the value up to `lower`, then the pointwise `min` pushes it down to
    /// `upper`, producing `upper` at every axis (since `upper < lower`
    /// per-axis makes `min(anything ≥ lower, upper) == upper`). This
    /// matches [`Ord::clamp`]'s "min ≤ max is a precondition, otherwise
    /// behaviour is unspecified but well-defined" contract on total orders;
    /// callers routing preset pairs through `clamp` maintain the
    /// `lower.leq(upper)` invariant at their bounds' construction site,
    /// not at every clamp call site.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
    /// proofs; the bracket projection of a preset-carried resource proof
    /// against two bound preset-carried resource proofs is itself a
    /// `ResourceLimits` whose proof content is the input's proof intersected
    /// with the ceiling's and unioned with the floor's, and this method is
    /// the typed named entry composing them. THEORY.md §V.1 — knowable
    /// platform; the bracket combinator becomes a TYPE-level operation on
    /// the posture algebra rather than an inline two-step composition at
    /// every consumer that enforces a policy range — with the (lower,
    /// upper) parameter order baked in so the consumer cannot swap the
    /// two combinators (a silent distortion that would clip the input to
    /// the wrong bracket order). Frontier inspiration: [`Ord::clamp`] on
    /// total orders — the stdlib exposes a first-class named bracket
    /// combinator alongside the pairwise `min` / `max`, and the bounded-
    /// lattice extension is the same shape one dimension up (per-axis
    /// pointwise on a Cartesian product of total orders). Translation
    /// through pleme-io primitives is the plain `const fn` composition
    /// below, no trait indirection — the pairwise combinators already
    /// exist as `const fn` on the algebra so the bracket picks them up
    /// structurally.
    #[must_use]
    pub const fn clamp(self, lower: Self, upper: Self) -> Self {
        self.most_permissive(lower).strictest(upper)
    }

    /// Pointwise bracket-membership predicate — `self` sits within the closed
    /// range `[lower, upper]` iff every axis's ceiling satisfies
    /// `lower ≤ self ≤ upper`. `a.within(lower, upper)` holds iff
    /// `lower.leq(self) && self.leq(upper)`: `self`'s per-axis ceilings all
    /// sit at or above `lower`'s AND at or below `upper`'s per-axis ceilings.
    ///
    /// The boolean PREDICATE peer of the BRACKET COMBINATOR [`Self::clamp`]
    /// one PRIMITIVE-KIND axis over on the bracket-primitive surface: where
    /// `clamp` PROJECTS an arbitrary input into the `[lower, upper]` bracket,
    /// this DECIDES whether the input already sits within it. Peer of
    /// [`Self::leq`] one ARITY axis over on the lattice-relation surface:
    /// where `leq` is the pairwise partial-order RELATION between two
    /// postures, this is the three-input CONTAINMENT RELATION deciding
    /// whether a posture sits between two bounds. Together the (leq, within)
    /// pair closes the (2-input, 3-input) row on the relation-arity face of
    /// the [`ResourceLimits`] lattice-algebra surface — the boolean twin of
    /// the (`strictest`+`most_permissive`, `clamp`) combinator-arity closure.
    ///
    /// **Clamp fixed-point theorem** (`a.within(lower, upper) ⇔
    /// a.clamp(lower, upper) == a`): the input sits within the bracket iff
    /// the clamp is the identity on it. The forward direction is the
    /// in-range identity arm of [`Self::clamp`] (already pinned as
    /// `resource_limits_clamp_of_posture_already_in_range_returns_the_posture`);
    /// the reverse follows from the bracket-membership contract on `clamp`
    /// (the clamp result always sits within the bracket, so if the clamp
    /// equals the input, the input also sits within the bracket). Pinned as
    /// `resource_limits_within_agrees_with_clamp_fixed_point` — the CANONICAL
    /// cross-check axiom binding the predicate to the combinator, analogous
    /// to the meet-agreement (`a.leq(b) ⇔ a.strictest(b) == a`) and
    /// join-agreement (`a.leq(b) ⇔ a.most_permissive(b) == b`) axioms binding
    /// the `leq` relation to its combinator peers.
    ///
    /// **In-range identity**: if `lower.leq(self) && self.leq(upper)`
    /// (the input already sits within the bracket), then `a.within(lower,
    /// upper) == true`. Pinned as
    /// `resource_limits_within_of_posture_in_range_is_true`.
    ///
    /// **Below-lower rejection**: if the input is strictly tighter than the
    /// bracket floor on any axis (`!lower.leq(self)`), then
    /// `a.within(lower, upper) == false` regardless of `self`'s relation to
    /// `upper` — the boolean conjunction rejects the input. Pinned as
    /// `resource_limits_within_of_posture_below_lower_is_false`.
    ///
    /// **Above-upper rejection**: if the input is strictly looser than the
    /// bracket ceiling on any axis (`!self.leq(upper)`), then
    /// `a.within(lower, upper) == false`. Pinned as
    /// `resource_limits_within_of_posture_above_upper_is_false`.
    ///
    /// **Extrema-bracket identity**: `a.within(EMPTY_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS) == true` for every posture, since every
    /// posture sits within the widest possible bracket — the bounded-lattice
    /// cross-check with the identity elements previously lifted. Pinned as
    /// `resource_limits_within_with_lattice_extrema_is_true`.
    ///
    /// **Degenerate-bracket collapse**: `a.within(x, x) ⇔ a == x` — a
    /// zero-width bracket admits only the single point `x`. Follows from
    /// antisymmetry of `leq`: `x.leq(a) && a.leq(x) → a == x`. Pinned as
    /// `resource_limits_within_of_equal_bounds_iff_equal_to_bound`.
    ///
    /// **Reflexive-bracket identity**: `a.within(a, a) == true` for every
    /// posture — every input trivially sits within the zero-width bracket
    /// at itself, since `a.leq(a)` holds by reflexivity of `leq`. Pinned as
    /// `resource_limits_within_of_self_is_reflexive`.
    ///
    /// `const fn` so a caller can pin a preset-bracket-membership identity
    /// at compile time (`const _: () = assert!(DEFAULT_RESOURCE_LIMITS
    /// .within(EMPTY_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS));`) — the
    /// typed bracket-predicate peer of the const-fn evaluability on
    /// [`Self::leq`] and [`Self::clamp`].
    ///
    /// Pre-lift, a caller wanting to decide whether a posture sat within a
    /// `[lower, upper]` bracket composed the two-primitive scaffolding at its
    /// call site as `lower.leq(a) && a.leq(upper)` — the same PRIME DIRECTIVE
    /// ≥2 pattern the pairwise `strictest` / `most_permissive` / `leq`
    /// combinators already lifted one arity down from six-inline-primitive
    /// per-axis cascades. The clamp test cohort exercises this shape at
    /// every prerequisite pin (`FLOOR.leq(MID) && MID.leq(CEILING)`) AND at
    /// the bracket-membership contract's core assertion (`FLOOR.leq(clamped)
    /// && clamped.leq(CEILING)`); post-lift both bindings route through ONE
    /// named method whose signature carries the containment relation into the
    /// type system rather than the consumer composing the two-primitive
    /// conjunction at every call site — a copy-paste that swapped the
    /// bounds would test `upper.leq(a) && a.leq(lower)` (the WRONG
    /// containment direction returning `true` only for postures that
    /// simultaneously exceed the ceiling AND fall below the floor, i.e.
    /// only for the impossible `upper.leq(a) && a.leq(lower)` case when
    /// `lower.leq(upper)`), a silent distortion the type system did not gate
    /// pre-lift and now does through the method's parameter order.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
    /// proofs; the bracket-membership predicate on three preset-carried
    /// resource proofs is itself a typed named entry composing the input's
    /// containment ordering. THEORY.md §V.1 — knowable platform; the
    /// pointwise `≤`-conjunction combinator becomes a TYPE-level operation
    /// on the posture algebra rather than an inline two-primitive
    /// conjunction at every consumer that decides bracket membership — with
    /// the (lower, upper) parameter order baked in so the consumer cannot
    /// swap the two bounds. Frontier inspiration: the interval-containment
    /// predicate is the natural boolean twin of stdlib's [`Ord::clamp`] —
    /// stdlib lacks an `is_in_range(min, max)` method, but the bounded-
    /// lattice extension of the pattern is straightforward on the pointwise
    /// partial order and closes the (combinator, predicate) row on the
    /// bracket-primitive surface. Translation through pleme-io primitives is
    /// the plain `const fn` `leq`-conjunction below, no trait indirection —
    /// the partial-order relation already exists as a `const fn` on the
    /// algebra so the predicate picks it up structurally.
    #[must_use]
    pub const fn within(self, lower: Self, upper: Self) -> bool {
        lower.leq(self) && self.leq(upper)
    }

    /// Boolean `leq`-conjunction across a slice of postures — `self` sits
    /// at-or-below every operand in `postures`. `a.is_lower_bound_of(&[b,
    /// c, d])` holds iff `a.leq(b) && a.leq(c) && a.leq(d)`: on every
    /// operand `self`'s per-axis ceilings sit at-or-below the operand's,
    /// so `self` is a common lower bound for the slice.
    ///
    /// The N-ary boolean PREDICATE peer of the pairwise partial-order
    /// relation [`Self::leq`] one ARITY axis over on the lattice-relation
    /// surface: where `leq` decides the two-input partial-order between
    /// two postures, this decides the (1 + N)-input containment-from-below
    /// between `self` and a slice of postures. Peer of
    /// [`Self::strictest_of`] one PRIMITIVE-KIND axis over on the N-ary
    /// aggregation surface: where `strictest_of` COMPUTES the meet (the
    /// greatest lower bound of the slice), this DECIDES whether `self` is
    /// a lower bound of the slice (member of the lower-bound set the meet
    /// is the largest element of). Together `strictest_of` and
    /// `is_lower_bound_of` close the (combinator, predicate) row on the
    /// N-ary-aggregation face, exactly the way (`strictest`,
    /// `most_permissive`) ↔ `leq` closes the pairwise row and (`clamp` ↔
    /// `within`) closes the bracket row on the (combinator, predicate) ×
    /// (pairwise, N-ary, bracket) primitive surface.
    ///
    /// **Empty-slice vacuous truth**: `a.is_lower_bound_of(&[]) == true`
    /// for every posture — the empty conjunction is vacuously true, since
    /// every posture is trivially a lower bound of the empty set. Peer of
    /// `strictest_of(&[]) == UNBOUNDED_RESOURCE_LIMITS`'s empty-slice
    /// identity: the empty slice aggregates to the identity element of
    /// the underlying operation (`true` for boolean conjunction,
    /// [`UNBOUNDED_RESOURCE_LIMITS`] for pointwise `min`), so the empty
    /// aggregate never rejects. Pinned as
    /// `resource_limits_is_lower_bound_of_empty_slice_is_vacuously_true`.
    ///
    /// **Single-element identity**: `a.is_lower_bound_of(&[b]) ==
    /// a.leq(b)` — the 1-input predicate reduces to the pairwise
    /// relation, the same way `strictest_of(&[a]) == a` reduces the
    /// 1-input N-ary combinator to the operand verbatim. Pinned as
    /// `resource_limits_is_lower_bound_of_single_element_reduces_to_leq`.
    ///
    /// **Meet witness**: `strictest_of(&postures).is_lower_bound_of(&
    /// postures) == true` for every slice — the N-ary meet is always a
    /// lower bound of the slice it aggregates. The definitional link
    /// between the N-ary COMBINATOR and the N-ary PREDICATE: the
    /// aggregate `strictest_of` produces is a member of the lower-bound
    /// set `is_lower_bound_of` characterizes. Pinned as
    /// `resource_limits_is_lower_bound_of_holds_for_the_meet_of_the_slice`.
    ///
    /// **Universal-bottom witness**: `EMPTY_RESOURCE_LIMITS
    /// .is_lower_bound_of(&postures) == true` for every slice — the
    /// lattice bottom is a common lower bound of every set, since
    /// `EMPTY.leq(a) == true` for every posture by the lattice-bottom
    /// axiom (`0 ≤ x` per-axis). Pinned as
    /// `resource_limits_empty_is_universal_lower_bound_of_every_slice`.
    ///
    /// **Any-operand rejection**: if `!self.leq(postures[i])` for any
    /// `i`, then `a.is_lower_bound_of(&postures) == false` — the
    /// conjunction short-circuits on the first violating operand and
    /// rejects. Pinned as
    /// `resource_limits_is_lower_bound_of_rejects_when_any_operand_is_below_self`.
    ///
    /// **Peer** — [`Self::is_upper_bound_of`] one COMBINATOR-DIRECTION
    /// axis over: the two close the (`is_lower_bound_of`,
    /// `is_upper_bound_of`) N-ary boolean-conjunction pair the pairwise
    /// `leq` extends from 2 to N, itself peer of the (`strictest_of`,
    /// `most_permissive_of`) N-ary combinator pair one PRIMITIVE-KIND
    /// axis over.
    ///
    /// `const fn` so a caller can pin an N-ary-bound-membership identity
    /// at compile time (`const _: () = assert!(EMPTY_RESOURCE_LIMITS
    /// .is_lower_bound_of(&[DEFAULT_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS]));`) — the N-ary predicate peer of the
    /// const-fn evaluability on [`Self::leq`] and [`Self::within`].
    /// `Copy` on [`ResourceLimits`] lets the const-fn loop index the
    /// slice by value without an explicit `.clone()` (which const-fn
    /// would not permit anyway).
    ///
    /// Pre-lift, a caller wanting to decide whether a posture was a
    /// common lower bound for a slice composed the
    /// `postures.iter().all(|p| self.leq(*p))` two-primitive scaffolding
    /// at every call site — the same PRIME DIRECTIVE ≥2 pattern the
    /// pairwise `leq` combinator already lifted one arity down from the
    /// six-inline-primitive per-axis cascade, and the same shape the
    /// pairwise `within` combinator already lifted one arity down from
    /// the two-primitive `lower.leq(a) && a.leq(upper)` conjunction.
    /// Post-lift the N-ary predicate binds at ONE typed method whose
    /// signature carries the containment direction (`self ≤ every
    /// operand`) into the type system rather than the consumer composing
    /// the `all()`-conjunction at every call site — a copy-paste that
    /// flipped the leq direction would test `postures[i].leq(self)` (the
    /// dual `is_upper_bound_of` question returning `true` only when
    /// `self` DOMINATES rather than UNDERLIES the slice), a silent
    /// distortion the method's parameter direction now gates.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the N-ary containment-from-below predicate on
    /// (1 + N) preset-carried resource proofs is itself a typed named
    /// entry composing the pairwise partial-order relation. THEORY.md
    /// §V.1 — knowable platform; the N-ary `leq`-conjunction becomes a
    /// TYPE-level operation on the posture algebra rather than an inline
    /// two-primitive conjunction at every consumer that decides
    /// N-ary-bound membership. Frontier inspiration: the algebraic-
    /// datatypes tradition of a `Foldable` typeclass exposing `all` /
    /// `Data.Foldable.all` alongside the pairwise relation — the N-ary
    /// traversal of a collection through a boolean-conjunction seed is a
    /// first-class named method the typeclass carries. Translation
    /// through pleme-io primitives is the plain `const fn` slice-walk
    /// below, no typeclass indirection — the partial-order relation
    /// already exists as a `const fn` on the algebra so the predicate
    /// picks it up structurally.
    #[must_use]
    pub const fn is_lower_bound_of(self, postures: &[Self]) -> bool {
        let mut i = 0;
        while i < postures.len() {
            if !self.leq(postures[i]) {
                return false;
            }
            i += 1;
        }
        true
    }

    /// Boolean `leq`-conjunction across a slice of postures — every operand
    /// in `postures` sits at-or-below `self`. `a.is_upper_bound_of(&[b, c,
    /// d])` holds iff `b.leq(a) && c.leq(a) && d.leq(a)`: on every operand
    /// the operand's per-axis ceilings sit at-or-below `self`'s, so `self`
    /// is a common upper bound for the slice.
    ///
    /// The DUAL N-ary predicate of [`Self::is_lower_bound_of`] one
    /// COMBINATOR-DIRECTION axis over: the two close the (lower, upper)
    /// N-ary boolean-conjunction pair the pairwise `leq` extends from 2
    /// to N, itself peer of the (`strictest_of`, `most_permissive_of`)
    /// N-ary combinator pair one PRIMITIVE-KIND axis over on the N-ary-
    /// aggregation face of the (combinator, predicate) × (pairwise,
    /// N-ary, bracket) primitive surface. Peer of
    /// [`Self::most_permissive_of`] one PRIMITIVE-KIND axis over on the
    /// N-ary aggregation surface: where `most_permissive_of` COMPUTES
    /// the join (the least upper bound of the slice), this DECIDES
    /// whether `self` is an upper bound of the slice (member of the
    /// upper-bound set the join is the smallest element of).
    ///
    /// **Empty-slice vacuous truth**: `a.is_upper_bound_of(&[]) == true`
    /// for every posture — the empty conjunction is vacuously true. Peer
    /// of `most_permissive_of(&[]) == EMPTY_RESOURCE_LIMITS`'s empty-
    /// slice identity: the empty aggregate binds structurally to the
    /// identity element of the underlying operation. Pinned as
    /// `resource_limits_is_upper_bound_of_empty_slice_is_vacuously_true`.
    ///
    /// **Single-element identity**: `a.is_upper_bound_of(&[b]) ==
    /// b.leq(a)` — the 1-input predicate reduces to the pairwise
    /// relation with the direction flipped (since `self` sits ABOVE the
    /// operand rather than BELOW it). Pinned as
    /// `resource_limits_is_upper_bound_of_single_element_reduces_to_leq`.
    ///
    /// **Join witness**: `most_permissive_of(&postures).is_upper_bound_of(&
    /// postures) == true` for every slice — the N-ary join is always an
    /// upper bound of the slice it aggregates. The dual definitional link
    /// between N-ary COMBINATOR and N-ary PREDICATE: the aggregate
    /// `most_permissive_of` produces is a member of the upper-bound set
    /// `is_upper_bound_of` characterizes. Pinned as
    /// `resource_limits_is_upper_bound_of_holds_for_the_join_of_the_slice`.
    ///
    /// **Universal-top witness**: `UNBOUNDED_RESOURCE_LIMITS
    /// .is_upper_bound_of(&postures) == true` for every slice — the
    /// lattice top is a common upper bound of every set, since
    /// `a.leq(UNBOUNDED) == true` for every posture by the lattice-top
    /// axiom (`x ≤ usize::MAX` per-axis). Pinned as
    /// `resource_limits_unbounded_is_universal_upper_bound_of_every_slice`.
    ///
    /// **Any-operand rejection**: if `!postures[i].leq(self)` for any
    /// `i`, then `a.is_upper_bound_of(&postures) == false` — the
    /// conjunction short-circuits and rejects. Pinned as
    /// `resource_limits_is_upper_bound_of_rejects_when_any_operand_is_above_self`.
    ///
    /// `const fn` so a caller can pin an N-ary-bound-membership identity
    /// at compile time. See [`Self::is_lower_bound_of`] for the shared
    /// pre-lift ≥2 pattern (`postures.iter().all(|p| p.leq(*self))`), the
    /// theory anchor (THEORY.md §II.1 invariant 5, §V.1), and the
    /// `Foldable::all` frontier inspiration — this method carries the
    /// dual `postures[i].leq(self)` direction rather than
    /// `self.leq(postures[i])`.
    #[must_use]
    pub const fn is_upper_bound_of(self, postures: &[Self]) -> bool {
        let mut i = 0;
        while i < postures.len() {
            if !postures[i].leq(self) {
                return false;
            }
            i += 1;
        }
        true
    }

    /// Strict pointwise partial-order relation across the six ceilings —
    /// `self` is STRICTLY tighter than `other` iff `self.leq(other)` AND
    /// `self != other`. `a.lt(b)` holds iff every input the `a` posture
    /// admits the `b` posture also admits AND there is at least one axis
    /// on which `a`'s ceiling is strictly smaller than `b`'s: `a`'s per-
    /// axis ceilings all sit at-or-below `b`'s AND at least one field
    /// closes the inequality strictly, so `b` strictly extends `a`'s
    /// admissible input set on at least one axis.
    ///
    /// The STRICT peer of [`Self::leq`] one STRICTNESS axis over on the
    /// pairwise partial-order surface: where `leq` is the REFLEXIVE
    /// non-strict `≤` relation (`a.leq(a) == true`), this is the
    /// IRREFLEXIVE strict `<` relation (`a.lt(a) == false`). Together
    /// the two close the (non-strict, strict) partial-order pair on the
    /// pairwise-relation face of the (combinator, predicate) ×
    /// (strictness) primitive surface — itself peer of the
    /// (`strictest`, `most_permissive`) meet/join combinator pair one
    /// PRIMITIVE-KIND axis over (both bind against the same pointwise
    /// `≤` ordering).
    ///
    /// Encoded as `self.leq(other) && !other.leq(self)` — the two-
    /// primitive antisymmetric encoding of strict `<` on any partial
    /// order, pointwise or otherwise. Equivalent on the
    /// [`ResourceLimits`] pointwise partial order (which is
    /// antisymmetric) to `self.leq(other) && self != other`:
    /// antisymmetry says `self.leq(other) && other.leq(self) ⇒ self ==
    /// other`, so `self.leq(other) && !other.leq(self)` iff
    /// `self.leq(other) && self != other`. The antisymmetric-leq
    /// encoding is chosen because it does NOT rely on
    /// [`PartialEq::eq`] being `const fn` (which the derived impl is
    /// not on stable) — both [`Self::leq`] calls are already `const fn`
    /// on the algebra.
    ///
    /// **Irreflexivity**: `a.lt(a) == false` for every posture. A
    /// posture is never strictly tighter than itself, since
    /// `a.leq(a) && !a.leq(a)` short-circuits `false` on the second
    /// conjunct. Pinned as
    /// `resource_limits_lt_is_irreflexive`.
    ///
    /// **Asymmetry**: `a.lt(b) ⇒ !b.lt(a)` for every pair. The two
    /// directions of the strict relation cannot both hold, since
    /// `a.lt(b)` implies `!b.leq(a)`, and `b.lt(a)` requires
    /// `b.leq(a)` — the two are contradictory. Pinned as
    /// `resource_limits_lt_is_asymmetric`.
    ///
    /// **Transitivity**: `a.lt(b) && b.lt(c) ⇒ a.lt(c)` for every
    /// triple. Inherits from the transitivity of [`Self::leq`] on both
    /// conjuncts, with the strictness carried through by the outer
    /// antisymmetric leg (if `c.leq(a)` held, transitivity of `leq`
    /// would give `b.leq(a)` contradicting `a.lt(b)`). Pinned as
    /// `resource_limits_lt_is_transitive`.
    ///
    /// **Refines [`Self::leq`]**: `a.lt(b) ⇒ a.leq(b)` for every pair
    /// — the strict relation refines the non-strict one. Conversely
    /// `a.leq(b) && !a.lt(b) ⇒ a == b` (the reflexive tie is exactly
    /// the non-strict-minus-strict gap). Pinned as
    /// `resource_limits_lt_refines_leq` AND
    /// `resource_limits_lt_agrees_with_leq_minus_equality`.
    ///
    /// **Bounded-lattice diagonal**:
    /// `EMPTY_RESOURCE_LIMITS.lt(DEFAULT_RESOURCE_LIMITS)` AND
    /// `DEFAULT_RESOURCE_LIMITS.lt(UNBOUNDED_RESOURCE_LIMITS)` AND
    /// `EMPTY_RESOURCE_LIMITS.lt(UNBOUNDED_RESOURCE_LIMITS)` — the
    /// strict chain across the (bottom, middle, top) preset triple on
    /// the bounded-lattice diagonal. Every `DEFAULT_MAX_*` module
    /// constant is a concrete positive value strictly less than
    /// [`usize::MAX`] and strictly greater than `0`, so the two
    /// endpoints and the interior are strictly ordered on every axis.
    /// Pinned as `resource_limits_lt_of_bottom_diagonal_pinned`.
    ///
    /// **Incomparable rejection**: on the two hand-authored asymmetric
    /// postures (three axes smaller in each direction), both
    /// directions of the strict relation fail (`!a.lt(b) && !b.lt(a)`)
    /// because neither `leq` direction holds. The predicate does NOT
    /// promote incomparable pairs to a comparison verdict. Pinned as
    /// `resource_limits_lt_rejects_incomparable_postures`.
    ///
    /// **Antisymmetric-encoding cross-check**: `a.lt(b) == (a.leq(b)
    /// && !b.leq(a))` at every pair by definition, AND `a.lt(b) ==
    /// (a.leq(b) && a != b)` at every pair by antisymmetry. Both
    /// encodings are pinned equal to the shipped body across the
    /// (empty, default, unbounded, mid, other) 5×5 preset matrix.
    /// Pinned as
    /// `resource_limits_lt_agrees_with_direct_antisymmetric_encoding`.
    ///
    /// `const fn` so a caller can pin a strict-order identity at
    /// compile time (`const _: () = assert!(EMPTY_RESOURCE_LIMITS.lt(
    /// DEFAULT_RESOURCE_LIMITS));`) rather than deferring the
    /// composition to a runtime chain — sibling of the const-fn
    /// evaluability pin on [`Self::leq`] one STRICTNESS axis over.
    ///
    /// Pre-lift, a caller wanting "is this posture STRICTLY tighter
    /// than that one?" composed the two-primitive
    /// `a.leq(b) && !b.leq(a)` (or equivalently `a.leq(b) && a != b`)
    /// conjunction at its call site — a PRIME DIRECTIVE ≥2 pattern
    /// once two consumers need it, and one that couples the strictness
    /// interpretation to the caller's chosen encoding
    /// (antisymmetric-leq vs. leq-and-not-equal, which coincide on
    /// pointwise partial orders but diverge on non-antisymmetric
    /// preorders). Post-lift the strict relation binds at ONE typed
    /// method the algebra exposes, and the encoding is a private
    /// implementation detail no caller can drift from.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the strict-tightening relation between two
    /// preset-carried resource proofs is itself a typed named `bool`
    /// predicate composing them via the underlying `leq`. THEORY.md
    /// §V.1 — knowable platform; the strict `<` relation becomes a
    /// TYPE-level primitive on the posture algebra rather than an
    /// inline two-primitive conjunction at every consumer that
    /// decides "did we strictly tighten?" `tatara-lattice`'s partial
    /// order on `Classification` closes the SAME shape one layer
    /// down: an entity's classification lattice carries a strict `<`
    /// peer of its `leq` for the same reason a resource posture does.
    /// Frontier inspiration: [`PartialOrd::lt`] on Rust's partial-
    /// order trait; [`Ord::lt`] on the total-order trait — the
    /// strict variant of `≤` is a first-class named method the
    /// standard library exposes rather than leaving each consumer to
    /// compose `partial_cmp(&other) == Some(Less)` at its call site.
    /// Translation through pleme-io primitives is the plain `const
    /// fn` antisymmetric encoding below, no trait indirection — the
    /// non-strict [`Self::leq`] already exists as a `const fn` on the
    /// algebra so the strict variant picks it up structurally.
    #[must_use]
    pub const fn lt(self, other: Self) -> bool {
        self.leq(other) && !other.leq(self)
    }

    /// Strict pointwise partial-order relation dual of [`Self::lt`] —
    /// `a.gt(b) == b.lt(a)`. `self` is STRICTLY looser than `other`
    /// iff `other.leq(self)` AND `self != other`: on every axis
    /// `self`'s ceiling sits at-or-above `other`'s, and at least one
    /// axis closes the inequality strictly, so `self` strictly extends
    /// `other`'s admissible input set on at least one axis.
    ///
    /// The DIRECTION peer of [`Self::lt`] one DIRECTION axis over on
    /// the strict-pairwise-relation face — where `lt` is the strict
    /// "below" relation (`a < b`), this is the strict "above"
    /// relation (`a > b`). Together the two close the (below, above)
    /// direction pair on the strict pairwise relation, exactly as
    /// [`Self::is_lower_bound_of`] / [`Self::is_upper_bound_of`] close
    /// the (below, above) direction pair on the non-strict N-ary
    /// relation one ARITY axis over.
    ///
    /// Same laws as [`Self::lt`] with directions flipped:
    /// irreflexive (`a.gt(a) == false`), asymmetric
    /// (`a.gt(b) ⇒ !b.gt(a)`), transitive
    /// (`a.gt(b) && b.gt(c) ⇒ a.gt(c)`); refines a hypothetical `geq`
    /// (the reflexive `≥`) exactly as `lt` refines `leq`. Pinned on
    /// the shipped preset triangle: `UNBOUNDED_RESOURCE_LIMITS.gt(
    /// DEFAULT_RESOURCE_LIMITS) && DEFAULT_RESOURCE_LIMITS.gt(
    /// EMPTY_RESOURCE_LIMITS)`.
    ///
    /// Encoded as `other.lt(self)` — one primitive delegation to
    /// [`Self::lt`] so the strict-relation encoding lives at exactly
    /// one implementation site, and a future re-derivation of `lt`
    /// (e.g. to a different antisymmetry encoding) propagates to `gt`
    /// mechanically rather than requiring a per-method fix-up.
    ///
    /// `const fn` for the same compile-time-pin reasons as
    /// [`Self::lt`]. See [`Self::lt`] for the full docstring, the
    /// pre-lift `a.leq(b) && !b.leq(a)` two-primitive PRIME DIRECTIVE
    /// ≥2 pattern, the theory anchor (THEORY.md §II.1 invariant 5,
    /// §V.1), and the [`Ord::gt`] frontier inspiration.
    #[must_use]
    pub const fn gt(self, other: Self) -> bool {
        other.lt(self)
    }

    /// Non-strict pointwise partial-order relation dual of
    /// [`Self::leq`] — `a.geq(b) == b.leq(a)`. `self` is AT-OR-LOOSER-
    /// THAN `other` iff on every axis `self`'s ceiling sits at-or-above
    /// `other`'s: every input the `other` posture admits the `self`
    /// posture also admits, so `self` dominates `other`'s admissible
    /// input set pointwise (possibly with equality on some or every
    /// axis).
    ///
    /// The DIRECTION peer of [`Self::leq`] one DIRECTION axis over on
    /// the non-strict pairwise-relation face — where `leq` is the
    /// non-strict "below" relation (`a ≤ b`), this is the non-strict
    /// "above" relation (`a ≥ b`). Together the two close the
    /// (below, above) direction pair on the non-strict pairwise
    /// relation, exactly as [`Self::lt`] / [`Self::gt`] close the
    /// (below, above) direction pair on the STRICT pairwise relation
    /// one STRICTNESS axis over. The STRICTNESS peer of [`Self::gt`]
    /// one STRICTNESS axis over on the "above" column of the
    /// (direction × strictness) 2×2 partial-order face — where `gt` is
    /// the IRREFLEXIVE strict `>` relation (`a.gt(a) == false`), this
    /// is the REFLEXIVE non-strict `≥` relation (`a.geq(a) == true`).
    /// The four methods `(leq, lt, gt, geq)` EXHAUSTIVELY close the
    /// (below, above) × (non-strict, strict) 2×2 pairwise partial-order
    /// face on [`ResourceLimits`], with each method the single-axis
    /// peer of two others (one DIRECTION axis over AND one STRICTNESS
    /// axis over).
    ///
    /// Same laws as [`Self::leq`] with directions flipped:
    /// reflexive (`a.geq(a) == true`), antisymmetric
    /// (`a.geq(b) && b.geq(a) ⇒ a == b`), transitive
    /// (`a.geq(b) && b.geq(c) ⇒ a.geq(c)`); refines [`Self::gt`]
    /// (`a.gt(b) ⇒ a.geq(b)`) exactly as `leq` is refined by `lt`.
    /// NOT total on incomparable postures: on the two hand-authored
    /// asymmetric postures both directions of `geq` fail — the
    /// non-strict relation does not promote incomparable pairs to a
    /// comparison verdict any more than the strict one does. Pinned on
    /// the shipped preset triangle:
    /// `UNBOUNDED_RESOURCE_LIMITS.geq(DEFAULT_RESOURCE_LIMITS) &&
    /// DEFAULT_RESOURCE_LIMITS.geq(EMPTY_RESOURCE_LIMITS)`.
    ///
    /// Encoded as `other.leq(self)` — one primitive delegation to
    /// [`Self::leq`] so the non-strict-relation encoding lives at
    /// exactly one implementation site, and a future re-derivation of
    /// `leq` (e.g. to a different pointwise conjunction) propagates to
    /// `geq` mechanically rather than requiring a per-method fix-up.
    /// Mirrors [`Self::gt`]'s `other.lt(self)` delegation one
    /// STRICTNESS axis over.
    ///
    /// **N-ary-predicate link**: `a.geq(b) == a.is_upper_bound_of(&[b])`
    /// — the pairwise "above" relation is exactly the 1-input
    /// specialization of the N-ary upper-bound predicate. The
    /// (`geq`, `is_upper_bound_of`) pair sits on the same ARITY axis
    /// as (`leq`, `is_lower_bound_of`) one DIRECTION axis over — every
    /// pairwise partial-order relation extends to an N-ary bound-
    /// membership predicate the substrate carries as a named entry.
    ///
    /// `const fn` for the same compile-time-pin reasons as
    /// [`Self::leq`] (`const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS
    /// .geq(DEFAULT_RESOURCE_LIMITS));`). See [`Self::leq`] for the
    /// full docstring, the pre-lift six-inline-`>=`-conjunction pattern
    /// callers wrote before the pairwise relation was named, the
    /// theory anchor (THEORY.md §II.1 invariant 5, §V.1), and the
    /// [`PartialOrd::ge`] frontier inspiration.
    #[must_use]
    pub const fn geq(self, other: Self) -> bool {
        other.leq(self)
    }

    /// Antichain characterization on the [`ResourceLimits`] partial
    /// order — `true` iff `self` and `other` are INCOMPARABLE, i.e.,
    /// NEITHER `self.leq(other)` NOR `self.geq(other)` holds. The two
    /// postures then sit on distinct branches of the lattice: at least
    /// one axis has `self` strictly below `other`, and at least one
    /// axis has `self` strictly above `other`, so neither pointwise-
    /// domination direction closes and neither preset dominates the
    /// other on every field.
    ///
    /// The ANTICHAIN CORNER on the (leq, geq, lt, gt, incomparable)
    /// pairwise-relation surface — the corner that the four pairwise
    /// partial-order predicates leave open. On a TOTAL order every
    /// pair of elements sits at exactly one of `{Less, Equal,
    /// Greater}`, so `is_incomparable` would fold to `false`
    /// unconditionally; on the [`ResourceLimits`] pointwise partial
    /// order the antichain is non-empty (witnessed by
    /// `HAND_AUTHORED_MID_POSTURE` + `HAND_AUTHORED_OTHER_POSTURE`,
    /// which the just-lifted [`Self::leq`] / [`Self::geq`] / [`Self::lt`]
    /// / [`Self::gt`] tests already pin as neither-`leq`-nor-`geq`), so
    /// the corner carries a genuine bit distinct from
    /// `!self.leq(other) && !self.geq(other)` inlined at the callsite.
    /// The (leq, geq, lt, gt) 2×2 pairwise partial-order face the just-
    /// lifted [`Self::geq`] EXHAUSTIVELY closes at its (below, above) ×
    /// (non-strict, strict) grid pins the COMPARABLE cases; THIS
    /// projection pins the DISJOINT antichain complement one COVER
    /// axis over — the (comparable, incomparable) two-cell partition of
    /// the total (ordered pair × verdict) surface.
    ///
    /// Symmetric on its argument order: `a.is_incomparable(b) ==
    /// b.is_incomparable(a)` — the composition `!self.leq(other) &&
    /// !self.geq(other)` folds through `self.leq(other) ==
    /// other.geq(self)` (dual identity on [`Self::geq`]) and the
    /// conjunction's commutativity, so the projection is
    /// order-independent on its two inputs. This SYMMETRY POSTURE
    /// distinguishes it from [`Self::leq`] / [`Self::lt`] (both
    /// antisymmetric — swapping inputs FLIPS the verdict) and from
    /// [`Self::within`] (asymmetric — the first input is the target
    /// and the last two are the bracket bounds).
    ///
    /// Irreflexive on its own argument: `a.is_incomparable(a) ==
    /// false` — every posture is comparable to itself via
    /// [`Self::leq`]'s reflexivity (`a.leq(a) == true`), so the
    /// conjunction's `!self.leq(other)` leg forces the verdict to
    /// `false` at every diagonal input. Sibling posture to
    /// [`Self::lt`]'s irreflexivity one COVER axis over: `lt` is
    /// irreflexive because the strict relation rules out equality;
    /// THIS projection is irreflexive because the comparable
    /// relation already includes equality.
    ///
    /// **Bottom-pole absorption**: `a.is_incomparable(
    /// EMPTY_RESOURCE_LIMITS) == false` on every posture `a` —
    /// [`EMPTY_RESOURCE_LIMITS`] is the bounded-lattice bottom, so
    /// `EMPTY.leq(a)` holds on every axis (`0 <= a.max_*` on `usize`),
    /// which gives `a.geq(EMPTY)` through the [`Self::geq`] dual
    /// identity, which falsifies the `!self.geq(other)` leg. The
    /// bounded-lattice bottom is comparable to every posture. Pinned
    /// on the canonical preset roster.
    ///
    /// **Top-pole absorption**: `a.is_incomparable(
    /// UNBOUNDED_RESOURCE_LIMITS) == false` on every posture `a` —
    /// [`UNBOUNDED_RESOURCE_LIMITS`] is the bounded-lattice top, so
    /// `a.leq(UNBOUNDED)` holds on every axis (`a.max_* <=
    /// usize::MAX` unconditionally), which falsifies the
    /// `!self.leq(other)` leg. The bounded-lattice top is comparable
    /// to every posture. Pinned on the canonical preset roster.
    ///
    /// **Antichain load-bearing arm**:
    /// `HAND_AUTHORED_MID_POSTURE.is_incomparable(
    /// HAND_AUTHORED_OTHER_POSTURE) == true` — the two hand-authored
    /// asymmetric postures sit on distinct branches (each is smaller
    /// on three axes and larger on the other three), so neither
    /// pointwise-domination direction closes and the antichain
    /// verdict is `true`. Pairs with
    /// `resource_limits_geq_rejects_incomparable_postures` +
    /// `resource_limits_leq_rejects_incomparable_postures` one COVER
    /// axis over: those pin the two comparable-direction predicates
    /// FALSIFY on this pair; THIS projection pins the antichain
    /// verdict HOLDS on the SAME pair — the two are the negation-
    /// paired sides of the (comparable, incomparable) two-cell
    /// partition.
    ///
    /// **De Morgan duality**: `a.is_incomparable(b) == !(a.leq(b) ||
    /// a.geq(b))` — the antichain corner is the SET-COMPLEMENT of
    /// the union of the two pointwise-domination directions. Pinned
    /// by `resource_limits_is_incomparable_is_de_morgan_dual_of_comparable`
    /// which sweeps every ordered pair in the preset roster and
    /// confirms the equivalence at every cell.
    ///
    /// Encoded as `!self.leq(other) && !self.geq(other)` — one
    /// primitive delegation each to [`Self::leq`] and [`Self::geq`]
    /// (with [`Self::geq`] itself delegating to [`Self::leq`]) so the
    /// antichain characterization lives at exactly one implementation
    /// site, and a future re-derivation of [`Self::leq`] (e.g. to a
    /// different pointwise conjunction) propagates to
    /// `is_incomparable` mechanically rather than requiring a per-
    /// method fix-up. Mirrors [`Self::gt`]'s `other.lt(self)`
    /// delegation and [`Self::geq`]'s `other.leq(self)` delegation one
    /// COVER axis over on the pairwise-relation surface.
    ///
    /// `const fn` for the same compile-time-pin reasons as
    /// [`Self::leq`] (`const _: () =
    /// assert!(!DEFAULT_RESOURCE_LIMITS.is_incomparable(
    /// EMPTY_RESOURCE_LIMITS));`), so a caller can pin an antichain-
    /// disagreement identity at compile time — a build-break rather
    /// than a runtime `assert!` on the first execution.
    ///
    /// Pre-lift, a caller that wanted "these two postures are
    /// incomparable on the pointwise partial-order" composed
    /// `!a.leq(b) && !b.leq(a)` at the callsite (or the algebraically
    /// equivalent `!a.leq(b) && !a.geq(b)` after `geq` landed), a
    /// two-primitive composition that appeared verbatim at every
    /// prospective antichain-detection site pre-lift — a ≥2 PRIME
    /// DIRECTIVE trigger with the (comparable, incomparable) two-cell
    /// partition of the ordered pair × verdict surface as its
    /// substrate posture. Post-lift the antichain characterization is
    /// ONE named primitive on the [`ResourceLimits`] surface,
    /// `const fn`-composable into a compile-time bound, and the two-
    /// primitive `!leq && !geq` composition lives at ONE
    /// implementation site.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the antichain characterization is the
    /// SET-COMPLEMENT of the union of the two comparable-direction
    /// predicates, and pinning the projection at ONE typed primitive
    /// makes the (comparable, incomparable) two-cell partition of the
    /// ordered-pair × verdict surface a substrate-level THEOREM
    /// rather than a per-consumer inline `!leq && !geq` sanity check.
    /// THEORY.md §V.1 — knowable platform; the antichain-detection
    /// corner was an unnamed two-primitive composition recurring at
    /// every prospective "these two postures sit on distinct
    /// branches?" callsite pre-lift.
    ///
    /// Frontier inspiration: Haskell's `Data.PartialOrd` typeclass'
    /// `compare :: PartialOrd a => a -> a -> Maybe Ordering` returning
    /// `Nothing` on incomparable inputs — the antichain corner is
    /// exactly the `isNothing` projection of that method; Julia's
    /// `Base.Order.NoOrder` sentinel on the same abstract; Rust's own
    /// `PartialOrd::partial_cmp` returning `Option<Ordering>` whose
    /// `None` arm is the antichain corner; Coq's `PreOrder` +
    /// classical LEM-derived `~ (leq a b) /\ ~ (leq b a)` proof
    /// obligation on the antichain arm. Translation through pleme-io
    /// primitives: the antichain characterization on the closed-set-
    /// paired [`ResourceLimits`] posture binds through the just-
    /// lifted [`Self::leq`] and [`Self::geq`] primitives (both const-
    /// evaluable, both delegating to [`Self::leq`]) with a two-arm
    /// conjunction on the negated forms — no new dep, no supertrait
    /// bound (`Sized + Copy + 'static`-plus-`Eq` stays untouched), no
    /// allocation, `const fn` throughout so the antichain verdict is
    /// a compile-time expression at every preset-tuple call site.
    #[must_use]
    pub const fn is_incomparable(self, other: Self) -> bool {
        !self.leq(other) && !self.geq(other)
    }

    /// Pointwise partial-order COMPARABILITY relation across the six
    /// ceilings — `true` iff `self` and `other` sit on the SAME lattice
    /// branch, i.e., EITHER `self.leq(other)` OR `self.geq(other)`
    /// holds. The two postures then admit a pointwise-domination
    /// verdict in at least one direction: every axis has `self` at-or-
    /// below `other` (the `leq` branch) or every axis has `self`
    /// at-or-above `other` (the `geq` branch), so at least one
    /// direction closes and one preset dominates the other on every
    /// field.
    ///
    /// The COMPARABLE CORNER on the (leq, geq, lt, gt, incomparable,
    /// comparable) pairwise-relation surface — the DIRECT POSITIVE
    /// DUAL of [`Self::is_incomparable`] one COVER-COMPLEMENT axis
    /// over on the (comparable, incomparable) two-cell partition of
    /// the ordered pair × verdict surface. The just-lifted
    /// [`Self::is_incomparable`] projection pins the ANTICHAIN half of
    /// that partition (the pairs where NEITHER pointwise-domination
    /// direction closes); THIS projection pins the DUAL COMPARABLE
    /// half (the pairs where AT LEAST ONE direction closes) —
    /// EXHAUSTIVELY CLOSING the (comparable, incomparable) two-cell
    /// partition at its FINAL SECOND tile on the pairwise-relation
    /// surface. The (leq, geq, lt, gt) 2×2 pairwise partial-order face
    /// carries the four DIRECTIONAL comparable predicates one COVER
    /// axis over; THIS projection folds them into ONE POSITIVE
    /// COMPARABILITY verdict — the SET-UNION of the two pointwise-
    /// domination directions.
    ///
    /// Symmetric on its argument order: `a.is_comparable(b) ==
    /// b.is_comparable(a)` — the composition `self.leq(other) ||
    /// self.geq(other)` folds through `self.leq(other) ==
    /// other.geq(self)` (dual identity on [`Self::geq`]) and the
    /// disjunction's commutativity, so the projection is order-
    /// independent on its two inputs. This SYMMETRY POSTURE mirrors
    /// [`Self::is_incomparable`]'s symmetry one CELL axis over on the
    /// (comparable, incomparable) partition: both cells of an
    /// EXHAUSTIVE-AND-DISJOINT partition of a symmetric surface must
    /// themselves be symmetric — the two verdicts flip in lockstep on
    /// argument swap. Distinguishes it from [`Self::leq`] / [`Self::lt`]
    /// (both antisymmetric — swapping inputs FLIPS the verdict).
    ///
    /// Reflexive on its own argument: `a.is_comparable(a) == true` —
    /// every posture is comparable to itself via [`Self::leq`]'s
    /// reflexivity (`a.leq(a) == true`), so the disjunction's
    /// `self.leq(other)` leg holds at every diagonal input. Sibling
    /// posture to [`Self::leq`]'s reflexivity one COVER axis over:
    /// the diagonal COMPARABLE cell is a substrate-level THEOREM
    /// falling out of the partial-order axioms, and THIS projection
    /// pins it as ONE positive verdict rather than the caller re-
    /// deriving `a.leq(a) || a.geq(a) == true` at every diagonal
    /// callsite.
    ///
    /// **Bottom-pole absorption**: `a.is_comparable(
    /// EMPTY_RESOURCE_LIMITS) == true` on every posture `a` —
    /// [`EMPTY_RESOURCE_LIMITS`] is the bounded-lattice bottom, so
    /// `EMPTY.leq(a)` holds on every axis (`0 <= a.max_*` on `usize`),
    /// which gives `a.geq(EMPTY)` through the [`Self::geq`] dual
    /// identity, which satisfies the `self.geq(other)` leg. The
    /// bounded-lattice bottom is comparable to every posture. The
    /// COMPLEMENT of [`Self::is_incomparable`]'s bottom-pole
    /// absorption pin one CELL axis over — where the antichain
    /// verdict FOLDS FALSE at the bottom pole, the comparability
    /// verdict FOLDS TRUE. Pinned on the canonical preset roster.
    ///
    /// **Top-pole absorption**: `a.is_comparable(
    /// UNBOUNDED_RESOURCE_LIMITS) == true` on every posture `a` —
    /// [`UNBOUNDED_RESOURCE_LIMITS`] is the bounded-lattice top, so
    /// `a.leq(UNBOUNDED)` holds on every axis (`a.max_* <=
    /// usize::MAX` unconditionally), which satisfies the
    /// `self.leq(other)` leg. The bounded-lattice top is comparable
    /// to every posture. The COMPLEMENT of [`Self::is_incomparable`]'s
    /// top-pole absorption pin one CELL axis over; pinned on the
    /// canonical preset roster.
    ///
    /// **Antichain load-bearing arm**:
    /// `HAND_AUTHORED_MID_POSTURE.is_comparable(
    /// HAND_AUTHORED_OTHER_POSTURE) == false` — the two hand-authored
    /// asymmetric postures sit on distinct branches (each is smaller
    /// on three axes and larger on the other three), so NEITHER
    /// pointwise-domination direction closes and the comparability
    /// verdict is `false`. The DIRECT FALSIFICATION of
    /// [`Self::is_incomparable`]'s antichain-arm HOLDS pin one CELL
    /// axis over on the SAME pair — the two are the negation-paired
    /// sides of the (comparable, incomparable) two-cell partition,
    /// and pinning BOTH cells' verdicts on the SAME load-bearing
    /// antichain pair closes the partition as a substrate-level
    /// EXCLUSIVITY THEOREM rather than one direction's assertion.
    ///
    /// **De Morgan duality**: `a.is_comparable(b) == !a.is_incomparable(b)`
    /// — the comparable corner is the SET-COMPLEMENT of the antichain
    /// corner. Pinned by
    /// `resource_limits_is_comparable_is_de_morgan_dual_of_incomparable`
    /// which sweeps every ordered pair in the preset roster and
    /// confirms the equivalence at every cell. Together with
    /// `resource_limits_is_incomparable_is_de_morgan_dual_of_comparable`
    /// (which pins the OTHER direction on
    /// `a.leq(b) || a.geq(b)` composition), the two projections carry
    /// the (comparable, incomparable) two-cell partition as an
    /// EXHAUSTIVE-AND-DISJOINT decomposition of the ordered pair ×
    /// verdict surface.
    ///
    /// Encoded as `self.leq(other) || self.geq(other)` — one
    /// primitive delegation each to [`Self::leq`] and [`Self::geq`]
    /// (with [`Self::geq`] itself delegating to [`Self::leq`]) so the
    /// comparability characterization lives at exactly one
    /// implementation site, and a future re-derivation of [`Self::leq`]
    /// (e.g. to a different pointwise conjunction) propagates to
    /// `is_comparable` mechanically rather than requiring a per-
    /// method fix-up. Mirrors [`Self::is_incomparable`]'s
    /// `!self.leq(other) && !self.geq(other)` delegation one COVER
    /// axis over on the pairwise-relation surface — the two share
    /// the SAME two-primitive substrate and diverge only on the
    /// negation posture (`!… && !…` vs `… || …`), which De Morgan's
    /// law pins as the SAME projection.
    ///
    /// `const fn` for the same compile-time-pin reasons as
    /// [`Self::is_incomparable`] (`const _: () =
    /// assert!(DEFAULT_RESOURCE_LIMITS.is_comparable(
    /// EMPTY_RESOURCE_LIMITS));`), so a caller can pin a
    /// comparability-agreement identity at compile time — a build-
    /// break rather than a runtime `assert!` on the first execution.
    ///
    /// Pre-lift, a caller that wanted "these two postures are
    /// comparable on the pointwise partial-order" composed
    /// `a.leq(b) || a.geq(b)` at the callsite — a two-primitive
    /// composition that appeared verbatim at every prospective
    /// comparability-detection site pre-lift, and the NEGATION of the
    /// same two-primitive composition [`Self::is_incomparable`]
    /// lifted one COVER axis over — a ≥2 PRIME DIRECTIVE trigger with
    /// the (comparable, incomparable) two-cell partition of the
    /// ordered pair × verdict surface as its substrate posture. Post-
    /// lift the comparability characterization is ONE named primitive
    /// on the [`ResourceLimits`] surface, `const fn`-composable into
    /// a compile-time bound, and the two-primitive `leq || geq`
    /// composition lives at ONE implementation site.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the comparability characterization is the
    /// SET-UNION of the two pointwise-domination directions, and
    /// pinning the projection at ONE typed primitive makes the
    /// (comparable, incomparable) two-cell partition of the ordered-
    /// pair × verdict surface a substrate-level THEOREM proved on
    /// BOTH SIDES rather than one side asserted and the other
    /// inferred at consumer sites. THEORY.md §V.1 — knowable
    /// platform; the comparability-detection corner was an unnamed
    /// two-primitive composition recurring at every prospective
    /// "these two postures sit on the same branch?" callsite pre-
    /// lift.
    ///
    /// Frontier inspiration: Haskell's `Data.PartialOrd` typeclass'
    /// `compare :: PartialOrd a => a -> a -> Maybe Ordering` — the
    /// comparable corner is exactly the `isJust` projection of that
    /// method (the DUAL of `is_incomparable`'s `isNothing` projection
    /// on the SAME method); Julia's `Base.Order.lt` + `Base.Order.gt`
    /// disjunction on the pairwise-comparability check; Rust's own
    /// `PartialOrd::partial_cmp` whose `Some(_)` arm is the
    /// comparable corner; Coq's `PreOrder` + classical LEM-derived
    /// `leq a b \/ leq b a` proof obligation on the comparable arm.
    /// Translation through pleme-io primitives: the comparability
    /// characterization on the closed-set-paired [`ResourceLimits`]
    /// posture binds through the just-lifted [`Self::leq`] and
    /// [`Self::geq`] primitives (both const-evaluable, both
    /// delegating to [`Self::leq`]) with a two-arm disjunction on the
    /// direct forms — no new dep, no supertrait bound (`Sized + Copy + 'static`-plus-`Eq` stays untouched), no allocation, `const fn`
    /// throughout so the comparability verdict is a compile-time
    /// expression at every preset-tuple call site.
    #[must_use]
    pub const fn is_comparable(self, other: Self) -> bool {
        self.leq(other) || self.geq(other)
    }

    /// Pointwise partial-order VERDICT across the six ceilings — the
    /// `Option<Ordering>` corner on the pairwise-relation surface. Folds
    /// the four possible outcomes ([`Ordering::Less`], [`Ordering::Equal`],
    /// [`Ordering::Greater`], INCOMPARABLE) into ONE typed value, so a
    /// caller that wants "how do these two postures relate?" gets the
    /// FULL verdict in a single call rather than composing
    /// [`Self::leq`] / [`Self::geq`] / [`Self::lt`] / [`Self::gt`] /
    /// `PartialEq::eq` at its callsite.
    ///
    /// The `Option<Ordering>` PROJECTION on the pairwise-relation surface —
    /// the DIRECT LIFT of the frontier inspiration the just-lifted
    /// [`Self::is_incomparable`] + [`Self::is_comparable`] pair explicitly
    /// named (Rust's `PartialOrd::partial_cmp`, Haskell's
    /// `Data.PartialOrd.compare :: a -> a -> Maybe Ordering`, Julia's
    /// `Base.Order`, Coq's `PreOrder` decidability obligation). Those two
    /// projections pinned ONE ARM each of the surface — the antichain
    /// arm ([`Self::is_incomparable`] → `is_none()`) and the comparability
    /// arm ([`Self::is_comparable`] → `is_some()`); THIS lift closes the
    /// surface at its FULL VERDICT corner by returning the ordering
    /// direction on the comparable arm and `None` on the antichain arm —
    /// the (Less, Equal, Greater, None) 4-tile partition of the ordered
    /// pair × verdict surface at ONE named primitive rather than a
    /// four-way conditional composition at every consumer that wanted
    /// the full verdict.
    ///
    /// **Antichain-arm identity**: `a.partial_cmp(b).is_none() ==
    /// a.is_incomparable(b)` — the `None` arm of the return coincides
    /// EXACTLY with the antichain-corner projection [`Self::is_incomparable`]
    /// lifts. On the antichain the two-arm conjunction `!self.leq(other)
    /// && !self.geq(other)` holds; neither branch of THIS method's
    /// disjunction closes, so the fall-through arm binds. Pinned as a
    /// substrate-level identity in the test cohort.
    ///
    /// **Comparability-arm identity**: `a.partial_cmp(b).is_some() ==
    /// a.is_comparable(b)` — the `Some(_)` arm of the return coincides
    /// EXACTLY with the comparability-corner projection [`Self::is_comparable`]
    /// lifts. On every comparable pair at least one of the two
    /// pointwise-domination legs closes, so the method returns a
    /// concrete [`Ordering`] variant. Together with the antichain-arm
    /// identity, THIS method is the JOINT LIFT of the (comparable,
    /// incomparable) two-cell partition into ONE `Option<Ordering>`
    /// value.
    ///
    /// **Equality on the diagonal**: `a.partial_cmp(a) ==
    /// Some(Ordering::Equal)` on every posture — the `leq` reflexivity
    /// (`a.leq(a) == true`) AND the `geq` reflexivity (`a.geq(a) ==
    /// true`) both hold at the diagonal, so both branches of the
    /// conjunction close and the equality arm fires. The diagonal cell
    /// of the (Less, Equal, Greater, None) 4-tile partition on the
    /// ordered pair × verdict surface pins to the Equal tile.
    ///
    /// **Ordering-direction agreement**: `a.partial_cmp(b) ==
    /// Some(Ordering::Less)` iff `a.lt(b)` (strict less); `a.partial_cmp(b)
    /// == Some(Ordering::Greater)` iff `a.gt(b)` (strict greater);
    /// `a.partial_cmp(b) == Some(Ordering::Equal)` iff `a == b` (via
    /// antisymmetry `a.leq(b) && a.geq(b) → a == b`). The four-arm
    /// dispatch below binds each verdict tile to its named companion
    /// primitive at exactly one implementation site, so a caller that
    /// wants the strict-less verdict binds through either `a.lt(b)` OR
    /// `matches!(a.partial_cmp(b), Some(Ordering::Less))` and both route
    /// to the same substrate.
    ///
    /// **Antisymmetry under argument swap**: `a.partial_cmp(b) ==
    /// b.partial_cmp(a).map(Ordering::reverse)` — swapping the argument
    /// pair FLIPS the ordering-direction verdict (`Less <-> Greater`,
    /// `Equal` fixed, `None` fixed). Discriminates [`Self::is_incomparable`] /
    /// [`Self::is_comparable`] (both SYMMETRIC on argument swap) one
    /// POSTURE axis over: the projections carry no directional content
    /// and are argument-order-independent; the FULL verdict carries
    /// directional content and inverts under swap. Pinned in the test
    /// cohort.
    ///
    /// **Bottom-pole absorption**: `EMPTY_RESOURCE_LIMITS.partial_cmp(a)`
    /// returns `Some(Ordering::Less)` for every posture `a` strictly
    /// above [`EMPTY_RESOURCE_LIMITS`] on the pointwise partial order,
    /// AND `Some(Ordering::Equal)` at `a == EMPTY_RESOURCE_LIMITS`.
    /// [`EMPTY_RESOURCE_LIMITS`] is the bounded-lattice bottom, so on
    /// every posture the `EMPTY.leq(a)` leg closes; the antisymmetric
    /// leg discriminates the strict-less arm (concrete positive posture)
    /// from the equality arm (`a == EMPTY`). The DIRECT REFINEMENT of
    /// [`Self::is_comparable`]'s bottom-pole absorption pin one
    /// DIRECTION-CONTENT axis over — where the comparability projection
    /// folds TRUE at the bottom pole across every posture, THIS method
    /// discriminates the equality-vs-strict-less refinement on the
    /// SAME preset roster.
    ///
    /// **Top-pole absorption**: symmetric statement — `a.partial_cmp(
    /// UNBOUNDED_RESOURCE_LIMITS)` returns `Some(Ordering::Less)` for
    /// every posture `a` strictly below the top and
    /// `Some(Ordering::Equal)` at `a == UNBOUNDED`. Pinned on the
    /// canonical preset roster.
    ///
    /// **Antichain load-bearing arm**: `HAND_AUTHORED_MID_POSTURE
    /// .partial_cmp(HAND_AUTHORED_OTHER_POSTURE) == None` — the two
    /// hand-authored asymmetric postures sit on distinct branches
    /// (each is smaller on three axes and larger on the other three),
    /// so NEITHER pointwise-domination direction closes and the
    /// fall-through `None` arm fires. The DIRECT LIFT of
    /// [`Self::is_incomparable`]'s antichain-arm HOLDS pin AND
    /// [`Self::is_comparable`]'s antichain-arm FALSIFIES pin one
    /// PROJECTION axis over on the SAME hand-authored pair — the two
    /// projections pinned each ARM's cell verdict; THIS method pins
    /// the FULL `Option<Ordering>` return at the antichain corner
    /// (`None`).
    ///
    /// Encoded as `if self.leq(other) && other.leq(self) { Equal } else
    /// if self.leq(other) { Less } else if other.leq(self) { Greater }
    /// else { None }` — a four-arm dispatch on the (`self.leq(other)`,
    /// `other.leq(self)`) 2×2 boolean truth-table, with each arm binding
    /// to its named companion primitive at exactly one implementation
    /// site so a future re-derivation of [`Self::leq`] propagates to
    /// EVERY ordering-direction verdict mechanically rather than
    /// requiring a per-arm fix-up. The `self.leq(other) && other.leq(self)`
    /// conjunction is the pointwise antisymmetric-equality
    /// characterization — pinned as a substrate-level identity by the
    /// `resource_limits_leq_is_antisymmetric` test cohort, so the
    /// Equal-arm binding above is a substrate-level THEOREM rather than
    /// an ad-hoc composition.
    ///
    /// `const fn` for the same compile-time-pin reasons as [`Self::leq`]
    /// / [`Self::geq`] / [`Self::lt`] / [`Self::gt`] / [`Self::is_incomparable`]
    /// / [`Self::is_comparable`] one COVER axis over on the pairwise-
    /// relation surface (`const _: () = assert!(matches!(
    /// EMPTY_RESOURCE_LIMITS.partial_cmp(UNBOUNDED_RESOURCE_LIMITS),
    /// Some(Ordering::Less)));`) — a caller can pin a full-verdict
    /// identity at compile time as a build-break rather than a runtime
    /// `assert!` on the first execution. [`Ordering`] itself is
    /// `const`-constructible (the three variants are plain enum
    /// constructors), so the return-value cascade below stays inside
    /// stable const-fn scope with no runtime allocation, no supertrait
    /// bound, and no new dep.
    ///
    /// Pre-lift, a caller that wanted the FULL pointwise ordering
    /// verdict either (a) composed four separate calls
    /// (`a.lt(b)` / `a == b` / `a.gt(b)` / `a.is_incomparable(b)`) at
    /// its callsite and dispatched on the resulting 4-way conditional —
    /// a per-consumer FOUR-primitive composition whose exhaustiveness
    /// the type system did NOT gate (a dropped arm silently miscategorized
    /// the pair) — or (b) invoked [`Self::is_comparable`] to get the
    /// `is_some`/`is_none` distinction and THEN chose one of `lt` / `gt`
    /// / equality on the `is_some` arm — a two-stage composition that
    /// double-evaluates the `leq` / `geq` primitives on every consumer.
    /// Post-lift the full verdict is ONE named primitive returning
    /// `Option<Ordering>`, `const fn`-composable into a compile-time
    /// bound, and the two-primitive `leq(self, other)` + `leq(other, self)`
    /// substrate binds at ONE implementation site — a ≥2 PRIME
    /// DIRECTIVE trigger, since the four-way ordering dispatch appeared
    /// inline at every prospective full-verdict callsite pre-lift.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the FULL pointwise partial-order verdict on
    /// two preset-carried resource proofs is itself a typed
    /// `Option<Ordering>` value whose four arms each carry a distinct
    /// substrate-level relation proof (`Less` ⇒ strict-less on every
    /// axis; `Equal` ⇒ pointwise equality on every axis; `Greater` ⇒
    /// strict-greater on every axis; `None` ⇒ antichain — asymmetric
    /// per-axis orderings). Pinning the projection at ONE typed
    /// primitive makes the (Less, Equal, Greater, None) 4-tile
    /// partition of the ordered pair × verdict surface a substrate-
    /// level THEOREM rather than a per-consumer inline four-way
    /// dispatch. THEORY.md §V.1 — knowable platform; the full-verdict
    /// projection was an unnamed four-primitive composition recurring
    /// at every prospective "how do these two postures relate?"
    /// callsite pre-lift.
    ///
    /// Frontier inspiration: Rust's own `PartialOrd::partial_cmp :: fn
    /// partial_cmp(&self, &Self) -> Option<Ordering>` — the CANONICAL
    /// `Option<Ordering>` corner on any partial-order-carrying type;
    /// Haskell's `Data.PartialOrd.compare :: PartialOrd a => a -> a
    /// -> Maybe Ordering`; Julia's `Base.Order.NoOrder` sentinel folded
    /// into `Option<Ordering>` on the `Base.Order`-compatible partial
    /// order; Coq's `PreOrder` + `Decidable` typeclass composition
    /// giving `forall a b, {leq a b} + {leq b a} + {~(leq a b) /\
    /// ~(leq b a)}` — the three-way decidable sum where the third
    /// disjunct is the antichain corner. Translation through pleme-io
    /// primitives: the full-verdict projection binds through the just-
    /// lifted [`Self::leq`] primitive (invoked twice — once in each
    /// argument order — to derive the (`self.leq(other)`,
    /// `other.leq(self)`) 2×2 truth-table the four-arm dispatch reads
    /// against), no new dep, no supertrait bound (`Sized + Copy +
    /// 'static`-plus-`Eq` stays untouched), no allocation, `const fn`
    /// throughout. This method does NOT wire an `impl PartialOrd for
    /// ResourceLimits` — the derive would give lexicographic ordering
    /// on the six fields (WRONG for the pointwise lattice), and manually
    /// implementing the trait would expose `<` / `<=` / `>` / `>=`
    /// operators that overlap the named `lt` / `leq` / `gt` / `geq`
    /// primitives already lifted one COVER axis over. Keeping the
    /// `Option<Ordering>` corner at an inherent method preserves the
    /// tight name-directed surface without introducing an operator
    /// alias for each of the four directional predicates.
    #[must_use]
    pub const fn partial_cmp(self, other: Self) -> Option<Ordering> {
        let self_leq = self.leq(other);
        let other_leq = other.leq(self);
        if self_leq && other_leq {
            Some(Ordering::Equal)
        } else if self_leq {
            Some(Ordering::Less)
        } else if other_leq {
            Some(Ordering::Greater)
        } else {
            None
        }
    }

    /// Boolean `is_comparable`-conjunction across every distinct pair of a
    /// slice of postures — `postures` is a CHAIN (a totally-ordered subset of
    /// the pointwise partial-order lattice) iff every distinct pair
    /// `(postures[i], postures[j])` sits on the same lattice branch
    /// (`postures[i].is_comparable(postures[j])`).
    ///
    /// The SET-LEVEL N-ary peer of [`Self::is_comparable`] one CARDINALITY
    /// axis over on the (comparable, incomparable) × (pair-level, set-level)
    /// primitive surface. Where [`Self::is_comparable`] decides the pairwise
    /// question "do THESE TWO postures sit on the same branch?", THIS
    /// projection decides the set-level question "does EVERY PAIR in this
    /// slice sit on the same branch?" — the natural lift of the pair-level
    /// verdict to the collection level, matching the arity extension the
    /// [`Self::is_lower_bound_of`] / [`Self::is_upper_bound_of`] pair carries
    /// one PRIMITIVE-KIND axis over on the (leq, comparable) × (pairwise,
    /// N-ary) primitive surface.
    ///
    /// **Empty-slice vacuous truth**: `ResourceLimits::is_chain(&[]) == true`
    /// — the empty conjunction is vacuously true; the empty slice contains
    /// no distinct pairs to reject. Peer of
    /// `is_lower_bound_of(&[]) == true`'s empty-slice identity one
    /// PRIMITIVE-KIND axis over. Pinned as
    /// `resource_limits_is_chain_empty_slice_is_vacuously_true`.
    ///
    /// **Singleton vacuous truth**: `ResourceLimits::is_chain(&[a]) == true`
    /// for every posture `a` — a one-element slice contains no distinct
    /// pairs, so the outer-and-inner-index conjunction never enters the
    /// inner loop and returns `true` vacuously. Pinned as
    /// `resource_limits_is_chain_singleton_is_vacuously_true`.
    ///
    /// **Diagonal-duplicate identity**: `ResourceLimits::is_chain(&[a, a])
    /// == true` for every posture `a` — [`Self::is_comparable`] is
    /// REFLEXIVE (`a.is_comparable(a) == true`), so the single distinct
    /// index pair `(0, 1)` binds `a.is_comparable(a) == true` and the
    /// conjunction holds. Distinguishes it from [`Self::is_antichain`] one
    /// COVER-COMPLEMENT axis over, whose diagonal-duplicate verdict is
    /// `false` (via [`Self::is_incomparable`]'s IRREFLEXIVITY). Pinned as
    /// `resource_limits_is_chain_of_diagonal_duplicate_is_true`.
    ///
    /// **Ordered-chain closure**: `ResourceLimits::is_chain(
    /// &[EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS]) == true` — the shipped-preset triple on
    /// the bounded-lattice diagonal is an ascending chain (`EMPTY <=
    /// DEFAULT <= UNBOUNDED` pointwise), so every distinct pair among the
    /// three is comparable. Pinned as
    /// `resource_limits_is_chain_holds_on_the_shipped_preset_triple`.
    ///
    /// **Antichain rejection**: `ResourceLimits::is_chain(
    /// &[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE]) == false`
    /// — the two hand-authored asymmetric postures sit on distinct branches
    /// (each is smaller on three axes and larger on the other three), so
    /// neither pointwise-domination direction closes and the pair is
    /// INCOMPARABLE. The chain conjunction rejects at the first
    /// incomparable pair. Pinned as
    /// `resource_limits_is_chain_rejects_the_hand_authored_antichain_pair`.
    ///
    /// **Mixed-set rejection**: `ResourceLimits::is_chain(
    /// &[DEFAULT_RESOURCE_LIMITS, HAND_AUTHORED_MID_POSTURE,
    /// HAND_AUTHORED_OTHER_POSTURE]) == false` — even though the first two
    /// AND the first-and-third pairs are comparable in isolation, the
    /// second-and-third pair is incomparable, so the whole-set conjunction
    /// rejects. The set-level chain verdict is stricter than the union of
    /// its pair-level verdicts — one antichain pair anywhere in the slice
    /// falsifies the whole projection. Pinned as
    /// `resource_limits_is_chain_rejects_mixed_slice_with_one_antichain_pair`.
    ///
    /// **`most_permissive_of` closure witness**: on every slice `postures`
    /// where `ResourceLimits::is_chain(postures)` holds, the N-ary join
    /// `most_permissive_of(postures)` is a MEMBER of the slice (not just a
    /// bound above it) — the maximum element of a chain sits inside the
    /// chain. The set-level verdict thus underwrites the pointwise-`max`
    /// identification of the chain's top element. NOT pinned as a test in
    /// this cohort (the general witness needs a slice-membership predicate
    /// not yet lifted); recorded here as the future callsite the chain
    /// verdict unlocks.
    ///
    /// Encoded as a doubly-indexed const-`while` walk (`i in 0..n`, `j in
    /// i+1..n`) with one [`Self::is_comparable`] delegation per distinct
    /// pair. The `j = i + 1` inner starting index skips the diagonal AND
    /// the mirror pairs (`(j, i)` pairs the outer loop already visited from
    /// the `(i, j)` direction) — [`Self::is_comparable`] is SYMMETRIC on
    /// argument swap, so the mirror pair carries no additional information
    /// and the (n choose 2) unique-pair count is the tight iteration budget
    /// for the set-level verdict. `postures[i].is_comparable(postures[j])`
    /// (not `.leq(...) || .geq(...)` directly) so the primitive delegation
    /// lives at exactly one implementation site — a future re-derivation of
    /// [`Self::is_comparable`] (e.g. to a different comparability
    /// characterization) propagates to `is_chain` mechanically rather than
    /// requiring a per-callsite fix-up.
    ///
    /// `const fn` for the same compile-time-pin reasons as
    /// [`Self::is_comparable`] one CARDINALITY axis over on the (comparable,
    /// incomparable) × (pair-level, set-level) primitive surface (`const _:
    /// () = assert!(ResourceLimits::is_chain(&[EMPTY_RESOURCE_LIMITS,
    /// DEFAULT_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS]));`), so a
    /// caller can pin a chain-membership identity at compile time — a
    /// build-break rather than a runtime `assert!` on the first execution.
    /// `Copy` on [`ResourceLimits`] lets the const-fn loop index the slice
    /// by value without an explicit `.clone()` (which const-fn would not
    /// permit anyway).
    ///
    /// Pre-lift, a caller wanting "is this slice a chain?" composed the
    /// doubly-indexed `postures.iter().enumerate().all(|(i, a)|
    /// postures[i + 1..].iter().all(|b| a.is_comparable(*b)))` two-primitive
    /// scaffolding at every prospective callsite — a PRIME DIRECTIVE ≥2
    /// pattern once two consumers need the set-level chain verdict, and one
    /// whose exhaustiveness the type system did NOT gate (a slice iterator
    /// that stopped at the first `false` still needed the caller to bind
    /// the outer-and-inner-index conjunction correctly, and a copy-paste
    /// that swapped `postures[i]` with `postures[j]` would test the SAME
    /// pair via [`Self::is_comparable`]'s symmetry — silent no-op — but a
    /// copy-paste that inverted the primitive delegation to
    /// [`Self::is_incomparable`] would test the DUAL question and silently
    /// distort the verdict). Post-lift the chain verdict binds at ONE typed
    /// method the algebra exposes, and the doubly-indexed all-pairs
    /// scaffolding lives at ONE implementation site.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
    /// proofs; the set-level chain verdict on N preset-carried resource
    /// proofs is itself a typed named `bool` predicate composing them via
    /// the underlying pair-level [`Self::is_comparable`] projection.
    /// THEORY.md §V.1 — knowable platform; the doubly-indexed all-pairs
    /// comparability conjunction becomes a TYPE-level operation on the
    /// posture algebra rather than an inline two-primitive scaffolding at
    /// every consumer that decides "is this slice a totally-ordered
    /// subset?"
    ///
    /// Frontier inspiration: Haskell's `Data.List.isSorted`
    /// (adjacent-pair-comparability variant on `Ord a`); Coq's `Sorted`
    /// inductive on lists over a `TotalOrder`; Idris's `Sorted` predicate
    /// over `Ord`-carrying lists; the order-theoretic notion of a CHAIN
    /// (a totally-ordered subset of a poset) canonicalized in
    /// Birkhoff's *Lattice Theory* and every subsequent poset text.
    /// Translation through pleme-io primitives: on a `PartialOrd`-derived
    /// carrier the frontier `isSorted` variants reduce to adjacent-pair
    /// comparability because total-order transitivity closes the chain; on
    /// a PARTIAL order (the pointwise lattice) the adjacent-pair check is
    /// INSUFFICIENT (three postures `a, b, c` where `a` and `c` are
    /// comparable but `b` is incomparable to at least one of them satisfy
    /// adjacent-pair comparability without forming a chain), so this
    /// projection walks EVERY distinct pair rather than only the adjacent
    /// ones — the strict partial-order generalization of the frontier
    /// total-order predicate. No new dep, no supertrait bound, `const fn`
    /// throughout.
    #[must_use]
    pub const fn is_chain(postures: &[Self]) -> bool {
        let n = postures.len();
        let mut i = 0;
        while i < n {
            let mut j = i + 1;
            while j < n {
                if !postures[i].is_comparable(postures[j]) {
                    return false;
                }
                j += 1;
            }
            i += 1;
        }
        true
    }

    /// Boolean `is_incomparable`-conjunction across every distinct pair of a
    /// slice of postures — `postures` is an ANTICHAIN (a pairwise-
    /// incomparable subset of the pointwise partial-order lattice) iff every
    /// distinct pair `(postures[i], postures[j])` sits on distinct branches
    /// (`postures[i].is_incomparable(postures[j])`).
    ///
    /// The SET-LEVEL N-ary peer of [`Self::is_incomparable`] one CARDINALITY
    /// axis over on the (comparable, incomparable) × (pair-level, set-level)
    /// primitive surface — the DIRECT SET-LEVEL DUAL of [`Self::is_chain`]
    /// one COVER-COMPLEMENT axis over on the SAME set-level cardinality
    /// slice. Together the two close the (chain, antichain) two-cell face
    /// on the set-level pairwise-relation surface, exactly ONE CARDINALITY
    /// axis over from the (comparable, incomparable) two-cell partition of
    /// the ordered-pair × verdict surface [`Self::is_comparable`] and
    /// [`Self::is_incomparable`] closed one arity down.
    ///
    /// The (chain, antichain) pair is NOT a partition of the set-level
    /// verdict surface: a slice of ≥3 postures whose pair-level verdicts
    /// mix comparable and incomparable pairs is neither a chain nor an
    /// antichain, so the two set-level projections carry a THREE-cell
    /// face (chain, antichain, mixed) at the set level whose ends the two
    /// projections lifted here pin. Distinguishes it from the pair-level
    /// (comparable, incomparable) partition [`Self::is_comparable`] +
    /// [`Self::is_incomparable`] EXHAUSTIVELY closed one arity down: at
    /// arity 2 every pair is exactly one of comparable-or-incomparable, and
    /// the two projections partition the ordered-pair × verdict surface; at
    /// arity ≥3 the mixed-set cell opens up between them and the two
    /// set-level projections carry the ends of that three-cell face.
    ///
    /// **Empty-slice vacuous truth**: `ResourceLimits::is_antichain(&[])
    /// == true` — the empty conjunction is vacuously true; the empty slice
    /// contains no distinct pairs to reject. Peer of [`Self::is_chain`]'s
    /// empty-slice identity one COVER-COMPLEMENT axis over: both cells of
    /// the (chain, antichain) set-level pair AGREE at the empty slice on
    /// the vacuous-truth verdict — the two cells coincide at the empty
    /// face of the set-level verdict surface. Pinned as
    /// `resource_limits_is_antichain_empty_slice_is_vacuously_true`.
    ///
    /// **Singleton vacuous truth**: `ResourceLimits::is_antichain(&[a])
    /// == true` for every posture `a` — a one-element slice contains no
    /// distinct pairs, so the outer-and-inner-index conjunction never
    /// enters the inner loop and returns `true` vacuously. Peer of
    /// [`Self::is_chain`]'s singleton-vacuous-truth identity: both cells
    /// AGREE at singleton slices too — the (chain, antichain) verdict
    /// surface coincides at every slice with strictly fewer than two
    /// distinct pairs. Pinned as
    /// `resource_limits_is_antichain_singleton_is_vacuously_true`.
    ///
    /// **Diagonal-duplicate rejection**: `ResourceLimits::is_antichain(
    /// &[a, a]) == false` for every posture `a` — [`Self::is_incomparable`]
    /// is IRREFLEXIVE (`a.is_incomparable(a) == false`), so the single
    /// distinct index pair `(0, 1)` binds `a.is_incomparable(a) == false`
    /// and the conjunction rejects. Distinguishes it from [`Self::is_chain`]
    /// one COVER-COMPLEMENT axis over, whose diagonal-duplicate verdict is
    /// `true` (via [`Self::is_comparable`]'s REFLEXIVITY). The reflexivity/
    /// irreflexivity divergence between the two pair-level projections
    /// PROPAGATES to the set-level projections at any slice with a
    /// duplicated element — the two set-level cells DIVERGE at every
    /// diagonal-duplicate slice, the mirror of their AGREEMENT at every
    /// empty-or-singleton slice one CARDINALITY axis over. Pinned as
    /// `resource_limits_is_antichain_of_diagonal_duplicate_is_false`.
    ///
    /// **Hand-authored antichain closure**: `ResourceLimits::is_antichain(
    /// &[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE]) == true`
    /// — the two hand-authored asymmetric postures sit on distinct
    /// branches (each is smaller on three axes and larger on the other
    /// three), so neither pointwise-domination direction closes and the
    /// pair is INCOMPARABLE. The antichain conjunction accepts every
    /// distinct pair of the slice. Pinned as
    /// `resource_limits_is_antichain_holds_on_the_hand_authored_antichain_pair`.
    ///
    /// **Chain rejection**: `ResourceLimits::is_antichain(
    /// &[EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS]) == false` — the
    /// shipped-preset pair on the bounded-lattice diagonal is a strict
    /// chain (`EMPTY.lt(DEFAULT)`), so the single distinct pair is
    /// COMPARABLE and the antichain conjunction rejects. The DIRECT
    /// FALSIFICATION of [`Self::is_chain`]'s ordered-chain closure one
    /// CELL axis over on the SAME slice — the two set-level cells carry
    /// the negation-paired verdict at every strictly-chained slice, the
    /// mirror of their AGREEMENT at every empty-or-singleton slice one
    /// CARDINALITY axis over. Pinned as
    /// `resource_limits_is_antichain_rejects_the_shipped_preset_pair`.
    ///
    /// **Mixed-set rejection**: `ResourceLimits::is_antichain(
    /// &[DEFAULT_RESOURCE_LIMITS, HAND_AUTHORED_MID_POSTURE,
    /// HAND_AUTHORED_OTHER_POSTURE]) == false` — even though the
    /// second-and-third pair is incomparable, the first pair
    /// (`DEFAULT`-and-`MID`) is comparable, so the whole-set conjunction
    /// rejects. Pins the three-cell (chain, antichain, mixed) set-level
    /// face at the mixed-set cell: the same slice both [`Self::is_chain`]
    /// AND [`Self::is_antichain`] reject at, and the third cell of the
    /// three-cell face the two set-level projections carry the ends of.
    /// Pinned as
    /// `resource_limits_is_antichain_rejects_mixed_slice_with_one_comparable_pair`.
    ///
    /// **De Morgan mirror at arity 2**: on any two-element slice `[a, b]`
    /// (`a != b`), `ResourceLimits::is_antichain(&[a, b]) ==
    /// !ResourceLimits::is_chain(&[a, b])` — at exactly two DISTINCT
    /// elements the set-level (chain, antichain) two-cell face reduces to
    /// the pair-level (comparable, incomparable) two-cell partition and
    /// the two cells become MUTUALLY EXCLUSIVE (the mixed cell requires
    /// ≥3 elements to open). The set-level De Morgan mirror of the
    /// pair-level identity `a.is_comparable(b) == !a.is_incomparable(b)`
    /// [`Self::is_comparable`] pins one CARDINALITY axis over. Pinned as
    /// `resource_limits_is_antichain_and_is_chain_are_mutually_exclusive_on_distinct_pairs`.
    ///
    /// Encoded as a doubly-indexed const-`while` walk (`i in 0..n`, `j in
    /// i+1..n`) with one [`Self::is_incomparable`] delegation per distinct
    /// pair — the SAME iteration structure as [`Self::is_chain`] one
    /// PRIMITIVE-DELEGATION axis over, with only the inner primitive
    /// swapped between the two. The two set-level projections share the
    /// SAME two-primitive substrate (the doubly-indexed pair walk + one
    /// pair-level projection) and diverge only on the pair-level primitive
    /// they delegate to (`is_comparable` vs `is_incomparable`), which De
    /// Morgan's law pins as the pair-level negation-paired substrate.
    ///
    /// `const fn` for the same compile-time-pin reasons as
    /// [`Self::is_incomparable`] one CARDINALITY axis over on the
    /// (comparable, incomparable) × (pair-level, set-level) primitive
    /// surface (`const _: () = assert!(ResourceLimits::is_antichain(
    /// &[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE]));`), so
    /// a caller can pin an antichain-membership identity at compile time
    /// — a build-break rather than a runtime `assert!` on the first
    /// execution.
    ///
    /// Pre-lift, a caller wanting "is this slice an antichain?" composed
    /// the doubly-indexed `postures.iter().enumerate().all(|(i, a)|
    /// postures[i + 1..].iter().all(|b| a.is_incomparable(*b)))` two-
    /// primitive scaffolding at every prospective callsite — the SAME
    /// PRIME DIRECTIVE ≥2 pattern [`Self::is_chain`]'s pre-lift shape
    /// carried, with only the pair-level primitive swapped. Post-lift the
    /// antichain verdict binds at ONE typed method the algebra exposes,
    /// and the doubly-indexed all-pairs scaffolding lives at ONE
    /// implementation site — the same site [`Self::is_chain`] delegates
    /// to, factored down to a per-projection choice of pair-level
    /// primitive.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
    /// proofs; the set-level antichain verdict on N preset-carried
    /// resource proofs is itself a typed named `bool` predicate composing
    /// them via the underlying pair-level [`Self::is_incomparable`]
    /// projection. THEORY.md §V.1 — knowable platform; the doubly-indexed
    /// all-pairs incomparability conjunction becomes a TYPE-level
    /// operation on the posture algebra rather than an inline two-
    /// primitive scaffolding at every consumer that decides "is this
    /// slice a pairwise-incomparable subset?"
    ///
    /// Frontier inspiration: the order-theoretic notion of an ANTICHAIN
    /// (a pairwise-incomparable subset of a poset) canonicalized in
    /// Dilworth's theorem (a poset's width — the maximum antichain size —
    /// equals the minimum number of chains covering the poset) and the
    /// Robinson–Schensted correspondence's Young-tableau chain/antichain
    /// duality; Haskell's `Data.List` idiom of
    /// `all (uncurry incomparable) . pairs` for a partial-order carrier;
    /// Coq's `Antichain` inductive on lists over a `PartialOrder`.
    /// Translation through pleme-io primitives: the doubly-indexed pair
    /// walk directly, with [`Self::is_incomparable`] as the pair-level
    /// primitive, no new dep, no supertrait bound, `const fn` throughout.
    /// The (chain, antichain) set-level pair opens the door to Dilworth's
    /// width invariant on the [`ResourceLimits`] lattice at a future
    /// callsite — the maximum antichain size is a substrate-level
    /// dimension the two set-level projections lift here jointly
    /// characterize.
    #[must_use]
    pub const fn is_antichain(postures: &[Self]) -> bool {
        let n = postures.len();
        let mut i = 0;
        while i < n {
            let mut j = i + 1;
            while j < n {
                if !postures[i].is_incomparable(postures[j]) {
                    return false;
                }
                j += 1;
            }
            i += 1;
        }
        true
    }

    /// The MIDDLE-CELL corner of the (chain, antichain, mixed) three-cell
    /// face on the set-level pairwise-relation surface — `postures` is a
    /// MIXED slice iff it is NEITHER a chain NOR an antichain, computed
    /// as the boolean conjunction of the negations of the just-lifted
    /// [`Self::is_chain`] and [`Self::is_antichain`] projections.
    ///
    /// EXHAUSTIVELY CLOSES the (chain, antichain, mixed) three-cell face
    /// at its previously-open middle cell — the two set-level ENDS the
    /// just-lifted [`Self::is_chain`] / [`Self::is_antichain`] pair
    /// pinned already carried the (chain, antichain) two ends; this
    /// projection binds the third cell (F, F) as a NAMED typed `bool`.
    /// The three cells now sit at (T, F) — pure chain, (F, T) — pure
    /// antichain, and (F, F) — mixed. The fourth cell (T, T) is only
    /// achievable at the degenerate empty-or-singleton slice where BOTH
    /// projections agree on the vacuous-truth verdict — [`Self::is_mixed`]
    /// reports `false` there too, aligning with the intuition that a
    /// slice with strictly fewer than two distinct pairs is neither
    /// chain-mixed nor antichain-mixed.
    ///
    /// **Empty-slice contract**: `ResourceLimits::is_mixed(&[]) == false`
    /// — [`Self::is_chain`] and [`Self::is_antichain`] BOTH return `true`
    /// vacuously, so `!true && !true == false`. The empty slice is NOT
    /// mixed. Pinned as
    /// `resource_limits_is_mixed_empty_slice_is_false`.
    ///
    /// **Singleton contract**: `ResourceLimits::is_mixed(&[a]) == false`
    /// for every posture `a` — a one-element slice contains no distinct
    /// pairs; both [`Self::is_chain`] and [`Self::is_antichain`] return
    /// `true` vacuously. Pinned as
    /// `resource_limits_is_mixed_singleton_is_false`.
    ///
    /// **Diagonal-duplicate contract**: `ResourceLimits::is_mixed(&[a, a])
    /// == false` for every posture `a` — [`Self::is_chain`] returns
    /// `true` via [`Self::is_comparable`]'s REFLEXIVITY;
    /// [`Self::is_antichain`] returns `false` via
    /// [`Self::is_incomparable`]'s IRREFLEXIVITY; the conjunction is
    /// `!true && !false == false`. The diagonal-duplicate slice is a
    /// CHAIN, not mixed. Pinned as
    /// `resource_limits_is_mixed_of_diagonal_duplicate_is_false`.
    ///
    /// **Chain rejection**: `ResourceLimits::is_mixed(
    /// &[EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS]) == false` — the shipped-preset triple
    /// on the bounded-lattice diagonal is an ascending chain,
    /// [`Self::is_chain`] returns `true`, and `!true && …` short-
    /// circuits to `false`. Pinned as
    /// `resource_limits_is_mixed_rejects_the_shipped_preset_triple`.
    ///
    /// **Antichain rejection**: `ResourceLimits::is_mixed(
    /// &[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE]) ==
    /// false` — the hand-authored antichain pair binds
    /// [`Self::is_antichain`] `true`, and `!… && !true == false`. Pinned
    /// as
    /// `resource_limits_is_mixed_rejects_the_hand_authored_antichain_pair`.
    ///
    /// **Mixed-set closure (LOAD-BEARING `true`-arm catch)**:
    /// `ResourceLimits::is_mixed(&[DEFAULT_RESOURCE_LIMITS,
    /// HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE]) == true`
    /// — the (DEFAULT, MID) pair is comparable (falsifying
    /// [`Self::is_antichain`]) while the (MID, OTHER) pair is
    /// incomparable (falsifying [`Self::is_chain`]); the conjunction
    /// `!false && !false == true`. This is the SAME fixture the sibling
    /// [`Self::is_chain`] and [`Self::is_antichain`] BOTH reject at —
    /// pinning the DISCRIMINATING positive-arm catch for the (mixed)
    /// cell of the three-cell face. Pinned as
    /// `resource_limits_is_mixed_holds_on_the_mixed_slice_with_one_comparable_and_one_antichain_pair`.
    ///
    /// **Trichotomy exhaustiveness at arity ≥3 with distinct
    /// elements**: for every slice `postures` with `len() >= 2` and
    /// pairwise-distinct elements, EXACTLY ONE of [`Self::is_chain`],
    /// [`Self::is_antichain`], [`Self::is_mixed`] returns `true` — the
    /// three cells partition the set-level verdict surface at every
    /// non-degenerate slice. At arity < 2 (empty and singleton) the
    /// verdict surface degenerates to the vacuous-truth (T, T, F)
    /// cell; at arity ≥2 with any duplicated element the verdict
    /// surface degenerates to the chain-only (T, F, F) cell (chain
    /// wins via reflexivity, antichain drops via irreflexivity).
    /// Pinned as
    /// `resource_limits_is_chain_is_antichain_and_is_mixed_partition_the_verdict_surface_on_distinct_slices`.
    ///
    /// Encoded as the boolean conjunction of the negations of the two
    /// just-lifted set-level projections — one implementation site, ZERO
    /// new pair-level primitive delegations, `const fn` throughout via
    /// the underlying `const fn` bodies. The doubly-indexed all-pairs
    /// walk lives at ONE site (the [`Self::is_chain`] +
    /// [`Self::is_antichain`] implementations), and this projection
    /// factors THROUGH both without reopening it.
    ///
    /// Pre-lift, a caller wanting "is this slice a mixed subset (neither
    /// chain nor antichain)?" composed the doubly-indexed
    /// `!postures.iter().enumerate().all(|(i, a)|
    /// postures[i + 1..].iter().all(|b| a.is_comparable(*b))) &&
    /// !postures.iter().enumerate().all(|(i, a)|
    /// postures[i + 1..].iter().all(|b| a.is_incomparable(*b)))`
    /// two-scaffolding conjunction at every prospective callsite —
    /// the SAME PRIME DIRECTIVE ≥2 pattern the pair of just-lifted
    /// projections' pre-lift shapes carried, doubled. Post-lift the
    /// mixed-set verdict binds at ONE typed method the algebra exposes.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition
    /// preserves proofs; the set-level mixed-set verdict on N preset-
    /// carried resource proofs is itself a typed named `bool` predicate
    /// composing them via the underlying set-level [`Self::is_chain`] +
    /// [`Self::is_antichain`] projections. THEORY.md §V.1 — knowable
    /// platform; the doubly-negated set-level conjunction becomes a
    /// TYPE-level operation on the posture algebra rather than an inline
    /// negation-composition at every consumer that decides "is this
    /// slice a mixed subset?"
    ///
    /// Frontier inspiration: the order-theoretic notion of a MIXED
    /// subset (a subset that is neither a chain nor an antichain) sits
    /// at the interior of the (chain, antichain, mixed) trichotomy that
    /// canonicalizes the SET-LEVEL verdict surface of a poset — a slice
    /// whose Hasse-diagram induced subgraph carries both order-comparable
    /// AND order-incomparable edges. Dilworth's width invariant and the
    /// dual Mirsky theorem (a poset's height equals the minimum number of
    /// antichains covering it) both take mixed sets as their non-trivial
    /// inputs — a chain has width 1 and a mixed set of width ≥2 is
    /// exactly where the width invariant becomes informative. Haskell's
    /// `Data.List` idiom of `not . isChain && not . isAntichain`
    /// composition on a partial-order carrier. Translation through
    /// pleme-io primitives: the boolean conjunction of the negations of
    /// the just-lifted set-level projections, no new dep, no supertrait
    /// bound, `const fn` throughout.
    #[must_use]
    pub const fn is_mixed(postures: &[Self]) -> bool {
        !Self::is_chain(postures) && !Self::is_antichain(postures)
    }

    /// Boolean `leq`-conjunction across every CONSECUTIVE pair of a slice
    /// of postures — `postures` is ASCENDING (a leq-monotone sequence on
    /// the pointwise partial order) iff every consecutive pair
    /// `(postures[i], postures[i + 1])` satisfies
    /// `postures[i].leq(postures[i + 1])`.
    ///
    /// The SEQUENCE-LEVEL N-ary peer of [`Self::leq`] one CARDINALITY axis
    /// over on the (pairwise, sequence-level) primitive surface — the
    /// DIRECT SEQUENCE-LEVEL LIFT of the pair-level partial-order primitive
    /// through a consecutive-index walk. Opens a NEW AXIS one CONSECUTIVE-
    /// VS-ALL-PAIRS step over from the just-lifted set-level projections
    /// [`Self::is_chain`] / [`Self::is_antichain`] / [`Self::is_mixed`]:
    /// where the set-level triple quantifies over EVERY distinct pair
    /// `(i, j)` with `j > i`, this projection quantifies over only the
    /// `n - 1` CONSECUTIVE pairs `(i, i + 1)`. The two axes lift the same
    /// pair-level primitive family through DIFFERENT quantification shapes
    /// — the set-level triple carries UNORDERED verdicts about the whole
    /// slice's pairwise-relation graph, while this projection carries an
    /// ORDER-SENSITIVE verdict about the slice's specific enumeration.
    ///
    /// **Transitivity theorem — `is_ascending ⇒ is_chain`**: for every
    /// slice `postures`, `Self::is_ascending(postures) == true` implies
    /// `Self::is_chain(postures) == true`. The pointwise partial order is
    /// TRANSITIVE (`a.leq(b) && b.leq(c) ⇒ a.leq(c)` — verified structurally
    /// by [`Self::leq`]'s six-axis pointwise `<=` conjunction, since each
    /// `usize <=` is transitive), so a consecutive-pair leq-chain closes
    /// under transitive composition into the all-pairs leq-chain; every
    /// (i, j) pair with j > i decomposes into the composition of
    /// consecutive-pair leqs (i, i+1), (i+1, i+2), ..., (j-1, j), which
    /// transitivity collapses into `postures[i].leq(postures[j])`, and
    /// `leq` implies `is_comparable`. This is a LOAD-BEARING substrate-
    /// level theorem: the sequence-level ascending verdict is strictly
    /// STRONGER than the set-level chain verdict (a chain admits any
    /// permutation of a leq-sorted enumeration; an ascending sequence
    /// admits exactly the leq-sorted one). Pinned as
    /// `resource_limits_is_ascending_implies_is_chain_on_every_shipped_slice`.
    ///
    /// **Empty-slice vacuous truth**: `ResourceLimits::is_ascending(&[])
    /// == true` — the empty conjunction is vacuously true; the empty
    /// slice contains no consecutive pairs to reject. Peer of
    /// [`Self::is_chain`]'s empty-slice identity one CONSECUTIVE-VS-ALL-
    /// PAIRS axis over: both cells of the (set-level, sequence-level)
    /// projection pair AGREE at the empty slice on the vacuous-truth
    /// verdict — the two cells coincide at the empty face of the N-ary
    /// verdict surface. Pinned as
    /// `resource_limits_is_ascending_empty_slice_is_vacuously_true`.
    ///
    /// **Singleton vacuous truth**: `ResourceLimits::is_ascending(&[a])
    /// == true` for every posture `a` — a one-element slice contains no
    /// consecutive pairs, so the walk never enters the loop and returns
    /// `true` vacuously. Peer of [`Self::is_chain`]'s singleton-vacuous-
    /// truth identity: both projections AGREE at singleton slices too.
    /// Pinned as
    /// `resource_limits_is_ascending_singleton_is_vacuously_true`.
    ///
    /// **Diagonal-duplicate identity**: `ResourceLimits::is_ascending(
    /// &[a, a]) == true` for every posture `a` — [`Self::leq`] is
    /// REFLEXIVE (`a.leq(a) == true` via each axis's `<=` reflexivity), so
    /// the single consecutive pair `(0, 1)` binds `a.leq(a) == true` and
    /// the conjunction holds. AGREES with [`Self::is_chain`]'s diagonal-
    /// duplicate verdict at every diagonal-duplicate slice — the two
    /// projections diverge only where the ORDER matters, and duplicated
    /// elements carry no ordering information to distinguish them.
    /// Pinned as `resource_limits_is_ascending_of_diagonal_duplicate_is_true`.
    ///
    /// **Ascending shipped-preset triple closure**: `ResourceLimits::
    /// is_ascending(&[EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS]) == true` — the shipped-preset triple
    /// on the bounded-lattice diagonal is a leq-monotone ascending
    /// sequence (`EMPTY.leq(DEFAULT).leq(UNBOUNDED)` pointwise), so every
    /// consecutive pair satisfies `leq` and the conjunction closes.
    /// Pinned as
    /// `resource_limits_is_ascending_holds_on_the_ascending_shipped_preset_triple`.
    ///
    /// **Descending shipped-preset triple rejection**: `ResourceLimits::
    /// is_ascending(&[UNBOUNDED_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,
    /// EMPTY_RESOURCE_LIMITS]) == false` — the reversed enumeration of the
    /// same shipped-preset chain is a leq-monotone DESCENDING sequence, so
    /// the first consecutive pair binds `UNBOUNDED.leq(DEFAULT) == false`
    /// and the walk rejects at index 0. The DIRECT ORDER-SENSITIVITY
    /// FALSIFICATION of the ascending closure one PERMUTATION axis over on
    /// the SAME chain — [`Self::is_chain`] accepts BOTH orderings (its
    /// verdict is order-INSENSITIVE), while this projection accepts only
    /// the leq-sorted one. Pinned as
    /// `resource_limits_is_ascending_rejects_the_descending_shipped_preset_triple`.
    ///
    /// **Non-monotone chain permutation rejection**: `ResourceLimits::
    /// is_ascending(&[DEFAULT_RESOURCE_LIMITS, EMPTY_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS]) == false` — the third permutation of
    /// the shipped-preset chain has `DEFAULT.leq(EMPTY) == false` at the
    /// first consecutive pair, so the walk rejects, EVEN THOUGH the slice
    /// is a chain ([`Self::is_chain`] accepts it). Pins the DISCRIMINATING
    /// arm between the sequence-level and set-level projections: a chain
    /// permutation that is neither ascending nor descending falsifies BOTH
    /// sequence-level projections while both set-level projections accept
    /// it. Pinned as
    /// `resource_limits_is_ascending_rejects_the_non_monotone_chain_permutation`.
    ///
    /// **Hand-authored antichain rejection**: `ResourceLimits::is_ascending(
    /// &[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE]) == false`
    /// — the two hand-authored asymmetric postures are incomparable
    /// (neither `MID.leq(OTHER)` nor `OTHER.leq(MID)`), so the single
    /// consecutive pair rejects. Pinned as
    /// `resource_limits_is_ascending_rejects_the_hand_authored_antichain_pair`.
    ///
    /// Encoded as a singly-indexed const-`while` walk (`i in 0..n-1`) with
    /// one [`Self::leq`] delegation per consecutive pair — the SAME walk
    /// structure the standard-library `<[T]>::is_sorted_by` idiom carries
    /// on a totally-ordered carrier, generalized to the partial-order
    /// [`Self::leq`] primitive here. `const fn` throughout via the
    /// underlying `const fn` [`Self::leq`] body — a caller can pin an
    /// ascending-sequence identity at compile time
    /// (`const _: () = assert!(ResourceLimits::is_ascending(&[
    /// EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS]));`) — a build-break rather than a
    /// runtime `assert!` on the first execution.
    ///
    /// Pre-lift, a caller wanting "is this slice a leq-monotone ascending
    /// sequence?" composed the singly-indexed
    /// `postures.windows(2).all(|w| w[0].leq(w[1]))` two-primitive
    /// scaffolding at every prospective callsite — the SAME PRIME
    /// DIRECTIVE ≥2 pattern the set-level projections' pre-lift shapes
    /// carried, one CARDINALITY axis over. Post-lift the ascending
    /// verdict binds at ONE typed method the algebra exposes, and the
    /// consecutive-pair walk lives at ONE implementation site — the peer
    /// [`Self::is_descending`] shares the SAME walk structure and diverges
    /// only on the pair-level primitive it delegates to (`geq` in place of
    /// `leq`).
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
    /// proofs; the sequence-level ascending verdict on N preset-carried
    /// resource proofs is itself a typed named `bool` predicate composing
    /// them via the underlying pair-level [`Self::leq`] projection.
    /// THEORY.md §V.1 — knowable platform; the consecutive-pair leq
    /// conjunction becomes a TYPE-level operation on the posture algebra
    /// rather than an inline windowed scaffolding at every consumer that
    /// decides "is this slice a leq-monotone ascending sequence?"
    ///
    /// Frontier inspiration: the order-theoretic notion of a MONOTONE
    /// SEQUENCE on a poset — the standard-library `Iterator::is_sorted`
    /// / `<[T]>::is_sorted_by` idioms carry the totally-ordered case;
    /// Haskell's `Data.List` idiom of `and . zipWith leq xs . tail xs`
    /// on a partial-order carrier; Coq's `Sorted` inductive on lists over
    /// a `Relation`. Translation through pleme-io primitives: the singly-
    /// indexed consecutive-pair walk directly, with [`Self::leq`] as the
    /// pair-level primitive, no new dep, no supertrait bound, `const fn`
    /// throughout. The (ascending, descending) sequence-level pair opens
    /// the door to `is_strictly_ascending` / `is_strictly_descending` via
    /// [`Self::lt`] / [`Self::gt`] one STRICTNESS axis over, and to
    /// `is_monotone` (`is_ascending || is_descending`) one DIRECTION-
    /// AGNOSTIC axis over, at future callsites.
    #[must_use]
    pub const fn is_ascending(postures: &[Self]) -> bool {
        let n = postures.len();
        let mut i = 0;
        while i + 1 < n {
            if !postures[i].leq(postures[i + 1]) {
                return false;
            }
            i += 1;
        }
        true
    }

    /// Boolean `geq`-conjunction across every CONSECUTIVE pair of a slice
    /// of postures — `postures` is DESCENDING (a geq-monotone sequence on
    /// the pointwise partial order) iff every consecutive pair
    /// `(postures[i], postures[i + 1])` satisfies
    /// `postures[i].geq(postures[i + 1])`.
    ///
    /// The DIRECT SEQUENCE-LEVEL DUAL of [`Self::is_ascending`] one PAIR-
    /// LEVEL-PRIMITIVE axis over — where `is_ascending` delegates to
    /// [`Self::leq`], this projection delegates to [`Self::geq`]. The
    /// two together close the (ascending, descending) two-cell face on
    /// the sequence-level pairwise-relation surface, exactly one
    /// CONSECUTIVE-VS-ALL-PAIRS axis over from the set-level (chain,
    /// antichain) two-cell face [`Self::is_chain`] / [`Self::is_antichain`]
    /// pin, and exactly one PAIR-LEVEL-PRIMITIVE axis over from the
    /// (leq, geq) pair-level two-cell face [`Self::leq`] / [`Self::geq`]
    /// pin one CARDINALITY axis down.
    ///
    /// The (ascending, descending) pair is NOT a partition of the
    /// sequence-level verdict surface: a slice of ≥3 postures whose
    /// consecutive-pair verdicts mix leq and geq (or contain any
    /// incomparable consecutive pair) is neither ascending nor
    /// descending, so the two sequence-level projections carry a THREE-
    /// cell face (ascending, descending, non-monotone) at the sequence
    /// level whose ends the two projections lifted here pin. The
    /// (T, T) corner is achievable at every diagonal-duplicate slice
    /// AND at every empty-or-singleton slice — [`Self::leq`] and
    /// [`Self::geq`] are BOTH REFLEXIVE, so a repeated element passes
    /// both consecutive-pair conjunctions.
    ///
    /// **Transitivity theorem — `is_descending ⇒ is_chain`**: for every
    /// slice `postures`, `Self::is_descending(postures) == true` implies
    /// `Self::is_chain(postures) == true`, by the SAME transitive
    /// composition [`Self::is_ascending`] carries one PAIR-LEVEL-PRIMITIVE
    /// axis over — the pointwise partial order is transitive under `geq`
    /// (by [`Self::geq`]'s composition `other.leq(self)` and `leq`'s six-
    /// axis transitivity), so a consecutive-pair geq-chain closes under
    /// transitive composition into an all-pairs geq-chain, and `geq`
    /// implies `is_comparable`. Pinned as
    /// `resource_limits_is_descending_implies_is_chain_on_every_shipped_slice`.
    ///
    /// **Empty-slice vacuous truth**: `ResourceLimits::is_descending(&[])
    /// == true` — the empty conjunction is vacuously true. Peer of
    /// [`Self::is_ascending`]'s empty-slice identity one PAIR-LEVEL-
    /// PRIMITIVE axis over: both cells of the (ascending, descending)
    /// sequence-level pair AGREE at the empty slice. Pinned as
    /// `resource_limits_is_descending_empty_slice_is_vacuously_true`.
    ///
    /// **Singleton vacuous truth**: `ResourceLimits::is_descending(&[a])
    /// == true` for every posture `a`. Pinned as
    /// `resource_limits_is_descending_singleton_is_vacuously_true`.
    ///
    /// **Diagonal-duplicate identity**: `ResourceLimits::is_descending(
    /// &[a, a]) == true` for every posture `a` — [`Self::geq`] is
    /// REFLEXIVE, so the single consecutive pair binds `a.geq(a) == true`.
    /// AGREES with [`Self::is_ascending`]'s diagonal-duplicate verdict —
    /// both leq and geq carry reflexivity, so the sequence-level (T, T)
    /// corner opens at every diagonal-duplicate slice, distinct from the
    /// set-level (T, F) verdict [`Self::is_chain`] / [`Self::is_antichain`]
    /// carry on the same slice. Pinned as
    /// `resource_limits_is_descending_of_diagonal_duplicate_is_true`.
    ///
    /// **Descending shipped-preset triple closure**: `ResourceLimits::
    /// is_descending(&[UNBOUNDED_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,
    /// EMPTY_RESOURCE_LIMITS]) == true` — the reversed enumeration of the
    /// shipped-preset chain is a geq-monotone descending sequence. The
    /// DIRECT MIRROR of [`Self::is_ascending`]'s ascending closure one
    /// PERMUTATION axis over — pinning the two closures on the SAME chain
    /// in REVERSED orderings closes the (ascending, descending) sequence-
    /// level pair on the shipped chain. Pinned as
    /// `resource_limits_is_descending_holds_on_the_descending_shipped_preset_triple`.
    ///
    /// **Ascending shipped-preset triple rejection**: `ResourceLimits::
    /// is_descending(&[EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,
    /// UNBOUNDED_RESOURCE_LIMITS]) == false` — the ascending-sorted
    /// enumeration binds `EMPTY.geq(DEFAULT) == false`. The DIRECT
    /// FALSIFICATION of [`Self::is_ascending`]'s ascending closure one
    /// CELL axis over on the SAME slice. Pinned as
    /// `resource_limits_is_descending_rejects_the_ascending_shipped_preset_triple`.
    ///
    /// **Hand-authored antichain rejection**: `ResourceLimits::is_descending(
    /// &[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE]) == false`
    /// — the two hand-authored asymmetric postures are incomparable, so
    /// the single consecutive pair rejects. Pinned as
    /// `resource_limits_is_descending_rejects_the_hand_authored_antichain_pair`.
    ///
    /// Encoded as a singly-indexed const-`while` walk (`i in 0..n-1`)
    /// with one [`Self::geq`] delegation per consecutive pair — the SAME
    /// iteration structure as [`Self::is_ascending`] one PAIR-LEVEL-
    /// PRIMITIVE axis over, with only the inner primitive swapped between
    /// the two. `const fn` throughout via the underlying `const fn`
    /// [`Self::geq`] body.
    ///
    /// Pre-lift, a caller wanting "is this slice a geq-monotone descending
    /// sequence?" composed the singly-indexed
    /// `postures.windows(2).all(|w| w[0].geq(w[1]))` two-primitive
    /// scaffolding at every prospective callsite. Post-lift the
    /// descending verdict binds at ONE typed method the algebra exposes.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
    /// proofs. THEORY.md §V.1 — knowable platform.
    ///
    /// Frontier inspiration: `Iterator::is_sorted_by` with a reversed
    /// comparator on a totally-ordered carrier; Coq's `StronglySorted`
    /// on a `<=` relation applied with the argument order flipped.
    /// Translation through pleme-io primitives: the singly-indexed
    /// consecutive-pair walk directly, with [`Self::geq`] as the pair-
    /// level primitive.
    #[must_use]
    pub const fn is_descending(postures: &[Self]) -> bool {
        let n = postures.len();
        let mut i = 0;
        while i + 1 < n {
            if !postures[i].geq(postures[i + 1]) {
                return false;
            }
            i += 1;
        }
        true
    }
}

/// Cache key: (macro name, SipHash-2-4 of args). We hash `Sexp` directly via
/// its manual `Hash` impl — no serde_json round-trip per cache lookup.
type CacheKey = (String, u64);

/// A registered macro definition.
#[derive(Debug, Clone)]
pub struct MacroDef {
    pub name: String,
    pub params: MacroParams,
    /// The template body (usually a Quasiquote).
    pub body: Sexp,
}

impl MacroDef {
    /// Project the macro body to its substitution-walked form: the inner of
    /// the outer `Sexp::Quasiquote` when `(defmacro NAME (PARAMS) `(...))`
    /// authored the body through the canonical quasi-quote affordance, OR
    /// `&self.body` verbatim when authored without one. The two expansion
    /// strategies — bytecode (`compile_template`) and substitute (`apply`'s
    /// substitute fallback) — both walk this projection, never the raw
    /// `body`, because the outer quasi-quote is the syntactic "you're
    /// inside a template" marker and the substitution semantics operate on
    /// what's INSIDE it. Naming the projection lifts the inline
    /// `match &def.body { Sexp::Quasiquote(inner) => inner.as_ref(),
    /// other => other }` peel that appeared verbatim at BOTH sites — well
    /// past the ≥2 PRIME-DIRECTIVE trigger — into ONE function the two
    /// strategies share, so a regression that drifts ONE strategy's
    /// body-projection from the other (e.g. one path peels twice and the
    /// other peels once, or one path treats `Sexp::Quote(...)` as a
    /// template marker and the other doesn't) becomes structurally
    /// impossible: there is exactly one implementation both strategies
    /// call.
    ///
    /// Single-level peel by design: a nested `` ``form `` body unwraps to
    /// `` `form `` (the inner quasi-quote stays as-is), matching the v0
    /// "no nested quasi-quotes" scope the module preamble declares. A
    /// non-quasi-quote body — `(defmacro NAME (PARAMS) BODY)` where BODY
    /// is a plain `Sexp::List` / `Sexp::Atom` — returns `&self.body`
    /// verbatim, the "other" arm of the legacy match. The borrow is
    /// strictly `&'a Sexp` rooted in `&'a self.body` (no clone, no
    /// allocation); both `compile_node` (bytecode path) and `substitute`
    /// (substitute path) consume the projection immediately and never
    /// outlive the borrow.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition; two
    /// inline copies of the body-peel match is the ≥2 trigger, and the
    /// substrate names the projection ONCE so authoring surfaces and
    /// future expansion strategies (a third interpreter? a JIT? a
    /// debugger that wants to render the body without the outer
    /// quasi-quote marker?) bind to ONE primitive. THEORY.md §II.1
    /// invariant 2 — free middle; the two expansion strategies emit
    /// IDENTICAL output for the same (macro, args) pair, and sharing one
    /// body-projection makes that per-strategy agreement structural at
    /// the entry to the walker, not a two-site discipline the
    /// `expansion_layers_agree_on_output_and_cache_wins` benchmark only
    /// observes after the fact.
    #[must_use]
    pub fn template_body(&self) -> &Sexp {
        match &self.body {
            Sexp::Quasiquote(inner) => inner.as_ref(),
            other => other,
        }
    }
}

/// A macro's parameter list — structurally "zero or more required
/// positional params, then zero or more `&optional` params, then an OPTIONAL
/// single `&rest` param." This is the canonical Lisp lambda-list ordering
/// (Common Lisp `(req* &optional opt* &rest r)`), made a TYPE.
///
/// This shape promotes the invariants the reader ([`parse_params`])
/// previously upheld only by construction — `&rest` is LAST, there is AT MOST
/// ONE of it, and (now) `&optional` params sit strictly between the required
/// run and the rest — from *unobserved discipline* to *unrepresentable
/// state*. The prior representation `Vec<Param>` admitted `[Rest, Required]`
/// (a `&rest` in the middle) and `[Rest, Rest]` (two of them); both are
/// nonsense the binder cannot honor, yet the type permitted them. The flat
/// param INDEX that the bytecode references (`Subst(idx)` / `Splice(idx)`)
/// and the positional binder both walk would silently misalign on such a
/// `Vec` — a `Rest` at index 0 of `[Rest, Required]` makes the binder grab
/// every arg, then fail to bind the trailing `Required`, mapping the
/// template's index-1 substitution onto the wrong value. `MacroParams`
/// cannot express either shape: `rest` is exactly one `Option<String>`,
/// always conceptually after every `required` then every `optional` name,
/// and the three kinds live in distinct fields whose order is fixed by the
/// struct, not by a discipline the binder trusts a `Vec` to have upheld.
///
/// `optional` differs from `required` in the binder, not the index contract:
/// a required name with no arg at its position is a `MissingMacroArg`
/// rejection; an optional name with no arg binds to its declared default form
/// — `Sexp::Nil` when none was given, the parsed default literal when one was.
/// Both shapes — `&optional x` and `&optional (x 5)` — are now structural in
/// the typed [`OptionalParam`] entry rather than smeared across a flat
/// `Vec<String>` the binder would have had to discover the default for
/// elsewhere.
///
/// The flat-index contract the template bytecode depends on is preserved by
/// [`MacroParams::names`]: index `0..required.len()` are the required names
/// in order, the next `optional.len()` indices are the optional names, and
/// the final index (if present) is the rest name — the canonical lambda-list
/// order. [`MacroParams::bind`] produces the per-index bound values in that
/// same order, so the name-keyed (`bind_args` → `substitute`) and
/// index-keyed (`apply_compiled`) expansion strategies share ONE binder and
/// can never drift.
///
/// Theory anchor: THEORY.md §V.1 — knowable platform / "make invalid states
/// unrepresentable"; the lambda-list ordering (required → optional → rest,
/// rest-is-last, at-most-one-rest) becomes structural. THEORY.md §VI.1 —
/// generation over composition; the positional binding loop (verbatim in
/// both `bind_args` and `apply_compiled`, the ≥2 PRIME-DIRECTIVE trigger) is
/// lifted to ONE owner, `bind`, which the optional arm extends in one place.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MacroParams {
    pub required: Vec<String>,
    pub optional: Vec<OptionalParam>,
    pub rest: Option<String>,
}

/// One entry in a macro's `&optional` section — a name plus an optional
/// default form. The two surface shapes the reader admits collapse into this
/// single typed shape:
///
///   * `&optional x`        ⇒ `OptionalParam { name: "x", default: None }`
///   * `&optional (x 5)`    ⇒ `OptionalParam { name: "x", default: Some(Int(5)) }`
///
/// The `default: Option<Sexp>` slot makes the per-param default-form a
/// FIELD on each optional entry, not a discipline a sibling `Vec<Sexp>` would
/// have had to maintain in lock-step with `Vec<String>`. Without this shape
/// the binder cannot tell "no arg supplied, no default declared → bind nil"
/// from "no arg supplied, default `5` declared → bind `5`": both would
/// collapse onto `Sexp::Nil`, the precise silent misalignment the typed
/// shape exists to forbid.
///
/// The default is the LITERAL `Sexp` — there is no evaluator in v0, so a
/// `(x (foo 1))` spec parks `(foo 1)` verbatim as the bound value when `x`'s
/// arg is absent. This is the no-evaluator floor of CL semantics: any
/// arbitrary form is admitted at the gate, what it MEANS is the next layer's
/// concern. The default is parsed exactly once at `defmacro`/
/// `defpoint-template`/`defcheck` time (inside `parse_params`); every call
/// to that macro consumes the same parsed `Sexp` via `Clone`, never re-
/// reading the source.
///
/// Theory anchor: THEORY.md §V.1 — knowable platform / "make invalid states
/// unrepresentable"; the (name, default?) pair is one entry rather than two
/// parallel `Vec`s a regression could desynchronize. THEORY.md §VI.1 —
/// generation over composition; the binder's optional arm consults
/// `param.default` in ONE place, so the substitute and bytecode strategies
/// inherit identical default-resolution semantics from the shared `bind`.
#[derive(Debug, Clone, PartialEq)]
pub struct OptionalParam {
    pub name: String,
    pub default: Option<Sexp>,
}

impl OptionalParam {
    /// `&optional x` — a bare optional name with no default. An absent
    /// argument binds to `Sexp::Nil` (the no-default-form floor).
    #[must_use]
    pub fn bare(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            default: None,
        }
    }

    /// `&optional (x DEFAULT)` — an optional with a default form. An absent
    /// argument binds to `default.clone()`.
    #[must_use]
    pub fn with_default(name: impl Into<String>, default: Sexp) -> Self {
        Self {
            name: name.into(),
            default: Some(default),
        }
    }

    /// The bound value when an absent call leaves this optional slot unfilled:
    /// the declared default form (cloned) when one was authored, OR the
    /// canonical `Sexp::Nil` floor when none was — the CL `&optional` no-
    /// default-form floor. ONE named primitive on the typed [`OptionalParam`]
    /// every absent-call binder consults; before this lift the same two-arm
    /// fallback `param.default.clone().unwrap_or(Sexp::Nil)` lived inline at
    /// [`MacroParams::bind`]'s optional arm, and a future absence-resolver
    /// (the kwarg-gate's typed-default fill? a future `&supplied-p` slot's
    /// "was this defaulted?" bit?) would have had to re-derive the same
    /// two-arm fallback at every site that walks the optional run.
    ///
    /// The projection IS the structural identity binding the typed
    /// `default: Option<Sexp>` slot to its bound-value contract:
    ///   * `bare(name).resolved_default()` is `Sexp::Nil` (the no-default
    ///     floor — `default.is_none()`).
    ///   * `with_default(name, d).resolved_default()` is `d.clone()` (the
    ///     declared default — `default = Some(d)` projected through Clone).
    ///
    /// `resolved_default()` is the typed accessor companion to the
    /// `bare` / `with_default` constructors: those two constructors define
    /// the ONLY admissible shapes of the typed `default` slot, and this
    /// accessor names the BOUND-VALUE projection both shapes yield at the
    /// binder's absence arm. Together the three close the `OptionalParam`'s
    /// self-contained typed surface — every authored shape lands through ONE
    /// of two constructors, and every absent-call binder reads through this
    /// ONE accessor.
    ///
    /// Returns an owned `Sexp` (not `&Sexp`) because the binder pushes the
    /// resolved default into a fresh `Vec<Sexp>` slot at every absent call;
    /// the `default.clone()` projection is the same allocation the pre-lift
    /// inline expression performed, just named at the typed boundary. The
    /// `Sexp::Nil` floor is a free per-call construction (a unit variant
    /// with no payload), so the no-default path is free of allocation
    /// beyond the function return slot.
    ///
    /// Theory anchor: THEORY.md §V.1 — knowable platform / "make invalid
    /// states unrepresentable"; the "no-default-form floor" structural
    /// concept becomes a NAMED projection on [`OptionalParam`] rather than
    /// re-derived `param.default.clone().unwrap_or(Sexp::Nil)` arithmetic
    /// at every site that walks the bound optional run. Authoring tools
    /// (REPL, LSP, `tatara-check`) that want to render "this optional
    /// binds to {default-form|nil} when absent" bind to ONE method on the
    /// typed param. THEORY.md §VI.1 — generation over composition; the
    /// constructor pair `bare` / `with_default` defines the typed shapes
    /// and the `resolved_default` accessor names the symmetric
    /// bound-value projection — the typed accessor companion. THEORY.md
    /// §II.1 invariant 2 — free middle; both expansion strategies route
    /// through the SHARED `MacroParams::bind`, so the new accessor is
    /// exposed to the bytecode and substitute paths uniformly via that
    /// shared binder.
    #[must_use]
    pub fn resolved_default(&self) -> Sexp {
        self.default.clone().unwrap_or(Sexp::Nil)
    }
}

/// The value carrier a macro call binds its arguments in.
///
/// [`MacroParams::bind_carrier`] is the single positional binder every
/// expansion path routes through; this trait is the only thing that varies
/// between those paths. It names the two — and only two — places a binder
/// must SYNTHESIZE a value the caller never wrote:
///
///   * [`Self::lift_default`] — an `&optional` slot the call left unfilled
///     binds to the declared default form (or the `Sexp::Nil` floor). The
///     default is authored as plain `Sexp` at `defmacro` time, so each
///     carrier says how a template literal enters it.
///   * [`Self::collect_rest`] — the `&rest` slot collects the surplus args
///     into ONE value. `Sexp` wraps them in `Sexp::List`; a span-carrying
///     carrier additionally has to decide what span the synthesized list
///     wears.
///
/// Everything else in the binder — the required run, the arity rejections,
/// the required→optional→rest ordering — is carrier-independent and lives
/// exactly once.
///
/// `Site` is the per-call synthesis context. It is `()` for `Sexp`, whose
/// values carry no position; a span-carrying carrier sets it to the macro
/// CALL SITE, because a value the call never supplied has no source position
/// of its own and the call site is the honest place to point an error at.
///
/// Theory anchor: THEORY.md §V.1 — knowable platform; "which lambda-list
/// shapes does this expansion path accept?" stops being a per-path answer.
/// THEORY.md §VI.1 — generation over composition.
pub trait MacroArgCarrier: Clone {
    /// Per-call synthesis context — `()` when the carrier needs none.
    type Site: Copy;

    /// Lift a template-authored default form into this carrier, for an
    /// `&optional` slot the call left unfilled.
    fn lift_default(default: &Sexp, site: Self::Site) -> Self;

    /// Collect the `&rest` surplus into one carrier value.
    fn collect_rest(items: Vec<Self>, site: Self::Site) -> Self;
}

impl MacroArgCarrier for Sexp {
    /// `Sexp` carries no position, so there is nothing to thread — the unit
    /// site is the structural statement that this carrier synthesizes values
    /// without context.
    type Site = ();

    fn lift_default(default: &Sexp, (): ()) -> Self {
        default.clone()
    }

    fn collect_rest(items: Vec<Self>, (): ()) -> Self {
        Sexp::List(items)
    }
}

impl MacroParams {
    /// Canonical `&rest` marker — the ONE typed `&'static str` on
    /// [`MacroParams`] the parser's rest-slot dispatch specialises on.
    /// The Common-Lisp lambda-list `&rest` keyword names the position
    /// at which the parser stops collecting `required` / `optional`
    /// names and binds every subsequent arg into a `Sexp::List` at the
    /// [`Self::rest`] slot. Sibling posture to [`Self::OPTIONAL_MARKER`]
    /// (`"&optional"`) on the same lambda-list-keyword algebra layer:
    /// the two constants are the closed set of Common-Lisp
    /// lambda-list-keyword `&'static str` markers the parser's typed
    /// dispatch specialises on, sharing the canonical `char` lead byte
    /// [`Self::LAMBDA_LIST_KEYWORD_LEAD`] (`'&'`).
    ///
    /// Pre-lift the same `"&rest"` bytes lived inline as a single
    /// `s == "&rest"` comparison inside [`parse_params`], with the two
    /// typed `&'static str` markers the CL lambda-list algebra
    /// specialises on smeared across TWO parallel `s == "..."` inline
    /// comparisons at the SAME dispatch cascade. Post-lift the
    /// (`&rest` rest-slot marker, canonical `&'static str`) pairing
    /// binds at ONE constant on the typed [`MacroParams`] algebra that
    /// both the parser AND any future authoring / rendering surface
    /// route through; a refactor that swaps the marker (e.g. a
    /// Clojure-compat port to `&`  ONLY, an Elisp-compat port that
    /// keeps `&rest` as-is, a Scheme R7RS-style port to `.` for the
    /// dotted-pair rest slot) touches ONE constant rather than the
    /// two inline literals scattered across the parser AND the
    /// diagnostic message surfaces.
    ///
    /// Structural round-trip contract:
    /// `Self::REST_MARKER.starts_with(Self::LAMBDA_LIST_KEYWORD_LEAD)`
    /// — the projection law binding the `&'static str` marker to its
    /// canonical `char` lead byte on the typed algebra, pinned by
    /// `macro_params_rest_marker_prefixed_by_lambda_list_keyword_lead`.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 2 — free middle; the
    /// (`&rest` rest-slot marker, canonical `&'static str`) pairing
    /// binds at ONE `pub const` on the typed [`MacroParams`] algebra
    /// regardless of which parser / authoring surface reaches in.
    /// THEORY.md §V.1 — knowable platform; the canonical CL lambda-
    /// list `&rest` keyword becomes a TYPE-level constant on the
    /// typed macro-params algebra rather than an inline `"&rest"`
    /// literal at the parser's rest-slot dispatch arm.
    pub const REST_MARKER: &'static str = "&rest";

    /// Canonical `&optional` marker — the ONE typed `&'static str` on
    /// [`MacroParams`] the parser's optional-section dispatch
    /// specialises on. The Common-Lisp lambda-list `&optional` keyword
    /// names the position at which the parser switches subsequent
    /// bare-symbol names from the `required` bin to the `optional`
    /// bin, until either the end of the param list OR the
    /// [`Self::REST_MARKER`] terminal is reached. Sibling posture to
    /// [`Self::REST_MARKER`] (`"&rest"`) on the same lambda-list-
    /// keyword algebra layer: the two constants are the closed set of
    /// CL lambda-list-keyword `&'static str` markers the parser's
    /// typed dispatch specialises on, sharing the canonical `char`
    /// lead byte [`Self::LAMBDA_LIST_KEYWORD_LEAD`] (`'&'`).
    ///
    /// Structural round-trip contract:
    /// `Self::OPTIONAL_MARKER.starts_with(Self::LAMBDA_LIST_KEYWORD_LEAD)`
    /// — pinned by
    /// `macro_params_optional_marker_prefixed_by_lambda_list_keyword_lead`.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 2 — free middle; the
    /// (`&optional` section-switch marker, canonical `&'static str`)
    /// pairing binds at ONE `pub const` on the typed [`MacroParams`]
    /// algebra regardless of which parser / authoring surface reaches
    /// in. THEORY.md §V.1 — knowable platform; the canonical CL
    /// lambda-list `&optional` keyword becomes a TYPE-level constant
    /// on the typed macro-params algebra rather than an inline
    /// `"&optional"` literal at the parser's optional-section
    /// dispatch arm.
    pub const OPTIONAL_MARKER: &'static str = "&optional";

    /// Canonical `&` LEAD byte shared across [`Self::REST_MARKER`]
    /// (`"&rest"`) and [`Self::OPTIONAL_MARKER`] (`"&optional"`) — the
    /// ONE canonical `char` on the [`MacroParams`] algebra that the
    /// Common-Lisp lambda-list-keyword disjointness contract binds to.
    ///
    /// Sibling posture to the closed set of `pub const` per-role
    /// canonical bytes on the substrate's other closed-set outer
    /// algebras: [`crate::ast::Atom::STR_DELIMITER`] (`'"'`),
    /// [`crate::ast::Atom::STR_ESCAPE_LEAD`] (`'\\'`),
    /// [`crate::ast::Atom::KEYWORD_MARKER_LEAD`] (`':'`),
    /// [`crate::ast::Atom::BOOL_LITERAL_LEAD`] (`'#'`),
    /// [`crate::ast::Sexp::LIST_OPEN`] (`'('`),
    /// [`crate::ast::Sexp::LIST_CLOSE`] (`')'`),
    /// [`crate::ast::Sexp::COMMENT_LEAD`] (`';'`),
    /// [`crate::ast::Sexp::COMMENT_TERM`] (`'\n'`),
    /// [`crate::ast::QuoteForm::SPLICE_DISCRIMINATOR`] (`'@'`), and
    /// every `crate::ast::QuoteForm::lead_char` projection — every
    /// canonical per-role byte the substrate's typed algebras
    /// specialise on is now a `pub const` on its owning closed-set
    /// algebra. This constant closes the CL lambda-list-keyword
    /// family lead byte at the SAME algebra as its two `&'static str`
    /// marker projections so a delimiter swap (e.g. a Racket-compat
    /// port from CL `&rest` / `&optional` to `#!rest` / `#!optional`
    /// keyword-args, a Clojure-compat port to `&` ONLY as the rest
    /// marker) lands at ONE constant on the algebra.
    ///
    /// Structural round-trip contract:
    /// `Self::REST_MARKER.starts_with(Self::LAMBDA_LIST_KEYWORD_LEAD)`
    /// AND
    /// `Self::OPTIONAL_MARKER.starts_with(Self::LAMBDA_LIST_KEYWORD_LEAD)`
    /// — the projection law binding the two `&'static str` markers to
    /// their shared canonical `char` lead byte, pinned by
    /// `macro_params_rest_marker_prefixed_by_lambda_list_keyword_lead`
    /// and
    /// `macro_params_optional_marker_prefixed_by_lambda_list_keyword_lead`.
    ///
    /// Disjointness contract: `LAMBDA_LIST_KEYWORD_LEAD`'s byte MUST
    /// differ from every sibling outer-marker `char` the substrate's
    /// other closed-set algebras specialise on. A collision would
    /// silently break the reader's outer dispatch: an `&`-prefixed
    /// bare atom `&rest` / `&optional` would collide with whichever
    /// marker it aliased. Pinned structurally at
    /// `macro_params_lambda_list_keyword_lead_distinct_from_every_other_algebra_marker`.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 2 — free middle; the
    /// (CL lambda-list-keyword LEAD byte, canonical `'&'`) pairing
    /// binds at ONE constant on the typed [`MacroParams`] algebra
    /// regardless of which of the two `&'static str` marker consumers
    /// reaches in. THEORY.md §V.1 — knowable platform; the canonical
    /// CL lambda-list-keyword LEAD byte becomes a TYPE-level constant
    /// on the substrate algebra rather than an inline `'&'` glyph at
    /// every docstring pinning the family disjointness contract.
    pub const LAMBDA_LIST_KEYWORD_LEAD: char = '&';

    /// Closed-set forced-arity ALL array over the CL lambda-list-keyword
    /// `&'static str` markers the parser's typed dispatch specialises on
    /// — the [`Self::REST_MARKER`] (`"&rest"`) rest-slot marker followed
    /// by the [`Self::OPTIONAL_MARKER`] (`"&optional"`) optional-section
    /// marker, in the canonical CL lambda-list ordering (`&optional`
    /// binds AFTER `&required`, `&rest` binds AFTER `&optional`, so the
    /// declaration walk fires `REST_MARKER` FIRST as the terminal-arm
    /// early return; the ALL array's ordering keys on marker
    /// declaration order in this file, not on parse-time ordering).
    ///
    /// Sibling posture to the closed set of `pub const ALL: [Self; N]`
    /// forced-arity arrays on the substrate's other closed-set outer
    /// algebras: [`crate::ast::AtomKind::ALL`] (`[Self; 6]`),
    /// [`crate::ast::QuoteForm::ALL`] (`[Self; 4]`),
    /// [`crate::error::SexpShape::ALL`] (`[Self; 12]`),
    /// [`crate::error::UnquoteForm::ALL`] (`[Self; 2]`),
    /// [`crate::error::MacroDefHead::ALL`] (`[Self; 3]`) — every
    /// closed-set algebra the substrate carries pins its cardinality at
    /// the declaration site via a `pub const ALL` array whose forced
    /// arity fails compilation if a new variant lands without being
    /// added to the set. `LAMBDA_LIST_KEYWORDS` closes the same shape
    /// on the CL lambda-list-keyword family: a third marker (`&key`
    /// for keyword-args, `&aux` for auxiliaries, `&body` for the
    /// docstring-carrying tail of `defmacro` bodies) extends this ONE
    /// `pub const` + the matching per-role marker `pub const` above,
    /// AND rustc enforces every downstream consumer's closed-set
    /// sweep picks up the new marker at the SAME structural site.
    ///
    /// Pre-lift the two `&'static str` markers were named on the typed
    /// algebra but the family they close was NOT — the two structural
    /// round-trip pins (`_rest_marker_prefixed_by_lambda_list_keyword_
    /// lead` AND `_optional_marker_prefixed_by_lambda_list_keyword_
    /// lead`) each named ONE marker inline as a duplicate 3-line
    /// `assert!(A.starts_with(LEAD), ...)` shape, and the pairwise-
    /// disjointness pin (`_rest_and_optional_markers_pairwise_disjoint`)
    /// named the two markers as a hand-rolled `assert_ne!` pair.
    /// Post-lift the ALL array binds the family at the typed algebra so
    /// every family-wide contract (LEAD-byte round-trip, pairwise
    /// disjointness, membership gate) routes through the ONE array and
    /// a future `&key` / `&aux` extension automatically extends the
    /// sweep without re-deriving per-marker assertions.
    ///
    /// Structural round-trip contract: every element `m` of
    /// `Self::LAMBDA_LIST_KEYWORDS` satisfies
    /// `m.starts_with(Self::LAMBDA_LIST_KEYWORD_LEAD)` — pinned by
    /// `macro_params_every_lambda_list_keyword_prefixed_by_lambda_list_keyword_lead`.
    /// Cardinality contract: `Self::LAMBDA_LIST_KEYWORDS.len() == 2`
    /// pins the current family size at the type level; a future third
    /// marker extends the array's arity AND updates every downstream
    /// pin at ONE structural site. Pairwise-disjointness contract:
    /// every distinct index pair `(i, j)` in `Self::LAMBDA_LIST_KEYWORDS`
    /// satisfies `Self::LAMBDA_LIST_KEYWORDS[i] !=
    /// Self::LAMBDA_LIST_KEYWORDS[j]` — pinned by
    /// `macro_params_lambda_list_keywords_pairwise_distinct`.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 2 — free middle; the
    /// CL lambda-list-keyword family closure binds at ONE `pub const`
    /// on the typed [`MacroParams`] algebra regardless of which
    /// consumer (parser dispatch, family-wide contract sweep,
    /// authoring / rendering surface, `is_lambda_list_keyword`
    /// membership gate) reaches in. THEORY.md §V.1 — knowable
    /// platform; the family's cardinality becomes a TYPE-level
    /// constant on the substrate algebra rather than a per-consumer
    /// hand-rolled enumeration of the two markers. THEORY.md §VI.1 —
    /// generation over composition; the family-wide contract sweeps
    /// (LEAD-byte round-trip, pairwise disjointness, membership gate)
    /// emerge from the composition of TWO substrate primitives (this
    /// `pub const` array + the per-role `pub const REST_MARKER` /
    /// `pub const OPTIONAL_MARKER`) rather than as per-marker inline
    /// assertions the current pins duplicate structurally.
    ///
    /// Frontier inspiration: Common Lisp's `LAMBDA-LIST-KEYWORDS`
    /// standard variable (CLHS §3.4.1) — the runtime-reflectable list
    /// of every reserved lambda-list keyword the implementation
    /// recognises; `LAMBDA_LIST_KEYWORDS` is the substrate's typed-Rust
    /// peer at compile time, with the closed-set ALL array standing in
    /// for CL's runtime-mutable list. Translation through pleme-io
    /// primitives: a `pub const [&'static str; N]` on the typed
    /// [`MacroParams`] algebra rather than a runtime-mutable list;
    /// forced-arity closure at the type layer with the same
    /// family-reflective read surface.
    pub const LAMBDA_LIST_KEYWORDS: [&'static str; 2] = [Self::REST_MARKER, Self::OPTIONAL_MARKER];

    /// Typed membership gate over the closed set
    /// [`Self::LAMBDA_LIST_KEYWORDS`] — `true` iff `s` matches some
    /// element of the ALL array byte-for-byte, `false` for every other
    /// input.
    ///
    /// The typed "does this symbol name a CL lambda-list keyword?"
    /// projection on the [`MacroParams`] algebra. Sibling posture to the
    /// closed set of per-algebra membership / classifier gates the
    /// substrate carries:
    /// [`crate::ast::QuoteForm::from_lead_char`] (per-char quote-family
    /// dispatch — Some/None on a closed 3-char set),
    /// [`crate::ast::Sexp::is_bare_atom_boundary`] (six-fold
    /// bare-atom-boundary sweep), and
    /// [`crate::ast::Atom::decode_str_escape`] (Str-escape decode table
    /// on a closed 6-arm set) — every family-membership gate the
    /// substrate carries binds at ONE method on the closed-set
    /// algebra so a family extension lands at ONE place plus the
    /// per-role marker without re-deriving per-consumer inline
    /// enumerations.
    ///
    /// Pre-lift the "is this symbol a CL lambda-list keyword?" concept
    /// existed structurally but was NOT named on the algebra — the
    /// disjointness pin (`_rest_and_optional_markers_pairwise_disjoint`)
    /// AND the cross-axis disjointness sweep
    /// (`_lambda_list_keyword_lead_distinct_from_every_other_algebra_marker`)
    /// each named the concept implicitly as a hand-rolled per-marker
    /// `assert_ne!` sweep. Post-lift the membership gate binds at ONE
    /// typed method on the algebra a future consumer (a parser-time
    /// "this symbol looks like a lambda-list keyword but isn't
    /// recognised" hint, an authoring-surface completion bar that
    /// suggests `&rest` / `&optional` at param-list positions, a
    /// pretty-printer that colors CL lambda-list keywords distinctly)
    /// binds against without re-deriving the per-marker enumeration
    /// at every consumer site.
    ///
    /// Contract:
    ///   * Every element of [`Self::LAMBDA_LIST_KEYWORDS`] classifies
    ///     as `true` — pinned by
    ///     `macro_params_is_lambda_list_keyword_accepts_every_marker`.
    ///   * The bare CL lambda-list-keyword LEAD byte
    ///     ([`Self::LAMBDA_LIST_KEYWORD_LEAD`]) as a 1-char string
    ///     classifies as `false` — pinned by
    ///     `macro_params_is_lambda_list_keyword_rejects_bare_lead_byte`.
    ///   * Symbols starting with the LEAD byte but naming an
    ///     unrecognised keyword (`"&key"`, `"&aux"`, `"&body"`)
    ///     classify as `false` — pinned by
    ///     `macro_params_is_lambda_list_keyword_rejects_unrecognised_ampersand_prefixed_names`.
    ///
    /// Theory anchor: THEORY.md §II.1 invariant 2 — free middle; the
    /// closed-set membership gate binds at ONE typed method on the
    /// [`MacroParams`] algebra regardless of which consumer reaches
    /// in. THEORY.md §III — the typescape; the "is this a CL
    /// lambda-list keyword?" projection becomes a TYPE projection on
    /// the substrate algebra rather than per-consumer inline
    /// enumeration of the two markers. THEORY.md §V.1 — knowable
    /// platform; a future third marker (`&key`, `&aux`, `&body`)
    /// extends [`Self::LAMBDA_LIST_KEYWORDS`] ONCE and every
    /// membership-gate consumer picks up the new marker for free.
    ///
    /// Frontier inspiration: Common Lisp's `(find X LAMBDA-LIST-KEYWORDS)`
    /// pattern for testing lambda-list keyword membership at runtime;
    /// `is_lambda_list_keyword` is the substrate's typed-Rust peer at
    /// compile time. Translation through pleme-io primitives: a linear
    /// sweep over the [`Self::LAMBDA_LIST_KEYWORDS`] `pub const` array
    /// rather than a runtime `find` over a mutable list; ordinary
    /// slice `contains` on the `&'static str` array.
    #[must_use]
    pub fn is_lambda_list_keyword(s: &str) -> bool {
        Self::LAMBDA_LIST_KEYWORDS.contains(&s)
    }

    /// The flat, ordered param-name list the template bytecode indexes into:
    /// every `required` name in order, then every `optional` name in order,
    /// then the `rest` name if present. `names()[i]` is the param `Subst(i)`
    /// / `Splice(i)` reference.
    #[must_use]
    pub fn names(&self) -> Vec<&str> {
        self.required
            .iter()
            .map(String::as_str)
            .chain(self.optional.iter().map(|p| p.name.as_str()))
            .chain(self.rest.as_deref())
            .collect()
    }

    /// The rest-less maximum arity of this param list: `required.len() +
    /// optional.len()`. Two equivalent readings collapse into ONE primitive
    /// on the typed `MacroParams`:
    ///
    ///   * The **rest-start boundary**: when `self.rest` is `Some`, the
    ///     `&rest` slot collects `args[fixed_arity()..]` into a
    ///     `Sexp::List` (the empty slice when the call is exactly
    ///     saturated). `fixed_arity()` IS that slice's start index.
    ///   * The **rest-less maximum arity**: when `self.rest` is `None`,
    ///     `args.len() > fixed_arity()` is the surplus-args rejection
    ///     boundary [`bind`](Self::bind) checks before raising
    ///     `LispError::TooManyMacroArgs` (the call-site mirror of
    ///     `RestParamTrailingTokens`'s definition-site rejection).
    ///
    /// Both readings ARE the same arithmetic; [`bind`](Self::bind)
    /// previously inlined the same `self.required.len() +
    /// self.optional.len()` expression THREE times — once inside the
    /// `Vec::with_capacity(required + optional + rest?)` slot, once at
    /// the `rest_start` site (inside `if let Some(_rest_name) =
    /// self.rest`), and once at the `expected` site (inside the
    /// rest-less `else`). The latter two live in mutually-exclusive
    /// branches yet name ONE structural concept; lifting the arithmetic
    /// to a single named primitive makes that concept first-class on
    /// the typed param list.
    ///
    /// `fixed_arity()` IGNORES the `rest` slot by construction — a
    /// `&rest` param has no maximum and is not part of the fixed run.
    /// `names().len() == fixed_arity() + usize::from(self.rest.is_some())`
    /// is the structural identity binding this primitive to
    /// [`names`](Self::names) and to the `Vec::with_capacity` hint
    /// [`bind`](Self::bind) computes for the bound-values vec.
    ///
    /// Theory anchor: THEORY.md §V.1 — knowable platform; the structural
    /// "rest-start boundary / rest-less max arity" concept becomes a
    /// named `&MacroParams` projection rather than re-derived arithmetic
    /// at every site that walks the bound run. Authoring tools (REPL,
    /// LSP, `tatara-check`) that want to render "this macro takes
    /// between `required.len()` and `fixed_arity()` args (or unbounded
    /// if `rest.is_some()`)" bind to ONE method on the typed param
    /// list. THEORY.md §VI.1 — generation over composition; three
    /// inline copies of the same arithmetic in one function is past
    /// the ≥2 PRIME-DIRECTIVE trigger once the structural shape is
    /// named. THEORY.md §II.1 invariant 2 — free middle; both
    /// expansion strategies route through the SHARED `bind`, so the
    /// new primitive is exposed to the bytecode and substitute paths
    /// uniformly — no per-strategy drift in how the boundary is
    /// computed.
    #[must_use]
    pub fn fixed_arity(&self) -> usize {
        self.required.len() + self.optional.len()
    }

    /// The TOTAL lambda-list arity of this param list — every named
    /// slot the reader accepted, in the canonical CL lambda-list
    /// ordering: `required.len() + optional.len() + rest.is_some() as
    /// usize`. Peer to [`Self::fixed_arity`] one REST-SLOT axis over
    /// on the `MacroParams` algebra — where [`Self::fixed_arity`]
    /// ignores the rest slot (the rest-less maximum-arity /
    /// rest-start-boundary reading, unbounded on the call-time surface
    /// when `self.rest.is_some()`), this projection INCLUDES the rest
    /// slot as one additional named param (the total-slots reading,
    /// bounded on the type-time surface regardless of `rest`).
    ///
    /// `Self::total_arity() == Self::names().len()` — a `Vec`-free
    /// projection of the [`Self::names`] flat-index list's length. Two
    /// equivalent readings collapse into ONE named primitive on the
    /// typed [`MacroParams`] algebra:
    ///
    ///   * The **`Vec::with_capacity` hint**: [`Self::bind`] previously
    ///     inlined `self.fixed_arity() + usize::from(self.rest.is_some())`
    ///     as the bound-vec capacity hint. That expression IS this
    ///     primitive.
    ///   * The **REGISTER-time arity ceiling**: on the arity-bomb
    ///     `(defmacro huge (a-1 a-2 … a-N) `,a-1)` [`Expander::register_macro_def`]
    ///     compares `def.params.total_arity()` against
    ///     [`Expander::max_macro_arity`] BEFORE the body-size gate walks
    ///     the body or any insert lands. `total_arity()` IS that gate's
    ///     axis.
    ///
    /// The structural identity
    /// `names().len() == fixed_arity() + usize::from(rest.is_some())
    ///                 == total_arity()`
    /// binds the primitive to [`Self::names`] and [`Self::fixed_arity`]
    /// on the [`MacroParams`] algebra — pinned by
    /// `macro_params_total_arity_matches_names_len` AND
    /// `macro_params_total_arity_equals_fixed_arity_plus_rest_bit`.
    ///
    /// Theory anchor: THEORY.md §V.1 — knowable platform; the
    /// "how many named slots does this macro declare?" projection
    /// becomes a NAMED `&MacroParams` accessor rather than re-derived
    /// arithmetic at [`Self::bind`]'s capacity hint AND at the
    /// [`Expander::register_macro_def`] arity-ceiling gate.
    /// THEORY.md §VI.1 — generation over composition; two inline copies
    /// of the same three-arm arithmetic across two consumers is the
    /// ≥2 PRIME-DIRECTIVE trigger once the structural shape is named.
    /// THEORY.md §II.1 invariant 2 — free middle; both the binder AND
    /// the arity-guard consult ONE primitive, so a regression that
    /// drifts the guard's arity computation from the binder's capacity
    /// hint (e.g. one counts `rest` as one slot, the other counts it
    /// as zero) becomes structurally impossible.
    #[must_use]
    pub fn total_arity(&self) -> usize {
        self.fixed_arity() + usize::from(self.rest.is_some())
    }

    /// Bind call args to params positionally, returning the per-index bound
    /// values parallel to [`names`](Self::names): each required name takes
    /// the arg at its position (a missing one is
    /// [`missing_macro_arg`](self::missing_macro_arg)); each optional name
    /// takes the arg at its position, or — when the call ran out of args —
    /// its declared default form (`Sexp::Nil` when none was declared,
    /// matching CL's `&optional` floor); and a present `rest` collects every
    /// arg beyond the required+optional run into a `Sexp::List` (the empty
    /// list when none remain). Args beyond a REST-LESS param list have
    /// nowhere to bind and are rejected
    /// ([`too_many_macro_args`](self::too_many_macro_args)) rather than
    /// silently truncated. This is the single binding loop every expansion
    /// strategy shares — `apply_compiled` consumes the index vec directly,
    /// `bind_args` zips it against `names()` into the name-keyed map — and
    /// it is the `Sexp` instantiation of the carrier-generic
    /// [`Self::bind_carrier`].
    fn bind(&self, macro_name: &str, args: &[Sexp]) -> Result<Vec<Sexp>> {
        self.bind_carrier(macro_name, args, ())
    }

    /// The ONE positional binder, generic over the value carrier a macro call
    /// binds its arguments in — [`Sexp`] for the plain `Sexp`→`Sexp`
    /// expander, `Spanned` for the span-preserving one, and any future
    /// carrier a consumer implements [`MacroArgCarrier`] for.
    ///
    /// Genericising this loop is what makes ONE lambda-list semantics
    /// (required run → `&optional` run with per-param defaults → at-most-one
    /// `&rest`, plus the too-few / too-many arity rejections) reachable from
    /// every expansion path, instead of each path restating the loop against
    /// its own value type. Before this lift the span-preserving expander
    /// carried its own `bind_spanned_args` that knew only `Required`/`Rest`
    /// — so `(defmacro f (a &optional b) …)` parsed on one path and was
    /// rejected on the other, and a surplus argument was a hard error on one
    /// path and silently dropped on the other. Both divergences are now
    /// structurally impossible: there is exactly one loop.
    ///
    /// `site` is the carrier's synthesis context — `()` for `Sexp` (a
    /// default form and a rest list need no context to construct), the
    /// macro CALL SITE span for `Spanned` (a value the CALL never supplied
    /// has no source position of its own, so it is stamped at the call).
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition; the
    /// binding loop had reached three copies (plain, spanned, and
    /// `tatara-lisp-eval`'s macro-time env binder), well past the ≥2
    /// PRIME-DIRECTIVE trigger.
    pub fn bind_carrier<V: MacroArgCarrier>(
        &self,
        macro_name: &str,
        args: &[V],
        site: V::Site,
    ) -> Result<Vec<V>> {
        let mut out = Vec::with_capacity(self.total_arity());
        for (i, name) in self.required.iter().enumerate() {
            let arg = args
                .get(i)
                .cloned()
                .ok_or_else(|| missing_macro_arg(macro_name, name))?;
            out.push(arg);
        }
        let opt_start = self.required.len();
        for (j, param) in self.optional.iter().enumerate() {
            // Absent optional slot binds to the typed `resolved_default()`
            // projection on `OptionalParam`: the declared default form when
            // one was authored, OR the `Sexp::Nil` no-default floor when
            // none was. The two-arm fallback `param.default.clone().
            // unwrap_or(Sexp::Nil)` previously inlined here is now ONE named
            // accessor on the typed param both expansion strategies share via
            // `MacroParams::bind_carrier`.
            let arg = match args.get(opt_start + j) {
                Some(supplied) => supplied.clone(),
                None => V::lift_default(&param.resolved_default(), site),
            };
            out.push(arg);
        }
        if let Some(_rest_name) = self.rest.as_ref() {
            // The `&rest` slot collects args[fixed_arity()..] (the empty
            // slice when the call is exactly saturated); the boundary is
            // the typed `fixed_arity()` primitive both branches share.
            let rest = args.get(self.fixed_arity()..).unwrap_or(&[]).to_vec();
            out.push(V::collect_rest(rest, site));
        } else {
            // No `&rest` slot — the param list has a FIXED maximum arity
            // of `fixed_arity()`. Surplus args have nowhere to bind;
            // reject rather than silently truncate. Closes the call-site
            // mirror of `RestParamTrailingTokens` (the definition-site
            // rejection lifted by the prior-run typed-promotion lineage),
            // so the typed-entry macro-call-gate is structurally complete
            // in both directions: too-few (`MissingMacroArg`) AND too-many
            // (`TooManyMacroArgs`).
            let expected = self.fixed_arity();
            if args.len() > expected {
                return Err(too_many_macro_args(macro_name, expected, args.len()));
            }
        }
        Ok(out)
    }
}

/// Macro environment. Collects `defmacro` forms and rewrites callers.
///
/// Expansion strategy is tunable per-expander:
///   - **Compiled (default)** — every registered macro's template is walked once
///     and flattened into a linear `CompiledTemplate` (a tiny bytecode: Literal,
///     Subst(index), Splice(index), BeginList, EndList). Expansion of a call
///     is then a linear pass with no HashMap lookups and no recursion through
///     the template Sexp. Purely-literal subtrees compile to a single
///     `Literal(Sexp)` op — huge win for macros where most of the body is fixed.
///   - **Substitute-only** — runs the name-keyed `substitute` walker. Slower
///     but proves equivalence; used in the benchmark test to measure the
///     compiled-vs-substituted speedup.
#[derive(Clone, Default)]
pub struct Expander {
    macros: HashMap<String, MacroDef>,
    /// Pre-compiled template bytecodes, populated when `compile_templates`.
    templates: HashMap<String, CompiledTemplate>,
    /// When true, register a CompiledTemplate alongside each macro and dispatch
    /// expansion through the bytecode interpreter.
    compile_templates: bool,
    /// Memoization of `apply(macro, args)` — repeated calls with identical
    /// args skip expansion entirely. Shared across clones so realizations of
    /// the same `CompilerSpec` benefit across .compile() invocations.
    cache: Arc<Mutex<HashMap<CacheKey, Sexp>>>,
    /// Toggle caching. Default on — caching is the actual performance win
    /// the bytecode layer enables.
    cache_enabled: bool,
    /// The six resource ceilings, held as ONE typed [`ResourceLimits`] bundle
    /// rather than six sibling `max_*: usize` fields. Peer of the six
    /// getter/setter pairs one AGGREGATION axis over — where each pair
    /// projects ONE ceiling, this field carries the SIX-fold cross-product
    /// so [`Self::resource_limits`] returns `self.limits` verbatim and
    /// [`Self::set_resource_limits`] assigns through the bundle in ONE move.
    ///
    /// Adding a SEVENTH ceiling touches [`ResourceLimits`] + the matching
    /// `DEFAULT_MAX_*` module constant + the paired individual getter/setter
    /// — the [`Expander`] struct, its constructors, AND
    /// [`Self::resource_limits`] / [`Self::set_resource_limits`] stay
    /// exactly as they are. That's the compounding win of the
    /// consolidation: the (Expander, constructors, bulk getter, bulk
    /// setter) four-corner face is field-shape-agnostic — it composes with
    /// the bundle by value, not by field-by-field literal.
    ///
    /// Consumers on the read path (`register_macro_def`'s three REGISTER-time
    /// gates, `expand_with_depth`'s depth + output-size gates, `apply`'s
    /// cache-entries gate) dereference through `self.limits.max_*`; the
    /// projection is a `Copy usize` load — same shape as reading a bare
    /// field, no `Deref`, no `Arc`, no lock.
    limits: ResourceLimits,
}

impl Expander {
    /// Default-posture expander with an operator-supplied resource-ceiling
    /// bundle — the AGGREGATION-axis peer of
    /// [`Self::set_resource_limits`] one CONSTRUCTOR-STAGE axis over.
    /// Where [`Self::set_resource_limits`] applies the bundled six ceilings
    /// POST-construction on an already-built expander, this constructor
    /// binds them AT construction so a call-site that wants a fresh
    /// expander with a non-default posture composes ONE typed call
    /// (`Expander::with_limits(limits)`) rather than the two-step
    /// (`let mut e = Expander::new(); e.set_resource_limits(limits);`)
    /// dance the post-construction sibling still admits.
    ///
    /// The (compile_templates, cache_enabled) execution-strategy pair
    /// carries the [`Self::new`] default posture (`true, true`) — the
    /// bytecode-with-cache strategy — since callers that want the
    /// substitute-only strategy still route through
    /// [`Self::new_substitute_only`]. Post-lift both convenience
    /// constructors delegate their `macros` / `templates` / `cache` field
    /// literals through THIS primitive at the resource-posture axis: the
    /// four-out-of-six field literals (`HashMap::new()` × 2 +
    /// `Arc::new(Mutex::new(HashMap::new()))` + `limits`) lived
    /// byte-identical across [`Self::new`] and [`Self::new_substitute_only`]
    /// pre-lift; the two divergent flags (`compile_templates`,
    /// `cache_enabled`) still differ between the two constructors, and the
    /// substitute-only variant flips them AFTER threading through
    /// `with_limits` — same shape as [`Self::new_bytecode_no_cache`] does
    /// on the `cache_enabled` flag.
    ///
    /// Round-trip identity: `Expander::with_limits(limits).resource_limits()
    /// == limits` for any `ResourceLimits` — pinned as a typed theorem in
    /// the test cohort. The at-construction assignment is a direct `Copy`
    /// of the bundled field (no per-field cascade), so a mid-construction
    /// panic window on the six knobs is structurally impossible. Peer of
    /// the `Expander::with_limits(DEFAULT_RESOURCE_LIMITS) ==
    /// Expander::new()` delegation identity — pinned on the resource-
    /// posture projection so a future refactor that drifts the two
    /// constructors on the ceiling axis fails loudly.
    ///
    /// Frontier inspiration: Cranelift's `settings::Flags::new(builder)` —
    /// codegen ceilings (opt level, allocator strategy, feature enables)
    /// bind at CONSTRUCTION-time on a typed `Flags` bundle rather than
    /// composed through post-construction setters on the `Isa`. Same
    /// posture as this lift: the (getter, setter, at-construction)
    /// three-corner face on the resource-posture surface now binds at ONE
    /// typed bundle across ALL three surfaces.
    ///
    /// Theory grounding: THEORY.md §II.1 invariants 1 + 2 — typed entry +
    /// free middle. Pre-lift the "expander with a chosen resource posture"
    /// concept was untyped: consumers composed [`Self::new`] +
    /// [`Self::set_resource_limits`] at their call site with no
    /// compile-time gate that BOTH steps land atomically. Post-lift the
    /// concept has ONE named entry point on the `Expander` surface, and a
    /// future consumer (`RealizedCompiler` builder that ships a
    /// CI-tightened preset, an LSP session that ships a REPL-permissive
    /// preset, a test-harness fixture that ships an `UNBOUNDED`-style
    /// preset) binds through ONE typed constructor.
    pub fn with_limits(limits: ResourceLimits) -> Self {
        Self {
            macros: HashMap::new(),
            templates: HashMap::new(),
            compile_templates: true,
            cache: Arc::new(Mutex::new(HashMap::new())),
            cache_enabled: true,
            limits,
        }
    }

    /// Default expander — compiled bytecode + expansion cache enabled.
    /// Delegates to [`Self::with_limits`] with [`DEFAULT_RESOURCE_LIMITS`]
    /// so the (macros, templates, cache, limits) field-shape agreement
    /// with every other constructor on this `Expander` surface lives at
    /// ONE literal.
    pub fn new() -> Self {
        Self::with_limits(DEFAULT_RESOURCE_LIMITS)
    }

    /// Expander using the legacy substitute path (no template compilation,
    /// no cache). Kept for benchmarking + equivalence testing.
    /// Delegates to [`Self::with_limits`] with [`DEFAULT_RESOURCE_LIMITS`]
    /// and flips the two divergent execution-strategy flags — same
    /// composition shape as [`Self::new_bytecode_no_cache`] one flag over.
    pub fn new_substitute_only() -> Self {
        let mut e = Self::with_limits(DEFAULT_RESOURCE_LIMITS);
        e.compile_templates = false;
        e.cache_enabled = false;
        e
    }

    /// Expander with bytecode on but expansion cache off — isolates the cache
    /// contribution from the bytecode infrastructure. Benchmark baseline.
    pub fn new_bytecode_no_cache() -> Self {
        let mut e = Self::new();
        e.cache_enabled = false;
        e
    }

    /// Toggle the expansion cache at runtime.
    pub fn set_cache_enabled(&mut self, enabled: bool) {
        self.cache_enabled = enabled;
    }

    /// How many entries are currently cached.
    pub fn cache_size(&self) -> usize {
        self.cache.lock().unwrap().len()
    }

    /// Clear the expansion cache (e.g., after redefining a macro).
    pub fn clear_cache(&self) {
        self.cache.lock().unwrap().clear();
    }

    /// The configured ceiling on `expand`'s recursive re-entry into a
    /// macro-call form. Defaults to [`DEFAULT_MAX_EXPANSION_DEPTH`].
    #[must_use]
    pub fn max_expansion_depth(&self) -> usize {
        self.limits.max_expansion_depth
    }

    /// Set the ceiling on `expand`'s recursive re-entry into a macro-call
    /// form. Tests bind low values (e.g. `4`) to pin the runaway-rejection
    /// shape without paying for a 256-round walk; consumers that compose
    /// deep proven macro cascades can raise it. Zero is admitted and
    /// makes every first macro-call return
    /// [`LispError::ExpansionDepthExceeded`] immediately — useful for
    /// contract-tests that assert "this reader path never expands a
    /// macro."
    pub fn set_max_expansion_depth(&mut self, depth: usize) {
        self.limits.max_expansion_depth = depth;
    }

    /// The configured ceiling on the expansion cache's entry count.
    /// Defaults to [`DEFAULT_MAX_CACHE_ENTRIES`]. Peer to
    /// [`Self::max_expansion_depth`] one RESOURCE axis over.
    #[must_use]
    pub fn max_cache_entries(&self) -> usize {
        self.limits.max_cache_entries
    }

    /// Set the ceiling on the expansion cache's entry count. Tests bind
    /// low values (e.g. `2`) to pin the bounded-cache contract without
    /// paying for an 8K-entry walk; consumers that expand many distinct
    /// argument shapes can raise it. Zero is admitted and effectively
    /// disables caching (every fresh `(name, args)` pair skips the
    /// insert path) — useful for contract-tests that assert "this
    /// expander realizes without ever caching." [`usize::MAX`] is the
    /// unbounded-cache mode for batch compilation runs where memory is
    /// not the concern.
    pub fn set_max_cache_entries(&mut self, cap: usize) {
        self.limits.max_cache_entries = cap;
    }

    /// The configured ceiling on a single macro-`apply` output's
    /// [`crate::ast::Sexp::node_count`]. Defaults to
    /// [`DEFAULT_MAX_EXPANSION_SIZE`]. Peer to
    /// [`Self::max_expansion_depth`] and [`Self::max_cache_entries`]
    /// one RESOURCE-DIMENSION axis over.
    #[must_use]
    pub fn max_expansion_size(&self) -> usize {
        self.limits.max_expansion_size
    }

    /// Set the ceiling on a single macro-`apply` output's node count.
    /// Tests bind low values (e.g. `8`) to pin the "expansion bomb"
    /// rejection shape without materializing a 64K-node blob;
    /// consumers that compose deep proven macro cascades can raise it.
    /// [`usize::MAX`] admits any lawful output (the ceiling is
    /// effectively lifted); operators that want strict "your macros
    /// must fit in N nodes" contract-tests set it exactly.
    pub fn set_max_expansion_size(&mut self, size: usize) {
        self.limits.max_expansion_size = size;
    }

    /// The configured ceiling on a registered macro's BODY
    /// [`crate::ast::Sexp::node_count`]. Defaults to
    /// [`DEFAULT_MAX_MACRO_BODY_SIZE`]. Peer to
    /// [`Self::max_expansion_depth`], [`Self::max_cache_entries`],
    /// and [`Self::max_expansion_size`] one PIPELINE-STAGE axis over
    /// (the three prior guards fire at EXPAND time; this one fires
    /// at REGISTER time).
    #[must_use]
    pub fn max_macro_body_size(&self) -> usize {
        self.limits.max_macro_body_size
    }

    /// Set the ceiling on a registered macro's BODY node count.
    /// Tests bind low values (e.g. `4`) to pin the authoring-bomb
    /// rejection shape without materializing a 16K-node blob;
    /// consumers that author deep proven macro-body templates can
    /// raise it. [`usize::MAX`] admits any lawful body (the ceiling
    /// is effectively lifted). Zero is admitted and rejects every
    /// non-empty body immediately (a `Nil` body is 1 node, so the
    /// smallest lawful body is still rejected under a zero
    /// ceiling) — useful for contract-tests that assert "this
    /// expander refuses every registration."
    pub fn set_max_macro_body_size(&mut self, size: usize) {
        self.limits.max_macro_body_size = size;
    }

    /// The configured ceiling on the [`Self::macros`] table's entry
    /// count. Defaults to [`DEFAULT_MAX_REGISTERED_MACROS`]. Peer to
    /// [`Self::max_macro_body_size`] one RESOURCE-DIMENSION axis over
    /// on the REGISTER-time surface, and to [`Self::max_cache_entries`]
    /// one PIPELINE-STAGE axis over.
    #[must_use]
    pub fn max_registered_macros(&self) -> usize {
        self.limits.max_registered_macros
    }

    /// Set the ceiling on the [`Self::macros`] table's entry count.
    /// Tests bind low values (e.g. `3`) to pin the registration-bomb
    /// rejection shape without materializing a 4K-entry macros table;
    /// consumers that compose deep proven typescapes can raise it.
    /// [`usize::MAX`] admits any lawful cumulative registration count
    /// (the ceiling is effectively lifted). Zero is admitted and
    /// rejects every FRESH registration immediately — useful for
    /// contract-tests that assert "this expander accepts no new
    /// macros" — while still admitting overwrites of any macro that
    /// was registered before the ceiling was set (a re-registration
    /// of an existing key never grows the table).
    pub fn set_max_registered_macros(&mut self, cap: usize) {
        self.limits.max_registered_macros = cap;
    }

    /// The configured ceiling on a registered macro's lambda-list
    /// arity. Defaults to [`DEFAULT_MAX_MACRO_ARITY`]. Peer to
    /// [`Self::max_macro_body_size`] and [`Self::max_registered_macros`]
    /// one RESOURCE-DIMENSION axis over on the REGISTER-time surface.
    #[must_use]
    pub fn max_macro_arity(&self) -> usize {
        self.limits.max_macro_arity
    }

    /// Set the ceiling on a registered macro's lambda-list arity —
    /// the [`MacroParams::total_arity`] projection of `def.params`.
    /// Tests bind low values (e.g. `2`) to pin the arity-bomb rejection
    /// shape without materializing a 128-slot authoring blob;
    /// consumers that author high-arity domain macros (a `defschema`
    /// with 40 typed slots) can raise it. [`usize::MAX`] admits any
    /// lawful arity (the ceiling is effectively lifted). Zero is
    /// admitted and rejects every non-nullary macro registration
    /// immediately — a `(defmacro nullary () BODY)` is still admitted
    /// (its `total_arity()` is `0`, and only strict overrun rejects) —
    /// useful for contract-tests that assert "this expander accepts
    /// only nullary macros."
    pub fn set_max_macro_arity(&mut self, cap: usize) {
        self.limits.max_macro_arity = cap;
    }

    /// Snapshot the six configured resource ceilings as ONE typed
    /// [`ResourceLimits`] value — the bundled peer of the six
    /// [`Self::max_expansion_depth`] / [`Self::max_cache_entries`] /
    /// [`Self::max_expansion_size`] / [`Self::max_macro_body_size`] /
    /// [`Self::max_registered_macros`] / [`Self::max_macro_arity`]
    /// individual getters. Consumers that want to inspect the full
    /// resource posture (a test that compares a preset expander to a
    /// reference posture, a diagnostic that renders "the six ceilings"
    /// as one line, a caller that clones + selectively overrides one
    /// field via a struct-update literal) bind to this projection at
    /// ONE call site rather than composing the six individual getters.
    ///
    /// Post the [`Self::limits`]-field consolidation the projection is
    /// a direct `Copy` of the bundled field — a `usize`-sized fixed
    /// return with no per-field literal walk. Adding a SEVENTH ceiling
    /// extends [`ResourceLimits`] and the paired individual
    /// getter/setter; this bulk getter is field-shape-agnostic and
    /// stays exactly as it is.
    #[must_use]
    pub fn resource_limits(&self) -> ResourceLimits {
        self.limits
    }

    /// Bulk-replace the six configured resource ceilings from ONE typed
    /// [`ResourceLimits`] value — the bundled peer of the six
    /// [`Self::set_max_expansion_depth`] /
    /// [`Self::set_max_cache_entries`] /
    /// [`Self::set_max_expansion_size`] /
    /// [`Self::set_max_macro_body_size`] /
    /// [`Self::set_max_registered_macros`] /
    /// [`Self::set_max_macro_arity`] individual setters. Presets
    /// (a hardened CI expander, a permissive REPL expander, a
    /// throttled test harness) compose the six ceilings ONCE at the
    /// preset call site and apply them ATOMICALLY here rather than
    /// threading six independent setter invocations whose ordering
    /// the type system does not gate.
    ///
    /// Round-trip identity: `let l = e.resource_limits(); e.set_resource_limits(l);`
    /// leaves `e` in an equivalent posture — pinned as a typed theorem
    /// in the [`ResourceLimits`] test cohort. Post the [`Self::limits`]-
    /// field consolidation the assignment is a direct `Copy` of the
    /// bundled field, structurally atomic — no per-field destructure +
    /// six-way write cascade in which a mid-cascade panic could leave
    /// the six knobs in a half-updated posture. Sibling of
    /// [`Self::resource_limits`]; the pair closes the (getter, setter)
    /// face on the aggregation axis.
    pub fn set_resource_limits(&mut self, limits: ResourceLimits) {
        self.limits = limits;
    }

    pub fn with_macros<I: IntoIterator<Item = MacroDef>>(defs: I) -> Result<Self> {
        let mut e = Self::new();
        for d in defs {
            e.register_macro_def(d)?;
        }
        Ok(e)
    }

    /// Register a parsed [`MacroDef`] into this expander's macro tables —
    /// the single named primitive on the `Expander` surface every
    /// macro-registration consumer routes through.
    ///
    /// The registration discipline is a two-step composition:
    ///   1. When [`Self::compile_templates`](Self::new) is on (the
    ///      `Self::new` default; flipped off by [`Self::new_substitute_only`]),
    ///      [`compile_template`] pre-compiles the macro body to a typed
    ///      [`CompiledTemplate`] bytecode and inserts it into `self.templates`
    ///      keyed by `def.name`.
    ///   2. The `MacroDef` is moved into `self.macros` keyed by `def.name` —
    ///      always, regardless of `compile_templates`, because the substitute
    ///      strategy reads `self.macros` exclusively while the bytecode
    ///      strategy consults `self.templates` first and falls back to
    ///      `self.macros` for the body and params.
    ///
    /// The order is structural: `compile_template` borrows `&def` while
    /// `self.macros.insert(def.name.clone(), def)` consumes `def` — the
    /// template pre-compile MUST precede the move into `self.macros`, and the
    /// `def.name.clone()` projection captures the key for the moved insert.
    /// `?`-routing through `compile_template` preserves the structural
    /// ordering of the rejection chain end-to-end: a template-compile error
    /// (`UnboundTemplateVar` for an unbound `,name`, `NonSymbolUnquoteTarget`
    /// for `,5` / `,(nested)`, et al.) short-circuits BEFORE `self.macros`
    /// is mutated, so a failed registration leaves both tables exactly as
    /// they were — no partial-write window in which `self.macros.has(name)`
    /// is true but `self.templates.has(name)` is missing (a regression that
    /// would silently coerce the bytecode strategy onto the substitute path
    /// for that one macro despite `compile_templates: true`).
    ///
    /// Before this lift the same two-step block —
    ///
    /// ```ignore
    /// if self.compile_templates {
    ///     self.templates.insert(def.name.clone(), compile_template(&def)?);
    /// }
    /// self.macros.insert(def.name.clone(), def);
    /// ```
    ///
    /// — lived byte-identical (modulo `self`/`e` and `def`/`d` substitutions)
    /// at TWO sites: [`Self::with_macros`] (the constructor that
    /// bulk-registers an `IntoIterator<Item = MacroDef>`, e.g. a curated
    /// preloaded set the caller assembled out-of-band) and
    /// [`Self::expand_program`]'s `(defmacro …)`-head arm (the program-level
    /// walker that recognizes a `defmacro` / `defpoint-template` / `defcheck`
    /// head via [`macro_def_from`] and registers it as a side-effect of
    /// walking the program). After this lift the registration block lives in
    /// ONE method on the `Expander`; both consumers and any future
    /// macro-registration surface bind to ONE primitive instead of
    /// re-deriving the two-step discipline at every call site.
    ///
    /// `pub` so authoring surfaces (an LSP that incrementally registers a
    /// `(defmacro …)` head as the user finishes typing it without a full
    /// program re-expand, a REPL `:define-macro` command that registers a
    /// pre-parsed `MacroDef` directly, a future "library merge" operation
    /// that absorbs another expander's macro set MacroDef-by-MacroDef) can
    /// register a typed `MacroDef` without round-tripping through source
    /// serialization first. Sibling of [`Self::with_macros`] (the
    /// bulk-from-iterator constructor — itself the
    /// `defs.into_iter().try_fold((), |_, d| self.register_macro_def(d))`
    /// shape on a fresh expander) and [`Self::expand_program`] (the
    /// source-level walker that recognizes `(defmacro …)` heads via
    /// [`macro_def_from`] — itself the program-level fold-over-defmacro-heads
    /// of this method). All three end up at this primitive.
    ///
    /// Returns `Result<()>` so the consumer's rejection chain composes with
    /// `?`-routing — `with_macros` short-circuits its bulk loop on the first
    /// `compile_template` failure; `expand_program` short-circuits its
    /// program walk at the offending `(defmacro …)` form. Infallibility on
    /// the `compile_templates: false` path is preserved (`compile_template`
    /// is gated behind the conditional), so a substitute-only expander never
    /// emits the `compile_template`-side rejection chain.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition; two
    /// byte-identical inline copies of the registration block across
    /// `with_macros` and `expand_program` is past the ≥2 PRIME-DIRECTIVE
    /// trigger once the structural shape is named. THEORY.md §V.1 — knowable
    /// platform; the macro-registration discipline becomes a NAMED primitive
    /// on the substrate's `Expander` surface rather than a per-consumer
    /// inline duplication that future emitters (an LSP, a REPL, a library-
    /// merge operator) would have had to re-derive. THEORY.md §II.1
    /// invariant 2 — free middle; both consumers route through the SAME
    /// registration primitive, so a regression that drifts ONE consumer's
    /// discipline from the other (one path skips the template pre-compile,
    /// one path inserts the `self.macros` entry in a different order, a
    /// future third side-effect — logging, attestation, metrics — emitted
    /// at one site but not the other) cannot reach the substrate's runtime:
    /// there is exactly one implementation both consumers route through.
    ///
    /// Frontier inspiration: Racket's `(define-syntax name template)` at
    /// REPL is exactly this — register a typed macro into the live
    /// namespace, no source round-trip; the substrate's `register_macro_def`
    /// is the Rust-typed peer of that surface, lifted onto the `Expander`'s
    /// table-level algebra (`macros: HashMap<String, MacroDef>` +
    /// `templates: HashMap<String, CompiledTemplate>`). MLIR's
    /// `OpRegistry::registerOp<Op>()` — typed-op registration into a
    /// dialect's live table at construction-time AND at JIT-walk-time
    /// through ONE registration entry point; `register_macro_def` is the
    /// pleme-io peer of that registration entry point on the macro-table
    /// algebra.
    pub fn register_macro_def(&mut self, def: MacroDef) -> Result<()> {
        // Reject a registration-bomb (a code-generator emitting
        // unbounded fresh `(defmacro fresh-N (x) `(list ,x))` heads
        // whose bodies each sit comfortably under
        // `max_macro_body_size` yet collectively saturate process
        // memory) at the cheapest gate on the REGISTER-time surface
        // — a `HashMap::len` comparison, no body walk. Peer to the
        // body-size gate below one RESOURCE-DIMENSION axis over
        // (COUNT vs. SIZE) and to the expand-time cache-entries gate
        // in `apply` one PIPELINE-STAGE axis over (REGISTER-time
        // COUNT vs. EXPAND-time COUNT). Fires BEFORE the body-size
        // gate walks `def.body.node_count()` or any insert lands, so
        // a failed registration leaves BOTH tables exactly as they
        // were. Overwrites (a re-registration of an already-
        // registered key) are ADMITTED at any table size — a
        // re-`defmacro` never grows the table, so the ceiling cannot
        // gate operator redefinitions. Keyed on `>=` (a table
        // already at ceiling rejects a fresh key) so
        // `max_registered_macros` names the LARGEST admissible
        // `self.macros.len()` — same posture the expand-time
        // cache-entries gate holds on the memoization cache.
        let is_overwrite = self.macros.contains_key(&def.name);
        if !is_overwrite && self.macros.len() >= self.limits.max_registered_macros {
            return Err(LispError::RegisteredMacrosExceeded {
                macro_name: def.name.clone(),
                count: self.macros.len(),
                limit: self.limits.max_registered_macros,
            });
        }
        // Reject an arity-bomb `(defmacro huge (a-1 a-2 … a-N-million)
        // `,a-1)` — a code-generator whose macro body sits at ONE node
        // (well under `max_macro_body_size`) yet whose param list
        // carries millions of fresh names the per-index binder walks on
        // every call. Peer to the body-size gate below one RESOURCE-
        // DIMENSION axis over on the REGISTER-time surface (per-body
        // ARITY vs. per-body SIZE), AND peer to the table-count gate
        // above one RESOURCE-DIMENSION axis over on the REGISTER-time
        // surface (per-registration WIDTH vs. cumulative COUNT). Fires
        // BEFORE the body-size gate walks `def.body.node_count()` or
        // any insert lands, so a failed registration leaves BOTH tables
        // exactly as they were. Cheaper than the body-size gate — a
        // three-arm addition on `def.params` fields, no AST walk —
        // hence positioned BEFORE it on the O(1)-first ordering of the
        // REGISTER-time chain. Keyed on `>` (equality is admitted, only
        // strict overrun rejects) so `max_macro_arity` names the
        // LARGEST admissible `def.params.total_arity()` — same posture
        // the body-size gate holds on the body node count.
        let arity = def.params.total_arity();
        if arity > self.limits.max_macro_arity {
            return Err(LispError::MacroArityExceeded {
                macro_name: def.name.clone(),
                arity,
                limit: self.limits.max_macro_arity,
            });
        }
        // Reject an authoring-bomb `(defmacro huge (x) `<template-of-
        // N-million-nodes>)` at the REGISTRATION boundary — the
        // PIPELINE-STAGE peer of the EXPAND-time output-size gate in
        // `expand_with_depth`. Fires BEFORE `compile_template` walks
        // the body or `self.macros.insert` lands the entry, so a
        // failed registration leaves BOTH tables exactly as they
        // were (no partial-write window in which the body-size
        // rejection happened but the template pre-compile already
        // consumed cycles or the macros table already carries the
        // over-ceiling entry). Keyed on `>` rather than `>=` so
        // `max_macro_body_size` names the LARGEST admissible body —
        // equality is admitted, only strict overrun rejects — same
        // posture the expand-time output-size gate holds.
        let body_size = def.body.node_count();
        if body_size > self.limits.max_macro_body_size {
            return Err(LispError::MacroBodySizeExceeded {
                macro_name: def.name.clone(),
                size: body_size,
                limit: self.limits.max_macro_body_size,
            });
        }
        if self.compile_templates {
            self.templates
                .insert(def.name.clone(), compile_template(&def)?);
        }
        self.macros.insert(def.name.clone(), def);
        Ok(())
    }

    /// Expand a whole program. Returns the list of top-level forms after
    /// `defmacro` definitions are registered and all macro calls expanded.
    pub fn expand_program(&mut self, forms: Vec<Sexp>) -> Result<Vec<Sexp>> {
        let mut out = Vec::new();
        for form in forms {
            if let Some(def) = macro_def_from(&form)? {
                self.register_macro_def(def)?;
                continue;
            }
            out.push(self.expand(&form)?);
        }
        Ok(out)
    }

    /// Read a source string into top-level forms via [`crate::reader::read`],
    /// then route the forms through [`expand_program`](Self::expand_program) —
    /// the from-source posture of the yield-all-forms-after-expansion primitive,
    /// in ONE method on the `Expander` surface.
    ///
    /// Before this lift the same two-step chain — `let forms = read(src)?;
    /// <expander>.expand_program(forms)` — lived inline at two sites in
    /// [`crate::compiler_spec`]: [`RealizedCompiler::compile`](crate::compiler_spec::RealizedCompiler::compile)
    /// (the public from-source untyped-expansion entry on a realized compiler,
    /// returning the expanded `Vec<Sexp>` for untyped consumers like
    /// `tatara-check`'s per-form dispatcher) AND [`realize_in_memory`](crate::compiler_spec::realize_in_memory)'s
    /// `:macros` library load loop (the per-spec-macro source absorption that
    /// builds the preloaded expander's macro library through `expand_program`'s
    /// `defmacro` recognition side-effect). After this lift the read-then-expand
    /// composition lives in ONE method on the `Expander`; each of the two
    /// consumers binds it with the per-site expander posture that fits its call
    /// boundary — `self.preloaded.clone()` for `RealizedCompiler::compile`'s
    /// per-call clone, `&mut preloaded` for `realize_in_memory`'s shared
    /// build-up.
    ///
    /// Sibling of [`expand_source_and_collect_calls_to`](Self::expand_source_and_collect_calls_to)
    /// — that method stacks the typed-keyword projection on top of the
    /// from-source pipeline (`read + expand_program + iter_calls_to(_,
    /// keyword) + map + collect`); this method is the bare yield-all-forms
    /// from-source primitive (`read + expand_program`) the typed dispatchers
    /// stack their keyword projection atop. The two together close the
    /// from-source posture of the program-level walk family on the
    /// `Expander` surface: bare (this method) vs. typed-keyword-projected
    /// (the sibling).
    ///
    /// Closes the 2×2 program-level walk family on the `Expander` surface:
    /// from-forms × yield-all ([`expand_program`](Self::expand_program)),
    /// from-forms × keyword-projected ([`expand_and_collect_calls_to`](Self::expand_and_collect_calls_to)),
    /// from-source × keyword-projected ([`expand_source_and_collect_calls_to`](Self::expand_source_and_collect_calls_to)),
    /// AND now from-source × yield-all (this method). The four together name
    /// the canonical surfaces a dispatcher composes with to extract an
    /// expanded program from either a pre-parsed `Vec<Sexp>` (from-forms
    /// posture, for callers composing with another `Sexp`-producing surface)
    /// or a raw `&str` (from-source posture, for callers consuming
    /// authoring-surface source text directly), with or without a
    /// typed-keyword filter on the result.
    ///
    /// `?`-routing through `read` preserves the structural ordering of the
    /// rejection chain end-to-end: a reader error (lexer / parser /
    /// unbalanced-paren / unterminated-string) short-circuits BEFORE
    /// `expand_program` runs; an `expand_program` error
    /// (`defmacro`-NAME-not-a-symbol, `OptionalParamMalformed`,
    /// `RestParamMissingName`, et al.) short-circuits at the offending form.
    /// Each consumer's rejection chain remains exactly what it was pre-lift,
    /// now sourced from ONE composition point rather than two.
    ///
    /// `defmacro`-registration side-effects fire on `&mut self` exactly as
    /// they do for the from-forms primitive — `realize_in_memory`'s per-spec
    /// build-up depends on every `defmacro` in every `:macros` source
    /// landing in `self.macros` (and, when `compile_templates` is on, in
    /// `self.templates`); `RealizedCompiler::compile`'s per-call clone
    /// posture isolates absorption to the cloned expander, so a
    /// `defmacro` in the user's source does NOT leak into the persistent
    /// realized compiler. Both postures' absorption semantics are
    /// preserved by routing through this primitive instead of inlining
    /// the two-step chain.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition; two
    /// inline copies of the `let forms = read(src)?; <expander>.expand_program(forms)`
    /// two-step chain across `RealizedCompiler::compile` and
    /// `realize_in_memory` is past the ≥2 PRIME-DIRECTIVE trigger once the
    /// structural shape is named. THEORY.md §V.1 — knowable platform; the
    /// read-then-expand composition becomes a NAMED primitive on the
    /// substrate's `Expander` surface rather than a re-derived two-step
    /// inline pipeline at every consumer. THEORY.md §II.1 invariant 2 —
    /// free middle; both consumers route through the SAME composition
    /// primitive, so a regression that drifts ONE consumer's pipeline
    /// shape from the other cannot reach the substrate's runtime.
    ///
    /// Frontier inspiration: Racket's `(eval-string str ns)` against a
    /// namespace — the from-source-string entry to namespace-level
    /// program evaluation is the Racket idiom; the substrate's
    /// `expand_source_program` is the Rust-typed peer of that, sourced
    /// from `&str` and yielding the post-macroexpansion `Vec<Sexp>`
    /// without a typed-keyword filter — exactly the shape an untyped
    /// consumer (`tatara-check`'s per-form dispatcher, a REPL's
    /// "expand this buffer" command, an LSP's "show me the expanded
    /// program" handler) binds to.
    pub fn expand_source_program(&mut self, src: &str) -> Result<Vec<Sexp>> {
        let forms = crate::reader::read(src)?;
        self.expand_program(forms)
    }

    /// Compose the expander's program-level expansion with the substrate's
    /// slice-side typed-keyword projection ([`iter_calls_to`]) and a
    /// caller-supplied per-form projection — `expand_program(forms)?` followed
    /// by `iter_calls_to(&expanded, keyword).map(project).collect()`, in ONE
    /// method on the `Expander` surface. Both [`compile_typed`](crate::compile::compile_typed)
    /// and [`compile_named_from_forms`](crate::compile::compile_named_from_forms)
    /// route through this primitive — they differ only in the per-form
    /// projection `F`: `T::compile_from_args` for the bare-kwargs form
    /// (`compile_typed`), and the NAME-then-`T::compile_from_args` split
    /// (`compile_named_from_forms`).
    ///
    /// Before this lift each dispatcher opened the same three-step pipeline
    /// inline — `let mut exp = Expander::new(); let expanded =
    /// exp.expand_program(forms)?; iter_calls_to(&expanded, T::KEYWORD)
    /// .map(<per-site>).collect()` — past the ≥2 PRIME-DIRECTIVE trigger
    /// once the structural shape is named. After this lift the pipeline
    /// lives in ONE method on the `Expander` surface and the two
    /// dispatchers thread their per-site projection through `F`; a
    /// regression that drifts ONE dispatcher's pipeline from the other (a
    /// future emitter that re-derives `expand_program + iter_calls_to`
    /// inline rather than composing through this primitive, a future
    /// preloaded-expander consumer that wants the same walk but on its
    /// own `Expander` rather than a fresh one) is no longer a silent
    /// two-site divergence: the method binds the composition once and
    /// every consumer threads the per-site projection through `F`.
    ///
    /// Method on `Expander` (not a free function) so the primitive
    /// composes with the broader expander surface: a preloaded expander
    /// (e.g., one that has already absorbed a set of `defmacro` forms
    /// via `expand_program` or `with_macros`) can call this method on
    /// its own state to walk a follow-up program — the
    /// `compiler_spec`'s realize path is the natural future consumer for
    /// that shape. `compile_typed` and `compile_named_from_forms`
    /// instantiate a fresh `Expander::new()` and dispatch through this
    /// method on it; a future preloaded consumer dispatches through it
    /// on the preloaded expander directly. ONE primitive, two postures
    /// (fresh vs. preloaded), no per-posture duplication of the
    /// `expand_program + iter_calls_to + map + collect` pipeline.
    ///
    /// `F` is `FnMut(&[Sexp]) -> Result<R>` — the per-form projection
    /// that fits the consumer's call site. The standard-library
    /// `Iterator::map` bound is `FnMut`, so a closure that captures
    /// mutable state (a future dispatcher that threads a running index
    /// or a borrowed accumulator into the projection) composes
    /// naturally. The `Result<R>` projection short-circuits on the
    /// first error via `Iterator::collect::<Result<Vec<R>, _>>()`, so
    /// the per-form rejection chain (`compile_named_from_forms`'s
    /// `NamedFormMissingName` for the missing NAME slot,
    /// `NamedFormNonSymbolName` for the non-symbol NAME slot,
    /// `T::compile_from_args`'s typed-entry kwargs gate, AND
    /// `compile_typed`'s bare-kwargs `T::compile_from_args` rejection)
    /// fires in the same order under the new shape.
    ///
    /// `R` is owned by construction — the iterator's `&[Sexp]` items
    /// borrow from the local `expanded: Vec<Sexp>` and that borrow
    /// ends when the `.collect()` consumes the iterator, so a `R`
    /// that borrowed from `expanded` would fail to compile here. The
    /// two production consumers (`Vec<T>`, `Vec<NamedDefinition<T>>`)
    /// are both owned-`R` shapes, matching the borrow's structural
    /// constraint.
    ///
    /// Sibling of [`expand_program`](Self::expand_program) — that
    /// method names the FIRST step of the pipeline (program-level
    /// macroexpansion, yielding `Vec<Sexp>`); this method composes it
    /// with the SECOND step (slice-side typed-keyword projection +
    /// per-form mapper). The split lets a consumer that wants the
    /// expanded forms WITHOUT the keyword filter (`tatara-check`'s
    /// per-form dispatcher walks every form, not just matched
    /// keywords) bind to `expand_program` directly; a consumer that
    /// wants both halves composed binds to this method.
    ///
    /// Closes the substrate's program-level walk family on the
    /// `Expander` surface: `expand_program` (yield-all-forms-after-
    /// expansion), `expand` (per-form recursive expansion), `apply`
    /// (per-call substitution), AND now `expand_and_collect_calls_to`
    /// (typed-keyword projection of the expanded forms with a per-form
    /// mapper). Together the four name the canonical surfaces a
    /// dispatcher composes with to extract a typed program from a
    /// post-expansion form set.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition;
    /// two inline copies of the `Expander::new() + expand_program +
    /// iter_calls_to(_, T::KEYWORD) + map + collect` pipeline across
    /// `compile_typed` and `compile_named_from_forms` is past the ≥2
    /// PRIME-DIRECTIVE trigger once the structural shape is named.
    /// THEORY.md §V.1 — knowable platform; the program-level walk's
    /// typed-keyword-projection composition becomes a NAMED primitive
    /// on the substrate's `Expander` surface rather than a re-derived
    /// three-step inline pipeline at every consumer. Authoring tools
    /// (REPL, LSP, `tatara-check`) that want to walk a program by
    /// typed keyword bind to ONE method on the `Expander` instead of
    /// re-implementing the composition. THEORY.md §II.1 invariant 1 —
    /// typed entry; the typed-keyword filter over an expanded program
    /// IS the rust-level typed-entry-batch gate, and naming its
    /// single shape lifts the gate from two-site duplication to one
    /// rust method the substrate's diagnostic promotions hang off of.
    /// THEORY.md §II.1 invariant 2 — free middle; both consumers
    /// route through the SAME composition primitive, each binding the
    /// per-form projection that fits its call site — a regression
    /// that drifts ONE dispatcher's pipeline shape from the other
    /// cannot reach the substrate's runtime.
    ///
    /// Frontier inspiration: MLIR's `Region::walk<Op>(callback)` —
    /// every typed rewriter that wants "for every Op of kind K in this
    /// region, run callback" binds to ONE typed walker that composes
    /// the kind filter with the per-op visitor; the substrate's
    /// `expand_and_collect_calls_to` is the unstructured-projection
    /// peer of that walker, lifted onto the post-expansion `&[Sexp]`
    /// algebra with the per-form projection as the visitor. Racket's
    /// `syntax-parse` `~seq (keyword args ...) ...` ellipsis-form —
    /// the program-level typed-keyword filter with per-match handler
    /// is the closed-form sibling of `~seq`'s repeated-pattern
    /// matcher, translated through pleme-io primitives as ONE method
    /// on `Expander` composing `expand_program` with `iter_calls_to`
    /// and a per-form mapper. GHC Core's `everything :: forall b. (b
    /// -> b -> b) -> GenericQ b -> GenericQ b` — the typed-IR rewriter's
    /// program-level fold over a typed selector is named ONCE and
    /// every consumer threads the per-node projection; the substrate's
    /// `expand_and_collect_calls_to` is the keyword-projected sibling
    /// of that fold on the `&[Sexp]` algebra.
    pub fn expand_and_collect_calls_to<R, F>(
        &mut self,
        forms: Vec<Sexp>,
        keyword: &str,
        mut project: F,
    ) -> Result<Vec<R>>
    where
        F: FnMut(&[Sexp]) -> Result<R>,
    {
        // Routes through the typed-decoded classifier sibling
        // [`Self::expand_and_collect_calls_to_any`] with a constant-
        // classifier decoder — the same constant-classifier composition
        // [`crate::ast::iter_calls_to`] uses to route through
        // [`crate::ast::iter_calls_to_any`] on the slice algebra. The
        // discarded `()` typed witness (`then_some(())`) is consumed by
        // the wrapper projection `|(), args| project(args)` so the
        // keyword consumer's per-form mapper sees only the args tail,
        // matching the pre-lift signature exactly. Both the keyword AND
        // classifier expander walks now share ONE pipeline implementation
        // (`expand_program + iter_calls_to_any + map + collect`); a
        // regression that drifts a future debug-mode logger, span-aware
        // borrow walker, or fused-iterator invariant from one expander
        // walk to the other becomes structurally impossible.
        self.expand_and_collect_calls_to_any(
            forms,
            |h| (h == keyword).then_some(()),
            move |(), args| project(args),
        )
    }

    /// Compose the expander's program-level expansion with the substrate's
    /// slice-side typed-decoded classifier projection ([`iter_calls_to_any`])
    /// and a caller-supplied per-form projection — `expand_program(forms)?`
    /// followed by `iter_calls_to_any(&expanded, decode).map(|(decoded, args)|
    /// project(decoded, args)).collect()`, in ONE method on the `Expander`
    /// surface. The typed-decoded sibling of
    /// [`Self::expand_and_collect_calls_to`] — where that method filters by
    /// ONE constant keyword, this method filters AND TYPES by a caller-
    /// supplied classifier, yielding the typed witness alongside the per-form
    /// projection's args input.
    ///
    /// Closes the substrate's program-level walk family on the `Expander`
    /// surface at the typed-decoded corner the prior runs' slice-side
    /// `iter_calls_to_any` lift left open — the (keyword, classifier) 2×2
    /// of compose-on-iter projections:
    ///
    /// |                | per-form algebra            | slice algebra                | expander surface                    |
    /// |----------------|-----------------------------|------------------------------|-------------------------------------|
    /// | keyword        | [`Sexp::as_call_to`]        | [`iter_calls_to`]            | [`Self::expand_and_collect_calls_to`] |
    /// | classifier `F` | [`Sexp::as_call_to_any`]    | [`iter_calls_to_any`]        | `expand_and_collect_calls_to_any` (this) |
    ///
    /// The keyword corner now ROUTES through the classifier corner at every
    /// row: [`Sexp::as_call_to`] = constant-classifier projection of
    /// [`Sexp::as_call_to_any`]; [`iter_calls_to`] = constant-classifier
    /// projection of [`iter_calls_to_any`]; [`Self::expand_and_collect_calls_to`]
    /// = constant-classifier projection of THIS method. The substrate's
    /// soft-dispatch family is structurally complete at every algebra
    /// level — per-form, slice, AND expander — so a regression that drifts
    /// a future debug-mode logger, span-aware borrow walker, or
    /// fused-iterator invariant from one walk to its sibling at any algebra
    /// level becomes structurally impossible.
    ///
    /// Two plausible future consumer shapes the typed-decoded expander walk
    /// admits with no boilerplate:
    ///   * **Closed-set classifier** — `expand_and_collect_calls_to_any(forms,
    ///     MacroDefHead::from_keyword, |head, args| dispatch(head, args))`
    ///     macroexpands a program and walks each `(defmacro …)` /
    ///     `(defpoint-template …)` / `(defcheck …)` form decoded to the typed
    ///     `MacroDefHead` enum with its args tail. Future `tatara-check`
    ///     consumers that want "for every macro-definition form in this
    ///     buffer, dispatch by typed kind" bind to ONE method on the
    ///     `Expander` rather than the three-step `expand_program +
    ///     iter_calls_to_any + map + collect` pipeline at each consumer site.
    ///   * **Live-registry classifier** — `expand_and_collect_calls_to_any(forms,
    ///     |h| registry.lookup(h), |handler, args| handler.handle(args))`
    ///     macroexpands a program and walks each form whose head matches a
    ///     runtime registry, decoded to a handler reference. Future
    ///     `tatara-check`-shaped runtime dispatchers (the kind already named
    ///     by [`iter_calls_to_any`]'s docstring as "the natural future
    ///     consumer") bind to ONE method on the `Expander` rather than the
    ///     three-step pipeline.
    ///
    /// The closed-form composition binding the keyword sibling to this typed-
    /// decoded primitive is the structural identity every consumer can pin
    /// against:
    ///
    /// ```ignore
    /// expand_and_collect_calls_to(forms, k, p) ==
    ///     expand_and_collect_calls_to_any(forms,
    ///         |h| (h == k).then_some(()),
    ///         |(), args| p(args))
    /// ```
    ///
    /// `D` is `FnMut(&str) -> Option<T>` — the typed-decoded classifier the
    /// substrate's per-form algebra already shapes ([`Sexp::as_call_to_any`]
    /// uses `FnOnce`, the slice algebra and this method use `FnMut` for the
    /// same reason: the walk calls the decoder once per matching form, and a
    /// decoder that captures mutable state (a counter, a registry cache, a
    /// visited-set) maintains that state across the program-level walk).
    /// `F` is `FnMut(T, &[Sexp]) -> Result<R>` — the per-form projection that
    /// receives BOTH the typed witness AND the args tail; the keyword sibling
    /// discards the (unit) typed witness via `|(), args| project(args)`. The
    /// `Result<R>` projection short-circuits on the first error via
    /// `Iterator::collect::<Result<Vec<R>, _>>()` so the per-form rejection
    /// chain fires in source order at the first failing matched form.
    ///
    /// `R` is owned by construction — same constraint as the keyword
    /// sibling. `T` is owned because the underlying [`iter_calls_to_any`]
    /// requires `T: 'a` where `'a` is the post-expansion `Vec<Sexp>` borrow
    /// lifetime; consumers projecting to a typed `Copy` enum
    /// (`MacroDefHead`, a future `AuthoringDirective`) get the value
    /// directly per form, consumers projecting to a borrowed `&'static str`
    /// (a closed-set head) project to `&'static str` and inherit the static
    /// lifetime through the classifier, consumers projecting to a `&Handler`
    /// (a live-registry classifier) bind through the registry's owned
    /// borrow with `&self` outliving the walk.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition; the
    /// keyword sibling [`Self::expand_and_collect_calls_to`] is now a
    /// CONSEQUENCE of this typed-decoded primitive + a constant-classifier
    /// decoder, parallel to how [`iter_calls_to`] is a consequence of
    /// [`iter_calls_to_any`] on the slice algebra. The substrate's
    /// program-level walk family is no longer two parallel implementations
    /// the type system fails to bind (a future regression that drifts the
    /// keyword pipeline's instrumentation from the classifier pipeline's
    /// instrumentation cannot reach the runtime — both compose through ONE
    /// `expand_program + iter_calls_to_any + map + collect` body, with the
    /// keyword filter expressed as a closed-form classifier). THEORY.md
    /// §V.1 — knowable platform; the typed-decoded expander walk becomes a
    /// NAMED primitive on the substrate's `Expander` surface rather than a
    /// future re-derived three-step inline pipeline per consumer.
    /// Authoring tools (REPL, LSP, `tatara-check`) that want to walk a
    /// program by typed-decoded classifier bind to ONE method on the
    /// `Expander` instead of re-implementing the composition. THEORY.md
    /// §II.1 invariant 2 — free middle; both expander-surface dispatchers
    /// (keyword + classifier) route through the SAME `expand_program +
    /// iter_calls_to_any + map + collect` composition primitive.
    ///
    /// Frontier inspiration: MLIR's `Region::walk<OpInterface,
    /// OpInterface2, …>([&](auto op) { … })` — the typed-IR walk over a
    /// region yielding ops decoded to their typed interface witness with
    /// per-op callback is the MLIR idiom; the substrate's
    /// `expand_and_collect_calls_to_any` is the unstructured-Rust peer on
    /// the post-expansion `&[Sexp]` algebra, with `decode: FnMut(&str) ->
    /// Option<T>` standing in for MLIR's typed-interface dyn-cast bag and
    /// `project: FnMut(T, &[Sexp]) -> Result<R>` standing in for the
    /// typed-op callback. Racket's `syntax-parse` `~or* (~datum defX)
    /// (~datum defY) (head args …)` over an ellipsis-form combined with a
    /// `#:with name:id` typed-witness binder — the program-level
    /// typed-decoded filter with per-match handler is the closed-form
    /// sibling of `syntax-parse`'s typed-choice repeater, translated
    /// through pleme-io primitives as ONE method on `Expander`. GHC Core's
    /// `everythingBut :: (a -> a -> a) -> GenericQ (a, Bool) -> GenericQ a`
    /// — the typed-IR rewriter's program-level fold over a typed
    /// kind-with-stop selector is named ONCE and every consumer threads
    /// the per-node typed projection; this method is the typed-decoded
    /// peer on the `Vec<Sexp>` algebra, with the classifier playing
    /// `everythingBut`'s typed-selector role.
    pub fn expand_and_collect_calls_to_any<R, F, D, T>(
        &mut self,
        forms: Vec<Sexp>,
        decode: D,
        mut project: F,
    ) -> Result<Vec<R>>
    where
        D: FnMut(&str) -> Option<T>,
        F: FnMut(T, &[Sexp]) -> Result<R>,
    {
        let expanded = self.expand_program(forms)?;
        crate::ast::iter_calls_to_any(&expanded, decode)
            .map(|(decoded, args)| project(decoded, args))
            .collect()
    }

    /// Read a source string into top-level forms via [`crate::reader::read`],
    /// then route the forms through
    /// [`expand_and_collect_calls_to`](Self::expand_and_collect_calls_to) — the
    /// from-source posture of the program-level walk, in ONE method on the
    /// `Expander` surface.
    ///
    /// Before this lift the same two-step chain — `let forms = read(src)?;
    /// <expander>.expand_and_collect_calls_to(forms, keyword, project)` — lived
    /// inline at four sites: the two free-function typed dispatchers
    /// ([`compile_typed`](crate::compile::compile_typed) and
    /// [`compile_named`](crate::compile::compile_named) via
    /// [`compile_named_from_forms`](crate::compile::compile_named_from_forms))
    /// AND the two preloaded-expander methods on
    /// [`RealizedCompiler`](crate::compiler_spec::RealizedCompiler)
    /// (`compile_typed`, `compile_named`). After this lift the read-then-walk
    /// composition lives in ONE method on the `Expander`; each of the four
    /// dispatchers binds it with the per-site `(expander posture, projection)`
    /// pair that fits its call boundary — `Expander::new()` for the
    /// fresh-expander dispatchers, `self.preloaded.clone()` for the
    /// preloaded-expander dispatchers; `T::compile_from_args` for the
    /// bare-kwargs projection, `named_form_projection::<T>` for the
    /// NAME-then-kwargs projection.
    ///
    /// Sibling of [`expand_and_collect_calls_to`](Self::expand_and_collect_calls_to)
    /// — that method takes a pre-parsed `Vec<Sexp>` (the from-forms posture,
    /// for callers that have already read or that compose with another
    /// `Sexp`-producing surface like a macro-expanded subform); this method
    /// takes a `&str` (the from-source posture, for callers consuming
    /// authoring-surface source text directly). Both compose with the same
    /// `expand_program + iter_calls_to + map + collect` pipeline through ONE
    /// from-forms primitive — the from-source posture stacks one read step on
    /// top, projecting `crate::reader::read`'s `Result<Vec<Sexp>>` into the
    /// from-forms primitive via `?`.
    ///
    /// `?`-routing through `read` preserves the structural ordering of the
    /// rejection chain end-to-end: a reader error (lexer / parser /
    /// unbalanced-paren / unterminated-string) short-circuits BEFORE
    /// `expand_program` runs; an `expand_program` error
    /// (`defmacro`-NAME-not-a-symbol, `OptionalParamMalformed`,
    /// `RestParamMissingName`, et al.) short-circuits BEFORE the keyword
    /// filter walks anything; a per-form `project` error
    /// (`NamedFormMissingName`, `NamedFormNonSymbolName`,
    /// `T::compile_from_args`'s typed-entry kwargs gate) short-circuits at the
    /// first failing matched form via `Iterator::collect::<Result<Vec<R>, _>>()`.
    /// Each dispatcher's rejection chain remains exactly what it was pre-lift,
    /// now sourced from ONE composition point rather than four.
    ///
    /// Closes the program-level walk family on the `Expander` surface across
    /// BOTH the from-forms posture
    /// ([`expand_and_collect_calls_to`](Self::expand_and_collect_calls_to))
    /// AND the from-source posture (this method) — together with
    /// `expand_program` (yield-all-forms-after-expansion), `expand` (per-form
    /// recursive expansion), and `apply` (per-call substitution), they name
    /// the canonical surfaces a dispatcher composes with to extract a typed
    /// program from a post-expansion form set. A future dispatcher that wants
    /// "read this source, then walk every call to keyword K and project each
    /// to R" — a debug-mode REPL command, an LSP "find all typed-domain
    /// definitions in this buffer" handler, a `tatara-check` command that
    /// dispatches each typed `(defX …)` form in `checks.lisp` to its
    /// registered domain — binds to ONE method on the `Expander` instead of
    /// re-deriving the two-step `read + expand_and_collect_calls_to` chain.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition; four
    /// inline copies of the `read(src)? + <expander>.expand_and_collect_calls_to`
    /// chain across the two fresh-expander dispatchers and the two
    /// preloaded-expander dispatchers is past the ≥2 PRIME-DIRECTIVE trigger
    /// once the structural shape is named. THEORY.md §V.1 — knowable
    /// platform; the read-then-walk composition becomes a NAMED primitive on
    /// the substrate's `Expander` surface rather than a re-derived two-step
    /// inline pipeline at every dispatcher. THEORY.md §II.1 invariant 2 —
    /// free middle; all four dispatchers route through the SAME composition
    /// primitive, so a regression that drifts ONE dispatcher's read-then-walk
    /// pipeline from the others cannot reach the substrate's runtime — the
    /// type system binds all consumers to the from-source primitive's single
    /// emission shape.
    ///
    /// Frontier inspiration: Racket's `(eval-string str ns)` against a
    /// namespace populated with the preloaded compiler's `require`d macros —
    /// the from-source-string entry to typed-program evaluation inside a
    /// namespace that carries the macro library is the Racket idiom; the
    /// substrate's `expand_source_and_collect_calls_to` is the Rust-typed
    /// peer of that, with the typed-keyword projection composed in.
    ///
    /// Post-lift the body routes through the typed-decoded sibling
    /// [`Self::expand_source_and_collect_calls_to_any`] with a
    /// constant-classifier decoder — the same constant-classifier
    /// composition [`Self::expand_and_collect_calls_to`] uses to route
    /// through [`Self::expand_and_collect_calls_to_any`] on the
    /// from-forms axis, and that [`crate::ast::iter_calls_to`] uses to
    /// route through [`crate::ast::iter_calls_to_any`] on the slice
    /// algebra. The discarded `()` typed witness (`then_some(())`) is
    /// consumed by the wrapper projection `|(), args| project(args)`
    /// so the keyword consumer's per-form mapper sees only the args
    /// tail. Both the keyword AND classifier from-source walks now
    /// share ONE pipeline implementation (`read + expand_program +
    /// iter_calls_to_any + map + collect`) — a regression that drifts
    /// a future debug-mode logger, span-aware borrow walker, or
    /// fused-iterator invariant from one from-source walk to the
    /// other becomes structurally impossible.
    pub fn expand_source_and_collect_calls_to<R, F>(
        &mut self,
        src: &str,
        keyword: &str,
        mut project: F,
    ) -> Result<Vec<R>>
    where
        F: FnMut(&[Sexp]) -> Result<R>,
    {
        self.expand_source_and_collect_calls_to_any(
            src,
            |h| (h == keyword).then_some(()),
            move |(), args| project(args),
        )
    }

    /// Read a source string into top-level forms via [`crate::reader::read`],
    /// then route the forms through
    /// [`expand_and_collect_calls_to_any`](Self::expand_and_collect_calls_to_any) —
    /// the from-source posture of the typed-decoded classifier walk, in
    /// ONE method on the `Expander` surface. The typed-decoded sibling of
    /// [`Self::expand_source_and_collect_calls_to`] — where that method
    /// filters by ONE constant keyword, this method filters AND TYPES by
    /// a caller-supplied classifier, yielding the typed witness alongside
    /// the per-form projection's args input. Sourced from `&str` rather
    /// than a `Vec<Sexp>`.
    ///
    /// Closes the substrate's program-level walk family on the `Expander`
    /// surface across BOTH input postures × BOTH projection forms — the
    /// (from-forms, from-source) × (keyword, classifier) 2×2 of
    /// compose-on-iter projections:
    ///
    /// |                | from-forms (`Vec<Sexp>`)                                      | from-source (`&str`)                                                |
    /// |----------------|---------------------------------------------------------------|---------------------------------------------------------------------|
    /// | keyword        | [`Self::expand_and_collect_calls_to`]                         | [`Self::expand_source_and_collect_calls_to`]                        |
    /// | classifier `F` | [`Self::expand_and_collect_calls_to_any`]                     | `expand_source_and_collect_calls_to_any` (this)                     |
    ///
    /// Each row's keyword corner now ROUTES through the classifier corner
    /// at every column: [`Self::expand_source_and_collect_calls_to`]'s
    /// body composes this typed-decoded primitive with a
    /// `|h| (h == keyword).then_some(())` decoder and the wrapper
    /// projection `|(), args| project(args)`, parallel to how
    /// [`Self::expand_and_collect_calls_to`] routes through
    /// [`Self::expand_and_collect_calls_to_any`] on the from-forms axis
    /// and [`crate::ast::iter_calls_to`] routes through
    /// [`crate::ast::iter_calls_to_any`] on the slice algebra. The 2×2
    /// reduces to ONE pipeline implementation
    /// (`read + expand_program + iter_calls_to_any + map + collect`)
    /// every consumer threads its `(decoder, project)` pair through.
    ///
    /// Future consumer shapes the typed-decoded from-source primitive
    /// admits:
    ///   * **Closed-set classifier** — `expand_source_and_collect_calls_to_any(
    ///     src, MacroDefHead::from_keyword, |head, args| { … })` walks a
    ///     source buffer dispatching every `(defmacro …)` / `(defpoint-template …)` /
    ///     `(defcheck …)` form to its typed `MacroDefHead` arm — exactly the
    ///     shape a future LSP "find every macro-definition form in this
    ///     buffer, decode each by typed kind" handler reaches for, sourced
    ///     from authoring text directly rather than a pre-parsed
    ///     `Vec<Sexp>`.
    ///   * **Live-registry classifier** — `expand_source_and_collect_calls_to_any(
    ///     src, |h| registry.get(h), |handler, args| handler.compile(args))`
    ///     walks a source buffer dispatching every form whose head is
    ///     registered to its typed handler — exactly the shape
    ///     `tatara-check`'s "macroexpand checks.lisp and dispatch every
    ///     `(defX …)` form through the registered domain dispatcher"
    ///     walker reaches for, sourced from disk-loaded source text
    ///     rather than the round-tripped `Vec<Sexp>` the typed
    ///     dispatchers consume.
    ///
    /// `?`-routing through `read` preserves the structural ordering of
    /// the rejection chain end-to-end: a reader error (lexer / parser /
    /// unbalanced-paren / unterminated-string) short-circuits BEFORE
    /// `expand_program` runs; an `expand_program` error short-circuits
    /// BEFORE the classifier filter walks anything; a per-form `project`
    /// error short-circuits at the first failing matched form via
    /// `Iterator::collect::<Result<Vec<R>, _>>()`. Each consumer's
    /// rejection chain inherits the from-forms typed-decoded primitive's
    /// shape verbatim, now sourced from `&str` via ONE composition point.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition;
    /// the (from-forms, from-source) × (keyword, classifier) 2×2 closes
    /// at the from-source classifier corner this method establishes —
    /// the prior runs' from-forms classifier sibling
    /// (`expand_and_collect_calls_to_any`, run e47d043) AND from-source
    /// keyword sibling (`expand_source_and_collect_calls_to`, run
    /// b477d81) AND slice-side classifier sibling (`iter_calls_to_any`,
    /// run 38625e3) named three of the four corners; this lift names
    /// the fourth so the family is structurally complete at every
    /// algebra level. THEORY.md §V.1 — knowable platform; the
    /// read-then-classifier-walk composition becomes a NAMED primitive
    /// on the substrate's `Expander` surface rather than a future
    /// re-derived `read(src)? + expand_and_collect_calls_to_any(…)`
    /// two-step chain at every consumer that wants to walk source text
    /// by typed-decoded classifier. THEORY.md §II.1 invariant 2 — free
    /// middle; the from-source keyword filter
    /// (`expand_source_and_collect_calls_to`) now routes through the
    /// from-source classifier filter via the constant-classifier
    /// composition, so a regression that drifts the keyword filter's
    /// instrumentation from the classifier filter's instrumentation
    /// becomes structurally impossible. The pre-lift inline
    /// `read(src)? + expand_and_collect_calls_to(forms, keyword, project)`
    /// chain is now a TYPED CONSEQUENCE of the typed-decoded primitive
    /// composed with a constant-classifier decoder, not a parallel
    /// implementation the type system happens to not catch.
    ///
    /// Frontier inspiration: Racket's `(eval-string str ns)` against a
    /// namespace + typed-syntax-class dispatch — the from-source-string
    /// entry to typed-program evaluation inside a namespace that carries
    /// the macro library, dispatching by typed syntax-class is the
    /// Racket idiom; the substrate's
    /// `expand_source_and_collect_calls_to_any` is the Rust-typed peer
    /// of that, with the typed-decoded classifier composed in. MLIR's
    /// `parseSourceFile<Op>(srcFile, ctx)` then `mod.walk<OpInterface>(
    /// callback)` — the parse-then-typed-walk over a source buffer
    /// dispatching by typed-interface witness is the MLIR idiom; this
    /// method is the substrate's typed `&[Sexp]`-algebra peer.
    pub fn expand_source_and_collect_calls_to_any<R, F, D, T>(
        &mut self,
        src: &str,
        decode: D,
        project: F,
    ) -> Result<Vec<R>>
    where
        D: FnMut(&str) -> Option<T>,
        F: FnMut(T, &[Sexp]) -> Result<R>,
    {
        let forms = crate::reader::read(src)?;
        self.expand_and_collect_calls_to_any(forms, decode, project)
    }

    /// Compose the expander's program-level expansion with the substrate's
    /// typed-decoded classifier walk AND the named-form NAME-shape gate
    /// ([`crate::compile::split_name_slot`]) — the from-forms posture of
    /// the (named NAME-then-kwargs × typed-decoded classifier) cell of
    /// the typed-dispatcher matrix on the `Expander` surface, sibling of
    /// [`Self::expand_to_named`] (the constant-`T::KEYWORD` × named cell)
    /// and of [`Self::expand_and_collect_calls_to_any`] (the from-forms
    /// classifier × bare-kwargs cell).
    ///
    /// Routes through [`Self::expand_and_collect_calls_to_any`] with a
    /// wrapper projection that composes [`crate::compile::split_name_slot`]
    /// (the named-form arity + NAME-shape gate on the substrate's
    /// `&[Sexp]` algebra) with the caller-supplied per-form projection.
    /// The decoder yields `Option<(T, &'static str)>` — the typed witness
    /// PAIRED with the canonical static keyword the named-form structural
    /// rejection variants ([`crate::error::LispError::NamedFormMissingName`],
    /// [`crate::error::LispError::NamedFormNonSymbolName`]) carry as
    /// `&'static str` slots. Threading the `&'static` constraint through
    /// the decoder's return type pins the same compile-time discipline
    /// [`crate::compile::split_name_slot`]'s `keyword: &'static str`
    /// parameter pins at the gate boundary — a typo in the canonical
    /// keyword can never drift into the diagnostic at runtime, same posture
    /// as the constant-`T::KEYWORD` cell where `T::KEYWORD` is
    /// `&'static str` by trait construction.
    ///
    /// Closes the (named × typed-decoded classifier) corner of the
    /// typed-dispatcher matrix on the `Expander` surface that the prior
    /// run's [`crate::compile::split_name_slot`] lift (dd50801) named as
    /// the future change the slice-side gate's named lift enables. The
    /// 2×2 of compose-on-iter projections on the named-form axis becomes
    /// structurally complete on the `Expander` surface:
    ///
    /// |                | constant `T::KEYWORD`               | typed-decoded classifier                     |
    /// |----------------|-------------------------------------|----------------------------------------------|
    /// | from-forms     | [`Self::expand_to_named`]           | `expand_and_collect_named_calls_to_any` (this) |
    /// | from-source    | [`Self::expand_source_to_named`]    | [`Self::expand_source_and_collect_named_calls_to_any`] |
    ///
    /// The constant-`T::KEYWORD` column is the typed CONSEQUENCE of the
    /// classifier column: an `expand_to_named::<T>(forms)` call composes
    ///
    /// ```ignore
    /// expand_and_collect_named_calls_to_any(forms,
    ///     |h| (h == T::KEYWORD).then_some(((), T::KEYWORD)),
    ///     |(), name, spec_args| {
    ///         let spec = T::compile_from_args(spec_args)?;
    ///         Ok(NamedDefinition { name: name.to_string(), spec })
    ///     })
    /// ```
    ///
    /// Both columns route through ONE composition point on the
    /// `Expander` surface (the typed-decoded classifier walk inside
    /// [`Self::expand_and_collect_calls_to_any`]) and ONE gate body on
    /// the `&[Sexp]` algebra ([`crate::compile::split_name_slot`]). A
    /// regression that drifts ONE cell's NAME-slot rejection chain from
    /// the others is structurally impossible — every cell binds to the
    /// SAME `split_name_slot` body, the SAME `expand_program +
    /// iter_calls_to_any + map + collect` pipeline. The
    /// pre-lift `NamedFormMissingName` / `NamedFormNonSymbolName`
    /// rejection chain inside `compile::named_form_projection` (the
    /// `pub(crate)` typed-domain SPECIALIZATION that
    /// [`Self::expand_to_named`] routes through) fires identically
    /// through this classifier primitive — both consumers compose
    /// [`crate::compile::split_name_slot`] with their per-site typed
    /// continuation.
    ///
    /// Future consumer shapes the typed-decoded named-form primitive
    /// admits with no boilerplate:
    ///   * **Closed-set classifier** — a `tatara-check` runner that
    ///     dispatches every `(defmonitor NAME …)` / `(defnotify NAME …)`
    ///     / `(defalertpolicy NAME …)` form in `checks.lisp` through ONE
    ///     classifier (a closed-set enum `Domain::{Monitor, Notify,
    ///     AlertPolicy}` with `Domain::from_keyword`) decoding each
    ///     head to its typed kind PAIRED with its canonical static
    ///     keyword, then dispatches in the per-form projection — binds
    ///     to ONE method rather than two-step `expand_and_collect_calls_to_any
    ///     + split_name_slot` composition at each consumer site.
    ///   * **Live-registry classifier** — a future `tatara-check`-shaped
    ///     runtime dispatcher: `expand_and_collect_named_calls_to_any(forms,
    ///     |h| registry.get(h).map(|d| (d, d.keyword())), |dispatcher,
    ///     name, args| dispatcher.compile(name, args))` walks a program
    ///     dispatching every named form whose head is in a runtime
    ///     registry, decoded to a handler reference AND its canonical
    ///     keyword (sourced from the dispatcher itself, NOT from the
    ///     matched head text). The `&'static str` discipline on the
    ///     keyword slot is preserved through the dispatcher's own
    ///     `keyword() -> &'static str` accessor.
    ///   * **`compile_named_any` free function family** — the natural
    ///     fresh-expander free-function + preloaded-`RealizedCompiler`
    ///     consumer pair, sibling of the existing `compile_typed_any`
    ///     / `RealizedCompiler::compile_typed_any` pair. A future run
    ///     lands those as 3-line composes on top of this primitive.
    ///
    /// `D` is `FnMut(&str) -> Option<(T, &'static str)>` — the typed-
    /// decoded classifier yields a typed witness `T` AND its canonical
    /// static keyword for the gate. `F` is `FnMut(T, &str, &[Sexp]) ->
    /// Result<R>` — the per-form projection receives the typed witness
    /// `T` ALONGSIDE the NAME slot's BORROWED `&str` projection (sourced
    /// from [`Sexp::as_symbol_or_string`], which accepts BOTH symbol and
    /// string NAME-author surfaces) AND the spec args tail. Consumers
    /// that need owned ownership of the NAME (`NamedDefinition.name:
    /// String`, JSON-serialized payloads) `.to_string()` themselves —
    /// pushing the clone to the consumer boundary keeps the primitive
    /// allocation-free. The `Result<R>` projection short-circuits on
    /// the first error via `Iterator::collect::<Result<Vec<R>, _>>()`
    /// inside [`Self::expand_and_collect_calls_to_any`].
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition;
    /// the (named × typed-decoded classifier) cell becomes a NAMED
    /// primitive on the `Expander` surface composed FROM TWO substrate
    /// primitives ([`Self::expand_and_collect_calls_to_any`] +
    /// [`crate::compile::split_name_slot`]) rather than re-derived
    /// inline at every named-classifier consumer's call site.
    /// THEORY.md §II.1 invariant 1 — typed entry; the typed-decoded
    /// classifier-filtered + NAME-shape-gated + caller-projected walk
    /// IS the typed-entry-batch gate for named-form dispatch at the
    /// `Expander` surface, with the `&'static str` keyword discipline
    /// preserved through the decoder's return type. THEORY.md §II.1
    /// invariant 2 — free middle; ALL four cells of the named-form
    /// dispatcher matrix on the `Expander` surface route through ONE
    /// composition point — a regression that drifts ONE cell's
    /// instrumentation from the others is structurally impossible.
    /// THEORY.md §V.1 — knowable platform; the named-form classifier
    /// walk becomes a discoverable primitive that LSP / REPL /
    /// `tatara-check` consumers bind to ONE method on the `Expander`
    /// instead of re-implementing the two-step `expand_and_collect_calls_to_any
    /// + split_name_slot` composition.
    ///
    /// Frontier inspiration: MLIR's `Region::walk<NamedOpInterface>(
    /// [&](auto op) { auto name = op.getName(); … })` — the typed-IR
    /// walk over a region yielding ops decoded to their typed interface
    /// witness with the named-symbol accessor pre-extracted is the
    /// MLIR idiom for named typed dispatch; this method is the
    /// substrate's unstructured-Rust peer with the typed-decoded
    /// classifier composed in and the NAME slot extracted via the
    /// substrate's `split_name_slot` gate. Racket's `syntax-parse`
    /// `~or* ((~datum defX) name:id arg ...) ((~datum defY) name:id
    /// arg ...) ((~datum defZ) name:id arg ...)` over an ellipsis-form
    /// — the typed-choice repeater with named-slot binder PAIRED with
    /// per-arm dispatch — is the Racket idiom; this primitive is the
    /// substrate's Rust-typed peer with the closed-set classifier
    /// playing the `~or*` typed-choice role and the NAME slot extracted
    /// by the substrate's slice-side gate.
    pub fn expand_and_collect_named_calls_to_any<R, F, D, T>(
        &mut self,
        forms: Vec<Sexp>,
        decode: D,
        mut project: F,
    ) -> Result<Vec<R>>
    where
        D: FnMut(&str) -> Option<(T, &'static str)>,
        F: FnMut(T, &str, &[Sexp]) -> Result<R>,
    {
        // Routes through the slice-side typed-decoded named projection
        // [`crate::ast::iter_named_calls_to_any`] — the same
        // `expand_program + iter_*_to_any + map + collect` shape
        // [`Self::expand_and_collect_calls_to_any`] uses on the bare-kwargs
        // axis. Pre-lift this method routed through the bare expander
        // surface and welded [`crate::compile::split_name_slot`] inside
        // the projection closure; post-lift the named gate composition
        // lives at the slice level (`iter_named_calls_to_any`'s body)
        // and the Expander surface inherits it through delegation. Both
        // rows of the Expander surface (bare-kwargs, named) now share
        // ONE pipeline skeleton on the slice algebra — a regression that
        // drifts a future debug-mode logger, span-aware borrow walker,
        // or fused-iterator invariant from one row to the other becomes
        // structurally impossible at the slice boundary.
        let expanded = self.expand_program(forms)?;
        crate::ast::iter_named_calls_to_any(&expanded, decode)
            .map(|maybe_triple| {
                let (decoded, name, spec_args) = maybe_triple?;
                project(decoded, name, spec_args)
            })
            .collect()
    }

    /// Read a source string into top-level forms via [`crate::reader::read`],
    /// then route the forms through
    /// [`Self::expand_and_collect_named_calls_to_any`] — the from-source
    /// posture of the (named × typed-decoded classifier) cell on the
    /// `Expander` surface, sibling of
    /// [`Self::expand_source_and_collect_calls_to_any`] (the from-source
    /// classifier × bare-kwargs cell).
    ///
    /// Closes the (from-forms, from-source) × (constant `T::KEYWORD`,
    /// typed-decoded classifier) 2×2 on the named-form axis of the
    /// `Expander` surface — together with [`Self::expand_to_named`],
    /// [`Self::expand_source_to_named`], and
    /// [`Self::expand_and_collect_named_calls_to_any`], every cell of the
    /// matrix binds to ONE composition point.
    ///
    /// `?`-routing through `read` preserves the structural ordering of
    /// the rejection chain end-to-end: a reader error (lexer / parser /
    /// unbalanced-paren / unterminated-string) short-circuits BEFORE
    /// `expand_program` runs; an `expand_program` error short-circuits
    /// BEFORE the classifier filter walks anything; the named-form gate
    /// (`split_first()` arity → `as_symbol_or_string()` shape) inside
    /// [`crate::compile::split_name_slot`] fires for the first matched
    /// form that violates either condition; a per-form `project` error
    /// short-circuits at the first failing matched form via
    /// `Iterator::collect::<Result<Vec<R>, _>>()`.
    ///
    /// Theory anchor: same as [`Self::expand_and_collect_named_calls_to_any`].
    /// THEORY.md §VI.1 (generation over composition; the from-source
    /// posture inherits the named-form gate composition through
    /// delegation rather than re-deriving the `read(src)? + walk + gate`
    /// chain at every from-source named-classifier consumer's call
    /// site), THEORY.md §II.1 invariant 2 (free middle; the from-source
    /// posture and the from-forms posture route through the SAME named-
    /// form composition).
    pub fn expand_source_and_collect_named_calls_to_any<R, F, D, T>(
        &mut self,
        src: &str,
        decode: D,
        project: F,
    ) -> Result<Vec<R>>
    where
        D: FnMut(&str) -> Option<(T, &'static str)>,
        F: FnMut(T, &str, &[Sexp]) -> Result<R>,
    {
        let forms = crate::reader::read(src)?;
        self.expand_and_collect_named_calls_to_any(forms, decode, project)
    }

    /// Macroexpand a pre-parsed program through `self` and project every
    /// `(keyword NAME :k v …)` form into `R` via a caller-supplied
    /// `(name, args) -> Result<R>` projection — the constant-keyword
    /// sibling of [`Self::expand_and_collect_named_calls_to_any`] on the
    /// named-form axis of the `Expander` surface, parallel to how
    /// [`Self::expand_and_collect_calls_to`] is the constant-keyword
    /// sibling of [`Self::expand_and_collect_calls_to_any`] on the
    /// bare-kwargs axis.
    ///
    /// Routes through the classifier sibling with a constant-classifier
    /// decoder that yields a discarded `()` typed witness paired with
    /// the `&'static str` keyword — the same `(T, &'static str)` decoder
    /// shape [`crate::compile::split_name_slot`] (composed inside the
    /// classifier primitive) pins at the slice-side gate boundary for
    /// the named-form structural rejection chain
    /// (`NamedFormMissingName.keyword`, `NamedFormNonSymbolName.keyword`).
    /// `&'static` is the same lifetime discipline the typed-decoded
    /// classifier signature enforces; the named gate's verbatim keyword
    /// threading inherits it through the constant-classifier composition.
    ///
    /// Projection signature `FnMut(&str, &[Sexp]) -> Result<R>` receives
    /// the BORROWED NAME slot and the BORROWED spec args tail. Consumers
    /// that need owned ownership (`NamedDefinition.name: String`) call
    /// `.to_string()` themselves — pushing the clone to the consumer
    /// boundary keeps the primitive allocation-free, matching the
    /// classifier sibling's projection signature on the NAME slot.
    ///
    /// Closes the (named NAME-then-kwargs × constant-keyword) cell of
    /// the `Expander` typed-walk family at the runtime-keyword × untyped
    /// `R` corner — pre-lift the cell was reachable ONLY through
    /// [`Self::expand_to_named`] with the `T: TataraDomain` type
    /// parameter baking `T::KEYWORD` AND the `T::compile_from_args`-
    /// based `crate::compile::named_form_projection<T>` projection
    /// into the dispatch through `expand_and_collect_calls_to(forms,
    /// T::KEYWORD, named_form_projection::<T>)`. Post-lift the cell
    /// surfaces as ONE method that takes the keyword and the
    /// `(name, args) -> R` projection as caller-supplied parameters,
    /// and [`Self::expand_to_named`] routes through it as the typed
    /// `T::KEYWORD`-constant specialization. The split lets a consumer
    /// that wants "walk every form whose head is a runtime keyword `kw`
    /// and project `(NAME, spec_args) -> R` for an arbitrary `R`" (a
    /// future REPL `:walk-named <kw>` command, an LSP "find-named-
    /// declarations-of-keyword `kw`" handler, a `tatara-check` runner
    /// dispatching on a single typed keyword whose projection isn't
    /// `T::compile_from_args`) bind to ONE method on the `Expander`
    /// surface rather than re-deriving the
    /// `expand_and_collect_named_calls_to_any(forms, |h| (h ==
    /// kw).then_some(((), kw)), |(), name, args| project(name, args))`
    /// two-line composition inline.
    ///
    /// Sibling of [`Self::expand_source_and_collect_named_calls_to`]
    /// — that method stacks a [`crate::reader::read`] step on top of
    /// this one (the from-source posture); this method takes a
    /// pre-parsed `Vec<Sexp>` (the from-forms posture). Together with
    /// [`Self::expand_and_collect_named_calls_to_any`] /
    /// [`Self::expand_source_and_collect_named_calls_to_any`], the four
    /// cells of the (named × {constant-keyword, classifier} ×
    /// {from-forms, from-source}) sub-matrix close on the `Expander`
    /// surface — each cell binds to ONE composition point, with the
    /// constant-keyword cells routing through the classifier cells via
    /// constant-classifier decoding.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition;
    /// the `split_name_slot` composition lived at TWO sites pre-lift
    /// (`crate::compile::named_form_projection` body, which
    /// [`Self::expand_to_named`] routes through, AND
    /// [`Self::expand_and_collect_named_calls_to_any`] body, which the
    /// typed-decoded classifier consumers route through) — past the
    /// ≥2 PRIME-DIRECTIVE trigger once the named-form gate is named.
    /// THEORY.md §V.1 — knowable platform; the named constant-keyword
    /// walk becomes a NAMED primitive on the `Expander` surface
    /// composable by any future consumer (REPL, LSP, `tatara-check`)
    /// instead of a re-derived two-line `expand_and_collect_named_
    /// calls_to_any(forms, constant-decoder, wrapper-projection)`
    /// composition. THEORY.md §II.1 invariant 2 — free middle; both
    /// the typed (`expand_to_named<T>`) and untyped (this method)
    /// constant-keyword named cells route through the SAME named
    /// classifier primitive — a regression that drifts ONE cell's
    /// NAME-slot rejection chain (`NamedFormMissingName`,
    /// `NamedFormNonSymbolName`) from the other becomes structurally
    /// impossible.
    ///
    /// Frontier inspiration: Racket's `syntax-parse` `((~datum kw)
    /// name:id arg ...)` arm — the named NAME-slot binder under a
    /// constant `~datum` keyword paired with a per-match handler is
    /// the Racket idiom; this method is the substrate's Rust-typed
    /// peer with the constant-keyword filter composed at the
    /// classifier corner. MLIR's `Region::walk<NamedOpKind>([&](auto
    /// op) { auto name = op.getName(); … })` against a single
    /// operation kind — the typed-IR walk yielding ops decoded to
    /// their typed kind with the named-symbol accessor pre-extracted,
    /// specialized on a constant kind; this method is the substrate's
    /// unstructured-`R` peer with the constant-classifier composition
    /// pinned at the call boundary.
    pub fn expand_and_collect_named_calls_to<R, F>(
        &mut self,
        forms: Vec<Sexp>,
        keyword: &'static str,
        mut project: F,
    ) -> Result<Vec<R>>
    where
        F: FnMut(&str, &[Sexp]) -> Result<R>,
    {
        // Routes through the typed-decoded named-classifier sibling
        // [`Self::expand_and_collect_named_calls_to_any`] with a
        // constant-classifier decoder — the same constant-classifier
        // composition [`Self::expand_and_collect_calls_to`] uses to
        // route through [`Self::expand_and_collect_calls_to_any`] on
        // the bare-kwargs axis, and that
        // [`crate::ast::iter_calls_to`] uses to route through
        // [`crate::ast::iter_calls_to_any`] on the slice algebra. The
        // discarded `()` typed witness (`then_some(((), keyword))`)
        // is consumed by the wrapper projection
        // `|(), name, args| project(name, args)` so the keyword
        // consumer's per-form mapper sees only `(name, spec_args)`,
        // matching the bare projection signature.
        self.expand_and_collect_named_calls_to_any(
            forms,
            |h| (h == keyword).then_some(((), keyword)),
            move |(), name, args| project(name, args),
        )
    }

    /// Read a source string into top-level forms via [`crate::reader::read`],
    /// then route the forms through
    /// [`Self::expand_and_collect_named_calls_to`] — the from-source
    /// posture of the (named × constant-keyword) cell on the
    /// `Expander` surface.
    ///
    /// Composes [`crate::reader::read`] with
    /// [`Self::expand_and_collect_named_calls_to`] — the
    /// `(keyword, project)` binding is bound in ONE place (the
    /// from-forms row) and this from-source sibling inherits the
    /// binding through delegation, mirroring how
    /// [`Self::expand_source_and_collect_calls_to`] composes
    /// [`crate::reader::read`] with [`Self::expand_and_collect_calls_to`]
    /// on the bare-kwargs axis.
    ///
    /// `?`-routing through `read` preserves the structural ordering of
    /// the rejection chain end-to-end: a reader error (lexer / parser /
    /// unbalanced-paren / unterminated-string) short-circuits BEFORE
    /// `expand_program` runs; an `expand_program` error short-circuits
    /// BEFORE the keyword filter walks anything; the named-form gate
    /// (`split_first()` arity → `as_symbol_or_string()` shape) inside
    /// [`crate::compile::split_name_slot`] fires for the first matched
    /// form that violates either condition; a per-form `project` error
    /// short-circuits at the first failing matched form via
    /// `Iterator::collect::<Result<Vec<R>, _>>()`. Each consumer's
    /// rejection chain inherits the constant-keyword named primitive's
    /// shape verbatim, now sourced from `&str` via ONE composition
    /// point.
    ///
    /// Sibling of [`Self::expand_and_collect_named_calls_to`] (the
    /// from-forms posture) and of [`Self::expand_source_and_collect_calls_to`]
    /// (the from-source × bare-kwargs cell on the constant-keyword
    /// row). The four cells of (named × {constant, classifier} ×
    /// {from-forms, from-source}) close on the `Expander` surface
    /// post-lift, each routing through ONE composition point.
    ///
    /// Theory anchor: same as [`Self::expand_and_collect_named_calls_to`].
    /// THEORY.md §VI.1 (generation over composition; the from-source
    /// posture inherits the constant-keyword named composition through
    /// delegation rather than re-deriving the
    /// `read(src)? + expand_and_collect_named_calls_to` chain at every
    /// from-source named-keyword consumer's call site),
    /// THEORY.md §II.1 invariant 2 (free middle; the from-source
    /// posture and the from-forms posture route through the SAME
    /// composition).
    pub fn expand_source_and_collect_named_calls_to<R, F>(
        &mut self,
        src: &str,
        keyword: &'static str,
        mut project: F,
    ) -> Result<Vec<R>>
    where
        F: FnMut(&str, &[Sexp]) -> Result<R>,
    {
        // From-source = from-forms × constant-classifier specialization
        // of the named classifier primitive's from-source sibling. The
        // discarded `()` typed witness and the `move |(), name, args|
        // project(name, args)` wrapper mirror the from-forms posture's
        // composition — both postures route through the SAME named
        // classifier primitive on the `Expander` surface, the
        // from-source row stacking one `read` step on top.
        self.expand_source_and_collect_named_calls_to_any(
            src,
            |h| (h == keyword).then_some(((), keyword)),
            move |(), name, args| project(name, args),
        )
    }

    /// Expand a single form. Top-level macro calls are rewritten; recurses
    /// into list children.
    ///
    /// Routes the macro-call dispatch surface through the substrate's
    /// typed-decoded call decomposition: `as_call_to_any(|h|
    /// self.macros.get(h))` answers "is this form an invocation of any
    /// registered macro, decoded to `(&MacroDef, args)`?" in ONE
    /// structural query on the `Sexp` algebra. Pre-lift the same site
    /// opened the three-step chain `as_list() + as_call() + self.macros.
    /// get(head)` inline — `as_list()` for the children-walk fallthrough,
    /// `as_call()` for the (head, args) decomposition (which itself
    /// re-derives `as_list()` internally), and `self.macros.get(head)`
    /// for the registry lookup; post-lift the call-recognition runs as
    /// ONE `as_call_to_any` projection with the HashMap lookup as its
    /// classifier, and the `as_list()` fallthrough fires only on the
    /// not-a-macro-call path. Sibling consumer to `macro_def_from` — the
    /// typed-macro-definition dispatcher that routes through
    /// `as_call_to_any(MacroDefHead::from_keyword)` with the closed-set
    /// enum classifier. With both in place, BOTH dispatch sites in the
    /// macro expander (definition-recognition + call-recognition)
    /// project through the SAME family primitive on the `Sexp` algebra,
    /// each binding the classifier that fits its candidate set — closed
    /// enum for the static head-set, HashMap lookup for the live
    /// registry. A regression that drifts ONE site from the other (a
    /// future emitter that re-derives `as_list()` + `head.as_symbol()` +
    /// `self.macros.get(_)` inline rather than routing through the
    /// family) is no longer a silent two-site divergence.
    pub fn expand(&self, form: &Sexp) -> Result<Sexp> {
        self.expand_with_depth(form, 0)
    }

    /// The depth-carrying peer of [`Self::expand`]. Each
    /// post-apply re-expansion increments `depth`; each tree-child
    /// descent passes `depth` through unchanged. The runaway
    /// `(defmacro loop (x) `(loop ,x))` accretes depth on the
    /// re-expansion path — one unit per round — and hits the ceiling
    /// in `max_expansion_depth` rounds; lawful nested macros
    /// (`(when1 (when1 x))`) accrete depth in the low single digits
    /// because tree traversal doesn't count.
    ///
    /// The `depth >= limit` check sits INSIDE the macro-call arm
    /// (`Some((def, args)) = form.as_call_to_any(…)`) rather than at
    /// the top of the function so `def.name.clone()` is available at
    /// the rejection site — the operator gets `macro_name` populated
    /// from the actual offending call rather than a `<unknown>`
    /// fallback. Tree-child descent is not gated on the ceiling
    /// because the tree-child arm does not accrete depth; a lawfully
    /// deep tree is bounded by the reader's own stack, not by this
    /// ceiling.
    ///
    /// The peer OUTPUT-SIZE gate (`expanded.node_count() >
    /// self.limits.max_expansion_size`) sits INSIDE the same macro-call arm,
    /// between the `apply` and the re-expansion recursion, so a
    /// single macro's `apply` output whose structural size crosses
    /// the ceiling is rejected AT the offending `apply` boundary
    /// (with `macro_name` populated from `def.name`) before the
    /// runaway tree feeds back into further expansion. The gate is
    /// keyed on `>` rather than `>=` so `max_expansion_size` names
    /// the LARGEST admissible output — the ceiling admits equality,
    /// only strict overrun rejects. Together with the depth ceiling
    /// (recursion length) and the cache ceiling (memoization width),
    /// this closes the expander's RESOURCE surface at three typed
    /// dimensions.
    fn expand_with_depth(&self, form: &Sexp, depth: usize) -> Result<Sexp> {
        if let Some((def, args)) = form.as_call_to_any(|h| self.macros.get(h)) {
            if depth >= self.limits.max_expansion_depth {
                return Err(LispError::ExpansionDepthExceeded {
                    macro_name: def.name.clone(),
                    limit: self.limits.max_expansion_depth,
                });
            }
            let expanded = self.apply(def, args)?;
            // Reject a single `apply` output whose structural node
            // count crosses the OUTPUT-SIZE ceiling — the RESOURCE
            // axis peer of the depth (recursion length) and
            // cache-entries (memoization width) ceilings. Catches
            // the canonical "expansion bomb" where a well-defined
            // macro produces a 2^N-node blob from a small input
            // while `depth` stays in the low single digits and the
            // cache entry count sits under any reasonable ceiling.
            let expanded_size = expanded.node_count();
            if expanded_size > self.limits.max_expansion_size {
                return Err(LispError::ExpansionSizeExceeded {
                    macro_name: def.name.clone(),
                    size: expanded_size,
                    limit: self.limits.max_expansion_size,
                });
            }
            // Recurse — the expansion itself may contain more macro calls.
            return self.expand_with_depth(&expanded, depth + 1);
        }
        // Not a macro call — expand children if this is a list; otherwise
        // (atom / Nil / quote-family wrapper) return the form verbatim.
        let Some(list) = form.as_list() else {
            return Ok(form.clone());
        };
        let mut out = Vec::with_capacity(list.len());
        for item in list {
            out.push(self.expand_with_depth(item, depth)?);
        }
        Ok(Sexp::List(out))
    }

    /// Apply a macro to its argument list.
    ///
    /// Three-layer fast path:
    ///   1. If `cache_enabled`, hash `(name, args)` and consult the memo table.
    ///   2. If a compiled template exists, run the bytecode interpreter.
    ///   3. Otherwise fall back to the name-keyed substitute walker.
    fn apply(&self, def: &MacroDef, args: &[Sexp]) -> Result<Sexp> {
        // Layer 1: expansion cache.
        let cache_key = if self.cache_enabled {
            args_cache_key(&def.name, args)
        } else {
            None
        };
        if let Some(ref key) = cache_key {
            if let Some(cached) = self.cache.lock().unwrap().get(key) {
                return Ok(cached.clone());
            }
        }

        // Layer 2: compiled bytecode.
        let result = if let Some(tmpl) = self.templates.get(&def.name) {
            apply_compiled(&def.name, &def.params, tmpl, args)?
        } else {
            // Layer 3: substitute fallback. Walk the body's substitution
            // projection — the inner of the outer quasi-quote when present,
            // the body verbatim otherwise — through the shared
            // `MacroDef::template_body` primitive both strategies route on.
            let bindings = bind_args(&def.name, &def.params, args)?;
            substitute(def.template_body(), &bindings)?
        };

        // Populate cache on miss — capped by `max_cache_entries` so the
        // memoization table cannot drift unboundedly across a long-
        // running host session. When the cap is reached the freshly-
        // computed result is returned verbatim; correctness is
        // unaffected because caching is a pure PERFORMANCE optimization
        // (the miss path always recomputes the same value the cache
        // would have returned).
        if let Some(key) = cache_key {
            let mut cache = self.cache.lock().unwrap();
            if cache.len() < self.limits.max_cache_entries {
                cache.insert(key, result.clone());
            }
        }
        Ok(result)
    }

    pub fn has(&self, name: &str) -> bool {
        self.macros.contains_key(name)
    }

    pub fn len(&self) -> usize {
        self.macros.len()
    }

    pub fn is_empty(&self) -> bool {
        self.macros.is_empty()
    }
}

// ── Compiled template bytecode ───────────────────────────────────────

/// One op in the template bytecode. Emitted during compilation; consumed at
/// expansion to materialize a form without HashMap lookups or recursion.
#[derive(Clone, Debug, PartialEq)]
pub enum TemplateOp {
    /// Push a literal Sexp. Used for atoms and entirely-literal subtrees.
    Literal(Sexp),
    /// Push the bound arg at the given param index.
    Subst(usize),
    /// If the bound arg is a list, append its items to the current list; else
    /// push it as a single item.
    Splice(usize),
    /// Begin a new List — pushes a fresh builder onto the expansion stack.
    BeginList,
    /// End the current List — pops the builder, wraps as `Sexp::List`.
    EndList,
}

/// Pre-compiled template. Built once per macro, interpreted many times.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CompiledTemplate {
    pub ops: Vec<TemplateOp>,
}

/// Walk a macro definition's template body and emit linear bytecode.
/// Purely-literal subtrees compile to a single `Literal(clone)` op.
///
/// Compilation can fail if the template references a name that isn't a
/// declared parameter — same semantic as the substitute path.
///
/// Top-level `,@X` bodies (the splice is the entire body, not nested inside
/// a `(... ,@xs ...)` list) are rejected here at compile time so the
/// bytecode path agrees with the substitute path's emission-time rejection
/// (`splice_outside_list`). Without this gate the bytecode interpreter's
/// outermost stack frame silently absorbed the splice's items, and the same
/// macro emitted different output across paths — `compiled_template_matches
/// _substitute_path` only covered well-positioned splice bodies. After this
/// gate every `,@-outside-list` body is rejected at registration time on
/// both paths with ONE structural variant (`LispError::SpliceOutsideList`).
///
/// The gate routes through [`Sexp::as_unquote`] — the typed-marker
/// projection that pairs `Sexp::UnquoteSplice ↔ UnquoteForm::Splice` at
/// ONE structural query — matching `Some((UnquoteForm::Splice, inner))`
/// rather than the per-arm `Sexp::UnquoteSplice(inner)` literal that
/// recurred at three sites pre-lift (`compile_node` Subst/Splice arms,
/// `substitute` top-level + list-inner). Sibling shape to `substitute`'s
/// list-inner Splice arm — both use the same `Some((UnquoteForm::Splice,
/// inner))` shape; `substitute`'s top-level arm uses the wider
/// `Some((kind, inner))` and dispatches inside on `kind`. After this lift
/// every production-site recognizer of "is this an `,@X` form" routes
/// through ONE typed-marker projection rather than re-deriving the
/// (Sexp variant, UnquoteForm variant) pair inline.
pub fn compile_template(def: &MacroDef) -> Result<CompiledTemplate> {
    // Walk the body's substitution projection — the inner of the outer
    // quasi-quote when present, the body verbatim otherwise — through the
    // shared `MacroDef::template_body` primitive the substitute path also
    // routes on. Same projection, both strategies, by construction.
    let body = def.template_body();
    if let Some((UnquoteForm::Splice, inner)) = body.as_unquote() {
        return Err(splice_outside_list(inner));
    }
    let names = def.params.names();
    let mut ops = Vec::new();
    compile_node(body, &names, &mut ops)?;
    Ok(CompiledTemplate { ops })
}

fn compile_node(node: &Sexp, params: &[&str], ops: &mut Vec<TemplateOp>) -> Result<()> {
    // Fast-path literal: if the subtree has no Unquote/UnquoteSplice, emit a
    // single Literal op. This is the big win for macros where most of the
    // template is fixed structure.
    if !contains_unquote(node) {
        ops.push(TemplateOp::Literal(node.clone()));
        return Ok(());
    }
    // Routes the `Sexp::Unquote(inner)` / `Sexp::UnquoteSplice(inner)` arms
    // through [`Sexp::as_unquote`] — the typed-marker projection that
    // pairs `Sexp::Unquote ↔ UnquoteForm::Unquote` and
    // `Sexp::UnquoteSplice ↔ UnquoteForm::Splice` at ONE site. The per-form
    // `TemplateOp` emission (`Subst` vs `Splice`) keys on the same typed
    // `form` value the gate-1+gate-2 composition `resolve_unquote_in_params`
    // threads through. Pre-lift the (Sexp variant, UnquoteForm variant)
    // pairing was bound per-arm — a future emitter that matched
    // `Sexp::Unquote(_)` but threaded `UnquoteForm::Splice` into
    // `resolve_unquote_in_params` (or vice versa) would type-check but
    // render a misleading diagnostic at the gate-1 / gate-2 rejection.
    // Post-lift the pair is bound at ONE projection function and the
    // `match form` mechanically lowers it to the bytecode op.
    if let Some((form, inner)) = node.as_unquote() {
        let idx = resolve_unquote_in_params(inner, params, form)?;
        ops.push(match form {
            UnquoteForm::Unquote => TemplateOp::Subst(idx),
            UnquoteForm::Splice => TemplateOp::Splice(idx),
        });
        return Ok(());
    }
    match node {
        Sexp::List(items) => {
            ops.push(TemplateOp::BeginList);
            for item in items {
                compile_node(item, params, ops)?;
            }
            ops.push(TemplateOp::EndList);
        }
        _ => ops.push(TemplateOp::Literal(node.clone())),
    }
    Ok(())
}

fn contains_unquote(node: &Sexp) -> bool {
    // Route every quote-family wrapper recognition — both the
    // unquote-only subset (Unquote/UnquoteSplice → short-circuit `true`)
    // AND the quote-only subset (Quote/Quasiquote → recurse into inner) —
    // through [`Sexp::as_quote_form`]'s typed-marker projection. Pre-lift
    // the recognizer split into two arms: `as_unquote().is_some()` (the
    // substitution subset gate) + the inline
    // `Sexp::Quote(inner) | Sexp::Quasiquote(inner)` arm (the remaining
    // quote-only subset). Post-lift both arms route through ONE
    // projection and the (Sexp variant, QuoteForm variant) pairing binds
    // at the closed-set algebra. The `form.as_unquote_form().is_some()`
    // gate is the SAME 2-of-4 subset projection [`Sexp::as_unquote`]
    // derives from, so recognizing "is this an unquote-family wrapper"
    // and "is this a quote-only wrapper" share ONE typed dispatch site;
    // rustc enforces that a future `Sexp` wrapper extension carry
    // through both `QuoteForm::ALL` AND `QuoteForm::as_unquote_form`'s
    // arm. Sibling posture to `Hash for Sexp`'s four-arm
    // `hash_discriminator` collapse, `Display for Sexp`'s `prefix`
    // collapse, `interop`'s `iac_forge_tag` collapse, and `domain`'s
    // `sexp_shape` collapse — every production-site quote-family
    // recognizer now routes through ONE projection on the algebra.
    if let Some((form, inner)) = node.as_quote_form() {
        return form.as_unquote_form().is_some() || contains_unquote(inner);
    }
    match node {
        Sexp::List(items) => items.iter().any(contains_unquote),
        _ => false,
    }
}

/// Splice a resolved template value into an in-progress list builder —
/// the SHARED coercion both expansion strategies apply once `,@name`'s
/// gate-1 (must-be-a-symbol) and gate-2 (must-be-bound-in-scope) have
/// resolved the bound value. ONE named primitive the bytecode path
/// (`apply_compiled`'s `TemplateOp::Splice` arm) AND the substitute path
/// (`substitute`'s list-inner `Sexp::UnquoteSplice` arm) share. Before
/// this lift the three-arm coercion —
///
/// ```ignore
/// match value {
///     Sexp::List(items) => builder.extend(items.iter().cloned()),
///     Sexp::Nil         => {}
///     other             => builder.push(other.clone()),
/// }
/// ```
///
/// — was inlined at BOTH sites; the splice RESULT semantics (the last
/// inline-duplicated piece of the splice path after the prior runs lifted
/// gate-1, gate-2, and their composition) lived in two places that MUST
/// agree. After this lift the coercion lives in ONE function, so a
/// regression that drifts one strategy's splice posture from the other —
/// e.g. changing the `Sexp::Nil` arm to push an empty list at the
/// bytecode path but not the substitute path, or coercing a non-list
/// scalar differently across the two strategies — becomes structurally
/// impossible: there is exactly one implementation both strategies call.
///
/// The coercion's three arms ARE the no-evaluator template language's
/// splice contract: a bound LIST flattens its elements into the builder
/// (the canonical splice), a bound NIL contributes nothing (splicing the
/// empty list), and any other bound value splices as a single element (a
/// scalar `,@x` degrades to `,x` rather than erroring — invariant 2's
/// "free middle" lets the macro author rely on this without a
/// mid-rewrite type check; the typed-exit gate re-validates the
/// assembled form). Naming the contract once gives a future gate-3
/// (typed-shape enforcement on bound splice targets) ONE site to wrap
/// rather than two inline arms to keep in lockstep.
///
/// Theory anchor: THEORY.md §II.1 invariant 2 — free middle; the two
/// expansion strategies MUST produce identical output for the same
/// (macro, args) pair, and naming the splice coercion once makes that
/// per-strategy agreement structural rather than a two-site discipline
/// the `expansion_layers_agree_on_output_and_cache_wins` benchmark only
/// observes after the fact. THEORY.md §V.1 — knowable platform; the
/// splice RESULT semantics becomes a NAMED primitive authoring tools and
/// future runs bind to. THEORY.md §VI.1 — generation over composition;
/// the two-site coercion is lifted to ONE function, closing the last
/// inline-duplicated piece of the splice path the prior runs' gate lifts
/// (02173dc gate-1, 68da647 gate-2, b456f1f composition) left behind.
fn splice_value_into(builder: &mut Vec<Sexp>, value: &Sexp) {
    match value {
        Sexp::List(items) => builder.extend(items.iter().cloned()),
        Sexp::Nil => {}
        other => builder.push(other.clone()),
    }
}

/// Promote the previously `LispError::Compile`-shaped helper into the
/// structural `LispError::TemplateInvariant { macro_name, kind }` variant.
/// The four reachable bytecode-runtime invariant violations in
/// `apply_compiled` — Subst-bad-index, Splice-bad-index, EndList-empty-
/// stack, final-no-value — funnel through ONE emission shape keyed on
/// the closed-set `TemplateInvariantKind` enum. The index payload of
/// the Subst / Splice gates lives INSIDE the variant (`SubstBadIndex(usize)`
/// / `SpliceBadIndex(usize)`), so the invalid combination "stack-gate
/// kind with an op-index" (e.g. `EndListEmptyStack` carrying a `usize`)
/// is structurally unrepresentable — the type system encodes "this gate
/// has an index, that gate does not."
///
/// Display matches the legacy `Compile`-shaped diagnostic byte-for-byte
/// across all four kinds (`"compile error in {macro_name}: <invariant>"`)
/// via the closed-set `TemplateInvariantKind::message()` projection, so
/// authoring-tool substring greps (`tatara-check`, REPL) see no drift
/// across the lift.
///
/// Theory anchor: THEORY.md §V.1 — knowable platform; the closed set
/// of bytecode-invariant failure modes becomes a TYPE rather than a
/// free-form `message: String` slot. THEORY.md §VI.1 — generation over
/// composition; the typed enum lands the structural-completeness floor
/// for the bytecode-runtime surface, parallel to how `CompilerSpecIoStage`
/// lands the structural-completeness floor for the disk-persistence
/// surface (`compiler_spec.rs`, the immediately prior claude-routine
/// lift on a sibling file). THEORY.md §II.1 invariant 5 (composition
/// preserves proofs): a well-formed bytecode invariant is the proof
/// that drives the interpreter; the structural variant makes the
/// proof's REJECTION shape first-class — authoring tools (REPL, LSP,
/// `tatara-check`) pattern-match on the `kind` slot and bind to the
/// gate identity directly instead of substring-parsing the rendered
/// diagnostic.
fn template_invariant_violation(macro_name: &str, kind: TemplateInvariantKind) -> LispError {
    LispError::TemplateInvariant {
        macro_name: macro_name.into(),
        kind,
    }
}

/// Look up a bound-arg by its template-bytecode index, or raise the
/// structural `LispError::TemplateInvariant` rejection with the
/// caller-supplied `kind` constructor applied to the bad index. ONE
/// named primitive both bytecode-runtime arms that read a bound arg
/// by index — [`TemplateOp::Subst`] (single-value push) AND
/// [`TemplateOp::Splice`] (list-splicing) — route through.
///
/// Before this lift the same `args_by_index.get(*idx).ok_or_else(||
/// template_invariant_violation(macro_name, KIND(*idx)))?` projection
/// appeared at BOTH arms of [`apply_compiled`], differing only in the
/// kind constructor: [`TemplateInvariantKind::SubstBadIndex`] at the
/// `Subst` arm, [`TemplateInvariantKind::SpliceBadIndex`] at the
/// `Splice` arm. The arms also diverged on what they did with the
/// returned `&Sexp` — `Subst` cloned and pushed, `Splice` consumed
/// the borrow through [`splice_value_into`] — but the lookup-and-
/// reject prelude was byte-identical modulo the kind, well past the
/// ≥2 PRIME-DIRECTIVE trigger.
///
/// After this lift the lookup-and-reject shape lives in ONE function;
/// the two arms thread the per-call-site kind constructor through the
/// helper and apply their respective post-lookup verbs at the call
/// site. The `kind: FnOnce(usize) -> TemplateInvariantKind` parameter
/// encodes the closed-set bytecode-runtime "this gate has an index"
/// surface at the type level — only the two
/// [`TemplateInvariantKind`] variants whose payload IS the bad index
/// (`SubstBadIndex(usize)` and `SpliceBadIndex(usize)`) construct
/// directly through `FnOnce(usize) -> TemplateInvariantKind`; the
/// stack-gate variants ([`TemplateInvariantKind::EndListEmptyStack`]
/// and [`TemplateInvariantKind::FinalNoValue`]) carry no payload and
/// would not type-check at this boundary, so the invalid combination
/// "stack-gate kind reached from an op-index lookup" is structurally
/// unrepresentable at the helper's call boundary the same way
/// [`TemplateInvariantKind`]'s closed-set shape makes it
/// unrepresentable in the variant itself.
///
/// Sibling of [`template_invariant_violation`]: that helper builds the
/// typed [`LispError::TemplateInvariant`] variant from a fully-formed
/// `kind`; this helper composes the index-keyed lookup with the
/// variant-builder, so the kind constructor doesn't have to be evaluated
/// eagerly at the call site (lazy via `FnOnce`, only fires on the bad-
/// index path). A future fifth bytecode op that reads a bound arg by
/// index (a hypothetical [`TemplateOp::Conditional`] that branches on a
/// bound boolean, a [`TemplateOp::Project`] that extracts a sub-field
/// of a bound `Sexp::List`) extends the family in ONE call to
/// `resolve_bound_arg` with the new kind constructor (`KIND(usize) ->
/// TemplateInvariantKind`) — the bytecode-runtime's bound-arg-by-index
/// projection becomes ONE structural primitive consumers compose with.
///
/// The returned `&'a Sexp` borrows from `args_by_index` verbatim —
/// `Subst`'s arm consumes it through `.clone()` (the consumer pushes
/// an owned value into the builder); `Splice`'s arm consumes it
/// through [`splice_value_into`] (the consumer borrows for the
/// per-arm coercion). The borrow's lifetime `'a` is the unified
/// lifetime of `args_by_index`, matching the call site's borrow
/// posture.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; two
/// inline copies of the index-lookup-and-reject prelude across the
/// `apply_compiled` body's `Subst` and `Splice` arms is past the ≥2
/// PRIME-DIRECTIVE trigger once the structural shape is named.
/// THEORY.md §V.1 — knowable platform / "make invalid states
/// unrepresentable"; the bytecode-runtime bound-arg-by-index lookup
/// becomes a NAMED primitive on the substrate's `&[Sexp]` algebra
/// rather than a re-derived `get + ok_or_else + template_invariant_
/// violation` chain at every op-arm that reads by index. A future
/// authoring tool (REPL, LSP, `tatara-check`) that wants to surface
/// "this bytecode op's bound-arg lookup misfired at idx N" binds to
/// ONE function. THEORY.md §II.1 invariant 2 — free middle; both
/// expansion strategies route through the SHARED `MacroParams::bind`,
/// AND the bytecode strategy's op-arms route through this SHARED
/// `resolve_bound_arg` lookup — the bytecode-runtime's
/// proof-of-well-formedness is now structurally uniform across the
/// two reachable index-lookup ops, so a regression that drifts ONE
/// arm's posture (e.g. accepts an out-of-range idx at one arm but
/// not the other, or swaps the kind constructor at a single arm) is
/// no longer a silent two-site divergence.
fn resolve_bound_arg<'a>(
    args_by_index: &'a [Sexp],
    idx: usize,
    macro_name: &str,
    kind: impl FnOnce(usize) -> TemplateInvariantKind,
) -> Result<&'a Sexp> {
    args_by_index
        .get(idx)
        .ok_or_else(|| template_invariant_violation(macro_name, kind(idx)))
}

/// Project the bytecode-runtime stack to its in-progress builder frame —
/// the `&mut Vec<Sexp>` every value-emitting op writes into. ONE named
/// primitive both push-emitting arms (`TemplateOp::Literal` /
/// `TemplateOp::Subst` / post-`EndList` parent fold) AND the splice-
/// emitting arm (`TemplateOp::Splice`) route through.
///
/// Before this lift the same `stack.last_mut().unwrap()` projection
/// appeared at FOUR sites inside [`apply_compiled`]'s op-loop:
///
///   * `TemplateOp::Literal` — pushes the literal `Sexp` into the
///     current builder.
///   * `TemplateOp::Subst` — pushes the cloned bound-arg into the
///     current builder.
///   * `TemplateOp::Splice` — splices the bound-arg into the current
///     builder via [`splice_value_into`].
///   * `TemplateOp::EndList` — after popping the just-finished list
///     frame, pushes the folded `Sexp::List(items)` into the parent
///     builder (the new current frame).
///
/// Four byte-identical re-derivations of the same projection, well past
/// the ≥2 PRIME-DIRECTIVE trigger. After this lift the four sites
/// collapse to a single `current_builder_mut(&mut stack).{push|extend}`
/// call, and the bytecode-runtime invariant the projection rests on
/// — "the op-loop always sees at least one stack frame" — lives in ONE
/// expect message rather than four silent `.unwrap()` calls.
///
/// The expect rationale: [`apply_compiled`] seeds the stack with the
/// outermost frame at entry (`vec![Vec::with_capacity(1)]`); every
/// `TemplateOp::BeginList` pushes a NEW frame and every
/// `TemplateOp::EndList` pops it, so the count stays at OR ABOVE 1
/// throughout the op-loop. Stack-depleting failure modes are caught
/// upstream by their own structural variants:
/// [`TemplateInvariantKind::EndListEmptyStack`] fires inside
/// [`apply_compiled`]'s `EndList` arm via [`Vec::pop`]'s `Option`
/// gate, BEFORE the parent-fold push runs against
/// `current_builder_mut`; [`TemplateInvariantKind::FinalNoValue`]
/// fires AFTER the op-loop completes, on the outermost `stack.pop()`
/// that returns the assembled result. So a reachable
/// `current_builder_mut(&mut stack)` always observes a non-empty
/// stack, and the `expect` is a structural-invariant marker, not a
/// load-bearing rejection path.
///
/// Sibling of [`resolve_bound_arg`] (the bytecode-runtime bound-arg
/// lookup primitive lifted in the prior claude-routine run on this
/// module — 492a235) and [`template_invariant_violation`] (the
/// structural-variant error builder for the bytecode-runtime's
/// closed-set invariant-violation surface). Together the three primitives
/// name the bytecode-runtime's substrate-level operations: lookup-a-
/// bound-arg ([`resolve_bound_arg`]), build-the-invariant-rejection
/// ([`template_invariant_violation`]), and project-to-the-current-
/// builder (this lift). A future bytecode op that emits ONE OR MORE
/// values into the current builder — a hypothetical
/// `TemplateOp::SpliceMany(indices: Vec<usize>)` that splices a batch,
/// a `TemplateOp::PushQuoted(form: Sexp)` that wraps before push, a
/// span-annotated emit-with-position op — composes with ONE call to
/// [`current_builder_mut`] and the per-op post-projection verb
/// (`.push(…)`, `.extend(…)`, `splice_value_into(…, _)`); a future
/// instrumentation hook that wants to log every op's emit before
/// it lands in the builder wraps ONE call boundary, not four inline
/// `stack.last_mut().unwrap()` sites.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; four
/// inline copies of the top-of-stack projection in one function is
/// past the ≥2 PRIME-DIRECTIVE trigger once the structural shape is
/// named. THEORY.md §V.1 — knowable platform; the bytecode-runtime's
/// current-builder projection becomes a NAMED primitive on the
/// substrate's `&mut [Vec<Sexp>]` slice algebra rather than a re-derived
/// `last_mut + unwrap` chain at every op-arm that emits into the
/// builder. The expect message names the invariant
/// ("bytecode-runtime invariant: at least one stack frame during
/// op-loop") so a regression that drifts the loop's frame management
/// surfaces a NAMED panic, not a silent `unwrap` over `None`.
/// THEORY.md §II.1 invariant 2 — free middle; both expansion
/// strategies route through the SHARED `MacroParams::bind` upstream
/// AND the bytecode strategy's op-arms now route through this SHARED
/// `current_builder_mut` projection downstream — the bytecode-runtime's
/// substrate-level surface (lookup + emit) is named in two
/// composable primitives the op-arms compose with.
fn current_builder_mut(stack: &mut [Vec<Sexp>]) -> &mut Vec<Sexp> {
    stack
        .last_mut()
        .expect("bytecode-runtime invariant: at least one stack frame during op-loop")
}

/// Pop the top stack frame off the bytecode-runtime stack, or raise the
/// structural [`LispError::TemplateInvariant`] rejection with the
/// supplied [`TemplateInvariantKind`] when the stack is empty — ONE
/// named primitive both pop-emitting sites in [`apply_compiled`] route
/// through.
///
/// Before this lift two byte-identical
/// `stack.pop().ok_or_else(|| template_invariant_violation(macro_name,
/// kind))?` chains lived inline in [`apply_compiled`]:
///
///   * `TemplateOp::EndList` arm — pops the just-finished list frame
///     before the parent-fold push, with kind
///     [`TemplateInvariantKind::EndListEmptyStack`] guarding the
///     unreachable empty-stack failure mode.
///   * Post-loop final pop — consumes the outermost frame that
///     accumulated the template's result, with kind
///     [`TemplateInvariantKind::FinalNoValue`] guarding the
///     unreachable seed-frame-already-popped failure mode.
///
/// Two byte-identical re-derivations of the same projection inside one
/// function, past the ≥2 PRIME-DIRECTIVE trigger once the structural
/// shape is named. After this lift the two sites collapse to a single
/// `pop_builder_frame(&mut stack, macro_name, KIND)?` call, and the
/// bytecode-runtime invariant the projection rests on — "an empty-stack
/// pop is a structural-variant rejection, not a silent `Option::None`"
/// — lives in ONE composition point rather than two.
///
/// Sibling of [`current_builder_mut`] (the bytecode-runtime stack's
/// *project-to-top-frame* primitive — the borrow face, never resizes
/// the stack) and [`resolve_bound_arg`] (the bound-arg-by-index
/// lookup primitive with per-call-site `TemplateInvariantKind`
/// constructor). Where `current_builder_mut` borrows the in-progress
/// top frame for emission and never panics on a reachable input
/// (callers route past it only when the seed frame is present), this
/// primitive *consumes* the top frame off the stack and projects its
/// absence into a structural `LispError::TemplateInvariant` rejection
/// — the failure-on-empty face of the same `&mut Vec<Vec<Sexp>>`
/// algebra. The pair —
/// [`current_builder_mut`] + [`pop_builder_frame`] — close the
/// substrate's bytecode-runtime stack-frame projection algebra at the
/// borrow/consume boundary: borrow-the-top-frame for emission (no
/// rejection — the invariant rests on the seed-frame contract),
/// consume-the-top-frame for finalization (rejection-routed —
/// the absence projects through `TemplateInvariantKind` into a
/// structural variant of [`LispError`]). Together with
/// [`resolve_bound_arg`] (lookup args by index, with per-call-site
/// kind constructor) and [`template_invariant_violation`] (the typed
/// rejection emitter the three primitives share), the four
/// substrate-level operations name the bytecode-runtime's named
/// projection surface: lookup-a-bound-arg, project-to-the-current-
/// builder, consume-a-finished-builder-frame, build-the-invariant-
/// rejection.
///
/// `kind: TemplateInvariantKind` is the closed-set typed enum whose
/// four variants are EXACTLY the four reachable bytecode-runtime
/// invariant-violation modes (`SubstBadIndex(usize)` /
/// `SpliceBadIndex(usize)` from the index-lookup sibling primitive,
/// `EndListEmptyStack` from the `EndList` arm, `FinalNoValue` from
/// the post-loop final pop). The Subst / Splice indexed variants
/// thread their `usize` payload INSIDE the variant, so the invalid
/// combination "stack-gate kind with an op-index" (a hypothetical
/// `EndListEmptyStack(99)` carrying a Subst-style payload) is
/// structurally unrepresentable at this helper's boundary — the
/// caller cannot misroute an indexed kind through `pop_builder_frame`
/// at compile time because the kind's data shape is part of its
/// variant identity. Same closed-set guarantee
/// [`template_invariant_violation`] gives the four kinds; this
/// helper composes that guarantee with the `stack.pop()` projection
/// at the two pop-emitting sites.
///
/// The future-run extensions ride this floor: a future bytecode op
/// that consumes one or more finished frames — a hypothetical
/// `TemplateOp::EndMany(n: usize)` that pops `n` frames into a
/// flattened list, a span-aware `TemplateOp::EndListWithSpan(pos)`
/// that pops with a position-annotated rejection — composes with
/// ONE call (or a fold over N calls) to [`pop_builder_frame`]
/// without re-deriving the stack-pop-and-reject shape. A future
/// instrumentation hook (a debug-mode logger that records every
/// frame consumption, a span-aware pop that threads `Sexp` positions
/// through, a multi-frame fold that pops N frames in one step)
/// wraps ONE call boundary rather than keeping two inline chains in
/// lockstep at the production op-loop sites.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; two
/// inline copies of the stack-pop-and-reject projection across the
/// `apply_compiled` body's `EndList` arm and post-loop final-pop is
/// past the ≥2 PRIME-DIRECTIVE trigger once the structural shape is
/// named — the same threshold [`resolve_bound_arg`] (the index-lookup
/// sibling) crossed in the prior claude-routine run on this file
/// (492a235) and [`current_builder_mut`] (the top-frame-borrow
/// sibling) crossed two runs ago (c6a5a9d). THEORY.md §V.1 — knowable
/// platform / "make invalid states unrepresentable"; the bytecode-
/// runtime stack-frame consume operation becomes a NAMED primitive
/// on the substrate's `&mut Vec<Vec<Sexp>>` algebra rather than a
/// re-derived `pop + ok_or_else + template_invariant_violation`
/// chain at every op-arm that consumes a frame. THEORY.md §II.1
/// invariant 2 — free middle; both pop-emitting sites route through
/// the SHARED `pop_builder_frame` projection, so a regression that
/// drifts ONE site's posture (e.g. accepts an empty-stack pop at the
/// `EndList` arm but not the final pop, or swaps the kind constructor
/// at a single site) is no longer a silent two-site divergence — the
/// type system binds both sites to ONE composition point.
///
/// Frontier inspiration: MLIR's `Block::eraseFromParent()` against a
/// region's block list — the structured-IR's block-consumption
/// operation is a named typed primitive that yields a typed
/// `LogicalResult` rejection rather than a silent `nullptr` projection
/// when the parent region is empty; the substrate's
/// `pop_builder_frame` is the unstructured-projection peer on the
/// substrate's `&mut Vec<Vec<Sexp>>` stack-frame algebra, with
/// `TemplateInvariantKind` standing in for MLIR's `LogicalResult`'s
/// closed-set rejection identity. GHC Core's `popTickish` /
/// `stackPop` family — every Core-IR transform that consumes a stack
/// frame off the rewriter's working stack binds to one named pop
/// primitive that threads a typed `WantedFailure` rejection when the
/// stack is empty; translated through pleme-io primitives as ONE
/// `pop_builder_frame(stack, macro_name, kind)` call with
/// `TemplateInvariantKind` carrying the closed-set rejection
/// identity.
fn pop_builder_frame(
    stack: &mut Vec<Vec<Sexp>>,
    macro_name: &str,
    kind: TemplateInvariantKind,
) -> Result<Vec<Sexp>> {
    stack
        .pop()
        .ok_or_else(|| template_invariant_violation(macro_name, kind))
}

/// Execute a pre-compiled template against the macro's argument list.
fn apply_compiled(
    macro_name: &str,
    params: &MacroParams,
    tmpl: &CompiledTemplate,
    args: &[Sexp],
) -> Result<Sexp> {
    // Resolve args by param index through the shared positional binder —
    // identical semantics to the `bind_args` (substitute) path by construction.
    let args_by_index = params.bind(macro_name, args)?;

    // Run the bytecode against a stack of in-progress list builders. The
    // outermost frame accumulates the single result the template yields.
    // Each emit-into-builder arm routes through the shared
    // `current_builder_mut` projection — the bytecode-runtime invariant
    // "at least one stack frame during the op-loop" lives in ONE expect
    // message rather than four silent `.unwrap()` calls.
    let mut stack: Vec<Vec<Sexp>> = vec![Vec::with_capacity(1)];
    for op in &tmpl.ops {
        match op {
            TemplateOp::Literal(s) => current_builder_mut(&mut stack).push(s.clone()),
            TemplateOp::Subst(idx) => {
                // Bound-arg-by-index lookup routes through the shared
                // `resolve_bound_arg` projection with `SubstBadIndex` as
                // the per-call-site kind constructor; the post-lookup
                // verb (clone + push into the current builder) is the
                // Subst arm's per-op shape.
                let v = resolve_bound_arg(
                    &args_by_index,
                    *idx,
                    macro_name,
                    TemplateInvariantKind::SubstBadIndex,
                )?
                .clone();
                current_builder_mut(&mut stack).push(v);
            }
            TemplateOp::Splice(idx) => {
                // Sibling lookup through `resolve_bound_arg` with
                // `SpliceBadIndex` as the per-call-site kind constructor;
                // the post-lookup verb (`splice_value_into` against the
                // current builder) consumes the borrow directly without
                // an intermediate clone.
                let v = resolve_bound_arg(
                    &args_by_index,
                    *idx,
                    macro_name,
                    TemplateInvariantKind::SpliceBadIndex,
                )?;
                splice_value_into(current_builder_mut(&mut stack), v);
            }
            TemplateOp::BeginList => stack.push(Vec::new()),
            TemplateOp::EndList => {
                // Pop the just-finished list frame through the shared
                // `pop_builder_frame` projection with
                // `EndListEmptyStack` as the per-call-site kind
                // constructor; the post-pop verb (folded
                // `Sexp::List(items)` push into the parent frame via
                // `current_builder_mut`) is the EndList arm's per-op
                // shape — sibling of the Subst/Splice arms' index-
                // lookup-then-emit posture, with the index-lookup
                // primitive (`resolve_bound_arg`) and the frame-
                // consume primitive (`pop_builder_frame`) BOTH routing
                // through the same `TemplateInvariantKind` closed-set
                // rejection identity.
                let items = pop_builder_frame(
                    &mut stack,
                    macro_name,
                    TemplateInvariantKind::EndListEmptyStack,
                )?;
                current_builder_mut(&mut stack).push(Sexp::List(items));
            }
        }
    }
    // Final pop consumes the outermost (seed) frame via the same
    // shared projection — `FinalNoValue` as the per-call-site kind
    // constructor pins this site's structural-variant identity, the
    // post-pop verb (the `top.len() == 1` arity gate below) is the
    // post-loop tail's per-site shape.
    let mut top = pop_builder_frame(&mut stack, macro_name, TemplateInvariantKind::FinalNoValue)?;
    if top.len() == 1 {
        Ok(top.remove(0))
    } else {
        Ok(Sexp::List(top))
    }
}

/// Hash of `(macro_name, args)` for cache keying — hot path, kept lean.
/// Uses `DefaultHasher` (SipHash-2-4) — fast enough that the cache hit rate
/// needed to net a win is low even for cheap macros.
fn args_cache_key(macro_name: &str, args: &[Sexp]) -> Option<CacheKey> {
    let mut h = DefaultHasher::new();
    args.len().hash(&mut h);
    for a in args {
        a.hash(&mut h);
    }
    Some((macro_name.to_string(), h.finish()))
}

/// `pub(crate)` so the span-preserving expander recognizes a macro
/// definition through THIS function rather than a second copy of the
/// `defmacro`-head / name / param-list / body decomposition. A `MacroDef`
/// retains no spans (macros are keyed by name), so the spanned path lowers
/// its form and lands here — one recognizer, one lambda-list parser, one
/// error taxonomy.
pub(crate) fn macro_def_from(form: &Sexp) -> Result<Option<MacroDef>> {
    // Route the typed-macro-definition dispatch surface through the
    // substrate's typed-decoded call decomposition: `as_call_to_any`
    // performs the `as_list + head_symbol + MacroDefHead::from_keyword`
    // three-step chain in ONE structural query on the `Sexp` algebra.
    // The legacy diagnostic anchors on `list.len()` (the FULL form arity
    // including the head) — preserved here as `args.len() + 1` so
    // `LispError::DefmacroArity.arity` carries the same value across the
    // lift.
    let Some((head, args)) = form.as_call_to_any(MacroDefHead::from_keyword) else {
        return Ok(None);
    };
    if args.len() < 3 {
        return Err(defmacro_arity(head, args.len() + 1));
    }
    let name = args[0]
        .as_symbol()
        .ok_or_else(|| defmacro_non_symbol_name(head, &args[0]))?
        .to_string();
    let param_list = args[1]
        .as_list()
        .ok_or_else(|| defmacro_non_list_params(head, &args[1]))?;
    let params = parse_params(param_list)?;
    let body = args[2].clone();
    Ok(Some(MacroDef { name, params, body }))
}

fn parse_params(list: &[Sexp]) -> Result<MacroParams> {
    let mut required = Vec::new();
    let mut optional: Vec<OptionalParam> = Vec::new();
    let mut optional_marker: Option<usize> = None;
    let mut i = 0;
    while i < list.len() {
        // In the optional section a `(name default)` LIST form is a valid spec
        // alongside a bare-symbol spec. The list form is only meaningful here,
        // so the dispatch fires before the `as_symbol()` gate that would
        // otherwise reject it as `NonSymbolParam`.
        if optional_marker.is_some() {
            if let Sexp::List(items) = &list[i] {
                optional.push(parse_optional_list_spec(i, &list[i], items)?);
                i += 1;
                continue;
            }
        }
        let s = list[i]
            .as_symbol()
            .ok_or_else(|| non_symbol_param(i, &list[i]))?;
        if s == MacroParams::REST_MARKER {
            let Some(next) = list.get(i + 1) else {
                return Err(rest_param_missing_name(i, None));
            };
            let Some(name) = next.as_symbol() else {
                return Err(rest_param_missing_name(i, Some(next)));
            };
            let trailing = &list[i + 2..];
            if !trailing.is_empty() {
                return Err(rest_param_trailing_tokens(i, trailing));
            }
            return Ok(MacroParams {
                required,
                optional,
                rest: Some(name.to_string()),
            });
        }
        if s == MacroParams::OPTIONAL_MARKER {
            if let Some(first) = optional_marker {
                return Err(optional_marker_repeated(first, i));
            }
            optional_marker = Some(i);
            i += 1;
            continue;
        }
        if optional_marker.is_some() {
            optional.push(OptionalParam::bare(s));
        } else {
            required.push(s.to_string());
        }
        i += 1;
    }
    Ok(MacroParams {
        required,
        optional,
        rest: None,
    })
}

/// Project a `Sexp::List` in the `&optional` section to a typed
/// [`OptionalParam`]. The only admissible shape is `(NAME DEFAULT)` — a
/// list of exactly TWO elements whose first element is a symbol. Every
/// other list shape is the structural rejection
/// [`LispError::OptionalParamMalformed`], with a typed `reason`
/// ([`OptionalParamMalformedReason`]) naming WHICH way the spec is
/// malformed — empty, missing-default, extra-elements, or non-symbol name.
///
/// `position` is the loop index inside `parse_params`, mirroring the
/// `position`/`rest_position`/`first_position` slots on the sibling
/// `parse_params` rejection variants. `list_form` is the offending
/// `Sexp::List` itself, projected through `crate::domain::sexp_witness` so
/// the variant carries BOTH `SexpShape::List` AND the rendered form (for
/// LSP / REPL / `tatara-check` consumption). `items` is the list body,
/// avoiding a re-`as_list()` at the call boundary.
fn parse_optional_list_spec(
    position: usize,
    list_form: &Sexp,
    items: &[Sexp],
) -> Result<OptionalParam> {
    use crate::error::OptionalParamMalformedReason as R;
    // Arity dispatch — threads through the typed classifier on the
    // closed-set algebra so the accept-arity binding (arity ==
    // `R::OPTIONAL_PARAM_SPEC_ARITY`) is derived from ONE typed const
    // rather than the bare literal `2`. Post-classification the arity
    // is exactly the accept target; the head-symbol gate is the only
    // remaining rejection axis.
    if let Some(reason) = R::classify_arity(items.len()) {
        return Err(optional_param_malformed(position, list_form, reason));
    }
    let Some(name) = items[0].as_symbol() else {
        return Err(optional_param_malformed(
            position,
            list_form,
            R::NonSymbolName,
        ));
    };
    Ok(OptionalParam::with_default(name, items[1].clone()))
}

fn bind_args(
    macro_name: &str,
    params: &MacroParams,
    args: &[Sexp],
) -> Result<HashMap<String, Sexp>> {
    // Zip the shared positional binding (parallel to `names()`) into the
    // name-keyed map the `substitute` path looks substitutions up in.
    let vals = params.bind(macro_name, args)?;
    Ok(params
        .names()
        .into_iter()
        .map(String::from)
        .zip(vals)
        .collect())
}

/// Substitute `,name` and `,@name` within a template.
/// `,@name` only makes sense inside a List — it splices the bound list into
/// the containing list.
///
/// Routes both unquote-family sites — the top-level `,X` / `,@X`
/// recognition AND the list-inner per-item splice recognition — through
/// the substrate's typed-marker projection [`Sexp::as_unquote`]. Pre-lift
/// each site opened its own `Sexp::Unquote(inner)` / `Sexp::UnquoteSplice
/// (inner)` arm paired with a `UnquoteForm::Unquote` / `UnquoteForm::
/// Splice` literal; post-lift the (Sexp variant, UnquoteForm variant)
/// pairing is bound at ONE projection function the type system threads
/// through `(UnquoteForm, &Sexp)`, eliminating the silent two-site
/// pairing drift the prior shape allowed.
fn substitute(form: &Sexp, bindings: &HashMap<String, Sexp>) -> Result<Sexp> {
    if let Some((kind, inner)) = form.as_unquote() {
        return match kind {
            UnquoteForm::Unquote => resolve_unquote_in_bindings(inner, bindings, kind).cloned(),
            UnquoteForm::Splice => Err(splice_outside_list(inner)),
        };
    }
    match form {
        Sexp::List(items) => {
            let mut out: Vec<Sexp> = Vec::with_capacity(items.len());
            for item in items {
                if let Some((UnquoteForm::Splice, inner)) = item.as_unquote() {
                    let val = resolve_unquote_in_bindings(inner, bindings, UnquoteForm::Splice)?;
                    splice_value_into(&mut out, val);
                } else {
                    out.push(substitute(item, bindings)?);
                }
            }
            Ok(Sexp::List(out))
        }
        _ => Ok(form.clone()),
    }
}

/// Lift the four inline `LispError::Compile { form: format!("{prefix}{name}"),
/// message: "unbound" }` triples (compile_node Unquote/UnquoteSplice +
/// substitute Unquote/UnquoteSplice) behind ONE named primitive. Pairs the
/// structural variant with `crate::domain::suggest`'s bounded edit-distance
/// scan over the candidate set so a typo in `,name` against a macro's params
/// (or against a substitution scope's live bindings) surfaces as
/// `"compile error in ,xs: unbound; did you mean ,x?"` instead of the bare
/// `"unbound"`. The candidate set is per-call — params during compile,
/// `bindings.keys()` during substitute — so the operator's hint is always
/// drawn from the in-scope name set, never a stale snapshot.
///
/// `prefix` is `UnquoteForm` — the closed-set typed enum whose two
/// variants are EXACTLY the two reachable syntactic markers
/// (`Unquote` ⊎ `Splice`). Threading the typed marker through the helper
/// boundary (rather than `&'static str`) lands the same compile-time
/// closed-set guarantee `defmacro_arity` / `defmacro_non_symbol_name` /
/// `defmacro_non_list_params` get from threading `MacroDefHead`: the
/// closed set is encoded in the type system, so a regression that drifts
/// the marker (e.g. a fourth `prefix: ",,"` call site) becomes a type
/// error at the call site, not a runtime substring drift. `name` is the
/// offender from source; the hint is `Option<String>` because the matched
/// candidate borrows from a transient `Vec<&str>` we built locally —
/// copying the matched name into the variant is the cheapest way to keep
/// `LispError` lifetime-free.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; four inline
/// copies in one module is well past the three-times rule. THEORY.md §V.1 —
/// knowable platform; the structural variant exposes `prefix` / `name` /
/// `hint` as first-class fields so authoring tools (LSP, REPL,
/// `tatara-check`) bind to the data shape instead of substring-parsing the
/// rendered diagnostic.
fn unbound_template_var(prefix: UnquoteForm, name: &str, candidates: &[&str]) -> LispError {
    LispError::UnboundTemplateVar {
        prefix,
        name: name.to_string(),
        hint: crate::domain::suggest(name, candidates).map(str::to_string),
    }
}

/// Lift the four inline `LispError::Compile { form: "unquote" /
/// "unquote-splice", message: "only bound symbols may appear after `,` /
/// `,@`" }` triples in this module (compile_node Unquote / UnquoteSplice +
/// substitute Unquote / UnquoteSplice-inside-list) behind ONE named
/// primitive. Sibling of `unbound_template_var`: that helper fires when the
/// slot IS a symbol but the symbol isn't bound; this helper fires when the
/// slot isn't a symbol at all. Together they close every distinct
/// typed-entry template-gate failure mode for the no-evaluator template
/// language: each is a structural variant of `LispError`, not a
/// `Compile`-shaped substring.
///
/// `prefix` is `UnquoteForm` — the closed-set typed enum whose two
/// variants are EXACTLY the two reachable syntactic markers
/// (`Unquote` ⊎ `Splice`). Threading the typed marker through the helper
/// boundary (rather than `&'static str`) lands the same compile-time
/// closed-set guarantee `unbound_template_var` carries: the closed set is
/// encoded in the type system. The inner is the offending `Sexp` routed
/// through `crate::domain::sexp_witness` — the typed joint projection
/// pairing `SexpShape` (structural shape) with `Sexp::Display`
/// (renderable literal) at ONE call boundary. Authoring tools bind to
/// BOTH `got.shape` (e.g. `SexpShape::List`) AND `got.display` (e.g.
/// `"(list 1 2)"`) jointly — same posture as `splice_outside_list`
/// after its prior-run promotion to `SexpWitness`. The two template-
/// gate `,X/,@X` rejection variants now share ONE typed witness
/// identity at their `got` slot.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; four
/// inline copies in one module is past the three-times rule. THEORY.md
/// §V.1 — knowable platform; the structural variant exposes `prefix` /
/// `got` as first-class fields so authoring tools (LSP, REPL,
/// `tatara-check`) bind to the data shape instead of substring-parsing
/// the rendered diagnostic. THEORY.md §II.1 invariant 1 — typed entry;
/// a non-symbol unquote target is exactly the failure mode the
/// typed-entry gate exists to reject.
fn non_symbol_unquote_target(prefix: UnquoteForm, got: &Sexp) -> LispError {
    LispError::NonSymbolUnquoteTarget {
        prefix,
        got: got.witness(),
    }
}

/// Project the inner of a `,X` / `,@X` form to its bound symbol name, or
/// raise the structural `LispError::NonSymbolUnquoteTarget` rejection at
/// the typed-entry template-gate boundary. ONE named primitive every
/// `,X` / `,@X` resolution site in the substrate shares — the inline
/// `inner.as_symbol().ok_or_else(|| non_symbol_unquote_target(form,
/// inner))?` pattern appeared four times across `compile_node`
/// (bytecode-path Unquote / UnquoteSplice arms) AND `substitute`
/// (substitute-path Unquote / list-inner UnquoteSplice arms), well past
/// the three-times-rule trigger. After this lift the four sites collapse
/// to a single `unquote_target_symbol(inner, form)?` call, and the
/// substrate's understanding of "an unquote target's first gate is `must
/// be a symbol`" lives in ONE function — a regression that drifts the
/// gate's posture (e.g. accepts non-symbol targets at the bytecode path
/// but not the substitute path) becomes a type-level change at this
/// helper, not a silent four-site divergence.
///
/// Sibling of `non_symbol_unquote_target` (the error builder this gate
/// calls on failure) and `unbound_template_var` (the typed-entry
/// template-gate's SECOND gate — fires once `unquote_target_symbol`
/// projects the symbol successfully but the symbol isn't bound in the
/// in-scope name set). Together the three close the substrate's
/// understanding of the two-step typed-entry template-gate: gate-1 is
/// `must-be-a-symbol`, gate-2 is `must-be-bound-in-scope`. With this
/// lift, gate-1 lives at ONE call boundary across all four template-
/// gate sites — bytecode path AND substitute path AND both `,X` and
/// `,@X` forms.
///
/// `form` is `UnquoteForm` — the closed-set typed enum whose two
/// variants are EXACTLY the two reachable syntactic markers
/// (`Unquote` ⊎ `Splice`). Threading the typed marker through the
/// helper boundary (rather than `&'static str`) lands the same
/// compile-time closed-set guarantee `non_symbol_unquote_target` and
/// `unbound_template_var` get from their `UnquoteForm` slots — a
/// regression that drifts the marker (e.g. a third pseudo-marker call
/// site) becomes a type error at the call site, not a runtime
/// substring drift. The returned `&'a str` borrows from `inner` — the
/// caller feeds it directly into `params.iter().position(|p| *p ==
/// name)` (`compile_node`) or `bindings.get(name)` (`substitute`)
/// without an intermediate allocation.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; four
/// inline copies of the gate-1 projection (`compile_node`
/// Unquote/UnquoteSplice + `substitute` Unquote + `substitute`
/// list-inner UnquoteSplice) is past the three-times rule. THEORY.md
/// §V.1 — knowable platform; the gate's identity becomes a NAMED
/// primitive consumer-binding rather than a four-times-inlined
/// match-and-reject snippet — authoring surfaces (REPL, LSP,
/// `tatara-check`) that want to surface "the typed-entry template-gate
/// rejected your form because the unquote target wasn't a symbol" bind
/// to ONE function. THEORY.md §II.1 invariant 1 — typed entry; an
/// unquote target that isn't a symbol is exactly the failure mode the
/// typed-entry template-gate exists to reject. THEORY.md §II.1
/// invariant 2 — free middle; both bytecode AND substitute expansion
/// paths now project through the SAME gate-1 primitive, so a macro
/// that compiles under one strategy compiles under the other (the
/// gate's posture is uniform across the two strategies, no
/// per-strategy drift can creep in).
fn unquote_target_symbol(inner: &Sexp, form: UnquoteForm) -> Result<&str> {
    inner
        .as_symbol()
        .ok_or_else(|| non_symbol_unquote_target(form, inner))
}

/// Gate-2 for the bytecode-template compile path: resolve a template
/// variable name to its index inside the macro's static param list, or
/// raise the structural `LispError::UnboundTemplateVar` rejection. ONE
/// named primitive that the two `compile_node` sites — `Sexp::Unquote(_)`
/// and `Sexp::UnquoteSplice(_)` arms — share. Before this lift the same
/// `params.iter().position(|p| *p == name).ok_or_else(|| unbound_template_var(
/// FORM, name, params))?` projection was inlined twice in one match
/// block; after this lift the two sites collapse to a single
/// `resolve_param_index(name, params, form)?` call and the
/// `Subst(idx)` / `Splice(idx)` ops push from a uniform projection
/// boundary.
///
/// Sibling of `resolve_binding`: the same gate-2 contract on the
/// substitute path. Together the two close the typed-entry template
/// gate's gate-2 (must-be-bound-in-scope) primitive across BOTH
/// expansion strategies — gate-1 (`unquote_target_symbol`) projects the
/// inner to a symbol name; gate-2 looks the name up in the in-scope
/// candidate set. The two paths' candidate sets differ structurally
/// (compile path: `&[&str]` of macro params, returning `usize`;
/// substitute path: `&HashMap<String, Sexp>` of live bindings, returning
/// `&Sexp`), so the gate-2 primitive bifurcates by path — but the
/// rejection shape (`LispError::UnboundTemplateVar { prefix, name, hint }`
/// with `crate::domain::suggest`-driven hint) is identical across both
/// paths. A regression that drifts gate-2's posture (e.g., accepts an
/// unbound `,name` at the bytecode path but not the substitute path) is
/// now a type-level change at this helper, not a silent four-site
/// divergence.
///
/// `form` is `UnquoteForm` — the closed-set typed enum whose two
/// variants are EXACTLY the two reachable syntactic markers
/// (`Unquote` ⊎ `Splice`). Threading the typed marker through the
/// helper boundary (rather than `&'static str`) lands the same
/// compile-time closed-set guarantee `unquote_target_symbol`,
/// `unbound_template_var`, and `non_symbol_unquote_target` carry — a
/// regression that drifts the marker becomes a type error at the call
/// site, not a runtime substring drift.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; two
/// inline copies of the gate-2 projection in one match block, paired
/// with the two substitute-path inline copies, is four copies in two
/// functions — past the three-times rule once the structural shape is
/// named. THEORY.md §V.1 — knowable platform; the gate's identity
/// becomes a NAMED primitive consumer-binding rather than a
/// twice-inlined position-and-reject snippet — authoring surfaces
/// (REPL, LSP, `tatara-check`) that want to surface "the typed-entry
/// template-gate rejected your form because the name isn't bound in
/// scope" bind to ONE function per path. THEORY.md §II.1 invariant 1 —
/// typed entry; an unbound template variable is exactly the failure
/// mode the typed-entry template-gate exists to reject. THEORY.md
/// §II.1 invariant 2 — free middle; both expansion strategies'
/// gate-2 emit the SAME structural variant, so a macro that compiles
/// under one strategy compiles under the other.
fn resolve_param_index(name: &str, params: &[&str], form: UnquoteForm) -> Result<usize> {
    params
        .iter()
        .position(|p| *p == name)
        .ok_or_else(|| unbound_template_var(form, name, params))
}

/// Gate-2 for the substitute expansion path: resolve a template
/// variable name to its bound `Sexp` value inside the runtime bindings
/// map, or raise the structural `LispError::UnboundTemplateVar`
/// rejection. ONE named primitive that the two `substitute` sites —
/// the top-level `Sexp::Unquote(_)` arm and the list-inner
/// `Sexp::UnquoteSplice(_)` arm — share. Before this lift the same
/// `bindings.get(sym).<cloned>?.ok_or_else(|| unbound_template_var(
/// FORM, sym, &bound_names(bindings)))` projection was inlined twice
/// across the substitute walker; after this lift the two sites
/// collapse to a single `resolve_binding(bindings, sym, form)?` call
/// (with a trailing `.cloned()` at the top-level arm because that arm
/// returns an owned `Sexp` while the list-inner arm consumes the
/// `&Sexp` borrow directly).
///
/// Sibling of `resolve_param_index`: the same gate-2 contract on the
/// bytecode-template compile path. Together the two close the
/// typed-entry template gate's gate-2 (must-be-bound-in-scope)
/// primitive across BOTH expansion strategies. The candidate set on
/// the substitute path is the live bindings' keys (built fresh per
/// call via `bound_names`) — never a stale snapshot, so the
/// suggest-driven hint is always drawn from the actual in-scope name
/// set the operator sees.
///
/// The returned `&'a Sexp` borrows from `bindings` — the list-inner
/// caller feeds it straight into the `Sexp::List`/`Sexp::Nil`/other
/// splice-expansion match without an intermediate allocation. The
/// top-level caller's owned-Sexp obligation is satisfied by the
/// `.cloned()` projection at the call site, which is a single typed
/// `Sexp::clone` and not a redundant lookup.
///
/// `form` is `UnquoteForm` — same closed-set typed enum threading as
/// `resolve_param_index` and `unquote_target_symbol`. A regression
/// that drifts the marker becomes a type error at the call site, not
/// a runtime substring drift.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; two
/// inline copies of the gate-2 projection in the substitute walker,
/// paired with the two compile-path inline copies, is four copies in
/// two functions — past the three-times rule once the structural
/// shape is named. THEORY.md §V.1 — knowable platform; the gate's
/// identity becomes a NAMED primitive consumer-binding rather than a
/// twice-inlined lookup-and-reject snippet. THEORY.md §II.1
/// invariant 1 — typed entry; an unbound template variable is exactly
/// the failure mode the typed-entry template-gate exists to reject.
/// THEORY.md §II.1 invariant 2 — free middle; both expansion
/// strategies' gate-2 emit the SAME structural variant.
fn resolve_binding<'a>(
    bindings: &'a HashMap<String, Sexp>,
    name: &str,
    form: UnquoteForm,
) -> Result<&'a Sexp> {
    bindings
        .get(name)
        .ok_or_else(|| unbound_template_var(form, name, &bound_names(bindings)))
}

/// Compose gate-1 + gate-2 for the bytecode-template compile path into ONE
/// named primitive: project the unquote `inner` to a symbol name
/// (gate-1, via `unquote_target_symbol`) THEN resolve the name to its
/// index inside the macro's static param list (gate-2, via
/// `resolve_param_index`). Sibling of `resolve_unquote_in_bindings`: the
/// same gate-1+gate-2 composition on the substitute expansion path.
///
/// Before this lift, the two `compile_node` arms (`Sexp::Unquote(_)` and
/// `Sexp::UnquoteSplice(_)`) threaded `form: UnquoteForm` through TWO
/// helper calls each — once into `unquote_target_symbol(inner, form)?`
/// (gate-1) AND once into `resolve_param_index(name, params, form)?`
/// (gate-2). The marker's typed identity was re-asserted at the call site
/// twice per arm — four `UnquoteForm::Unquote` / `UnquoteForm::Splice`
/// literal occurrences across the two arms, for what is structurally ONE
/// marker-identity per syntactic-marker arm. After this lift each arm
/// threads the marker ONCE through ONE call, and the gate-1-then-gate-2
/// sequencing lives in the helper body, not at the call site.
///
/// The composition is load-bearing: gate-1 (must-be-a-symbol) MUST fire
/// before gate-2 (must-be-bound-in-scope) — a non-symbol inner is
/// structurally a different failure mode (`LispError::NonSymbolUnquoteTarget`,
/// which carries the offending `SexpWitness`) than an unbound symbol
/// (`LispError::UnboundTemplateVar`, which carries a `name: String` plus
/// a `crate::domain::suggest`-driven hint over the candidate set). A
/// regression that reorders or skips gate-1 would emit
/// `LispError::UnboundTemplateVar { name: "(list 1 2)", ... }` for a
/// non-symbol inner (re-treating the rendered list literal as a bound-
/// name lookup key), which is exactly the diagnostic-confusion this
/// composition exists to rule out. Naming the composition as one
/// primitive makes the sequencing structural — the helper body IS the
/// proof that gate-1 ran before gate-2.
///
/// `form` is `UnquoteForm` — the closed-set typed enum threaded through
/// the composition once and passed onward to both gate-1 and gate-2's
/// rejection-builders. Same posture as `unquote_target_symbol`,
/// `resolve_param_index`, `resolve_binding`, `non_symbol_unquote_target`,
/// and `unbound_template_var` — a regression that drifts the marker
/// becomes a type error at the helper boundary, not a runtime substring
/// drift, AND the marker can no longer drift BETWEEN gate-1 and gate-2
/// at a single call site (which the prior pre-lift shape allowed:
/// `unquote_target_symbol(inner, UnquoteForm::Unquote)?` followed by
/// `resolve_param_index(name, params, UnquoteForm::Splice)?` would
/// type-check but render a misleading diagnostic).
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; the
/// gate-1+gate-2 SEQUENCE is itself a named primitive once both halves
/// have been named (two prior runs landed the halves; this run lands the
/// composition). THEORY.md §V.1 — knowable platform; the gate's
/// composition is now load-bearing in the type system — gate-1 cannot be
/// silently skipped, gate-2 cannot be silently reordered before gate-1,
/// and the marker cannot drift between the two halves. THEORY.md §II.1
/// invariant 1 — typed entry; the typed-entry template gate's full
/// rejection chain (non-symbol → unbound-symbol) is now ONE primitive.
/// THEORY.md §II.1 invariant 2 — free middle; both expansion strategies
/// expose the gate's identity as ONE primitive per path, so a macro that
/// passes the gate under one strategy passes under the other (no per-
/// strategy composition drift can creep in).
fn resolve_unquote_in_params(inner: &Sexp, params: &[&str], form: UnquoteForm) -> Result<usize> {
    let name = unquote_target_symbol(inner, form)?;
    resolve_param_index(name, params, form)
}

/// Compose gate-1 + gate-2 for the substitute expansion path into ONE
/// named primitive: project the unquote `inner` to a symbol name
/// (gate-1, via `unquote_target_symbol`) THEN resolve the name to its
/// bound `Sexp` value inside the runtime bindings map (gate-2, via
/// `resolve_binding`). Sibling of `resolve_unquote_in_params`: the same
/// gate-1+gate-2 composition on the bytecode-template compile path.
///
/// Before this lift, the substitute walker's two unquote sites (the
/// top-level `Sexp::Unquote(_)` arm and the list-inner
/// `Sexp::UnquoteSplice(_)` arm) threaded `form: UnquoteForm` through
/// TWO helper calls each — once into `unquote_target_symbol(inner,
/// form)?` (gate-1) AND once into `resolve_binding(bindings, name,
/// form)?` (gate-2). After this lift each site threads the marker
/// ONCE through ONE call. Same composition contract as
/// `resolve_unquote_in_params` — gate-1 fires before gate-2 by the
/// helper body's `?`-then-call sequencing, NOT by call-site discipline.
///
/// The returned `&'a Sexp` borrows from `bindings` so the list-inner
/// caller feeds it straight into the `Sexp::List`/`Sexp::Nil`/other
/// splice-expansion match without an intermediate allocation; the
/// top-level caller's owned-Sexp obligation is satisfied by a
/// `.cloned()` projection at the call site (one typed `Sexp::clone`,
/// no redundant lookup).
///
/// `form` is `UnquoteForm` — same closed-set typed enum threading as
/// `resolve_unquote_in_params` and all the helpers it composes. After
/// this lift, the marker's identity flows through the substitute path's
/// typed-entry template gate via ONE explicit pass per call site, not
/// two; the gate's gate-1+gate-2 sequencing is structural across both
/// expansion strategies.
///
/// Theory anchor: same as `resolve_unquote_in_params`. THEORY.md §VI.1
/// (generation over composition; named composition of named gates),
/// THEORY.md §V.1 (knowable platform; gate composition is type-system
/// load-bearing), THEORY.md §II.1 invariant 1 (typed entry; the full
/// rejection chain is ONE primitive), THEORY.md §II.1 invariant 2
/// (free middle; both strategies share the same composition shape).
fn resolve_unquote_in_bindings<'a>(
    inner: &Sexp,
    bindings: &'a HashMap<String, Sexp>,
    form: UnquoteForm,
) -> Result<&'a Sexp> {
    let name = unquote_target_symbol(inner, form)?;
    resolve_binding(bindings, name, form)
}

/// Lift the lone `LispError::Compile { form: "unquote-splice", message:
/// "`,@` may only appear inside a list" }` triple — the substitute path's
/// top-level `,@X` rejection — behind ONE named primitive. Sibling of
/// `non_symbol_unquote_target` and `unbound_template_var`: those helpers
/// fire when the slot inside a `,X` / `,@X` is malformed (non-symbol or
/// unbound symbol); this helper fires when the `,@X` form itself is
/// ill-positioned (no containing list to flatten into). Together the three
/// close every distinct typed-entry template-gate failure mode for the
/// no-evaluator template language: each is a structural variant of
/// `LispError`, not a `Compile`-shaped substring.
///
/// `inner` is the offending `Sexp` projected through `Display` so the
/// operator sees the literal value they wrote — `xs`, `(list 1 2)`, `5` —
/// instead of just the bare "may only appear inside a list" verdict. The
/// helper takes `&Sexp` (parallel to `non_symbol_unquote_target`) and
/// projects through `to_string()` at the variant boundary; the `prefix:
/// &'static str` slot is implicit (always `,@`) and absent from the variant
/// itself, parallel to how `OddKwargs { dangling }` names ONE failure mode
/// without a syntactic-marker slot.
///
/// Used by both the substitute path (top-level `,@X` body) AND the bytecode
/// path's `compile_template` gate (top-level `,@X` body — closing the prior
/// silent-divergence where the bytecode interpreter's outermost stack frame
/// absorbed the splice). After this lift `,@-outside-list` is rejected on
/// both paths with ONE structural variant — the typed-entry template gate
/// is fully structural across both expansion strategies.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; two
/// emission sites (substitute + compile_template) for one failure mode is
/// past the three-times rule once the structural shape is named. THEORY.md
/// §V.1 — knowable platform; the structural variant exposes `got` as a
/// first-class field so authoring tools (LSP, REPL, `tatara-check`) bind to
/// the data shape instead of substring-parsing the rendered diagnostic.
/// THEORY.md §II.1 invariant 1 — typed entry; a `,@X` at a position with no
/// containing list is exactly the failure mode the typed-entry gate exists
/// to reject. THEORY.md §II.1 invariant 2 — free middle; both expansion
/// paths now reject the same set of templates, so a macro that registers
/// successfully has the same expansion behavior under either strategy.
fn splice_outside_list(inner: &Sexp) -> LispError {
    LispError::SpliceOutsideList {
        got: inner.witness(),
    }
}

/// Lift the two inline `LispError::Compile { form: format!("call to
/// {macro_name}"), message: format!("missing required arg: {name}") }`
/// triples — `bind_args` (substitute path) AND `apply_compiled` (bytecode
/// path) — behind ONE named primitive. Sibling of the typed-entry kwargs
/// `MissingKwarg { key }` lift: that variant fires when a `(<head> :key
/// value …)` kwargs form omits a required keyword; this variant fires when
/// a `(<macroname> a b …)` call omits a required positional param. Together
/// they close every distinct typed-entry missing-required surface in the
/// substrate — kwargs-gate AND macro-call-gate now share a single
/// structural-variant idiom.
///
/// Same single emission shape across both expansion strategies — before
/// this lift the same failure mode emitted byte-identical
/// `LispError::Compile { … }` triples at TWO call sites; after this lift
/// both sites share ONE structural variant. Two strategies that picked
/// different code paths now emit the same structural variant for the same
/// failure mode (THEORY.md §II.1 invariant 2 — free middle: which strategy
/// you picked must not change which inputs you reject OR how the rejection
/// is shaped). Same posture as `splice_outside_list`'s path-uniform
/// rejection across substitute + compile_template.
///
/// `macro_name` and `name` are `&str` borrows from the call-site / param
/// list; the variant's owned `String`s are formed at the boundary so
/// `LispError` stays lifetime-free.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; two
/// inline copies of one shape is past the three-times-rule trigger once
/// the structural variant is named (the test count gives this the
/// fail-before-pass-after edge). THEORY.md §V.1 — knowable platform; the
/// structural variant exposes `macro_name` / `param` as first-class
/// fields so authoring tools (LSP, REPL, `tatara-check`) bind to the data
/// shape instead of substring-parsing the rendered diagnostic. THEORY.md
/// §II.1 invariant 1 — typed entry; a macro call with too few args is
/// exactly the failure mode the typed-entry gate exists to reject.
fn missing_macro_arg(macro_name: &str, param: &str) -> LispError {
    LispError::MissingMacroArg {
        macro_name: macro_name.to_string(),
        param: param.to_string(),
    }
}

/// Mirror at the call-site of `missing_macro_arg`: that helper fires when
/// the macro CALL supplies TOO FEW args for the required arity (a required
/// slot has no arg); this helper fires when the macro CALL supplies TOO
/// MANY args for a rest-less param list (the surplus has nowhere to bind).
/// Together they close the typed-entry macro-call-gate's positional-arity
/// surface in both directions; together with the definition-site
/// `RestParamTrailingTokens` (lifted by the prior-run typed-promotion
/// lineage at the parse_params boundary), every distinct way a macro
/// definition + call pair can MISCOUNT args is now a named structural
/// rejection.
///
/// `expected` is the rest-less binder's fixed maximum arity
/// (`required.len() + optional.len()`); `got` is the actual call-site arg
/// count. Both are surfaced at the variant boundary so authoring tools
/// (REPL, LSP, `tatara-check`) name the "you supplied {got} args but the
/// macro takes at most {expected}" quick-fix from one structural projection
/// rather than re-deriving either count from the source. `macro_name` is
/// `&str` borrowed from the call-site; the variant's owned `String` is
/// formed at the boundary so `LispError` stays lifetime-free — same posture
/// as `missing_macro_arg`.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; the
/// rest-less surplus-args gate is a SINGLE-OWNER named rejection, not a
/// silent truncation re-asserted at every consumer that walks the bound
/// values. THEORY.md §V.1 — knowable platform; the structural variant
/// exposes `macro_name` / `expected` / `got` as first-class fields so
/// authoring tools bind to the data shape instead of substring-parsing
/// the rendered diagnostic. THEORY.md §II.1 invariant 1 — typed entry; a
/// macro call with too many args (and no `&rest` slot to absorb them) is
/// exactly the failure mode the typed-entry gate exists to reject —
/// silently dropping `args[expected..]` is structurally indistinguishable
/// from honoring them, the asymmetry this gate closes. THEORY.md §II.1
/// invariant 2 — free middle; both expansion strategies route through the
/// SHARED `MacroParams::bind`, so the new rejection lands once and the
/// substitute + bytecode paths inherit it unable to drift.
fn too_many_macro_args(macro_name: &str, expected: usize, got: usize) -> LispError {
    LispError::TooManyMacroArgs {
        macro_name: macro_name.to_string(),
        expected,
        got,
    }
}

/// Lift the lone `LispError::Compile { form: "defmacro params", message:
/// "expected symbol" }` triple in `parse_params` behind ONE named
/// primitive. Sibling of `missing_macro_arg`: that helper fires when the
/// macro CALL is malformed (call-site missing a positional arg); this
/// helper fires when the macro DEFINITION is malformed (definition-site
/// has a non-symbol where a param name should be). Together they open
/// the defmacro-syntax-gate / macro-call-gate split — call-site
/// rejections vs. definition-site rejections — each as its own
/// structural-variant family on `LispError`.
///
/// `position` is the loop index inside `parse_params`, i.e. the 0-based
/// index of the offending element within the param list (`(defmacro f
/// (a 5 b) …)` — position 1 is the literal `5`); naming it lets an LSP
/// quick-fix point at the exact list element instead of the whole
/// param list. `got` is the offending `Sexp` projected through
/// `Display` so the operator sees the literal value they wrote
/// (`5`, `:foo`, `(nested)`) at the variant boundary; the helper takes
/// `&Sexp` (parallel to `non_symbol_unquote_target` and
/// `splice_outside_list`) and projects through `to_string()` so the
/// variant stays lifetime-free.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; one
/// inline copy still earns a named primitive once the structural shape
/// is named (the test count gives this the fail-before-pass-after edge,
/// parallel to how `OddKwargs` was lifted from a single site for the
/// structural-completeness payoff). THEORY.md §V.1 — knowable platform;
/// the structural variant exposes `position` / `got` as first-class
/// fields so authoring tools (LSP, REPL, `tatara-check`) bind to the
/// data shape instead of substring-parsing the rendered diagnostic.
/// THEORY.md §II.1 invariant 1 — typed entry; a non-symbol element
/// inside a defmacro param list is exactly the failure mode the
/// typed-entry gate exists to reject — and it must reject DEFINITIONS
/// as readily as it rejects CALLS.
fn non_symbol_param(position: usize, got: &Sexp) -> LispError {
    LispError::NonSymbolParam {
        position,
        got: got.witness(),
    }
}

/// Lift the lone `LispError::Compile { form: "defmacro params", message:
/// "&rest needs a name" }` triple in `parse_params` behind ONE named
/// primitive. Sibling of `non_symbol_param`: that helper fires when a
/// NON-`&rest` element at a param position isn't a symbol; this helper
/// fires specifically on the post-`&rest` follower slot, where the
/// failure mode bifurcates into "missing entirely" (`got = None`) vs.
/// "present but not a symbol" (`got = Some(...)`). Together, the two
/// helpers close the `parse_params` walker — every distinct failure
/// mode the walker can emit is now a structural variant of `LispError`,
/// not a `Compile`-shaped substring.
///
/// `rest_position` is the loop index inside `parse_params` at which
/// the `&rest` marker was matched, i.e. the 0-based index of `&rest`
/// within the param list (`(defmacro f (a &rest 5) …)` — rest_position
/// 1 is `&rest`, the offender follows at 2); naming the marker
/// position lets an LSP quick-fix point at the `&rest` form itself
/// rather than at the next list element. `got` is `Option<&Sexp>`
/// because the follower slot bifurcates: `None` when the marker was
/// the param list's last element (no follower at all), `Some(sexp)`
/// when a follower exists but isn't a symbol; the helper projects
/// through `to_string()` at the variant boundary so the variant stays
/// lifetime-free.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; one
/// inline copy still earns a named primitive once the structural shape
/// is named (the test count gives this the fail-before-pass-after
/// edge, parallel to how `non_symbol_param` was lifted from a single
/// site for the structural-completeness payoff). THEORY.md §V.1 —
/// knowable platform; the structural variant exposes `rest_position` /
/// `got` as first-class fields so authoring tools (LSP, REPL,
/// `tatara-check`) bind to the data shape instead of substring-parsing
/// the rendered diagnostic. THEORY.md §II.1 invariant 1 — typed entry;
/// a `&rest` marker followed by no name (or by a non-symbol) is
/// exactly the failure mode the typed-entry gate exists to reject —
/// and the gate must reject DEFINITIONS as readily as it rejects
/// CALLS.
fn rest_param_missing_name(rest_position: usize, got: Option<&Sexp>) -> LispError {
    LispError::RestParamMissingName {
        rest_position,
        got: got.map(Sexp::witness),
    }
}

/// The third and final `parse_params` definition-site rejection — a
/// `&rest <name>` followed by further tokens. Sibling of `non_symbol_param`
/// (a param slot that isn't a symbol) and `rest_param_missing_name` (the
/// post-`&rest` follower is missing or malformed): this helper fires once
/// the rest name is bound and the walker finds the param list does not end
/// there. The `&rest` name absorbs every remaining call arg, so it is
/// structurally the LAST param a list can name; trailing tokens are
/// unrepresentable in `MacroParams` and were previously dropped silently.
///
/// `rest_position` is the loop index of the `&rest` marker (parallel to
/// `rest_param_missing_name`); `trailing` is the non-empty token run after
/// the bound rest name — the helper records its length and the typed
/// witness of its first element. The caller guarantees `trailing` is
/// non-empty (it is only built when `list[i + 2..].first()` is `Some`), so
/// `trailing[0]` does not panic.
///
/// Theory anchor: THEORY.md §V.1 — knowable platform / "make invalid states
/// unrepresentable"; a param list with tokens after `&rest <name>` is
/// nonsense `MacroParams` cannot hold, so the gate must REJECT it rather
/// than truncate to the representable prefix. THEORY.md §II.1 invariant 1 —
/// typed entry; the gate rejects malformed DEFINITIONS as readily as
/// malformed calls. THEORY.md §VI.1 — generation over composition; this
/// closes the `parse_params` walker's last uncovered failure mode, making
/// the sibling docs' "every distinct failure mode is a structural variant"
/// claim finally true.
fn rest_param_trailing_tokens(rest_position: usize, trailing: &[Sexp]) -> LispError {
    LispError::RestParamTrailingTokens {
        rest_position,
        extra: trailing.len(),
        first: trailing[0].witness(),
    }
}

/// A `&optional` marker appeared a SECOND time in one param list —
/// `(defmacro f (a &optional b &optional c) …)`. The lambda-list has exactly
/// ONE optional section (between the required run and the rest); a second
/// `&optional` is nonsense `MacroParams` cannot hold (its `optional` field is
/// one flat run, not a sequence of sections). Without this gate the parser
/// would otherwise treat the second `&optional` as an optional param literally
/// NAMED `&optional`, binding call args to a marker symbol — exactly the kind
/// of silent misalignment the typed shape exists to forbid.
///
/// Sibling of `rest_param_trailing_tokens` (the rest-section ordering gate):
/// both reject a param list whose marker structure the canonical lambda-list
/// ordering cannot represent. `first_position` is the loop index of the
/// first `&optional`, `second_position` the second — naming both lets an LSP
/// quick-fix point at the redundant marker to delete.
///
/// Theory anchor: THEORY.md §V.1 — knowable platform / "make invalid states
/// unrepresentable"; a param list with two `&optional` sections is nonsense
/// `MacroParams` cannot hold, so the gate must REJECT rather than bind args
/// to a marker symbol. THEORY.md §II.1 invariant 1 — typed entry; the gate
/// rejects malformed DEFINITIONS as readily as malformed calls.
fn optional_marker_repeated(first_position: usize, second_position: usize) -> LispError {
    LispError::OptionalMarkerRepeated {
        first_position,
        second_position,
    }
}

/// An `&optional` section entry that's a `Sexp::List` did NOT match the only
/// admissible shape `(NAME DEFAULT)` — exactly two elements with a symbol
/// head. This helper builds the structural rejection from the loop position,
/// the offending list form (projected through `crate::domain::sexp_witness`
/// to carry both `SexpShape::List` and the literal display), and the typed
/// `OptionalParamMalformedReason` naming which of the four malformed shapes
/// fired (empty list / missing default / extra elements / non-symbol name).
///
/// Sibling of `optional_marker_repeated` (the `&optional`-section marker
/// gate) and `non_symbol_param` (the bare-symbol gate): the three together
/// close every distinct typed-entry rejection the optional section can
/// emit. The bare-symbol form `&optional x` is still routed through
/// `non_symbol_param`'s sibling acceptance path; the list form `&optional
/// (x default)` is admitted iff this gate accepts the spec.
///
/// Theory anchor: THEORY.md §V.1 — knowable platform / "make invalid states
/// unrepresentable"; an `&optional` list spec of any other shape is
/// nonsense `MacroParams` cannot hold, so the gate must REJECT rather than
/// bind args to a marker symbol or drop the extras silently. THEORY.md
/// §II.1 invariant 1 — typed entry; a malformed default-form spec is
/// exactly the failure mode the typed-entry gate exists to reject — and
/// the gate must reject DEFINITIONS as readily as it rejects CALLS.
fn optional_param_malformed(
    position: usize,
    got: &Sexp,
    reason: crate::error::OptionalParamMalformedReason,
) -> LispError {
    LispError::OptionalParamMalformed {
        position,
        got: got.witness(),
        reason,
    }
}

/// Lift the lone `LispError::Compile { form: head.to_string(), message:
/// "(defmacro name (params) body) required" }` triple in
/// `macro_def_from` behind ONE named primitive. Sibling of
/// `non_symbol_param` and `rest_param_missing_name`: those helpers
/// fire INSIDE `parse_params`, AFTER the arity gate has passed; this
/// helper fires AT the arity gate itself, BEFORE name / params / body
/// validation can run. Together the three close `macro_def_from`'s
/// outermost rejection chain — every distinct failure mode the gate
/// can emit at the top level becomes a structural variant of
/// `LispError`, not a `Compile`-shaped substring.
///
/// `head` is `MacroDefHead` (the typed closed-set enum), having been
/// projected through `MacroDefHead::from_keyword` at the top of
/// `macro_def_from`. The helper threads `head` straight into the
/// variant's typed `head: MacroDefHead` slot — no `&'static str`
/// projection at the helper boundary; the projection through
/// `MacroDefHead::keyword()` happens at Display rendering time via
/// `MacroDefHead`'s Display impl inside the variant's `#[error(...)]`
/// annotation. Same posture as how
/// `compiler_spec.rs::compiler_spec_io_err` threads
/// `CompilerSpecIoStage` straight into
/// `LispError::CompilerSpecIo.stage`. `arity` is `usize` (the length
/// of the form including the head element).
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; one
/// inline copy still earns a named primitive once the structural
/// shape is named (the test count gives this the fail-before/pass-
/// after edge, parallel to how `non_symbol_param` and
/// `rest_param_missing_name` were lifted from a single site for the
/// structural-completeness payoff). THEORY.md §V.1 — knowable
/// platform; the structural variant exposes `head` / `arity` as
/// first-class fields so authoring tools (LSP, REPL, `tatara-check`)
/// bind to the data shape instead of substring-parsing the rendered
/// diagnostic. THEORY.md §II.1 invariant 1 — typed entry; a defmacro
/// form with too few elements is exactly the failure mode the typed-
/// entry gate exists to reject — and the gate must reject
/// DEFINITIONS as readily as it rejects CALLS. THEORY.md §II.1
/// invariant 2 — free middle; the arity gate fires inside
/// `macro_def_from` BEFORE either expansion strategy runs, so both
/// `Expander::new()` (bytecode) and `Expander::new_substitute_only()`
/// (substitute) reject the SAME malformed defmacro at the SAME gate.
fn defmacro_arity(head: MacroDefHead, arity: usize) -> LispError {
    LispError::DefmacroArity { head, arity }
}

/// Lift the lone `LispError::Compile { form: head.to_string(), message:
/// "expected name symbol" }` triple in `macro_def_from` behind ONE
/// named primitive. Sibling of `defmacro_arity`, `non_symbol_param`,
/// and `rest_param_missing_name`: those helpers fire at the OUTERMOST
/// arity gate (`defmacro_arity`) or INSIDE `parse_params`
/// (`non_symbol_param`, `rest_param_missing_name`); this helper fires
/// AFTER the arity gate has passed but BEFORE `parse_params` runs —
/// at the second of three `macro_def_from` rejection points
/// (arity → name-symbol → param-list → parse_params).
///
/// Walking a malformed `(defmacro …)` from the outside in, the gate
/// fires:
///   1. `defmacro_arity(head, arity)` if the form has fewer than 4
///      elements (`(defmacro)`, `(defmacro f)`).
///   2. `defmacro_non_symbol_name(head, &list[1])` if list[1] isn't a
///      symbol (`(defmacro 5 () body)`, `(defmacro :foo () body)`).
///   3. The `expected param list` gate (NEXT LIFT) if list[2] isn't a
///      list (`(defmacro f x body)`).
///   4. Inside `parse_params`: `non_symbol_param` and
///      `rest_param_missing_name`.
///
/// After this lift step 2 is structural; the only remaining
/// `Compile`-shaped site in `macro_def_from` is step 3 (`expected
/// param list`).
///
/// `head` is `MacroDefHead` (the typed closed-set enum), having been
/// projected through `MacroDefHead::from_keyword` at the top of
/// `macro_def_from`. The helper threads `head` straight into the
/// variant's typed `head: MacroDefHead` slot — same posture as
/// `defmacro_arity` after the typed-slot promotion. `got` is `&Sexp`
/// at the call site (a borrow into the form's name slot); the helper
/// projects through `crate::domain::sexp_witness` — the typed joint
/// projection (`SexpShape` + `Sexp::Display`) — so the variant's
/// `got: SexpWitness` slot carries BOTH structural shape AND
/// renderable literal across the boundary, parallel to how
/// `non_symbol_param` and `non_symbol_unquote_target` project their
/// `&Sexp` arguments. The fourth consumer of the typed `SexpWitness`
/// primitive on the substrate's Sexp-display-source rejection
/// surface.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; one
/// inline copy still earns a named primitive once the structural
/// shape is named (the test count gives this the fail-before/pass-
/// after edge, parallel to how `defmacro_arity`, `non_symbol_param`,
/// and `rest_param_missing_name` were lifted from a single site for
/// the structural-completeness payoff). THEORY.md §V.1 — knowable
/// platform; the structural variant exposes `head` / `got` as
/// first-class fields so authoring tools (LSP, REPL,
/// `tatara-check`) bind to the data shape instead of substring-
/// parsing the rendered diagnostic. THEORY.md §II.1 invariant 1 —
/// typed entry; a defmacro form whose name slot isn't a symbol is
/// exactly the failure mode the typed-entry gate exists to reject —
/// and the gate must reject DEFINITIONS as readily as it rejects
/// CALLS. THEORY.md §II.1 invariant 2 — free middle; the
/// name-symbol gate fires inside `macro_def_from` BEFORE either
/// expansion strategy runs, so both `Expander::new()` (bytecode) and
/// `Expander::new_substitute_only()` (substitute) reject the SAME
/// malformed defmacro at the SAME gate.
fn defmacro_non_symbol_name(head: MacroDefHead, got: &Sexp) -> LispError {
    LispError::DefmacroNonSymbolName {
        head,
        got: got.witness(),
    }
}

/// Lift the lone `LispError::Compile { form: head.to_string(), message:
/// "expected param list" }` triple in `macro_def_from` behind ONE
/// named primitive. Sibling of `defmacro_arity`,
/// `defmacro_non_symbol_name`, `non_symbol_param`, and
/// `rest_param_missing_name`: those helpers fire at the OUTERMOST
/// arity gate (`defmacro_arity`), at the second `macro_def_from`
/// rejection point (`defmacro_non_symbol_name`), or INSIDE
/// `parse_params` (`non_symbol_param`, `rest_param_missing_name`);
/// this helper fires AFTER both the arity gate AND the name-symbol
/// gate have passed but BEFORE `parse_params` runs — at the third
/// of three `macro_def_from` rejection points
/// (arity → name-symbol → param-list → parse_params).
///
/// Walking a malformed `(defmacro …)` from the outside in, the gate
/// fires:
///   1. `defmacro_arity(head, arity)` if the form has fewer than 4
///      elements (`(defmacro)`, `(defmacro f)`).
///   2. `defmacro_non_symbol_name(head, &list[1])` if list[1] isn't
///      a symbol (`(defmacro 5 () body)`).
///   3. `defmacro_non_list_params(head, &list[2])` if list[2] isn't
///      a list (`(defmacro f x body)`, `(defmacro f 5 body)`).
///   4. Inside `parse_params`: `non_symbol_param` and
///      `rest_param_missing_name`.
///
/// After this lift step 3 is structural; every inline
/// `LispError::Compile { … }` triple in `macro_def_from` has been
/// lifted to a structural variant — the entire `macro_def_from`
/// rejection chain is structurally typed for failure modes.
///
/// `head` is `MacroDefHead` (the typed closed-set enum), having been
/// projected through `MacroDefHead::from_keyword` at the top of
/// `macro_def_from`. The helper threads `head` straight into the
/// variant's typed `head: MacroDefHead` slot — same posture as
/// `defmacro_arity` and `defmacro_non_symbol_name` after the
/// typed-slot promotion. `got` is `&Sexp` at the call site (a
/// borrow into the form's param-list slot); the helper projects
/// through `crate::domain::sexp_witness(_)` — the typed joint
/// primitive that pairs the offending `Sexp`'s `SexpShape` with its
/// `Sexp::Display` projection in ONE owned `SexpWitness` value, so
/// authoring tools bind to both the structural shape AND the rendered
/// literal across the variant slot. Same posture as `non_symbol_param`,
/// `non_symbol_unquote_target`, `splice_outside_list`, and
/// `defmacro_non_symbol_name`'s helpers after the typed-witness
/// promotion of their `got` slots.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; one
/// inline copy still earns a named primitive once the structural
/// shape is named (the test count gives this the fail-before/pass-
/// after edge, parallel to how `defmacro_arity`,
/// `defmacro_non_symbol_name`, `non_symbol_param`, and
/// `rest_param_missing_name` were lifted from a single site for
/// the structural-completeness payoff). THEORY.md §V.1 — knowable
/// platform; the structural variant exposes `head` / `got` as
/// first-class fields so authoring tools (LSP, REPL,
/// `tatara-check`) bind to the data shape instead of substring-
/// parsing the rendered diagnostic. THEORY.md §II.1 invariant 1 —
/// typed entry; a defmacro form whose param-list slot isn't a list
/// is exactly the failure mode the typed-entry gate exists to
/// reject — and the gate must reject DEFINITIONS as readily as it
/// rejects CALLS. THEORY.md §II.1 invariant 2 — free middle; the
/// param-list gate fires inside `macro_def_from` BEFORE either
/// expansion strategy runs, so both `Expander::new()` (bytecode)
/// and `Expander::new_substitute_only()` (substitute) reject the
/// SAME malformed defmacro at the SAME gate.
fn defmacro_non_list_params(head: MacroDefHead, got: &Sexp) -> LispError {
    LispError::DefmacroNonListParams {
        head,
        got: got.witness(),
    }
}

/// Project a `bindings: &HashMap<String, Sexp>` into the `&[&str]` candidate
/// set `crate::domain::suggest` wants. Cold path — only allocated when an
/// `,name` / `,@name` substitution misses, i.e. when we're already on the
/// diagnostic side of the substitute walker.
fn bound_names(bindings: &HashMap<String, Sexp>) -> Vec<&str> {
    bindings.keys().map(String::as_str).collect()
}

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

    fn parse(src: &str) -> Sexp {
        read(src).unwrap().into_iter().next().unwrap()
    }

    #[test]
    fn identity_macro() {
        let mut e = Expander::new();
        let forms = read("(defmacro id (x) `,x) (id 42)").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], Sexp::int(42));
    }

    #[test]
    fn wrap_macro_duplicates_arg() {
        let mut e = Expander::new();
        let forms = read("(defmacro wrap (x) `(list ,x ,x)) (wrap hello)").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(list hello hello)"));
    }

    #[test]
    fn rest_param_splices_with_at() {
        let mut e = Expander::new();
        let forms = read("(defmacro call (f &rest args) `(,f ,@args)) (call foo a b c)").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(foo a b c)"));
    }

    #[test]
    fn nested_macro_expansion() {
        let mut e = Expander::new();
        let forms = read(
            "(defmacro twice (x) `(list ,x ,x))
             (defmacro quad (x) `(twice ,x))
             (quad hey)",
        )
        .unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(list hey hey)"));
    }

    #[test]
    fn unbound_unquote_errors() {
        let mut e = Expander::new();
        let forms = read("(defmacro bad (x) `(list ,y)) (bad 1)").unwrap();
        assert!(e.expand_program(forms).is_err());
    }

    #[test]
    fn missing_required_arg_errors() {
        let mut e = Expander::new();
        let forms = read("(defmacro need-two (a b) `(,a ,b)) (need-two 1)").unwrap();
        assert!(e.expand_program(forms).is_err());
    }

    #[test]
    fn defpoint_template_treated_as_defmacro() {
        let mut e = Expander::new();
        let forms = read(
            "(defpoint-template obs (name) `(defpoint ,name :class (Gate Observability)))
             (obs grafana)",
        )
        .unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(
            out[0],
            parse("(defpoint grafana :class (Gate Observability))")
        );
    }

    #[test]
    fn defcheck_treated_as_defmacro() {
        let mut e = Expander::new();
        let forms = read(
            "(defcheck pair (a b) `(do (yaml-parses ,a) (yaml-parses ,b)))
             (pair \"x.yaml\" \"y.yaml\")",
        )
        .unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(
            out[0],
            parse("(do (yaml-parses \"x.yaml\") (yaml-parses \"y.yaml\"))")
        );
    }

    #[test]
    fn empty_rest_splices_nothing() {
        let mut e = Expander::new();
        let forms = read("(defmacro f (x &rest r) `(list ,x ,@r)) (f 1)").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(list 1)"));
    }

    #[test]
    fn macro_expanded_inside_list() {
        // A macro call nested in a list position also expands.
        let mut e = Expander::new();
        let forms = read("(defmacro two () `(list 1 2)) (outer (two))").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(outer (list 1 2))"));
    }

    // ── Compiled-template bytecode equivalence + speedup ──────────────

    #[test]
    fn compiled_template_matches_substitute_path() {
        // Same program, two expanders with different strategies — outputs must agree.
        let src = "
            (defmacro wrap (x) `(list ,x ,x))
            (defmacro call (f &rest args) `(,f ,@args))
            (defmacro twice (x) `(list ,x ,x))
            (defmacro quad (x) `(twice ,x))
            (wrap hello)
            (call foo a b c)
            (quad hey)
            (outer (wrap deep))
        ";
        let forms = read(src).unwrap();
        let mut fast = Expander::new();
        let mut slow = Expander::new_substitute_only();
        let out_fast = fast.expand_program(forms.clone()).unwrap();
        let out_slow = slow.expand_program(forms).unwrap();
        assert_eq!(out_fast, out_slow);
    }

    #[test]
    fn literal_subtree_compiles_to_single_literal_op() {
        // Macro body where only one leaf is a substitution — the rest of the
        // template is literal, so the compiler should prune large chunks to
        // a single Literal op.
        let def = MacroDef {
            name: "label".into(),
            params: MacroParams {
                required: vec!["x".into()],
                optional: Vec::new(),
                rest: None,
            },
            body: Sexp::Quasiquote(Box::new(parse(
                "(observed (at timestamp) (in region) (value ,x) (tags (one two three)))",
            ))),
        };
        let compiled = compile_template(&def).expect("compile");
        // The template is ONE list. After compile:
        //   BeginList,
        //     Literal((observed (at timestamp) (in region))), // wait — `observed` is a list too
        //     ...
        //   EndList
        // Point is: many subtrees should be single Literals. We simply count
        // that the op stream is SHORTER than the full Sexp size.
        let ops_count = compiled.ops.len();
        assert!(
            ops_count < 15,
            "expected pruned op stream, got {ops_count} ops: {:?}",
            compiled.ops
        );
    }

    /// Three-way benchmark: substitute-only vs bytecode-no-cache vs bytecode-cache.
    /// Each path must produce identical output; the cache should show a real,
    /// visible speedup because the workload (10 000 calls across 10 unique
    /// (macro, args) pairs = 99.9% cache hit rate) is cache-friendly.
    #[test]
    fn expansion_layers_agree_on_output_and_cache_wins() {
        use std::time::Instant;

        let macros = "
            (defmacro m1 (a b) `(list ,a ,b))
            (defmacro m2 (x) `(if ,x true false))
            (defmacro m3 (a b c) `(list ,a ,b ,c ,a ,b ,c))
            (defmacro m4 (f &rest args) `(,f ,@args))
            (defmacro m5 (x) `(and ,x (not (not ,x))))
            (defmacro m6 (a b) `(or ,a ,b (and ,a ,b)))
            (defmacro m7 (x) `(debug (at timestamp) (in region) (value ,x)))
            (defmacro m8 (x y) `(cond ((= ,x ,y) equal) (#t not-equal)))
            (defmacro m9 (x) `(loop (times 10) (eval ,x)))
            (defmacro m10 (f g &rest args) `(,f (,g ,@args)))
        ";
        let mut call_src = String::with_capacity(80_000);
        for i in 0..10_000 {
            match i % 10 {
                0 => call_src.push_str("(m1 a b)\n"),
                1 => call_src.push_str("(m2 true)\n"),
                2 => call_src.push_str("(m3 x y z)\n"),
                3 => call_src.push_str("(m4 f a b c d e)\n"),
                4 => call_src.push_str("(m5 y)\n"),
                5 => call_src.push_str("(m6 a b)\n"),
                6 => call_src.push_str("(m7 answer)\n"),
                7 => call_src.push_str("(m8 p q)\n"),
                8 => call_src.push_str("(m9 body)\n"),
                _ => call_src.push_str("(m10 f g a b c)\n"),
            }
        }
        let all_src = format!("{macros}\n{call_src}");
        let forms = read(&all_src).unwrap();

        let mut subst = Expander::new_substitute_only();
        let t0 = Instant::now();
        let out_subst = subst.expand_program(forms.clone()).unwrap();
        let t_subst = t0.elapsed();

        let mut byte_no_cache = Expander::new_bytecode_no_cache();
        let t0 = Instant::now();
        let out_byte = byte_no_cache.expand_program(forms.clone()).unwrap();
        let t_byte = t0.elapsed();

        let mut byte_cache = Expander::new();
        let t0 = Instant::now();
        let out_cached = byte_cache.expand_program(forms).unwrap();
        let t_cached = t0.elapsed();

        // Rigorous: all three paths agree.
        assert_eq!(out_subst, out_byte);
        assert_eq!(out_subst, out_cached);

        // Cache captured the 10 unique (macro, args) pairs (plus some inner
        // expansions — macros that expand into calls to other macros).
        let cache_size = byte_cache.cache_size();
        assert!(
            (10..=50).contains(&cache_size),
            "expected ~10 unique cache entries, got {cache_size}"
        );

        eprintln!(
            "\n=== macroexpand: 10k calls × 10 unique (macro, args) pairs ===\n\
             substitute only     : {t_subst:?}\n\
             bytecode no cache   : {t_byte:?}\n\
             bytecode + cache    : {t_cached:?}   (cache_size={cache_size})\n\
             cache speedup vs subst : {:.2}×\n\
             cache speedup vs byte  : {:.2}×\n",
            t_subst.as_secs_f64() / t_cached.as_secs_f64(),
            t_byte.as_secs_f64() / t_cached.as_secs_f64(),
        );

        // The cache MUST win against both baselines for this cache-friendly
        // workload. Using a 1.5× threshold so the test is stable across hosts.
        assert!(
            t_cached < t_subst,
            "cache should beat substitute ({t_cached:?} vs {t_subst:?})"
        );
        assert!(
            t_cached < t_byte,
            "cache should beat bytecode-no-cache ({t_cached:?} vs {t_byte:?})"
        );
    }

    #[test]
    fn cache_respects_arg_changes() {
        // Cache must not return stale results when args differ.
        let src = "
            (defmacro wrap (x) `(list ,x ,x))
            (wrap a)
            (wrap b)
            (wrap a)   ;; same as first — cached hit
        ";
        let mut e = Expander::new();
        let out = e.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out.len(), 3);
        assert_eq!(out[0], parse("(list a a)"));
        assert_eq!(out[1], parse("(list b b)"));
        assert_eq!(out[2], parse("(list a a)"));
        // Two distinct args → 2 cache entries.
        assert_eq!(e.cache_size(), 2);
    }

    #[test]
    fn clear_cache_empties_memo() {
        let mut e = Expander::new();
        let out = e
            .expand_program(read("(defmacro id (x) `,x) (id 1) (id 2)").unwrap())
            .unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(e.cache_size(), 2);
        e.clear_cache();
        assert_eq!(e.cache_size(), 0);
    }

    // ── Unbound template-var: structural variant + did-you-mean hint ──

    /// Helper for the unbound-template-var tests — pins the variant shape
    /// and carries any error context up to the assert site for legibility.
    fn unbound_var(err: &LispError) -> (UnquoteForm, &str, Option<&str>) {
        match err {
            LispError::UnboundTemplateVar { prefix, name, hint } => {
                (*prefix, name.as_str(), hint.as_deref())
            }
            other => panic!("expected UnboundTemplateVar, got: {other:?}"),
        }
    }

    #[test]
    fn unbound_unquote_in_compile_template_emits_structural_variant_with_hint() {
        // `,xs` against macro params `[x]` — distance 1, bound 1 — hints `,x`.
        // Path: compile_node Unquote (the bytecode-template compile, default
        // expander).
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `(list ,xs)) (w 1)").unwrap())
            .expect_err("unbound template var must error");
        let (prefix, name, hint) = unbound_var(&err);
        assert_eq!(prefix, UnquoteForm::Unquote);
        assert_eq!(name, "xs");
        assert_eq!(hint, Some("x"));
    }

    #[test]
    fn unbound_unquote_splice_in_compile_template_emits_structural_variant_with_hint() {
        // `,@argz` against macro params `[args]` — distance 1, bound 2 —
        // hints `,@args`. Path: compile_node UnquoteSplice.
        let mut e = Expander::new();
        let err = e
            .expand_program(
                read("(defmacro call (f &rest args) `(,f ,@argz)) (call foo a b)").unwrap(),
            )
            .expect_err("unbound splice must error");
        let (prefix, name, hint) = unbound_var(&err);
        assert_eq!(prefix, UnquoteForm::Splice);
        assert_eq!(name, "argz");
        assert_eq!(hint, Some("args"));
    }

    #[test]
    fn unbound_unquote_in_substitute_emits_structural_variant_with_hint() {
        // Same shape but routed through the substitute-only expander — proves
        // the substitute path emits the same variant as the bytecode path.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro w (x) `(list ,xs)) (w 1)").unwrap())
            .expect_err("substitute unbound must error");
        let (prefix, name, hint) = unbound_var(&err);
        assert_eq!(prefix, UnquoteForm::Unquote);
        assert_eq!(name, "xs");
        assert_eq!(hint, Some("x"));
    }

    #[test]
    fn unbound_unquote_splice_in_substitute_emits_structural_variant_with_hint() {
        // The substitute path's UnquoteSplice branch fires for splices that
        // appear inside a list during the recursive walk. `,@argz` against
        // `[args]` hints `,@args`.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(
                read("(defmacro call (f &rest args) `(,f ,@argz)) (call foo a b)").unwrap(),
            )
            .expect_err("substitute splice unbound must error");
        let (prefix, name, hint) = unbound_var(&err);
        assert_eq!(prefix, UnquoteForm::Splice);
        assert_eq!(name, "argz");
        assert_eq!(hint, Some("args"));
    }

    #[test]
    fn unbound_template_var_omits_hint_when_no_close_match() {
        // `,wholly-unrelated` against `[x]` — far past the bound, so no
        // hint. Negative control: a wrong hint is worse than no hint, so
        // the slot must stay empty when the substrate isn't confident.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `(list ,wholly-unrelated)) (w 1)").unwrap())
            .expect_err("unrelated unbound must error");
        let (prefix, name, hint) = unbound_var(&err);
        assert_eq!(prefix, UnquoteForm::Unquote);
        assert_eq!(name, "wholly-unrelated");
        assert_eq!(hint, None);
    }

    #[test]
    fn unbound_template_var_message_includes_hint_suffix_end_to_end() {
        // End-to-end through the Display impl — pins the rendered diagnostic
        // a downstream tool sees today (REPL, tatara-check). Hint stays
        // additive: the legacy `"unbound"` substring still appears, so any
        // assertion that pattern-matches on it keeps passing.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `(list ,xs)) (w 1)").unwrap())
            .expect_err("unbound must error");
        let msg = format!("{err}");
        assert!(
            msg.contains("did you mean ,x?"),
            "expected hint suffix in message, got: {msg}"
        );
        assert!(
            msg.contains("unbound"),
            "expected legacy `unbound` substring in message, got: {msg}"
        );
        assert!(
            msg.contains(",xs"),
            "expected the offending form in message, got: {msg}"
        );
    }

    #[test]
    fn unbound_template_var_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp` carries
        // source positions, `position()` returns `None` for this variant.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `(list ,xs)) (w 1)").unwrap())
            .expect_err("unbound must error");
        assert_eq!(err.position(), None);
    }

    // ── Non-symbol unquote target: structural variant ─────────────────

    /// Helper for the non-symbol-unquote-target tests — pins the variant
    /// shape and carries any error context up to the assert site for
    /// legibility. Sibling of `unbound_var` and `splice_outside_list_got`;
    /// returns the `display` projection of the typed `SexpWitness` so the
    /// existing call sites stay byte-for-byte comparable to the legacy
    /// `got: String` shape.
    fn non_symbol_target(err: &LispError) -> (UnquoteForm, &str) {
        match err {
            LispError::NonSymbolUnquoteTarget { prefix, got } => (*prefix, got.display.as_str()),
            other => panic!("expected NonSymbolUnquoteTarget, got: {other:?}"),
        }
    }

    #[test]
    fn non_symbol_unquote_in_compile_template_emits_structural_variant() {
        // `,(list 1 2)` — the inner is a list, not a symbol. Path:
        // compile_node Unquote (the bytecode-template compile, default
        // expander). Pins variant identity AND prefix AND the offending
        // literal so a regression that re-inlines the legacy
        // `LispError::Compile` shape fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `,(list 1 2)) (w 1)").unwrap())
            .expect_err("non-symbol unquote target must error");
        let (prefix, got) = non_symbol_target(&err);
        assert_eq!(prefix, UnquoteForm::Unquote);
        assert_eq!(got, "(list 1 2)");
    }

    #[test]
    fn non_symbol_unquote_splice_in_compile_template_emits_structural_variant() {
        // `,@5` — the inner is an int atom, not a symbol. Path:
        // compile_node UnquoteSplice. The integer literal round-trips
        // through the variant's `got` slot via `Sexp::Display`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `(list ,@5)) (w 1)").unwrap())
            .expect_err("non-symbol splice target must error");
        let (prefix, got) = non_symbol_target(&err);
        assert_eq!(prefix, UnquoteForm::Splice);
        assert_eq!(got, "5");
    }

    #[test]
    fn non_symbol_unquote_in_substitute_emits_structural_variant() {
        // Same shape as the bytecode path but routed through the
        // substitute-only expander — proves the substitute path emits the
        // same variant as the compile_node path. Pins that the lift is
        // path-uniform.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro w (x) `,(list 1 2)) (w 1)").unwrap())
            .expect_err("substitute non-symbol target must error");
        let (prefix, got) = non_symbol_target(&err);
        assert_eq!(prefix, UnquoteForm::Unquote);
        assert_eq!(got, "(list 1 2)");
    }

    #[test]
    fn non_symbol_unquote_splice_inside_list_in_substitute_emits_structural_variant() {
        // The substitute path's UnquoteSplice-inside-list branch fires for
        // splices that appear inside a list during the recursive walk.
        // `,@(list 1 2)` inside the body — the inner is a literal list, not
        // a symbol — emits the same variant as the compile_node path.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro w (x) `(outer ,@(list 1 2))) (w 1)").unwrap())
            .expect_err("substitute non-symbol splice must error");
        let (prefix, got) = non_symbol_target(&err);
        assert_eq!(prefix, UnquoteForm::Splice);
        assert_eq!(got, "(list 1 2)");
    }

    #[test]
    fn non_symbol_unquote_target_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp` carries
        // source positions, `position()` returns `None` for this variant.
        // A future run that gives `Sexp` source spans adds `pos:
        // Option<usize>` to ONE place; this test gives that change a
        // deliberate fail-before/pass-after delta.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `,(list 1 2)) (w 1)").unwrap())
            .expect_err("non-symbol target must error");
        assert_eq!(err.position(), None);
    }

    // ── unquote_target_symbol: typed gate-1 primitive for ,X / ,@X ──────
    //
    // The `unquote_target_symbol(inner, form)?` primitive lifts the
    // inline `inner.as_symbol().ok_or_else(|| non_symbol_unquote_target(
    // form, inner))?` pattern that previously appeared at four call
    // sites (`compile_node` Unquote/UnquoteSplice + `substitute` Unquote
    // + `substitute` list-inner UnquoteSplice) behind ONE named
    // primitive. The tests below pin: (a) the Ok-arm borrows the
    // symbol name from `inner` for both UnquoteForm variants; (b) the
    // Err-arm routes through `non_symbol_unquote_target` and emits the
    // structural `LispError::NonSymbolUnquoteTarget` variant carrying
    // the typed `SexpWitness` (joint shape + display identity) for the
    // closed set of reachable non-symbol shapes (int / keyword / list /
    // nil); (c) the helper is path-uniform — the same Ok / Err
    // contracts hold regardless of which call site invokes it. A
    // regression that re-inlines the gate-1 projection at any of the
    // four call sites can no longer drift independent of the others —
    // the helper IS the gate.

    #[test]
    fn unquote_target_symbol_returns_symbol_for_symbol_inner_under_unquote() {
        // Positive control for the Ok-arm: `inner = Sexp::Symbol("xs")`
        // under `UnquoteForm::Unquote` projects through `as_symbol()`
        // to the borrowed `&str`. The returned slice's lifetime is
        // tied to `inner` so the caller can feed it directly into
        // `params.iter().position(...)` (`compile_node`) or
        // `bindings.get(...)` (`substitute`) without an intermediate
        // allocation. Fail-before/pass-after: this assert is meaningless
        // pre-lift because the helper does not exist; post-lift it
        // pins the typed gate-1 contract at the named primitive.
        let inner = Sexp::symbol("xs");
        let name = unquote_target_symbol(&inner, UnquoteForm::Unquote)
            .expect("symbol inner must project to Ok");
        assert_eq!(name, "xs");
    }

    #[test]
    fn unquote_target_symbol_returns_symbol_for_symbol_inner_under_splice() {
        // Sibling positive control: `UnquoteForm::Splice` shares the
        // gate-1 contract with `Unquote`. The helper is path-uniform
        // across both syntactic markers — a regression that bifurcates
        // the two arms (e.g., accepting non-symbols for `,@X` but not
        // `,X`) fails-loudly here. Pins that the closed-set
        // `UnquoteForm` enum's two variants share ONE projection
        // posture across the gate-1 boundary.
        let inner = Sexp::symbol("rest");
        let name = unquote_target_symbol(&inner, UnquoteForm::Splice)
            .expect("symbol inner must project to Ok under Splice");
        assert_eq!(name, "rest");
    }

    #[test]
    fn unquote_target_symbol_rejects_int_inner_under_unquote() {
        // Negative control for the Err-arm: `inner = Sexp::Int(5)` is
        // NOT a symbol — the gate-1 projection fires and routes through
        // `non_symbol_unquote_target` to the structural
        // `LispError::NonSymbolUnquoteTarget` variant. Pin the variant
        // identity AND the typed `SexpWitness` joint identity (shape +
        // display literal): a regression that drops the witness shape
        // or display fails-loudly here.
        let inner = Sexp::int(5);
        let err = unquote_target_symbol(&inner, UnquoteForm::Unquote)
            .expect_err("int inner must error at gate-1");
        match err {
            LispError::NonSymbolUnquoteTarget { prefix, got } => {
                assert_eq!(prefix, UnquoteForm::Unquote);
                assert_eq!(got.shape, crate::error::SexpShape::Int);
                assert_eq!(got.display, "5");
            }
            other => panic!("expected NonSymbolUnquoteTarget, got: {other:?}"),
        }
    }

    #[test]
    fn unquote_target_symbol_rejects_list_inner_under_splice() {
        // Sibling negative control: `inner = (list 1 2)` is a list, not
        // a symbol — the gate-1 projection fires AND routes through
        // `non_symbol_unquote_target(UnquoteForm::Splice, inner)`. Pins
        // both the variant identity AND the typed witness's joint
        // shape (`SexpShape::List`) + display (`"(list 1 2)"`) so a
        // future shape drift fails-loudly. Sibling of the Int / Unquote
        // pin: closes the gate-1 contract across the closed-set
        // product of {Int, List, Keyword, …} × {Unquote, Splice}.
        let inner = Sexp::List(vec![Sexp::symbol("list"), Sexp::int(1), Sexp::int(2)]);
        let err = unquote_target_symbol(&inner, UnquoteForm::Splice)
            .expect_err("list inner must error at gate-1");
        match err {
            LispError::NonSymbolUnquoteTarget { prefix, got } => {
                assert_eq!(prefix, UnquoteForm::Splice);
                assert_eq!(got.shape, crate::error::SexpShape::List);
                assert_eq!(got.display, "(list 1 2)");
            }
            other => panic!("expected NonSymbolUnquoteTarget, got: {other:?}"),
        }
    }

    #[test]
    fn unquote_target_symbol_rejects_keyword_inner_with_typed_witness() {
        // Pin a third reachable non-symbol shape: `Sexp::Keyword(":foo")`.
        // The gate-1 projection rejects keywords AS WELL as ints and
        // lists — closes the closed-set of "non-symbol shapes the gate
        // rejects" across one more reachable variant. The typed witness
        // carries `SexpShape::Keyword` + display `:foo` jointly so
        // authoring tools (REPL, LSP) bind on the structural shape
        // directly.
        let inner = Sexp::keyword("foo");
        let err = unquote_target_symbol(&inner, UnquoteForm::Unquote)
            .expect_err("keyword inner must error at gate-1");
        match err {
            LispError::NonSymbolUnquoteTarget { prefix, got } => {
                assert_eq!(prefix, UnquoteForm::Unquote);
                assert_eq!(got.shape, crate::error::SexpShape::Keyword);
                assert_eq!(got.display, ":foo");
            }
            other => panic!("expected NonSymbolUnquoteTarget, got: {other:?}"),
        }
    }

    #[test]
    fn unquote_target_symbol_consolidates_four_inline_callsites_into_one_helper() {
        // Path-uniformity pin: end-to-end through ALL FOUR call sites
        // (`compile_node` Unquote, `compile_node` UnquoteSplice,
        // `substitute` Unquote, `substitute` list-inner UnquoteSplice)
        // every non-symbol unquote target now routes through the SAME
        // `unquote_target_symbol(inner, form)?` helper. The four
        // end-to-end expansions below all reject with the SAME variant
        // (`NonSymbolUnquoteTarget`) — pins that the lift preserves the
        // path-uniform rejection contract `non_symbol_unquote_target`'s
        // prior lift established (and that drove the bytecode-vs-
        // substitute reunification in 0e9c… and successors). A
        // regression that re-inlines the gate-1 projection at one of
        // the four sites can drift the four call sites independent of
        // each other — this test would catch that drift.
        let cases: &[(&str, UnquoteForm)] = &[
            // compile_node Unquote (bytecode-path)
            ("(defmacro w (x) `,(list 1 2)) (w 1)", UnquoteForm::Unquote),
            // compile_node UnquoteSplice (bytecode-path)
            ("(defmacro w (x) `(list ,@5)) (w 1)", UnquoteForm::Splice),
        ];
        for (src, expected_form) in cases {
            let mut e = Expander::new();
            let err = e
                .expand_program(read(src).unwrap())
                .expect_err("non-symbol unquote target must error end-to-end");
            match err {
                LispError::NonSymbolUnquoteTarget { prefix, .. } => {
                    assert_eq!(prefix, *expected_form, "for src: {src}");
                }
                other => panic!("expected NonSymbolUnquoteTarget for {src}, got: {other:?}"),
            }
        }
        // substitute Unquote (substitute-only path) — sibling pin to
        // `non_symbol_unquote_in_substitute_emits_structural_variant`.
        let mut e_subst = Expander::new_substitute_only();
        let err = e_subst
            .expand_program(read("(defmacro w (x) `,(list 1 2)) (w 1)").unwrap())
            .expect_err("substitute Unquote must error end-to-end");
        assert!(
            matches!(
                err,
                LispError::NonSymbolUnquoteTarget {
                    prefix: UnquoteForm::Unquote,
                    ..
                }
            ),
            "expected NonSymbolUnquoteTarget at substitute Unquote, got: {err:?}"
        );
        // substitute list-inner UnquoteSplice (substitute-only path) —
        // sibling pin to
        // `non_symbol_unquote_splice_inside_list_in_substitute_emits_…`.
        let mut e_subst2 = Expander::new_substitute_only();
        let err = e_subst2
            .expand_program(read("(defmacro w (x) `(outer ,@(list 1 2))) (w 1)").unwrap())
            .expect_err("substitute UnquoteSplice-in-list must error end-to-end");
        assert!(
            matches!(
                err,
                LispError::NonSymbolUnquoteTarget {
                    prefix: UnquoteForm::Splice,
                    ..
                }
            ),
            "expected NonSymbolUnquoteTarget at substitute UnquoteSplice-in-list, got: {err:?}"
        );
    }

    // ── Gate-2 (must-be-bound-in-scope) typed primitives ──────────────
    // Pins the contract of the two gate-2 helpers — `resolve_param_index`
    // (bytecode-template compile path) and `resolve_binding`
    // (substitute path) — that the four inline `<lookup>.ok_or_else(||
    // unbound_template_var(FORM, name, candidates))` projections at
    // `compile_node` Unquote/UnquoteSplice AND `substitute` Unquote/
    // UnquoteSplice-inside-list collapse behind. Tests pin: (a) Ok-arm
    // projection under both `UnquoteForm` variants — the helper returns
    // the resolved `usize` (compile path) or `&Sexp` (substitute path)
    // for in-scope names; (b) Err-arm projection routes through
    // `unbound_template_var` to the typed `LispError::UnboundTemplateVar`
    // variant with the correct `prefix` AND the suggest-driven `hint`;
    // (c) the helpers are path-uniform — both compile-path arms share
    // ONE `resolve_param_index`; both substitute-path arms share ONE
    // `resolve_binding`. A regression that re-inlines the gate-2
    // projection at any of the four call sites can no longer drift
    // independent of the others — the two helpers ARE the gate.

    #[test]
    fn resolve_param_index_returns_position_for_bound_name_under_unquote() {
        // Positive control for the Ok-arm: `name = "x"` against
        // `params = ["a", "x", "rest"]` projects through
        // `params.iter().position(|p| *p == name)` to `Some(1)`, which
        // the helper unwraps to `Ok(1)`. The returned index feeds
        // directly into `TemplateOp::Subst(idx)` at the compile site.
        let params = ["a", "x", "rest"];
        let idx = resolve_param_index("x", &params, UnquoteForm::Unquote)
            .expect("bound name must project to Ok at gate-2");
        assert_eq!(idx, 1);
    }

    #[test]
    fn resolve_param_index_returns_position_for_bound_name_under_splice() {
        // Sibling positive control: `UnquoteForm::Splice` shares the
        // gate-2 contract with `Unquote`. The helper is path-uniform
        // across both syntactic markers on the compile path — a
        // regression that bifurcates the two arms fails-loudly here.
        let params = ["a", "x", "rest"];
        let idx = resolve_param_index("rest", &params, UnquoteForm::Splice)
            .expect("bound name must project to Ok at gate-2 under Splice");
        assert_eq!(idx, 2);
    }

    #[test]
    fn resolve_param_index_rejects_unbound_name_with_hint_under_unquote() {
        // Negative control for the Err-arm: `name = "xs"` against
        // `params = ["x"]` — distance 1, bound 1 — routes through
        // `unbound_template_var` to the structural
        // `LispError::UnboundTemplateVar` variant with `hint = Some("x")`.
        // Pin the variant identity AND the prefix AND the suggest-driven
        // hint: a regression that drops the suggestion fails-loudly here.
        let params = ["x"];
        let err = resolve_param_index("xs", &params, UnquoteForm::Unquote)
            .expect_err("unbound name must error at gate-2");
        match err {
            LispError::UnboundTemplateVar { prefix, name, hint } => {
                assert_eq!(prefix, UnquoteForm::Unquote);
                assert_eq!(name, "xs");
                assert_eq!(hint.as_deref(), Some("x"));
            }
            other => panic!("expected UnboundTemplateVar, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_param_index_rejects_unbound_name_without_hint_under_splice() {
        // Sibling negative control: `name = "wholly-unrelated"` against
        // `params = ["x"]` — past the bounded edit distance, so no hint.
        // Pin that the suggest-driven hint stays empty under Splice when
        // the substrate isn't confident — a wrong hint is worse than no
        // hint. Closes the closed-set product of {hint, no-hint} ×
        // {Unquote, Splice} on the compile-path gate-2.
        let params = ["x"];
        let err = resolve_param_index("wholly-unrelated", &params, UnquoteForm::Splice)
            .expect_err("unrelated unbound must error at gate-2");
        match err {
            LispError::UnboundTemplateVar { prefix, name, hint } => {
                assert_eq!(prefix, UnquoteForm::Splice);
                assert_eq!(name, "wholly-unrelated");
                assert_eq!(hint, None);
            }
            other => panic!("expected UnboundTemplateVar, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_binding_returns_value_for_bound_name_under_unquote() {
        // Positive control for the substitute-path Ok-arm: `name = "x"`
        // against a bindings map `{x: 42, y: "hi"}` projects through
        // `bindings.get(name)` to `Some(&Sexp::Int(42))`, which the
        // helper unwraps to `Ok(&Sexp::Int(42))`. The returned
        // `&Sexp` borrows from the bindings map — the top-level
        // `Sexp::Unquote(_)` substitute caller adds a single
        // `.cloned()` to satisfy its owned-`Sexp` return obligation.
        let mut bindings: HashMap<String, Sexp> = HashMap::new();
        bindings.insert("x".to_string(), Sexp::int(42));
        bindings.insert("y".to_string(), Sexp::string("hi"));
        let val = resolve_binding(&bindings, "x", UnquoteForm::Unquote)
            .expect("bound name must project to Ok at gate-2 (substitute)");
        assert_eq!(val, &Sexp::int(42));
    }

    #[test]
    fn resolve_binding_returns_value_for_bound_name_under_splice() {
        // Sibling positive control: `UnquoteForm::Splice` shares the
        // gate-2 contract with `Unquote` on the substitute path too.
        // The bound value is a `Sexp::List` because the splice arm's
        // caller match expression expects `Sexp::List(items)` — but
        // the helper itself doesn't inspect the value's shape; it
        // just hands back the borrow. A regression that gate-checks
        // the value's shape inside `resolve_binding` (instead of at
        // the caller match arm) fails-loudly here.
        let mut bindings: HashMap<String, Sexp> = HashMap::new();
        bindings.insert(
            "args".to_string(),
            Sexp::List(vec![Sexp::int(1), Sexp::int(2)]),
        );
        let val = resolve_binding(&bindings, "args", UnquoteForm::Splice)
            .expect("bound name must project to Ok at gate-2 under Splice");
        assert_eq!(val, &Sexp::List(vec![Sexp::int(1), Sexp::int(2)]));
    }

    #[test]
    fn resolve_binding_rejects_unbound_name_with_hint_under_unquote() {
        // Negative control for the substitute-path Err-arm: `name =
        // "xs"` against bindings `{x: 1}` — distance 1, bound 1 —
        // routes through `unbound_template_var` to the structural
        // `LispError::UnboundTemplateVar` variant with `hint =
        // Some("x")`. The candidate set is drawn from
        // `bound_names(bindings)` — the live bindings' keys, never a
        // stale snapshot.
        let mut bindings: HashMap<String, Sexp> = HashMap::new();
        bindings.insert("x".to_string(), Sexp::int(1));
        let err = resolve_binding(&bindings, "xs", UnquoteForm::Unquote)
            .expect_err("unbound name must error at gate-2 (substitute)");
        match err {
            LispError::UnboundTemplateVar { prefix, name, hint } => {
                assert_eq!(prefix, UnquoteForm::Unquote);
                assert_eq!(name, "xs");
                assert_eq!(hint.as_deref(), Some("x"));
            }
            other => panic!("expected UnboundTemplateVar, got: {other:?}"),
        }
    }

    #[test]
    fn resolve_binding_rejects_unbound_name_without_hint_under_splice() {
        // Sibling negative control on the substitute path: past-bound
        // distance → no hint. Closes the closed-set product of
        // {hint, no-hint} × {Unquote, Splice} on the substitute-path
        // gate-2.
        let mut bindings: HashMap<String, Sexp> = HashMap::new();
        bindings.insert("args".to_string(), Sexp::Nil);
        let err = resolve_binding(&bindings, "wholly-unrelated", UnquoteForm::Splice)
            .expect_err("unrelated unbound must error at gate-2");
        match err {
            LispError::UnboundTemplateVar { prefix, name, hint } => {
                assert_eq!(prefix, UnquoteForm::Splice);
                assert_eq!(name, "wholly-unrelated");
                assert_eq!(hint, None);
            }
            other => panic!("expected UnboundTemplateVar, got: {other:?}"),
        }
    }

    #[test]
    fn gate_2_consolidates_four_inline_callsites_into_two_helpers() {
        // Path-uniformity pin: end-to-end through ALL FOUR call sites
        // (`compile_node` Unquote, `compile_node` UnquoteSplice,
        // `substitute` Unquote, `substitute` list-inner UnquoteSplice)
        // every unbound-template-var rejection now routes through one
        // of the TWO `resolve_param_index` / `resolve_binding` helpers
        // — `Expander::new()` runs the compile path, so its two arms
        // share `resolve_param_index`; `Expander::new_substitute_only()`
        // runs the substitute path, so its two arms share
        // `resolve_binding`. The four end-to-end expansions below all
        // reject with the SAME variant (`UnboundTemplateVar`) with the
        // expected `prefix` — pins that the lift preserves the
        // path-uniform rejection contract `unbound_template_var`'s
        // prior naming established. A regression that re-inlines the
        // gate-2 projection at one of the four sites can drift the
        // four call sites independent of each other — this test would
        // catch that drift.
        struct Case {
            src: &'static str,
            expander: fn() -> Expander,
            expected_form: UnquoteForm,
        }
        let cases: &[Case] = &[
            // compile_node Unquote (bytecode path) — uses resolve_param_index
            Case {
                src: "(defmacro w (x) `(list ,xs)) (w 1)",
                expander: Expander::new,
                expected_form: UnquoteForm::Unquote,
            },
            // compile_node UnquoteSplice (bytecode path) — uses resolve_param_index
            Case {
                src: "(defmacro call (f &rest args) `(,f ,@argz)) (call foo a b)",
                expander: Expander::new,
                expected_form: UnquoteForm::Splice,
            },
            // substitute Unquote (substitute-only path) — uses resolve_binding
            Case {
                src: "(defmacro w (x) `(list ,xs)) (w 1)",
                expander: Expander::new_substitute_only,
                expected_form: UnquoteForm::Unquote,
            },
            // substitute UnquoteSplice-in-list (substitute-only path) — uses resolve_binding
            Case {
                src: "(defmacro call (f &rest args) `(,f ,@argz)) (call foo a b)",
                expander: Expander::new_substitute_only,
                expected_form: UnquoteForm::Splice,
            },
        ];
        for case in cases {
            let mut e = (case.expander)();
            let err = e
                .expand_program(read(case.src).unwrap())
                .expect_err("unbound template var must error end-to-end");
            match err {
                LispError::UnboundTemplateVar { prefix, .. } => {
                    assert_eq!(prefix, case.expected_form, "for src: {}", case.src);
                }
                other => panic!(
                    "expected UnboundTemplateVar for {}, got: {other:?}",
                    case.src
                ),
            }
        }
    }

    // ── resolve_unquote_in_params / _in_bindings: gate-1+gate-2 composition ─

    #[test]
    fn resolve_unquote_in_params_returns_index_for_symbol_inner_under_unquote() {
        // Ok-arm composition under `UnquoteForm::Unquote`: gate-1 projects
        // the symbol-inner to "x"; gate-2 looks "x" up in `params` and
        // returns its index. The combined helper returns the gate-2
        // result directly — pins that gate-1's Ok-arm threads into
        // gate-2's input without intermediate state.
        let inner = Sexp::symbol("x");
        let params = ["x", "y"];
        let idx = resolve_unquote_in_params(&inner, &params, UnquoteForm::Unquote)
            .expect("symbol-inner bound at index 0 must resolve");
        assert_eq!(idx, 0);
    }

    #[test]
    fn resolve_unquote_in_params_returns_index_for_symbol_inner_under_splice() {
        // Sibling Ok-arm under `UnquoteForm::Splice`: pins that the
        // marker doesn't change the projection — only the rejection
        // path's `prefix` slot.
        let inner = Sexp::symbol("args");
        let params = ["f", "args"];
        let idx = resolve_unquote_in_params(&inner, &params, UnquoteForm::Splice)
            .expect("symbol-inner bound at index 1 must resolve");
        assert_eq!(idx, 1);
    }

    #[test]
    fn resolve_unquote_in_params_rejects_non_symbol_inner_at_gate_1() {
        // Err-arm at gate-1 (must-be-a-symbol): the inner is a list, not
        // a symbol, so gate-1 rejects via `non_symbol_unquote_target`
        // BEFORE gate-2's param lookup runs. Pins that the composition's
        // sequencing is gate-1-then-gate-2: a regression that runs
        // gate-2 first would attempt to look up "(list 1 2)" as a param
        // name and emit `LispError::UnboundTemplateVar { name: "(list 1
        // 2)", ... }` — a confusing diagnostic that would substring-grep
        // "unbound" instead of "expected symbol". This test pins the
        // structural floor: a non-symbol inner is rejected as a non-
        // symbol, never re-treated as a bound-name lookup key.
        let inner = Sexp::List(vec![Sexp::symbol("list"), Sexp::int(1), Sexp::int(2)]);
        let params = ["x"];
        let err = resolve_unquote_in_params(&inner, &params, UnquoteForm::Unquote)
            .expect_err("non-symbol inner must reject at gate-1");
        match err {
            LispError::NonSymbolUnquoteTarget { prefix, got } => {
                assert_eq!(prefix, UnquoteForm::Unquote);
                assert_eq!(got.display, "(list 1 2)");
            }
            other => panic!("expected NonSymbolUnquoteTarget (gate-1), got: {other:?}"),
        }
    }

    #[test]
    fn resolve_unquote_in_params_rejects_unbound_symbol_at_gate_2() {
        // Err-arm at gate-2 (must-be-bound-in-scope): the inner IS a
        // symbol (gate-1 passes) but the name isn't in `params`, so
        // gate-2 rejects via `unbound_template_var`. Pins that gate-1
        // forwards its Ok-arm `&str` borrow into gate-2's lookup, and
        // that the marker `prefix` is threaded into gate-2's rejection
        // unchanged (a regression that hard-codes `UnquoteForm::Unquote`
        // at the composition boundary would fail this Splice-marker
        // assertion).
        let inner = Sexp::symbol("missing");
        let params = ["x", "y"];
        let err = resolve_unquote_in_params(&inner, &params, UnquoteForm::Splice)
            .expect_err("unbound symbol must reject at gate-2");
        match err {
            LispError::UnboundTemplateVar { prefix, name, .. } => {
                assert_eq!(prefix, UnquoteForm::Splice);
                assert_eq!(name, "missing");
            }
            other => panic!("expected UnboundTemplateVar (gate-2), got: {other:?}"),
        }
    }

    #[test]
    fn resolve_unquote_in_bindings_returns_borrow_for_symbol_inner_under_unquote() {
        // Substitute-path sibling of `resolve_unquote_in_params_returns_
        // index_for_symbol_inner_under_unquote`. The combined helper
        // composes gate-1 (project inner to symbol) THEN gate-2 (look
        // up name in bindings). The returned `&Sexp` borrows from
        // `bindings` so the list-inner caller threads it straight into
        // the splice-expansion match without an intermediate allocation.
        let mut bindings: HashMap<String, Sexp> = HashMap::new();
        bindings.insert("v".to_string(), Sexp::int(42));
        let inner = Sexp::symbol("v");
        let val = resolve_unquote_in_bindings(&inner, &bindings, UnquoteForm::Unquote)
            .expect("symbol-inner bound to 42 must resolve");
        assert_eq!(val, &Sexp::int(42));
    }

    #[test]
    fn resolve_unquote_in_bindings_rejects_non_symbol_inner_at_gate_1() {
        // Substitute-path sibling of `resolve_unquote_in_params_rejects_
        // non_symbol_inner_at_gate_1`. Pins the gate-1-then-gate-2
        // sequencing on the substitute path: a non-symbol inner is
        // rejected as a non-symbol BEFORE the bindings map is consulted.
        let bindings: HashMap<String, Sexp> = HashMap::new();
        let inner = Sexp::int(5);
        let err = resolve_unquote_in_bindings(&inner, &bindings, UnquoteForm::Splice)
            .expect_err("non-symbol inner must reject at gate-1");
        match err {
            LispError::NonSymbolUnquoteTarget { prefix, got } => {
                assert_eq!(prefix, UnquoteForm::Splice);
                assert_eq!(got.display, "5");
            }
            other => panic!("expected NonSymbolUnquoteTarget (gate-1), got: {other:?}"),
        }
    }

    #[test]
    fn resolve_unquote_in_bindings_rejects_unbound_symbol_at_gate_2() {
        // Substitute-path sibling of `resolve_unquote_in_params_rejects_
        // unbound_symbol_at_gate_2`. Pins the gate-2 rejection on the
        // substitute path with the marker threaded into the rejection's
        // `prefix` slot.
        let mut bindings: HashMap<String, Sexp> = HashMap::new();
        bindings.insert("known".to_string(), Sexp::Nil);
        let inner = Sexp::symbol("missing");
        let err = resolve_unquote_in_bindings(&inner, &bindings, UnquoteForm::Unquote)
            .expect_err("unbound symbol must reject at gate-2");
        match err {
            LispError::UnboundTemplateVar { prefix, name, .. } => {
                assert_eq!(prefix, UnquoteForm::Unquote);
                assert_eq!(name, "missing");
            }
            other => panic!("expected UnboundTemplateVar (gate-2), got: {other:?}"),
        }
    }

    #[test]
    fn resolve_unquote_helpers_consolidate_four_inline_gate12_sites() {
        // End-to-end pin: all FOUR call sites of the gate-1+gate-2
        // composition (compile_node Unquote, compile_node UnquoteSplice,
        // substitute Unquote, substitute list-inner UnquoteSplice) now
        // share TWO composed primitives — `resolve_unquote_in_params`
        // on the bytecode path, `resolve_unquote_in_bindings` on the
        // substitute path — and ALL four reject gate-1 failures (non-
        // symbol inner) with the SAME `LispError::NonSymbolUnquoteTarget`
        // variant carrying the expected `prefix` slot. Before the lift,
        // each site threaded `form` twice through two helper calls; this
        // test pins that the lift preserves the gate's rejection-shape
        // identity across all four sites for a non-symbol inner — i.e.
        // gate-1 fires identically across both expansion strategies.
        struct Case {
            src: &'static str,
            expander: fn() -> Expander,
            expected_form: UnquoteForm,
        }
        let cases: &[Case] = &[
            Case {
                src: "(defmacro w (x) `,(list 1 2)) (w 1)",
                expander: Expander::new,
                expected_form: UnquoteForm::Unquote,
            },
            Case {
                src: "(defmacro w (x) `(outer ,@5)) (w 1)",
                expander: Expander::new,
                expected_form: UnquoteForm::Splice,
            },
            Case {
                src: "(defmacro w (x) `,(list 1 2)) (w 1)",
                expander: Expander::new_substitute_only,
                expected_form: UnquoteForm::Unquote,
            },
            Case {
                src: "(defmacro w (x) `(outer ,@(list 1 2))) (w 1)",
                expander: Expander::new_substitute_only,
                expected_form: UnquoteForm::Splice,
            },
        ];
        for case in cases {
            let mut e = (case.expander)();
            let err = e
                .expand_program(read(case.src).unwrap())
                .expect_err("non-symbol inner must error end-to-end");
            match err {
                LispError::NonSymbolUnquoteTarget { prefix, .. } => {
                    assert_eq!(prefix, case.expected_form, "for src: {}", case.src);
                }
                other => panic!(
                    "expected NonSymbolUnquoteTarget for {}, got: {other:?}",
                    case.src
                ),
            }
        }
    }

    // ── Splice outside list: structural variant + path-uniform rejection ─

    /// Helper for the splice-outside-list tests — pins the variant shape
    /// and carries the offending `got` field up to the assert site for
    /// legibility. Sibling of `unbound_var` and `non_symbol_target`.
    fn splice_outside_list_got(err: &LispError) -> &str {
        match err {
            LispError::SpliceOutsideList { got } => got.display.as_str(),
            other => panic!("expected SpliceOutsideList, got: {other:?}"),
        }
    }

    #[test]
    fn splice_outside_list_in_substitute_emits_structural_variant() {
        // `,@xs` at the body's top level — there is no containing list to
        // splice into. Path: substitute (the `Expander::new_substitute_only`
        // path's top-level `Sexp::UnquoteSplice(_)` arm). Pins variant
        // identity AND the offending inner so a regression that re-inlines
        // the legacy `LispError::Compile` shape fails-loudly here.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro f (xs) `,@xs) (f (list 1 2))").unwrap())
            .expect_err("splice outside list must error");
        assert_eq!(splice_outside_list_got(&err), "xs");
    }

    #[test]
    fn splice_outside_list_with_list_literal_in_substitute_emits_structural_variant() {
        // `,@(list 1 2)` at the body's top level — the inner is a literal
        // list, not a symbol. The structural variant carries the inner's
        // Sexp::Display projection so the operator sees the literal value
        // they wrote in the parenthetical.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro f (x) `,@(list 1 2)) (f 1)").unwrap())
            .expect_err("splice outside list must error");
        assert_eq!(splice_outside_list_got(&err), "(list 1 2)");
    }

    #[test]
    fn splice_outside_list_in_compile_template_emits_structural_variant() {
        // The bytecode path's `compile_template` gate now rejects top-level
        // `,@X` bodies BEFORE walking — closing the prior silent-divergence
        // where the bytecode interpreter's outermost stack frame absorbed
        // the splice. Pins that the bytecode path emits the SAME structural
        // variant the substitute path emits — `,@-outside-list` is rejected
        // path-uniformly. Path: `Expander::new()` (compile_templates = true)
        // → `compile_template` gate.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (xs) `,@xs) (f (list 1 2))").unwrap())
            .expect_err("compile-template splice outside list must error");
        assert_eq!(splice_outside_list_got(&err), "xs");
    }

    #[test]
    fn splice_outside_list_with_list_literal_in_compile_template_emits_structural_variant() {
        // Same shape as the substitute test but routed through the bytecode
        // path's `compile_template` gate. Proves the gate fires on a
        // non-symbol inner too — the slot's contents are irrelevant; only
        // the syntactic position matters.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (x) `,@(list 1 2)) (f 1)").unwrap())
            .expect_err("compile-template splice outside list must error");
        assert_eq!(splice_outside_list_got(&err), "(list 1 2)");
    }

    #[test]
    fn splice_outside_list_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME structural
        // variant (`SpliceOutsideList { got: "xs" }`) under both expansion
        // strategies. Before the `compile_template` gate, the bytecode path
        // silently produced a list while the substitute path errored —
        // expansion strategy was observable. After the gate, the gate is
        // strategy-uniform, so a macro that registers under one strategy
        // registers under the other.
        let src = "(defmacro f (xs) `,@xs) (f (list 1 2))";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(splice_outside_list_got(&err_subst), "xs");
        assert_eq!(splice_outside_list_got(&err_byte), "xs");
    }

    #[test]
    fn splice_outside_list_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp` carries
        // source positions, `position()` returns `None` for this variant.
        // A future run that gives `Sexp` source spans adds `pos:
        // Option<usize>` to ONE place; this test gives that change a
        // deliberate fail-before/pass-after delta.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro f (xs) `,@xs) (f (list 1 2))").unwrap())
            .expect_err("splice outside list must error");
        assert_eq!(err.position(), None);
    }

    #[test]
    fn splice_outside_list_message_renders_legacy_substring_with_offending_form() {
        // End-to-end through the Display impl — pins the rendered diagnostic
        // a downstream tool sees today (REPL, tatara-check). The legacy
        // substring `"\`,@\` may only appear inside a list"` is preserved
        // verbatim AND the parenthetical `(got ,@xs)` names the offending
        // form; tools that pattern-match on the variant gain structural
        // binding to `got`.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro f (xs) `,@xs) (f (list 1 2))").unwrap())
            .expect_err("splice outside list must error");
        let msg = format!("{err}");
        assert_eq!(
            msg,
            "compile error in ,@: `,@` may only appear inside a list (got ,@xs)"
        );
    }

    #[test]
    fn splice_inside_list_still_succeeds_under_both_paths() {
        // Negative control: a well-positioned splice (`,@xs` INSIDE a list)
        // continues to succeed under both paths — the new gate only fires
        // when the splice is the entire body. Pins that the gate is scoped
        // to top-level only, not all `,@` occurrences. Uses a `&rest`-bound
        // list so `xs` is unambiguously a Sexp::List `(1 2)` rather than a
        // bare list-literal whose first symbol would also splice through.
        let src = "(defmacro f (&rest xs) `(outer ,@xs)) (f 1 2)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let out_subst = subst.expand_program(read(src).unwrap()).unwrap();
        let out_byte = bytecode.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out_subst, out_byte);
        assert_eq!(out_subst[0], parse("(outer 1 2)"));
    }

    // ── splice_value_into: the shared splice-result coercion ──

    #[test]
    fn splice_value_into_list_flattens_elements_into_builder() {
        // The canonical splice arm: a bound LIST contributes its elements
        // in order, preserving anything already in the builder.
        let mut builder = vec![Sexp::symbol("outer")];
        splice_value_into(&mut builder, &Sexp::List(vec![Sexp::int(1), Sexp::int(2)]));
        assert_eq!(
            builder,
            vec![Sexp::symbol("outer"), Sexp::int(1), Sexp::int(2)]
        );
    }

    #[test]
    fn splice_value_into_nil_is_a_noop() {
        // Splicing the empty list (`Sexp::Nil`) contributes nothing —
        // the builder is unchanged.
        let mut builder = vec![Sexp::symbol("outer")];
        splice_value_into(&mut builder, &Sexp::Nil);
        assert_eq!(builder, vec![Sexp::symbol("outer")]);
    }

    #[test]
    fn splice_value_into_scalar_pushes_single_element() {
        // A non-list, non-nil bound value degrades `,@x` to `,x`: it
        // splices as exactly one element. Pins the "free middle" coercion
        // every scalar shape (int, keyword, …) shares.
        let mut builder = vec![Sexp::symbol("outer")];
        splice_value_into(&mut builder, &Sexp::int(5));
        assert_eq!(builder, vec![Sexp::symbol("outer"), Sexp::int(5)]);
        let mut other: Vec<Sexp> = vec![];
        splice_value_into(&mut other, &Sexp::keyword("k"));
        assert_eq!(other, vec![Sexp::keyword("k")]);
    }

    #[test]
    fn splice_of_non_list_value_coerces_identically_under_both_paths() {
        // The point of the lift: the NON-list splice arms (scalar → single
        // element, nil → nothing) coerce identically under the substitute
        // AND bytecode strategies. Before the coercion was lifted to ONE
        // primitive these two arms lived inline at two sites; this test
        // pins that the two strategies cannot drift on the non-list arms.
        let scalar = "(defmacro f (x) `(outer ,@x)) (f 5)";
        let empty = "(defmacro g (x) `(outer ,@x)) (g ())";
        for src in [scalar, empty] {
            let mut subst = Expander::new_substitute_only();
            let mut bytecode = Expander::new();
            let out_subst = subst.expand_program(read(src).unwrap()).unwrap();
            let out_byte = bytecode.expand_program(read(src).unwrap()).unwrap();
            assert_eq!(out_subst, out_byte, "strategies must agree for {src}");
        }
        let mut e = Expander::new();
        assert_eq!(
            e.expand_program(read(scalar).unwrap()).unwrap()[0],
            parse("(outer 5)")
        );
        let mut e2 = Expander::new();
        assert_eq!(
            e2.expand_program(read(empty).unwrap()).unwrap()[0],
            parse("(outer)")
        );
    }

    // ── Missing macro arg: structural variant + path-uniform rejection ──

    /// Helper for the missing-macro-arg tests — pins the variant shape
    /// and carries the failing macro's name + un-bound param up to the
    /// assert site for legibility. Sibling of `unbound_var`,
    /// `non_symbol_target`, and `splice_outside_list_got`.
    fn missing_macro_arg_fields(err: &LispError) -> (&str, &str) {
        match err {
            LispError::MissingMacroArg { macro_name, param } => {
                (macro_name.as_str(), param.as_str())
            }
            other => panic!("expected MissingMacroArg, got: {other:?}"),
        }
    }

    #[test]
    fn missing_macro_arg_in_compile_template_emits_structural_variant() {
        // `(need-two 1)` against `(need-two a b)` — `b` has no arg. Path:
        // `apply_compiled` (the bytecode-template path, default expander).
        // Pins variant identity AND macro_name AND the un-bound param so a
        // regression that re-inlines the legacy `LispError::Compile` shape
        // fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro need-two (a b) `(,a ,b)) (need-two 1)").unwrap())
            .expect_err("missing required macro arg must error");
        let (macro_name, param) = missing_macro_arg_fields(&err);
        assert_eq!(macro_name, "need-two");
        assert_eq!(param, "b");
    }

    #[test]
    fn missing_macro_arg_in_substitute_emits_structural_variant() {
        // Same shape as the bytecode test but routed through the
        // substitute-only expander → `bind_args` is the failing site.
        // Proves the substitute path emits the SAME structural variant the
        // bytecode path emits — `missing required arg` rejection is
        // path-uniform across both expansion strategies.
        let mut e = Expander::new_substitute_only();
        let err = e
            .expand_program(read("(defmacro need-two (a b) `(,a ,b)) (need-two 1)").unwrap())
            .expect_err("missing required macro arg must error");
        let (macro_name, param) = missing_macro_arg_fields(&err);
        assert_eq!(macro_name, "need-two");
        assert_eq!(param, "b");
    }

    #[test]
    fn missing_macro_arg_first_position_is_named() {
        // `(f)` against `(f a b)` — `a` (the FIRST required param) has no
        // arg. The variant names `a`, not `b` — naming the LEFTMOST
        // un-bound param is the shape `bind_args` / `apply_compiled` both
        // emit (each iterates positionally and bails on the first missing
        // slot). Pins the leftmost-bail contract so a regression that
        // names the rightmost (or a surplus) param fails-loudly.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a b) `(,a ,b)) (f)").unwrap())
            .expect_err("missing first required arg must error");
        let (macro_name, param) = missing_macro_arg_fields(&err);
        assert_eq!(macro_name, "f");
        assert_eq!(param, "a");
    }

    #[test]
    fn missing_macro_arg_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME structural
        // variant under both expansion strategies. Negative control for
        // the divergence-closing posture: a future refactor that drifts
        // either path's rejection shape (or drops one path's rejection
        // entirely) fails-loudly here. Sibling of
        // `splice_outside_list_substitute_and_bytecode_paths_agree` —
        // both close `THEORY.md §II.1 invariant 2 — free middle` for one
        // failure mode each.
        let src = "(defmacro need-two (a b) `(,a ,b)) (need-two 1)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(missing_macro_arg_fields(&err_subst), ("need-two", "b"));
        assert_eq!(missing_macro_arg_fields(&err_byte), ("need-two", "b"));
    }

    #[test]
    fn missing_macro_arg_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp` carries
        // source positions, `position()` returns `None` for this variant.
        // A future run that gives `Sexp` source spans adds `pos:
        // Option<usize>` to ONE place; this test gives that change a
        // deliberate fail-before/pass-after delta. Parallel to
        // `splice_outside_list_position_is_none_today`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro need-two (a b) `(,a ,b)) (need-two 1)").unwrap())
            .expect_err("missing required macro arg must error");
        assert_eq!(err.position(), None);
    }

    #[test]
    fn missing_macro_arg_message_renders_legacy_substring_with_macro_name() {
        // End-to-end through the Display impl — pins the rendered diagnostic
        // a downstream tool sees today (REPL, tatara-check). The legacy
        // substring `"missing required arg: {param}"` is preserved verbatim
        // AND the head clause names the failing macro via `"call to
        // {macro_name}"`; tools that pattern-match on the variant gain
        // structural binding to `macro_name` / `param`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro need-two (a b) `(,a ,b)) (need-two 1)").unwrap())
            .expect_err("missing required macro arg must error");
        assert_eq!(
            format!("{err}"),
            "compile error in call to need-two: missing required arg: b"
        );
    }

    #[test]
    fn missing_macro_arg_carries_kebab_case_macro_and_param_unchanged() {
        // Both `macro_name` (`wrap-twice`) and `param` (`notify-ref`)
        // round-trip through the variant unchanged. Pinning this contract
        // means a regression that camelCases or lowercases either side
        // fails-loudly here. Parallel to the
        // `unknown_kwarg_display_carries_kebab_case_keys_unchanged`
        // assertion for the kwarg-gate's symmetric surface.
        let mut e = Expander::new();
        let err = e
            .expand_program(
                read("(defmacro wrap-twice (notify-ref body) `(list ,notify-ref ,body)) (wrap-twice :a)")
                    .unwrap(),
            )
            .expect_err("missing required macro arg must error");
        let (macro_name, param) = missing_macro_arg_fields(&err);
        assert_eq!(macro_name, "wrap-twice");
        assert_eq!(param, "body");
    }

    #[test]
    fn rest_param_only_macro_with_no_args_still_succeeds() {
        // Negative control: a macro whose only param is `&rest` must NOT
        // error when called with zero args — the rest-param binds to the
        // empty list. The new structural variant fires only on REQUIRED
        // params; the `Param::Rest` arm in both `bind_args` and
        // `apply_compiled` continues to bind the empty tail. Pins that the
        // helper is scoped to required-param failure, not all
        // arity-mismatch shapes.
        let src = "(defmacro f (&rest xs) `(list ,@xs)) (f)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let out_subst = subst.expand_program(read(src).unwrap()).unwrap();
        let out_byte = bytecode.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out_subst, out_byte);
        assert_eq!(out_subst[0], parse("(list)"));
    }

    // ── TooManyMacroArgs: call-site mirror of RestParamTrailingTokens ──
    //
    // A rest-less param list has a FIXED maximum arity equal to
    // `required.len() + optional.len()`. Surplus call args have nowhere to
    // bind. Before this gate the surplus was silently truncated to the
    // slice the binder could consume — the typed-entry macro-call-gate
    // rejected too-few-args loudly (`MissingMacroArg`) but accepted
    // too-many silently, an asymmetry the definition-side `&rest <name>
    // extra` rejection (`RestParamTrailingTokens`) had no call-side dual.
    // After this gate the call-site arity surface is structurally
    // complete in both directions; the substitute + bytecode paths share
    // `MacroParams::bind`, so both inherit the rejection without drift.

    /// Helper for the too-many-args tests — projects to (macro_name,
    /// expected, got) for legibility. Sibling of `missing_macro_arg_fields`.
    fn too_many_macro_args_fields(err: &LispError) -> (&str, usize, usize) {
        match err {
            LispError::TooManyMacroArgs {
                macro_name,
                expected,
                got,
            } => (macro_name.as_str(), *expected, *got),
            other => panic!("expected TooManyMacroArgs, got: {other:?}"),
        }
    }

    #[test]
    fn too_many_macro_args_required_only_rejected_with_expected_and_got() {
        // `(defmacro f (a b) ...)` called as `(f 1 2 3)` — `3` has
        // nowhere to bind. The rest-less binder rejects via
        // `TooManyMacroArgs { macro_name: "f", expected: 2, got: 3 }`,
        // NOT silently drops `3`. Pins both the variant identity AND the
        // structural fields the typed gate exposes for authoring-tool
        // quick-fixes ("you supplied 3 args; the macro takes at most
        // 2").
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a b) `(list ,a ,b)) (f 1 2 3)").unwrap())
            .expect_err("surplus arg on rest-less call must error");
        let (macro_name, expected, got) = too_many_macro_args_fields(&err);
        assert_eq!(macro_name, "f");
        assert_eq!(expected, 2);
        assert_eq!(got, 3);
    }

    #[test]
    fn too_many_macro_args_required_plus_optional_capacity_includes_optional() {
        // The rest-less binder's fixed maximum arity is `required.len() +
        // optional.len()` — the optional section CONTRIBUTES to capacity.
        // `(defmacro f (a &optional b) ...)` accepts 1 OR 2 args; 3
        // args rejects with `expected: 2` (required + optional, NOT just
        // required). Pins the optional-counts-in-capacity contract so a
        // regression that omits optionals from the expected calculation
        // (and erroneously rejects 2-arg calls) fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a &optional b) `(list ,a ,b)) (f 1 2 3)").unwrap())
            .expect_err("surplus arg beyond required+optional must error");
        let (macro_name, expected, got) = too_many_macro_args_fields(&err);
        assert_eq!(macro_name, "f");
        assert_eq!(expected, 2);
        assert_eq!(got, 3);
    }

    #[test]
    fn too_many_macro_args_required_plus_two_optionals_arity_three() {
        // Larger optional section (capacity 1 + 2 = 3). 4 args rejects
        // with `expected: 3`. Pins that the capacity calculation scales
        // with optional.len(), not just at-most-one. Mixes a bare
        // optional with an optional carrying a default form — both shapes
        // contribute identically to capacity (the typed `OptionalParam`
        // entry's `default: Option<Sexp>` is irrelevant to the arity gate).
        let mut e = Expander::new();
        let err = e
            .expand_program(
                read("(defmacro f (a &optional b (c 5)) `(list ,a ,b ,c)) (f 1 2 3 4)").unwrap(),
            )
            .expect_err("surplus arg beyond required+two-optional must error");
        let (macro_name, expected, got) = too_many_macro_args_fields(&err);
        assert_eq!(macro_name, "f");
        assert_eq!(expected, 3);
        assert_eq!(got, 4);
    }

    #[test]
    fn too_many_macro_args_does_not_fire_when_rest_is_present() {
        // Negative control: a rest-PRESENT param list has no maximum
        // arity — the `&rest` slot collects every trailing arg into a
        // `Sexp::List`. `(defmacro f (a &rest xs) ...)` called as
        // `(f 1 2 3 4)` MUST succeed; the new gate fires ONLY when
        // `MacroParams.rest` is `None`. Pins the rest-present-path
        // remains permissive — a regression that wrongly fires the
        // too-many gate for any surplus (including the rest-collecting
        // path) would break every `&rest`-using macro.
        let src = "(defmacro f (a &rest xs) `(list ,a ,@xs)) (f 1 2 3 4)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let out_subst = subst.expand_program(read(src).unwrap()).unwrap();
        let out_byte = bytecode.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out_subst, out_byte);
        assert_eq!(out_subst[0], parse("(list 1 2 3 4)"));
    }

    #[test]
    fn too_many_macro_args_does_not_fire_at_exact_max_arity() {
        // Negative control: the rest-less gate fires STRICTLY when
        // `args.len() > expected` — at exact arity the binder accepts.
        // `(defmacro f (a &optional b) ...)` called as `(f 1 2)` binds
        // a=1, b=2 successfully (the optional takes its supplied arg,
        // not the default). Pins the boundary condition so a regression
        // that flips the comparison to `>=` (rejecting exact-arity
        // calls) fails-loudly here.
        let src = "(defmacro f (a &optional b) `(list ,a ,b)) (f 1 2)";
        let mut e = Expander::new();
        let out = e.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out[0], parse("(list 1 2)"));
    }

    #[test]
    fn too_many_macro_args_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME
        // structural variant under both expansion strategies. The
        // shared `MacroParams::bind` makes the rejection lands once and
        // both paths inherit it. Mirror of
        // `missing_macro_arg_substitute_and_bytecode_paths_agree` —
        // both close `THEORY.md §II.1 invariant 2 — free middle` for
        // one failure mode each.
        let src = "(defmacro pair (a b) `(cons ,a ,b)) (pair 1 2 3)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(too_many_macro_args_fields(&err_subst), ("pair", 2, 3));
        assert_eq!(too_many_macro_args_fields(&err_byte), ("pair", 2, 3));
    }

    #[test]
    fn too_many_macro_args_fires_after_missing_required_priority_held() {
        // Priority discipline: the required walk fires
        // `MissingMacroArg` BEFORE the rest-less surplus gate is
        // reached. `(defmacro f (a b c) …) (f 1)` is `MissingMacroArg
        // { param: "b" }`, NOT `TooManyMacroArgs` (and certainly not a
        // collision). The two failure modes are structurally disjoint:
        // too-few-required vs. too-many-with-no-rest. Pins the bail-on-
        // first-missing-required contract so a regression that swaps
        // the two gates' order would emit the wrong variant.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a b c) `(list ,a ,b ,c)) (f 1)").unwrap())
            .expect_err("missing required must error");
        assert!(
            matches!(err, LispError::MissingMacroArg { .. }),
            "expected MissingMacroArg (priority), got: {err:?}"
        );
    }

    #[test]
    fn too_many_macro_args_zero_required_zero_optional_rejects_any_args() {
        // Degenerate case: a nullary macro `(defmacro f () ...)` has
        // capacity 0; ANY supplied arg rejects with `expected: 0`. Pins
        // the gate fires even when the rest-less max-arity is zero —
        // i.e. the rejection is structural, not conditional on a
        // non-empty required+optional.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f () `(list)) (f 1)").unwrap())
            .expect_err("nullary macro called with arg must error");
        let (macro_name, expected, got) = too_many_macro_args_fields(&err);
        assert_eq!(macro_name, "f");
        assert_eq!(expected, 0);
        assert_eq!(got, 1);
    }

    #[test]
    fn too_many_macro_args_display_renders_legacy_compile_substring() {
        // The rendered Display matches the legacy `Compile`-shaped
        // diagnostic style — `"compile error in call to {macro_name}:
        // too many args: expected at most {expected}, got {got}"` — so
        // the existing `"compile error in call to"` substring authoring
        // tools' assertions key on stays unchanged. Pins the byte-level
        // rendered shape so a regression that drifts the prefix /
        // separator / labels fails-loudly here.
        let err = LispError::TooManyMacroArgs {
            macro_name: "pair".into(),
            expected: 2,
            got: 5,
        };
        assert_eq!(
            err.to_string(),
            "compile error in call to pair: too many args: expected at most 2, got 5"
        );
    }

    #[test]
    fn too_many_macro_args_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp`
        // carries source positions, `position()` returns `None` for
        // this variant. A future run that gives `Sexp` source spans
        // adds `pos: Option<usize>` to ONE place; this test gives that
        // change a deliberate fail-before/pass-after delta. Parallel to
        // `missing_macro_arg_position_is_none_today`.
        let err = LispError::TooManyMacroArgs {
            macro_name: "pair".into(),
            expected: 2,
            got: 3,
        };
        assert_eq!(err.position(), None);
    }

    /// Helper for the non-symbol-param tests — pins the variant shape and
    /// carries the failing position + offending element up to the assert
    /// site for legibility. Sibling of `missing_macro_arg_fields`.
    fn non_symbol_param_fields(err: &LispError) -> (usize, &str) {
        match err {
            LispError::NonSymbolParam { position, got } => (*position, got.display.as_str()),
            other => panic!("expected NonSymbolParam, got: {other:?}"),
        }
    }

    #[test]
    fn non_symbol_param_at_first_position_emits_structural_variant() {
        // `(defmacro f (5) ...)` — the first element of the param list is
        // an integer literal, not a symbol. Pins variant identity AND
        // that `position` is the loop index inside `parse_params` (0 for
        // the first slot) AND that `got` is the offending element via
        // `Sexp::Display` (`5`). A regression that re-inlines the legacy
        // `LispError::Compile` shape (which named neither the position
        // nor the offending element) fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (5) `(list ,a))").unwrap())
            .expect_err("non-symbol param must error");
        let (position, got) = non_symbol_param_fields(&err);
        assert_eq!(position, 0);
        assert_eq!(got, "5");
    }

    #[test]
    fn non_symbol_param_at_second_position_emits_structural_variant() {
        // `(defmacro f (a 5) ...)` — `a` parses fine, `5` at position 1
        // misfires. Pins that `position` advances with the loop index, so
        // an LSP quick-fix that wants to point at "the second element of
        // your param list" gains the index as data, no source re-parse
        // required.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a 5) `(,a))").unwrap())
            .expect_err("non-symbol param must error");
        let (position, got) = non_symbol_param_fields(&err);
        assert_eq!(position, 1);
        assert_eq!(got, "5");
    }

    #[test]
    fn non_symbol_param_carries_keyword_value_unchanged() {
        // `:k` at a param-list position. `Sexp::Display` for
        // `Atom::Keyword(s)` writes `:s`; pins that the variant's `got`
        // field round-trips the keyword form unchanged so an LSP that
        // surfaces "you wrote `:k` where a symbol was expected" gains
        // the literal keyword value as data, no re-parsing required.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (:k) `(list))").unwrap())
            .expect_err("non-symbol param must error");
        let (position, got) = non_symbol_param_fields(&err);
        assert_eq!(position, 0);
        assert_eq!(got, ":k");
    }

    #[test]
    fn non_symbol_param_carries_nested_list_value_unchanged() {
        // A nested list at a param-list position. `Sexp::Display` for
        // `List(xs)` writes `(<x1> <x2> ...)`; pins that the variant's
        // `got` field carries the nested form's full Display projection
        // unchanged so the operator sees what they wrote.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f ((nested)) `(list))").unwrap())
            .expect_err("non-symbol param must error");
        let (position, got) = non_symbol_param_fields(&err);
        assert_eq!(position, 0);
        assert_eq!(got, "(nested)");
    }

    #[test]
    fn non_symbol_param_in_defpoint_template_emits_same_variant() {
        // `defpoint-template` shares `parse_params` with `defmacro` (all
        // three head keywords route through `macro_def_from`). Pins that
        // the lift fires path-uniformly across the three head keywords
        // — `defmacro`, `defpoint-template`, `defcheck` — so the
        // structural-completeness floor holds for every defmacro-shaped
        // form, not just the one with the `defmacro` head literal.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defpoint-template obs (5) `(defpoint))").unwrap())
            .expect_err("non-symbol param must error");
        let (position, got) = non_symbol_param_fields(&err);
        assert_eq!(position, 0);
        assert_eq!(got, "5");
    }

    #[test]
    fn non_symbol_param_in_defcheck_emits_same_variant() {
        // Sibling of the defpoint-template test — `defcheck` is the
        // third head keyword `macro_def_from` recognizes. All three
        // route through the same `parse_params` and now reject
        // non-symbol params with the same structural variant.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defcheck pair (a 5) `(do))").unwrap())
            .expect_err("non-symbol param must error");
        let (position, got) = non_symbol_param_fields(&err);
        assert_eq!(position, 1);
        assert_eq!(got, "5");
    }

    #[test]
    fn non_symbol_param_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp`
        // carries source positions, `position()` on `LispError` returns
        // `None` for this variant. A future run that gives `Sexp`
        // source spans adds `pos: Option<usize>` to ONE place; this
        // test gives that change a deliberate fail-before/pass-after
        // delta. Parallel to `missing_macro_arg_position_is_none_today`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (5) `(list))").unwrap())
            .expect_err("non-symbol param must error");
        assert_eq!(err.position(), None);
    }

    #[test]
    fn non_symbol_param_message_renders_legacy_substring_with_position() {
        // End-to-end through Display — pins the rendered diagnostic that
        // downstream tools (REPL, `tatara-check`) see today. Legacy
        // substrings `"defmacro params"` AND `"expected symbol"` are
        // preserved verbatim; the appended `at position {position}, got
        // {got}` clause is the new structural detail. Tools that
        // pattern-match on the variant gain structural binding to
        // `position` / `got`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a 5) `(,a))").unwrap())
            .expect_err("non-symbol param must error");
        assert_eq!(
            format!("{err}"),
            "compile error in defmacro params: \
             expected symbol at position 1, got 5"
        );
    }

    #[test]
    fn non_symbol_param_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME
        // structural variant under both expansion strategies. The
        // defmacro-syntax-gate fires inside `macro_def_from` →
        // `parse_params`, BEFORE either strategy's expansion path runs;
        // so both `Expander::new()` (bytecode) and
        // `Expander::new_substitute_only()` (substitute) reject the
        // SAME malformed defmacro at the SAME gate. Sibling of
        // `missing_macro_arg_substitute_and_bytecode_paths_agree`.
        let src = "(defmacro f (a 5) `(,a))";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(non_symbol_param_fields(&err_subst), (1, "5"));
        assert_eq!(non_symbol_param_fields(&err_byte), (1, "5"));
    }

    /// Helper for the rest-param-missing-name tests — pins the variant
    /// shape and carries the marker position + offending follower (or
    /// its absence) up to the assert site for legibility. Sibling of
    /// `non_symbol_param_fields`.
    fn rest_param_missing_name_fields(err: &LispError) -> (usize, Option<&str>) {
        match err {
            LispError::RestParamMissingName { rest_position, got } => {
                (*rest_position, got.as_ref().map(|w| w.display.as_str()))
            }
            other => panic!("expected RestParamMissingName, got: {other:?}"),
        }
    }

    #[test]
    fn rest_param_missing_name_when_only_rest_emits_structural_variant_with_no_got() {
        // `(defmacro f (&rest))` — the marker is the only param-list
        // element; nothing follows. Pins variant identity AND that
        // `rest_position == 0` (the first slot) AND that `got == None`
        // (no follower exists). A regression that re-inlines the legacy
        // `LispError::Compile` shape (which named neither field) fails-
        // loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (&rest) `(list))").unwrap())
            .expect_err("&rest with no follower must error");
        let (rest_position, got) = rest_param_missing_name_fields(&err);
        assert_eq!(rest_position, 0);
        assert_eq!(got, None);
    }

    #[test]
    fn rest_param_missing_name_at_end_of_param_list_emits_structural_variant() {
        // `(defmacro f (a &rest))` — `a` parses fine, `&rest` at param-list
        // position 1 has no follower at all. Pins that `rest_position`
        // advances with the loop index, so an LSP quick-fix that wants to
        // point at "your `&rest` at position 1 has no name" gains the
        // marker position as data, no source re-parse required.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a &rest) `(,a))").unwrap())
            .expect_err("&rest with no follower must error");
        let (rest_position, got) = rest_param_missing_name_fields(&err);
        assert_eq!(rest_position, 1);
        assert_eq!(got, None);
    }

    #[test]
    fn rest_param_missing_name_with_int_follower_emits_structural_variant() {
        // `(defmacro f (&rest 5))` — `&rest` at position 0 followed by
        // `5` (an integer literal, not a symbol). Pins that the variant's
        // `got` field is `Some` and carries the offending follower's
        // `Sexp::Display` projection; the bifurcation between "missing
        // entirely" and "present but non-symbol" is in the renderable
        // detail, not in what the gate rejects.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (&rest 5) `(list))").unwrap())
            .expect_err("&rest followed by non-symbol must error");
        let (rest_position, got) = rest_param_missing_name_fields(&err);
        assert_eq!(rest_position, 0);
        assert_eq!(got, Some("5"));
    }

    #[test]
    fn rest_param_missing_name_with_keyword_follower_emits_structural_variant() {
        // `(defmacro f (a &rest :foo))` — keyword follower at the rest-name
        // slot. `Sexp::Display` for `Atom::Keyword(s)` writes `:s`; pins
        // that the variant's `got` field round-trips the keyword form
        // unchanged so an LSP that surfaces "you wrote `:foo` where a
        // rest-name was expected" gains the literal keyword value as
        // data, no re-parsing required.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a &rest :foo) `(,a))").unwrap())
            .expect_err("&rest followed by keyword must error");
        let (rest_position, got) = rest_param_missing_name_fields(&err);
        assert_eq!(rest_position, 1);
        assert_eq!(got, Some(":foo"));
    }

    #[test]
    fn rest_param_missing_name_with_nested_list_follower_emits_structural_variant() {
        // `(defmacro f (&rest (nested)))` — nested-list follower at the
        // rest-name slot. `Sexp::Display` for `List(xs)` writes
        // `(<x1> <x2> ...)`; pins that the variant's `got` field carries
        // the nested form's full Display projection unchanged so the
        // operator sees what they wrote.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (&rest (nested)) `(list))").unwrap())
            .expect_err("&rest followed by list must error");
        let (rest_position, got) = rest_param_missing_name_fields(&err);
        assert_eq!(rest_position, 0);
        assert_eq!(got, Some("(nested)"));
    }

    #[test]
    fn rest_param_missing_name_in_defpoint_template_emits_same_variant() {
        // `defpoint-template` shares `parse_params` with `defmacro` (all
        // three head keywords route through `macro_def_from`). Pins that
        // the lift fires path-uniformly across the three head keywords —
        // a regression that handles `defpoint-template`'s param list
        // differently from `defmacro`'s would fail-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defpoint-template t (a &rest) `(,a))").unwrap())
            .expect_err("&rest with no follower must error");
        let (rest_position, got) = rest_param_missing_name_fields(&err);
        assert_eq!(rest_position, 1);
        assert_eq!(got, None);
    }

    #[test]
    fn rest_param_missing_name_in_defcheck_emits_same_variant() {
        // Sibling for the `defcheck` head; rounds out the three-head-
        // keyword coverage so the lift is path-uniform across
        // `defmacro` / `defpoint-template` / `defcheck`. After this
        // test the defmacro-syntax-gate rejects `&rest`-without-name
        // identically across all three head keywords — the
        // typed-entry surface is single-shape across the cluster.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defcheck c (&rest 5) `(list))").unwrap())
            .expect_err("&rest followed by non-symbol must error");
        let (rest_position, got) = rest_param_missing_name_fields(&err);
        assert_eq!(rest_position, 0);
        assert_eq!(got, Some("5"));
    }

    #[test]
    fn rest_param_missing_name_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME
        // structural variant under both expansion strategies. The
        // defmacro-syntax-gate fires inside `macro_def_from` →
        // `parse_params`, BEFORE either strategy's expansion path
        // runs; so both `Expander::new()` (bytecode) and
        // `Expander::new_substitute_only()` (substitute) reject the
        // SAME malformed defmacro at the SAME gate. Sibling of
        // `non_symbol_param_substitute_and_bytecode_paths_agree`.
        let src = "(defmacro f (a &rest 5) `(,a))";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(rest_param_missing_name_fields(&err_subst), (1, Some("5")));
        assert_eq!(rest_param_missing_name_fields(&err_byte), (1, Some("5")));
    }

    #[test]
    fn rest_param_missing_name_message_renders_legacy_substring_with_marker() {
        // End-to-end through Display — pins the rendered diagnostic
        // consumers see today (REPL, tatara-check) AND the new `(rest
        // marker at position {rest_position}, got {got})` clause. The
        // legacy `"&rest needs a name"` substring rides through
        // verbatim.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a &rest 5) `(,a))").unwrap())
            .expect_err("&rest followed by non-symbol must error");
        assert_eq!(
            format!("{err}"),
            "compile error in defmacro params: &rest needs a name \
             (rest marker at position 1, got 5)"
        );
    }

    #[test]
    fn rest_param_missing_name_message_renders_none_provided_when_follower_absent() {
        // Same as the prior test but for the "missing entirely" branch.
        // The renderable detail is `(rest marker at position
        // {rest_position}, none provided)` — naming the absence
        // structurally instead of an empty / partial parenthetical.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a &rest) `(,a))").unwrap())
            .expect_err("&rest with no follower must error");
        assert_eq!(
            format!("{err}"),
            "compile error in defmacro params: &rest needs a name \
             (rest marker at position 1, none provided)"
        );
    }

    #[test]
    fn rest_param_missing_name_position_is_none_today() {
        // Pins that `position()` returns `None` so the future `pos:
        // Option<usize>` add (once `Sexp` carries source spans) lands
        // as a deliberate fail-before/pass-after delta rather than a
        // silent default. Parallel to
        // `non_symbol_param_position_is_none_today` and
        // `missing_macro_arg_position_is_none_today`.
        let err_missing = LispError::RestParamMissingName {
            rest_position: 1,
            got: None,
        };
        assert_eq!(err_missing.position(), None);
        let err_got = LispError::RestParamMissingName {
            rest_position: 0,
            got: Some(crate::error::SexpWitness::new(
                crate::error::SexpShape::Int,
                "5",
            )),
        };
        assert_eq!(err_got.position(), None);
    }

    // --- RestParamTrailingTokens: the parse_params gate's third (and
    // final) definition-site failure mode ---
    //
    // A `&rest <name>` absorbs every remaining call arg, so it is the LAST
    // thing a param list can name. Before this variant `parse_params`
    // returned the moment it bound the rest name, SILENTLY DROPPING any
    // trailing tokens — `(a &rest xs extra)` parsed as if `extra` weren't
    // there. These tests pin the loud rejection that replaces the silent
    // drop; the symbol `RestParamTrailingTokens` exists only after this
    // change, so the whole block is fail-before/pass-after by construction
    // (compile-time edge) and the end-to-end regression guard below pins
    // that the malformed defmacro no longer expands cleanly.

    /// Helper mirroring `rest_param_missing_name_fields` — pins the variant
    /// shape and lifts the marker position, trailing count, and first
    /// offender's display up to the assert site.
    fn rest_param_trailing_tokens_fields(err: &LispError) -> (usize, usize, &str) {
        match err {
            LispError::RestParamTrailingTokens {
                rest_position,
                extra,
                first,
            } => (*rest_position, *extra, first.display.as_str()),
            other => panic!("expected RestParamTrailingTokens, got: {other:?}"),
        }
    }

    #[test]
    fn parse_params_rejects_single_trailing_token_after_rest_name() {
        // `(a &rest c extra)` — `&rest c` is well-formed, but `extra`
        // follows. The rest name is bound at position 2, the marker at 1;
        // the lone trailing token `extra` is reported (extra == 1, first ==
        // "extra"). Before this variant `parse_params` returned at the rest
        // name and `extra` vanished.
        let err = parse_params(&read("a &rest c extra").unwrap())
            .expect_err("a trailing token after the rest name must error");
        assert_eq!(rest_param_trailing_tokens_fields(&err), (1, 1, "extra"));
    }

    #[test]
    fn rest_param_trailing_tokens_counts_the_whole_trailing_run() {
        // `(&rest c x y z)` — three tokens follow the rest name. `extra`
        // counts ALL of them (3), `first` is the first (`x`), and the
        // marker is at position 0. A regression that reports only the
        // first trailing token's presence (extra hard-coded to 1) fails
        // loudly here.
        let err = parse_params(&read("&rest c x y z").unwrap())
            .expect_err("multiple trailing tokens must error");
        assert_eq!(rest_param_trailing_tokens_fields(&err), (0, 3, "x"));
    }

    #[test]
    fn rest_param_trailing_tokens_first_witness_carries_non_symbol_display() {
        // `(a &rest c 5)` — the rest NAME `c` is a valid symbol, so this is
        // NOT a `RestParamMissingName`; the integer `5` is a trailing token
        // AFTER a well-formed `&rest c`. Pins that the two sibling failure
        // modes don't collide: a malformed rest-name is `RestParamMissingName`,
        // a well-formed rest-name followed by junk is
        // `RestParamTrailingTokens`. `first` round-trips `5` via the typed
        // witness's `Sexp::Display` projection.
        let err = parse_params(&read("a &rest c 5").unwrap())
            .expect_err("a trailing non-symbol after the rest name must error");
        assert_eq!(rest_param_trailing_tokens_fields(&err), (1, 1, "5"));
    }

    #[test]
    fn rest_param_trailing_tokens_no_longer_silently_dropped_end_to_end() {
        // The fidelity fix, end-to-end through `expand_program`: a defmacro
        // whose param list carries a stray token after `&rest <name>` now
        // ERRORS at the typed-entry gate instead of expanding as though the
        // stray token weren't there. This is the regression guard for the
        // silent-drop bug — before this change the same source expanded
        // cleanly and `extra` was discarded with no signal.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a &rest xs extra) `(,a))").unwrap())
            .expect_err("trailing token after &rest name must error");
        assert_eq!(rest_param_trailing_tokens_fields(&err), (1, 1, "extra"));
    }

    #[test]
    fn rest_param_trailing_tokens_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the gate fires inside `macro_def_from` →
        // `parse_params`, BEFORE either expansion strategy runs, so both
        // `Expander::new()` (bytecode) and `Expander::new_substitute_only()`
        // (substitute) reject the SAME malformed defmacro at the SAME gate.
        // Sibling of `rest_param_missing_name_substitute_and_bytecode_paths_agree`.
        let src = "(defmacro f (a &rest xs extra) `(,a))";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(
            rest_param_trailing_tokens_fields(&err_subst),
            (1, 1, "extra")
        );
        assert_eq!(
            rest_param_trailing_tokens_fields(&err_byte),
            (1, 1, "extra")
        );
    }

    #[test]
    fn rest_param_trailing_tokens_message_renders_legacy_style_prefix_and_suffix() {
        // End-to-end through Display — pins the rendered diagnostic AND the
        // new `(rest marker at position {n}, {extra} trailing after name,
        // first: {first})` clause. The `compile error in defmacro params:`
        // prefix matches the sibling `&rest needs a name` rendering's shape.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f (a &rest xs extra) `(,a))").unwrap())
            .expect_err("trailing token after &rest name must error");
        assert_eq!(
            format!("{err}"),
            "compile error in defmacro params: &rest name must be last \
             (rest marker at position 1, 1 trailing after name, first: extra)"
        );
    }

    #[test]
    fn rest_param_trailing_tokens_position_is_none_today() {
        // Pins `position() == None` so the future `pos: Option<usize>` add
        // (once `Sexp` carries source spans) lands as a deliberate
        // fail-before/pass-after delta. Parallel to
        // `rest_param_missing_name_position_is_none_today`.
        let err = LispError::RestParamTrailingTokens {
            rest_position: 1,
            extra: 1,
            first: crate::error::SexpWitness::new(crate::error::SexpShape::Symbol, "extra"),
        };
        assert_eq!(err.position(), None);
    }

    // --- MacroDefHead enum (the closed-set lift) ---
    //
    // The next nine tests pin the typed-enum lift that closes the
    // three-times rule on the `head: &str → &'static str` projection
    // idiom previously inlined at FOUR sites (the `matches!` gate at
    // the top of `macro_def_from` plus the projection match inside
    // each of `defmacro_arity`, `defmacro_non_symbol_name`,
    // `defmacro_non_list_params`). Every test in this block names
    // `MacroDefHead` directly — the symbol exists only after the
    // lift, so the entire block is fail-before/pass-after by
    // construction (compile-time edge). Theory anchor: THEORY.md
    // §VI.1 — three-times rule; THEORY.md §V.1 — the closed set is
    // a TYPE rather than a `matches!` literal.

    #[test]
    fn macro_def_head_from_keyword_recognizes_defmacro() {
        // Pins that `MacroDefHead::from_keyword("defmacro")` returns
        // `Some(MacroDefHead::Defmacro)` — the first of the three
        // canonical macro-definition head keywords. A regression that
        // re-inlines a `matches!`-only gate (without the typed-enum
        // projection) deletes `from_keyword` and fails-loudly here.
        assert_eq!(
            MacroDefHead::from_keyword("defmacro"),
            Some(MacroDefHead::Defmacro)
        );
    }

    #[test]
    fn macro_def_head_from_keyword_recognizes_defpoint_template() {
        // Pins that `MacroDefHead::from_keyword("defpoint-template")`
        // returns `Some(MacroDefHead::DefpointTemplate)` — the second
        // of the three canonical head keywords. The `defpoint-template`
        // form is the K8s-as-processes authoring surface (see
        // tatara-process); `macro_def_from` must recognize it
        // identically to `defmacro` so the `(defpoint-template …)`
        // form's macro-style binding works the same way.
        assert_eq!(
            MacroDefHead::from_keyword("defpoint-template"),
            Some(MacroDefHead::DefpointTemplate)
        );
    }

    #[test]
    fn macro_def_head_from_keyword_recognizes_defcheck() {
        // Pins that `MacroDefHead::from_keyword("defcheck")` returns
        // `Some(MacroDefHead::Defcheck)` — the third and final
        // canonical head keyword. The `defcheck` form is the
        // workspace-coherence authoring surface (see
        // tatara-reconciler/checks.lisp); `macro_def_from` must
        // recognize it identically to `defmacro` so user-defined
        // checks inherit the macro-style binding semantics.
        assert_eq!(
            MacroDefHead::from_keyword("defcheck"),
            Some(MacroDefHead::Defcheck)
        );
    }

    #[test]
    fn macro_def_head_from_keyword_rejects_unknown() {
        // Pins that `MacroDefHead::from_keyword` returns `None` for
        // anything outside the closed set — a non-symbol keyword
        // (`"if"`), a near-miss spelling (`"defmacroo"`,
        // `"defcheckk"`), and the empty string. `macro_def_from`
        // depends on this `None` projection to mean "this form is
        // not a defmacro form" and walk past — a regression that
        // accidentally accepts a near-miss head (e.g. via a
        // lower-cased `EqualFold` match) would route `(defmacroo …)`
        // through the arity gate, which is wrong. Pins all four
        // canonical near-miss / non-canonical inputs.
        assert_eq!(MacroDefHead::from_keyword("if"), None);
        assert_eq!(MacroDefHead::from_keyword("defmacroo"), None);
        assert_eq!(MacroDefHead::from_keyword("defcheckk"), None);
        assert_eq!(MacroDefHead::from_keyword(""), None);
    }

    #[test]
    fn macro_def_head_keyword_round_trips_each_variant() {
        // Pins that `MacroDefHead::keyword` returns the canonical
        // `&'static str` literal for each variant. Together with
        // `from_keyword` this closes the bidirectional projection:
        // for every canonical head keyword `s`, `MacroDefHead::
        // from_keyword(s).unwrap().keyword() == s`. The `&'static
        // str` lifetime on the return type is load-bearing — it's
        // what lets the `LispError::Defmacro*` variants carry
        // `head: &'static str` slots without an arbitrary owned
        // `String`. Pinning the `: &'static str` binding here
        // makes the lifetime requirement load-bearing in the test.
        let s_defmacro: &'static str = MacroDefHead::Defmacro.keyword();
        let s_defpoint: &'static str = MacroDefHead::DefpointTemplate.keyword();
        let s_defcheck: &'static str = MacroDefHead::Defcheck.keyword();
        assert_eq!(s_defmacro, "defmacro");
        assert_eq!(s_defpoint, "defpoint-template");
        assert_eq!(s_defcheck, "defcheck");
    }

    #[test]
    fn macro_def_head_keyword_round_trips_through_from_keyword() {
        // Pins that the two halves of the projection compose to the
        // identity on the closed set: for every canonical head
        // keyword, projecting `&str → MacroDefHead → &'static str`
        // returns the original literal. Sibling of
        // `macro_def_head_keyword_round_trips_each_variant` —
        // together they pin both directions of the bidirection.
        for kw in ["defmacro", "defpoint-template", "defcheck"] {
            let head = MacroDefHead::from_keyword(kw).expect("canonical keyword must project");
            assert_eq!(head.keyword(), kw);
        }
    }

    #[test]
    fn macro_def_head_threads_through_defmacro_arity_helper() {
        // Pins that `defmacro_arity` accepts a typed `MacroDefHead`
        // and threads it through to the variant's typed `head` slot
        // unchanged — no `&str` projection at the helper boundary
        // (the projection through `MacroDefHead::keyword()` happens at
        // Display rendering time inside the `#[error(...)]`
        // annotation). A regression that drops the `MacroDefHead`
        // parameter type (e.g. by reverting to `head: &str`) breaks
        // compilation here. Pinning each of the three variants gives
        // the typed-head threading the same path-uniformity edge the
        // existing `defmacro_arity_in_*_emits_same_variant` tests pin
        // for the call-site path through `macro_def_from`.
        for head in [
            MacroDefHead::Defmacro,
            MacroDefHead::DefpointTemplate,
            MacroDefHead::Defcheck,
        ] {
            let err = defmacro_arity(head, 2);
            match err {
                LispError::DefmacroArity { head: h, arity: 2 } => assert_eq!(h, head),
                other => panic!("expected DefmacroArity, got: {other:?}"),
            }
        }
    }

    #[test]
    fn macro_def_head_threads_through_defmacro_non_symbol_name_helper() {
        // Sibling of the `defmacro_arity` threading test — pins that
        // `defmacro_non_symbol_name` accepts a typed `MacroDefHead`
        // and threads it through to the variant's typed `head` slot
        // unchanged. The `got: &Sexp` parameter rides through
        // `crate::domain::sexp_witness` into the variant's typed
        // `got: SexpWitness` slot so BOTH the structural shape AND
        // the rendered literal are preserved across the helper
        // boundary, parallel to how `non_symbol_param` and
        // `non_symbol_unquote_target` project their `&Sexp` arguments
        // through the same typed joint primitive.
        let got = parse("5");
        for head in [
            MacroDefHead::Defmacro,
            MacroDefHead::DefpointTemplate,
            MacroDefHead::Defcheck,
        ] {
            let err = defmacro_non_symbol_name(head, &got);
            match err {
                LispError::DefmacroNonSymbolName { head: h, got: g } => {
                    assert_eq!(h, head);
                    assert_eq!(g.shape, crate::error::SexpShape::Int);
                    assert_eq!(g.display, "5");
                }
                other => panic!("expected DefmacroNonSymbolName, got: {other:?}"),
            }
        }
    }

    #[test]
    fn macro_def_head_threads_through_defmacro_non_list_params_helper() {
        // Sibling of the `defmacro_arity` and
        // `defmacro_non_symbol_name` threading tests — pins that
        // `defmacro_non_list_params` accepts a typed `MacroDefHead`
        // and threads it through to the variant's typed `head` slot
        // unchanged. Together the three threading tests close the
        // typed-enum lift across all three error helpers — every
        // call site that constructs a `LispError::Defmacro*` variant
        // takes its `head` from a `MacroDefHead`, never from a `&str`
        // match. The `got: &Sexp` parameter rides through
        // `crate::domain::sexp_witness` into the variant's typed
        // `got: SexpWitness` slot so BOTH the structural shape AND
        // the rendered literal are preserved across the helper
        // boundary, parallel to how `defmacro_non_symbol_name`,
        // `non_symbol_param`, and `non_symbol_unquote_target` project
        // their `&Sexp` arguments through the same typed joint
        // primitive.
        let got = parse("x");
        for head in [
            MacroDefHead::Defmacro,
            MacroDefHead::DefpointTemplate,
            MacroDefHead::Defcheck,
        ] {
            let err = defmacro_non_list_params(head, &got);
            match err {
                LispError::DefmacroNonListParams { head: h, got: g } => {
                    assert_eq!(h, head);
                    assert_eq!(g.shape, crate::error::SexpShape::Symbol);
                    assert_eq!(g.display, "x");
                }
                other => panic!("expected DefmacroNonListParams, got: {other:?}"),
            }
        }
    }

    /// Helper for the defmacro-arity tests — pins the variant shape and
    /// carries the head / arity up to the assert site for legibility.
    /// Sibling of `non_symbol_param_fields` and
    /// `rest_param_missing_name_fields`.
    fn defmacro_arity_fields(err: &LispError) -> (MacroDefHead, usize) {
        match err {
            LispError::DefmacroArity { head, arity } => (*head, *arity),
            other => panic!("expected DefmacroArity, got: {other:?}"),
        }
    }

    #[test]
    fn defmacro_arity_with_head_only_emits_structural_variant() {
        // `(defmacro)` — only the head, no name / params / body. Pins
        // variant identity AND that `arity == 1` (just the head
        // element) AND that `head == "defmacro"`. A regression that
        // re-inlines the legacy `LispError::Compile` shape (which
        // named neither field) fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro)").unwrap())
            .expect_err("defmacro arity gate must error");
        let (head, arity) = defmacro_arity_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(arity, 1);
    }

    #[test]
    fn defmacro_arity_with_head_and_name_emits_structural_variant() {
        // `(defmacro f)` — head + name, missing params + body. Pins
        // that `arity` advances with the actual form length (2 for
        // this case) so an LSP quick-fix that wants to surface "you
        // wrote 2 elements; need 4" gains the count as data, no
        // source re-parse required.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f)").unwrap())
            .expect_err("defmacro arity gate must error");
        let (head, arity) = defmacro_arity_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(arity, 2);
    }

    #[test]
    fn defmacro_arity_with_head_name_params_emits_structural_variant() {
        // `(defmacro f ())` — head + name + params, missing body
        // (the most-complete partial defmacro that still trips the
        // arity gate). Pins that `arity == 3` exactly so an LSP
        // quick-fix that wants to surface "your defmacro is one
        // element short — body is missing" gains the count as data.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f ())").unwrap())
            .expect_err("defmacro arity gate must error");
        let (head, arity) = defmacro_arity_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(arity, 3);
    }

    #[test]
    fn defmacro_arity_in_defpoint_template_emits_same_variant() {
        // `defpoint-template` shares `macro_def_from` with `defmacro`
        // (all three head keywords route through the same gate). Pins
        // that the lift fires path-uniformly across the three head
        // keywords AND that the variant's `head` slot carries the
        // actual head literal — `defpoint-template`, not `defmacro`
        // — so an LSP that wants to point at "your defpoint-template
        // form is missing elements" gains the head as data.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defpoint-template t)").unwrap())
            .expect_err("defpoint-template arity gate must error");
        let (head, arity) = defmacro_arity_fields(&err);
        assert_eq!(head, MacroDefHead::DefpointTemplate);
        assert_eq!(arity, 2);
    }

    #[test]
    fn defmacro_arity_in_defcheck_emits_same_variant() {
        // Sibling of the defpoint-template test — `defcheck` is the
        // third head keyword `macro_def_from` recognizes. All three
        // route through the same arity gate and now reject too-short
        // forms with the same structural variant.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defcheck)").unwrap())
            .expect_err("defcheck arity gate must error");
        let (head, arity) = defmacro_arity_fields(&err);
        assert_eq!(head, MacroDefHead::Defcheck);
        assert_eq!(arity, 1);
    }

    #[test]
    fn defmacro_arity_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME
        // structural variant under both expansion strategies. The
        // arity gate fires inside `macro_def_from` BEFORE either
        // strategy's expansion path runs; so both `Expander::new()`
        // (bytecode) and `Expander::new_substitute_only()`
        // (substitute) reject the SAME malformed defmacro at the
        // SAME gate. Sibling of
        // `non_symbol_param_substitute_and_bytecode_paths_agree` and
        // `rest_param_missing_name_substitute_and_bytecode_paths_agree`.
        let src = "(defmacro f)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(
            defmacro_arity_fields(&err_subst),
            (MacroDefHead::Defmacro, 2)
        );
        assert_eq!(
            defmacro_arity_fields(&err_byte),
            (MacroDefHead::Defmacro, 2)
        );
    }

    #[test]
    fn defmacro_arity_message_renders_legacy_substring_with_arity() {
        // End-to-end through Display — pins the rendered diagnostic
        // consumers see today (REPL, `tatara-check`) AND the new
        // `(got {arity} elements, need 4)` clause. The legacy
        // `"(defmacro name (params) body) required"` substring
        // rides through verbatim. Tools that pattern-match on the
        // variant gain structural binding to `head` / `arity`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f)").unwrap())
            .expect_err("defmacro arity gate must error");
        assert_eq!(
            format!("{err}"),
            "compile error in defmacro: (defmacro name (params) body) required \
             (got 2 elements, need 4)"
        );
    }

    #[test]
    fn defmacro_arity_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp`
        // carries source positions, `position()` on `LispError`
        // returns `None` for this variant. A future run that gives
        // `Sexp` source spans adds `pos: Option<usize>` to ONE place;
        // this test gives that change a deliberate fail-before/pass-
        // after delta. Parallel to
        // `non_symbol_param_position_is_none_today` and
        // `rest_param_missing_name_position_is_none_today`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro)").unwrap())
            .expect_err("defmacro arity gate must error");
        assert_eq!(err.position(), None);
    }

    #[test]
    fn defmacro_arity_does_not_fire_for_well_formed_arity_4_defmacro() {
        // Negative control: a defmacro with exactly 4 elements (head
        // + name + params + body) passes the arity gate. Pins that
        // the lift is scoped to the arity-deficient case, not to
        // every defmacro form. After this test, a regression that
        // tightens the arity gate to >= 5 (e.g. spuriously requiring
        // a docstring slot) fails-loudly here.
        let mut e = Expander::new();
        let out = e
            .expand_program(read("(defmacro id (x) `,x) (id 42)").unwrap())
            .expect("well-formed defmacro must succeed");
        assert_eq!(out[0], Sexp::int(42));
    }

    /// Helper for the defmacro-non-symbol-name tests — pins variant
    /// shape and carries the head / got up to the assert site for
    /// legibility. Sibling of `defmacro_arity_fields`,
    /// `non_symbol_param_fields`, and `rest_param_missing_name_fields`.
    fn defmacro_non_symbol_name_fields(err: &LispError) -> (MacroDefHead, &str) {
        match err {
            LispError::DefmacroNonSymbolName { head, got } => (*head, got.display.as_str()),
            other => panic!("expected DefmacroNonSymbolName, got: {other:?}"),
        }
    }

    #[test]
    fn defmacro_non_symbol_name_with_int_emits_structural_variant() {
        // `(defmacro 5 () body)` — the form passes the arity gate
        // (4 elements) but list[1] is `5`, not a symbol. Pins variant
        // identity AND that `head == "defmacro"` AND that `got ==
        // "5"`. A regression that re-inlines the legacy
        // `LispError::Compile { form: "defmacro", message: "expected
        // name symbol" }` shape (which named the failure mode but
        // not the offending element) fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro 5 () body)").unwrap())
            .expect_err("defmacro non-symbol name gate must error");
        let (head, got) = defmacro_non_symbol_name_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, "5");
    }

    #[test]
    fn defmacro_non_symbol_name_with_keyword_emits_structural_variant() {
        // `(defmacro :foo () body)` — list[1] is the keyword `:foo`,
        // not a symbol. Pins that `Sexp::Display` for
        // `Atom::Keyword(s)` writes `:s` and the variant's `got` slot
        // carries the keyword form unchanged. An LSP that wants to
        // surface "you wrote `:foo` where a name symbol was expected"
        // gains the literal keyword value as data, no source re-parse
        // required.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro :foo () body)").unwrap())
            .expect_err("defmacro non-symbol name gate must error");
        let (head, got) = defmacro_non_symbol_name_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, ":foo");
    }

    #[test]
    fn defmacro_non_symbol_name_with_string_emits_structural_variant() {
        // `(defmacro "name" () body)` — list[1] is the string
        // literal `"name"`, not a symbol. Pins that `Sexp::Display`
        // for `Atom::String(s)` writes `"s"` (with quotes) and the
        // variant's `got` slot carries the quoted form unchanged.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro \"name\" () body)").unwrap())
            .expect_err("defmacro non-symbol name gate must error");
        let (head, got) = defmacro_non_symbol_name_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, "\"name\"");
    }

    #[test]
    fn defmacro_non_symbol_name_with_nested_list_emits_structural_variant() {
        // `(defmacro (nested) () body)` — list[1] is a nested list,
        // not a symbol. Pins that `Sexp::Display` for a list writes
        // `(elements)` and the variant's `got` slot carries the
        // parenthesized form unchanged.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro (nested) () body)").unwrap())
            .expect_err("defmacro non-symbol name gate must error");
        let (head, got) = defmacro_non_symbol_name_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, "(nested)");
    }

    #[test]
    fn defmacro_non_symbol_name_in_defpoint_template_emits_same_variant() {
        // `defpoint-template` shares `macro_def_from` with `defmacro`
        // (all three head keywords route through the same gate).
        // Pins that the lift fires path-uniformly across the three
        // head keywords AND that the variant's `head` slot carries
        // the actual head literal — `defpoint-template`, not
        // `defmacro` — so an LSP that wants to point at "your
        // defpoint-template form's name slot isn't a symbol" gains
        // the head as data.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defpoint-template 7 () body)").unwrap())
            .expect_err("defpoint-template non-symbol name gate must error");
        let (head, got) = defmacro_non_symbol_name_fields(&err);
        assert_eq!(head, MacroDefHead::DefpointTemplate);
        assert_eq!(got, "7");
    }

    #[test]
    fn defmacro_non_symbol_name_in_defcheck_emits_same_variant() {
        // Sibling for the `defcheck` head — third head keyword
        // `macro_def_from` recognizes. Rounds out the three-head-
        // keyword coverage so the lift is path-uniform across
        // `defmacro` / `defpoint-template` / `defcheck`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defcheck :k () body)").unwrap())
            .expect_err("defcheck non-symbol name gate must error");
        let (head, got) = defmacro_non_symbol_name_fields(&err);
        assert_eq!(head, MacroDefHead::Defcheck);
        assert_eq!(got, ":k");
    }

    #[test]
    fn defmacro_non_symbol_name_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME
        // structural variant under both expansion strategies. The
        // name-symbol gate fires inside `macro_def_from` BEFORE
        // either expansion strategy runs, so the gate is naturally
        // path-uniform; pinning it gives a regression that drifts
        // either strategy's handling of non-symbol-name defmacros (or
        // makes one strategy accept what the other rejects) a fail-
        // before/pass-after edge. Sibling of
        // `defmacro_arity_substitute_and_bytecode_paths_agree`,
        // `non_symbol_param_substitute_and_bytecode_paths_agree`, and
        // `rest_param_missing_name_substitute_and_bytecode_paths_agree`.
        let src = "(defmacro 5 () body)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(
            defmacro_non_symbol_name_fields(&err_subst),
            (MacroDefHead::Defmacro, "5")
        );
        assert_eq!(
            defmacro_non_symbol_name_fields(&err_byte),
            (MacroDefHead::Defmacro, "5")
        );
    }

    #[test]
    fn defmacro_non_symbol_name_message_renders_legacy_substring_with_got() {
        // End-to-end through Display — pins the rendered diagnostic
        // consumers see today (REPL, `tatara-check`) AND the new
        // `, got {got}` clause. The legacy `"expected name symbol"`
        // substring rides through verbatim; the prefix matches the
        // legacy `Compile { form: "defmacro", message: "expected name
        // symbol" }` byte-for-byte. Tools that pattern-match on the
        // variant gain structural binding to `head` / `got`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro 5 () body)").unwrap())
            .expect_err("defmacro non-symbol name gate must error");
        assert_eq!(
            format!("{err}"),
            "compile error in defmacro: expected name symbol, got 5"
        );
    }

    #[test]
    fn defmacro_non_symbol_name_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp`
        // carries source positions, `position()` on `LispError`
        // returns `None` for this variant. A future run that gives
        // `Sexp` source spans adds `pos: Option<usize>` to ONE place;
        // this test gives that change a deliberate fail-before/pass-
        // after delta. Parallel to
        // `defmacro_arity_position_is_none_today`,
        // `non_symbol_param_position_is_none_today`, and
        // `rest_param_missing_name_position_is_none_today`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro 5 () body)").unwrap())
            .expect_err("defmacro non-symbol name gate must error");
        assert_eq!(err.position(), None);
    }

    #[test]
    fn defmacro_non_symbol_name_does_not_fire_for_well_formed_defmacro() {
        // Negative control: a defmacro whose name slot IS a symbol
        // passes the name-symbol gate. Pins that the lift is scoped
        // to the non-symbol-name case, not to every defmacro form.
        // After this test, a regression that tightens the gate to
        // reject e.g. kebab-cased names fails-loudly here.
        let mut e = Expander::new();
        let out = e
            .expand_program(read("(defmacro id (x) `,x) (id 42)").unwrap())
            .expect("well-formed defmacro must succeed");
        assert_eq!(out[0], Sexp::int(42));
    }

    #[test]
    fn defmacro_non_symbol_name_fires_after_arity_gate_passes() {
        // Pins the gate ordering: a 4-element defmacro whose name
        // slot is non-symbol fires `DefmacroNonSymbolName`, NOT
        // `DefmacroArity`. The arity gate (>= 4 elements) admits
        // this form; the name-symbol gate is the next checkpoint.
        // A regression that swaps the gate ordering (e.g. checks
        // name-symbol before arity, so `(defmacro 5)` would emit
        // `DefmacroNonSymbolName` instead of `DefmacroArity`) fails-
        // loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro 5 () body)").unwrap())
            .expect_err("name-symbol gate must error");
        assert!(
            matches!(err, LispError::DefmacroNonSymbolName { .. }),
            "expected DefmacroNonSymbolName, got: {err:?}"
        );

        let err_arity = e
            .expand_program(read("(defmacro 5)").unwrap())
            .expect_err("arity gate must error");
        assert!(
            matches!(err_arity, LispError::DefmacroArity { .. }),
            "expected DefmacroArity (arity < 4 short-circuits before name check), \
             got: {err_arity:?}"
        );
    }

    /// Helper for the defmacro-non-list-params tests — pins variant
    /// shape and carries the head / got up to the assert site for
    /// legibility. Sibling of `defmacro_arity_fields`,
    /// `defmacro_non_symbol_name_fields`, `non_symbol_param_fields`,
    /// and `rest_param_missing_name_fields`.
    fn defmacro_non_list_params_fields(err: &LispError) -> (MacroDefHead, &str) {
        match err {
            LispError::DefmacroNonListParams { head, got } => (*head, got.display.as_str()),
            other => panic!("expected DefmacroNonListParams, got: {other:?}"),
        }
    }

    #[test]
    fn defmacro_non_list_params_with_symbol_emits_structural_variant() {
        // `(defmacro f x body)` — the form passes both the arity gate
        // (4 elements) AND the name-symbol gate (`f` is a symbol) but
        // list[2] is the symbol `x`, not a list. Pins variant identity
        // AND that `head == "defmacro"` AND that `got == "x"`. A
        // regression that re-inlines the legacy `LispError::Compile {
        // form: "defmacro", message: "expected param list" }` shape
        // (which named the failure mode but not the offending element)
        // fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f x body)").unwrap())
            .expect_err("defmacro non-list params gate must error");
        let (head, got) = defmacro_non_list_params_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, "x");
    }

    #[test]
    fn defmacro_non_list_params_with_int_emits_structural_variant() {
        // `(defmacro f 5 body)` — list[2] is `5`, not a list. Pins
        // that `Sexp::Display` for `Atom::Int(n)` writes `n` and the
        // variant's `got` slot carries the integer form unchanged. An
        // LSP that surfaces "you wrote `5` where a param list was
        // expected" gains the literal value as data, no source
        // re-parse required.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f 5 body)").unwrap())
            .expect_err("defmacro non-list params gate must error");
        let (head, got) = defmacro_non_list_params_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, "5");
    }

    #[test]
    fn defmacro_non_list_params_with_keyword_emits_structural_variant() {
        // `(defmacro f :foo body)` — list[2] is the keyword `:foo`,
        // not a list. Pins that `Sexp::Display` for `Atom::Keyword(s)`
        // writes `:s` and the variant's `got` slot carries the
        // keyword form unchanged.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f :foo body)").unwrap())
            .expect_err("defmacro non-list params gate must error");
        let (head, got) = defmacro_non_list_params_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, ":foo");
    }

    #[test]
    fn defmacro_non_list_params_with_string_emits_structural_variant() {
        // `(defmacro f "params" body)` — list[2] is the string literal
        // `"params"`, not a list. Pins that `Sexp::Display` for
        // `Atom::String(s)` writes `"s"` (with quotes) and the
        // variant's `got` slot carries the quoted form unchanged.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f \"params\" body)").unwrap())
            .expect_err("defmacro non-list params gate must error");
        let (head, got) = defmacro_non_list_params_fields(&err);
        assert_eq!(head, MacroDefHead::Defmacro);
        assert_eq!(got, "\"params\"");
    }

    #[test]
    fn defmacro_non_list_params_in_defpoint_template_emits_same_variant() {
        // `defpoint-template` shares `macro_def_from` with `defmacro`
        // (all three head keywords route through the same gate).
        // Pins that the lift fires path-uniformly across the three
        // head keywords AND that the variant's `head` slot carries
        // the actual head literal — `defpoint-template`, not
        // `defmacro` — so an LSP that wants to point at "your
        // defpoint-template form's param-list slot isn't a list"
        // gains the head as data.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defpoint-template t x body)").unwrap())
            .expect_err("defpoint-template non-list params gate must error");
        let (head, got) = defmacro_non_list_params_fields(&err);
        assert_eq!(head, MacroDefHead::DefpointTemplate);
        assert_eq!(got, "x");
    }

    #[test]
    fn defmacro_non_list_params_in_defcheck_emits_same_variant() {
        // Sibling for the `defcheck` head — third head keyword
        // `macro_def_from` recognizes. Rounds out the three-head-
        // keyword coverage so the lift is path-uniform across
        // `defmacro` / `defpoint-template` / `defcheck`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defcheck c 7 body)").unwrap())
            .expect_err("defcheck non-list params gate must error");
        let (head, got) = defmacro_non_list_params_fields(&err);
        assert_eq!(head, MacroDefHead::Defcheck);
        assert_eq!(got, "7");
    }

    #[test]
    fn defmacro_non_list_params_substitute_and_bytecode_paths_agree() {
        // Path-uniform rejection: the SAME source emits the SAME
        // structural variant under both expansion strategies. The
        // param-list gate fires inside `macro_def_from` BEFORE either
        // expansion strategy runs, so the gate is naturally path-
        // uniform; pinning it gives a regression that drifts either
        // strategy's handling of non-list-params defmacros (or makes
        // one strategy accept what the other rejects) a fail-before/
        // pass-after edge. Sibling of
        // `defmacro_arity_substitute_and_bytecode_paths_agree`,
        // `defmacro_non_symbol_name_substitute_and_bytecode_paths_agree`,
        // `non_symbol_param_substitute_and_bytecode_paths_agree`, and
        // `rest_param_missing_name_substitute_and_bytecode_paths_agree`.
        let src = "(defmacro f x body)";
        let mut subst = Expander::new_substitute_only();
        let mut bytecode = Expander::new();
        let err_subst = subst
            .expand_program(read(src).unwrap())
            .expect_err("substitute must error");
        let err_byte = bytecode
            .expand_program(read(src).unwrap())
            .expect_err("bytecode must error");
        assert_eq!(
            defmacro_non_list_params_fields(&err_subst),
            (MacroDefHead::Defmacro, "x")
        );
        assert_eq!(
            defmacro_non_list_params_fields(&err_byte),
            (MacroDefHead::Defmacro, "x")
        );
    }

    #[test]
    fn defmacro_non_list_params_message_renders_legacy_substring_with_got() {
        // End-to-end through Display — pins the rendered diagnostic
        // consumers see today (REPL, `tatara-check`) AND the new
        // `, got {got}` clause. The legacy `"expected param list"`
        // substring rides through verbatim; the prefix matches the
        // legacy `Compile { form: "defmacro", message: "expected
        // param list" }` byte-for-byte. Tools that pattern-match on
        // the variant gain structural binding to `head` / `got`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f x body)").unwrap())
            .expect_err("defmacro non-list params gate must error");
        assert_eq!(
            format!("{err}"),
            "compile error in defmacro: expected param list, got x"
        );
    }

    #[test]
    fn defmacro_non_list_params_position_is_none_today() {
        // Negative control for the future-spans move: until `Sexp`
        // carries source positions, `position()` on `LispError`
        // returns `None` for this variant. A future run that gives
        // `Sexp` source spans adds `pos: Option<usize>` to ONE place;
        // this test gives that change a deliberate fail-before/pass-
        // after delta. Parallel to
        // `defmacro_arity_position_is_none_today`,
        // `defmacro_non_symbol_name_position_is_none_today`,
        // `non_symbol_param_position_is_none_today`, and
        // `rest_param_missing_name_position_is_none_today`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f x body)").unwrap())
            .expect_err("defmacro non-list params gate must error");
        assert_eq!(err.position(), None);
    }

    #[test]
    fn defmacro_non_list_params_does_not_fire_for_well_formed_defmacro() {
        // Negative control: a defmacro whose param-list slot IS a
        // list passes the param-list gate. Pins that the lift is
        // scoped to the non-list-params case, not to every defmacro
        // form. After this test, a regression that tightens the gate
        // to reject e.g. empty param lists fails-loudly here.
        let mut e = Expander::new();
        let out = e
            .expand_program(read("(defmacro id (x) `,x) (id 42)").unwrap())
            .expect("well-formed defmacro must succeed");
        assert_eq!(out[0], Sexp::int(42));
    }

    #[test]
    fn defmacro_non_list_params_fires_after_name_symbol_gate_passes() {
        // Pins the gate ordering: a 4-element defmacro whose name
        // slot IS a symbol but whose param-list slot is non-list
        // fires `DefmacroNonListParams`, NOT `DefmacroNonSymbolName`.
        // The name-symbol gate admits this form; the param-list gate
        // is the next checkpoint. A regression that swaps the gate
        // ordering (e.g. checks param-list before name-symbol, so
        // `(defmacro 5 x body)` would emit `DefmacroNonListParams`
        // instead of `DefmacroNonSymbolName`) fails-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f x body)").unwrap())
            .expect_err("param-list gate must error");
        assert!(
            matches!(err, LispError::DefmacroNonListParams { .. }),
            "expected DefmacroNonListParams, got: {err:?}"
        );

        let err_name = e
            .expand_program(read("(defmacro 5 x body)").unwrap())
            .expect_err("name-symbol gate must error");
        assert!(
            matches!(err_name, LispError::DefmacroNonSymbolName { .. }),
            "expected DefmacroNonSymbolName (name-symbol gate short-circuits before param-list check), \
             got: {err_name:?}"
        );
    }

    #[test]
    fn defmacro_non_list_params_fires_after_arity_gate_passes() {
        // Pins the full gate ordering: a 4-element defmacro whose
        // first three slots are head/symbol/non-list fires
        // `DefmacroNonListParams`, NOT `DefmacroArity`. The arity
        // gate (>= 4 elements) admits this form; the name-symbol
        // gate admits the symbol; the param-list gate is the third
        // checkpoint. A regression that drifts the gate sequence
        // (e.g. fires `DefmacroArity` for a 4-element form) fails-
        // loudly here. Parallel to
        // `defmacro_non_symbol_name_fires_after_arity_gate_passes`
        // — together they pin the full
        // arity → name-symbol → param-list ordering inside
        // `macro_def_from`.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro f x body)").unwrap())
            .expect_err("param-list gate must error");
        assert!(
            matches!(err, LispError::DefmacroNonListParams { .. }),
            "expected DefmacroNonListParams, got: {err:?}"
        );

        let err_arity = e
            .expand_program(read("(defmacro f x)").unwrap())
            .expect_err("arity gate must error");
        assert!(
            matches!(err_arity, LispError::DefmacroArity { .. }),
            "expected DefmacroArity (arity < 4 short-circuits before param-list check), \
             got: {err_arity:?}"
        );
    }

    #[test]
    fn rest_marker_at_param_list_position_is_not_non_symbol_param() {
        // Negative control: `&rest` is a symbol (`Atom::Symbol("&rest")`)
        // at the parser level, so `as_symbol()` succeeds for it. The
        // `NonSymbolParam` variant does NOT fire on the `&rest` marker
        // itself; the dedicated `&rest needs a name` rejection (a
        // separate failure mode in this cluster) handles malformed
        // rest-param shapes. Pins that the lift is scoped to
        // non-symbol elements at param-list positions, not to
        // every malformed-param shape.
        let mut e = Expander::new();
        let out = e
            .expand_program(read("(defmacro f (a &rest xs) `(list ,a ,@xs)) (f 1 2 3)").unwrap())
            .expect("&rest with name must succeed");
        assert_eq!(out[0], parse("(list 1 2 3)"));
    }

    #[test]
    fn non_symbol_unquote_target_message_renders_canonical_type_mismatch_shape() {
        // End-to-end through the Display impl — pins the rendered diagnostic
        // a downstream tool sees today (REPL, tatara-check). The shape is
        // parallel to the existing `TypeMismatch` variant: form, expected
        // shape, offending literal — all three slots present.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro w (x) `,(list 1 2)) (w 1)").unwrap())
            .expect_err("non-symbol target must error");
        assert_eq!(
            format!("{err}"),
            "compile error in ,: expected symbol, got (list 1 2)"
        );
    }

    // ── template_invariant_violation: structural lift ───────────────
    //
    // The four byte-identical inline `LispError::Compile { form:
    // macro_name.into(), message: <invariant> }` triples in `apply_compiled`
    // (Subst-bad-index, Splice-bad-index, EndList-empty-stack,
    // final-no-value gates) were lifted to `template_invariant_violation`,
    // and the helper's emission was promoted from `LispError::Compile`-
    // shape to the structural `LispError::TemplateInvariant { macro_name,
    // kind: TemplateInvariantKind }` variant. The index payload of the
    // Subst / Splice gates lives INSIDE the variant (`SubstBadIndex(usize)`
    // / `SpliceBadIndex(usize)`), so the invalid combination "stack-gate
    // kind with an op-index" (e.g. `EndListEmptyStack` carrying a `usize`)
    // is structurally unrepresentable. Display matches the legacy
    // `Compile`-shaped diagnostic byte-for-byte via the closed-set
    // `TemplateInvariantKind::message()` projection so authoring-tool
    // substring greps see no drift across the lift.
    //
    // The tests below pin: (a) the helper produces the structural
    // `LispError::TemplateInvariant` variant with `macro_name` and `kind`
    // first-class; (b) the Subst / Splice gates thread the bad index
    // through the typed variants `SubstBadIndex(usize)` / `SpliceBadIndex(usize)`
    // unchanged; (c) the two REACHABLE invariant-violation paths through
    // `apply_compiled` — Subst with out-of-bounds idx, Splice with
    // out-of-bounds idx — route through the helper end-to-end (the
    // EndList / no-value paths are guarded by `last_mut().unwrap()`
    // ahead of `pop().ok_or_else()` and are not reachable through any
    // single CompiledTemplate; they remain defensive against future
    // changes to the stack discipline); (d) the legacy Display
    // rendering matches byte-for-byte across the lift; (e) positive
    // controls: a well-formed CompiledTemplate routes PAST the helper
    // cleanly, and unrelated macro errors (missing-required-arg) do
    // NOT route through the helper.

    #[test]
    fn template_invariant_violation_emits_structural_variant_with_macro_name_and_kind() {
        // Direct unit test of the helper: a fixed macro_name and a
        // `TemplateInvariantKind` produce a `LispError::TemplateInvariant`
        // variant with the macro_name in the `macro_name` slot and the
        // kind passed through verbatim in the `kind` slot. A regression
        // that drifts the variant (e.g., back to `LispError::Compile`)
        // or swaps the slot positions fails-loudly here.
        let err = template_invariant_violation("test-macro", TemplateInvariantKind::FinalNoValue);
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "test-macro");
                assert_eq!(kind, TemplateInvariantKind::FinalNoValue);
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn template_invariant_violation_threads_subst_idx_through_typed_variant() {
        // The Subst gate's `usize` idx lives INSIDE the
        // `TemplateInvariantKind::SubstBadIndex(usize)` variant rather
        // than being substring-rendered into a free-form `message`
        // slot. Pin that the helper threads the bad index through the
        // typed variant unchanged; a regression that drops the index
        // payload (e.g., via a `usize -> ()` projection) fails here.
        let err = template_invariant_violation("wrap", TemplateInvariantKind::SubstBadIndex(7));
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "wrap");
                assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(7));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn apply_compiled_subst_bad_idx_routes_through_template_invariant_violation() {
        // Hand-crafted CompiledTemplate with a Subst(99) op against
        // an empty params list: `args_by_index` has length 0, so
        // `.get(99)` returns None and the `ok_or_else` triggers
        // through the helper. Fail-before-pass-after: this same input
        // pre-lift went through `LispError::Compile { form: macro_name,
        // message: format!("compiled template referenced bad param
        // index {idx}") }`; post-lift it routes through
        // `template_invariant_violation` and emits the structural
        // `TemplateInvariant { macro_name, kind: SubstBadIndex(99) }`
        // variant with the bad index threaded through as typed data.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Subst(99)],
        };
        let err = apply_compiled("test-macro", &MacroParams::default(), &tmpl, &[])
            .expect_err("bad idx must error");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "test-macro");
                assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(99));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn apply_compiled_splice_bad_idx_routes_through_template_invariant_violation() {
        // Hand-crafted CompiledTemplate with a Splice(42) op against
        // an empty params list. Sibling of the Subst-bad-idx test;
        // pins the Splice gate routes through the helper with the
        // typed `SpliceBadIndex(42)` kind carrying the bad index.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Splice(42)],
        };
        let err = apply_compiled("call-macro", &MacroParams::default(), &tmpl, &[])
            .expect_err("bad splice idx must error");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "call-macro");
                assert_eq!(kind, TemplateInvariantKind::SpliceBadIndex(42));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn apply_compiled_subst_bad_idx_renders_legacy_compile_shape() {
        // End-to-end through the `LispError` Display impl — pins the
        // rendered diagnostic byte-for-byte: `"compile error in
        // test-macro: compiled template referenced bad param index 99"`.
        // Authoring tools that substring-grep the rendered diagnostic
        // (`tatara-check`'s diagnostic capture, REPL substring-greps)
        // see no drift across the lift. Parallel to how
        // `compile_named_non_symbol_name_renders_legacy_compile_shape`
        // pins the sibling-file (compile.rs) lift's Display contract.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Subst(99)],
        };
        let err = apply_compiled("test-macro", &MacroParams::default(), &tmpl, &[])
            .expect_err("bad idx must error");
        assert_eq!(
            format!("{err}"),
            "compile error in test-macro: compiled template referenced bad param index 99"
        );
    }

    #[test]
    fn apply_compiled_splice_bad_idx_renders_legacy_compile_shape() {
        // Sibling Display test for the Splice gate. Pins the message
        // byte-for-byte through the `LispError` Display impl: `"compile
        // error in call-macro: compiled template referenced bad splice
        // index 42"`.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Splice(42)],
        };
        let err = apply_compiled("call-macro", &MacroParams::default(), &tmpl, &[])
            .expect_err("bad splice idx must error");
        assert_eq!(
            format!("{err}"),
            "compile error in call-macro: compiled template referenced bad splice index 42"
        );
    }

    #[test]
    fn apply_compiled_well_formed_template_routes_past_template_invariant_violation() {
        // Positive control: a CompiledTemplate produced by the
        // bytecode compiler (`compile_template`) for a well-formed
        // macro never references an out-of-bounds index nor
        // unbalances the stack, so `apply_compiled` routes PAST the
        // helper cleanly. A regression that fires the helper on
        // well-formed bytecode (e.g., off-by-one in the index
        // resolution) would fail here. End-to-end through the public
        // `Expander` surface so the test exercises the same code
        // path users see.
        let mut e = Expander::new();
        let out = e
            .expand_program(read("(defmacro id (x) `,x) (id 42)").unwrap())
            .expect("well-formed macro expansion must not fire template-invariant-violation");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], Sexp::int(42));
    }

    #[test]
    fn apply_compiled_missing_required_arg_does_not_route_through_template_invariant_violation() {
        // Negative control: the `missing_macro_arg` gate in the shared
        // positional binder (`MacroParams::bind`) fires BEFORE the bytecode
        // loop runs,
        // so a missing required arg routes through
        // `LispError::MissingMacroArg`, NOT through
        // `template_invariant_violation`. Pins the helper is
        // precisely scoped to bytecode-runtime invariant violations
        // (Subst / Splice / stack gates), not to macro-call arity
        // errors (the latter has its own structural variant). A
        // regression that conflates the two gate clusters would
        // route this case through `Compile { ... }` instead of
        // `MissingMacroArg` and fail-loudly here.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro need-one (x) `,x) (need-one)").unwrap())
            .expect_err("missing required arg must error");
        assert!(
            matches!(err, LispError::MissingMacroArg { .. }),
            "expected MissingMacroArg, got: {err:?}"
        );
    }

    // ── resolve_bound_arg: bytecode-runtime bound-arg-by-index lookup ──
    //
    // `resolve_bound_arg(args_by_index, idx, macro_name, kind)` lifts the
    // `args_by_index.get(*idx).ok_or_else(|| template_invariant_violation(
    // macro_name, KIND(*idx)))?` projection that recurred at BOTH the
    // `TemplateOp::Subst` and `TemplateOp::Splice` arms inside
    // `apply_compiled`. The arms differ in the kind constructor
    // (`SubstBadIndex` vs. `SpliceBadIndex`) and in their post-lookup
    // verb (clone+push vs. splice-coerce), but the lookup-and-reject
    // prelude is byte-identical modulo the constructor. These tests
    // pin the lifted helper's contract directly; the existing
    // `apply_compiled_*_bad_idx_*` tests are the path-uniformity
    // guards proving both production arms route through it without
    // behavior drift.

    #[test]
    fn resolve_bound_arg_in_range_returns_borrowed_reference_verbatim() {
        // For an in-range index, the helper returns `Ok(&args[idx])`
        // borrowed VERBATIM — same pointer as `args_by_index.get(idx)`.
        // Pins the borrow-not-clone contract: a regression that drifts
        // the helper to clone+return (`Result<Sexp>` instead of
        // `Result<&Sexp>`) would allocate per lookup at the production
        // `Subst`/`Splice` hot path. The kind constructor must NOT
        // fire on the success path (`FnOnce`'s lazy semantics) — pin
        // that the test passes a constructor that would panic if
        // called, asserting the helper short-circuits before invoking
        // it on the in-range arm.
        let args = vec![Sexp::int(1), Sexp::int(2), Sexp::int(3)];
        let got = resolve_bound_arg(&args, 1, "m", |_| {
            panic!("kind constructor must not fire on the in-range path")
        })
        .expect("in-range lookup must succeed");
        assert!(
            std::ptr::eq(got, &args[1]),
            "resolve_bound_arg must return the SAME pointer as args_by_index.get(idx)"
        );
        assert_eq!(*got, Sexp::int(2));
    }

    #[test]
    fn resolve_bound_arg_out_of_range_with_subst_kind_emits_typed_invariant() {
        // For an out-of-range index, the helper raises the structural
        // `LispError::TemplateInvariant` variant with the caller-
        // supplied `SubstBadIndex` kind constructor applied to the bad
        // index. Pins the post-lift emission shape (variant identity
        // + the kind constructor threaded with the actual idx); a
        // regression that drops the idx payload (e.g., via a `usize ->
        // ()` projection) or hard-codes a different kind at the helper
        // boundary fails-loudly here. Fail-before-pass-after: this
        // assert is contradicted by the pre-lift code path (which
        // never called `resolve_bound_arg` because it didn't exist),
        // ratifies the post-lift one.
        let args: Vec<Sexp> = Vec::new();
        let err = resolve_bound_arg(&args, 7, "test-macro", TemplateInvariantKind::SubstBadIndex)
            .expect_err("out-of-range lookup must error");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "test-macro");
                assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(7));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn resolve_bound_arg_threads_kind_constructor_per_call_site() {
        // Path-uniformity for the per-call-site kind constructor: the
        // SAME out-of-range idx via the `SpliceBadIndex` constructor
        // emits `kind: SpliceBadIndex(7)` — distinct from the sibling
        // `SubstBadIndex(7)` variant. Pins that the constructor is
        // chosen per call site (not hard-coded at the helper boundary),
        // closing the structural matrix `{Subst, Splice} × {in-range,
        // out-of-range}` the two production arms span across the
        // bytecode-runtime's bound-arg-by-index reads. A regression
        // that hard-codes a single kind at the helper boundary would
        // emit the same variant identity for both call sites and
        // fail-loudly here.
        let args: Vec<Sexp> = Vec::new();
        let err = resolve_bound_arg(
            &args,
            7,
            "test-macro",
            TemplateInvariantKind::SpliceBadIndex,
        )
        .expect_err("out-of-range lookup must error");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "test-macro");
                assert_eq!(kind, TemplateInvariantKind::SpliceBadIndex(7));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn resolve_bound_arg_threads_macro_name_verbatim() {
        // Path-uniformity for the `macro_name` slot: the helper threads
        // the caller's borrow into the variant's owned `String` slot
        // verbatim. Pin two distinct macro names route through with no
        // mutual interference — a regression that hard-codes a single
        // macro_name at the helper boundary or swaps the parameter
        // ordering fails-loudly here. Same posture as
        // `compiler_spec_io_err_threads_each_stage_through_unchanged`
        // pins the typed `stage` slot in the disk-persistence sibling
        // lift.
        let args: Vec<Sexp> = Vec::new();
        for name in ["wrap", "call-macro", "obs"] {
            let err = resolve_bound_arg(&args, 0, name, TemplateInvariantKind::SubstBadIndex)
                .expect_err("out-of-range lookup must error");
            match err {
                LispError::TemplateInvariant { macro_name, kind } => {
                    assert_eq!(macro_name, name, "macro_name slot drifted for {name}");
                    assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(0));
                }
                other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
            }
        }
    }

    #[test]
    fn resolve_bound_arg_yields_first_element_when_idx_is_zero() {
        // Edge case: idx 0 with a single-element args_by_index returns
        // `Ok(&args[0])`. Pins the lower-bound of the in-range surface
        // — a regression that off-by-ones the lookup (e.g., `get(idx +
        // 1)` or `get(idx).filter(|_| idx > 0)`) would fail here.
        // Sibling to the upper-bound `resolve_bound_arg_out_of_range_
        // with_subst_kind_emits_typed_invariant` test.
        let args = vec![Sexp::int(42)];
        let got = resolve_bound_arg(&args, 0, "m", |_| {
            panic!("kind constructor must not fire on the in-range path")
        })
        .expect("idx-0 lookup must succeed");
        assert!(std::ptr::eq(got, &args[0]));
        assert_eq!(*got, Sexp::int(42));
    }

    #[test]
    fn resolve_bound_arg_yields_last_element_at_exact_upper_bound() {
        // Edge case: idx `len - 1` is the highest valid index. Pin
        // that it routes through the success arm (NOT the error arm),
        // closing the in-range surface end-to-end with the lower-
        // bound sibling. A regression that off-by-ones the upper
        // bound (e.g., `get(idx).filter(|_| idx < args.len() - 1)`)
        // would fail here.
        let args = vec![Sexp::int(1), Sexp::int(2), Sexp::int(3)];
        let got = resolve_bound_arg(&args, args.len() - 1, "m", |_| {
            panic!("kind constructor must not fire on the in-range path")
        })
        .expect("last-element lookup must succeed");
        assert!(std::ptr::eq(got, args.last().unwrap()));
        assert_eq!(*got, Sexp::int(3));
    }

    #[test]
    fn resolve_bound_arg_at_exact_length_routes_to_error_arm() {
        // Boundary case: idx EQUAL to `args.len()` is out-of-range
        // (since `get` is 0-indexed). Pin that this routes through
        // the error arm with the kind constructor applied to the
        // EXACT idx that was tried. A regression that off-by-ones
        // the boundary (e.g., admits `idx == len`) would fail here.
        // This is the canonical off-by-one trap; the helper's
        // contract pins it at the variant-construction boundary.
        let args = vec![Sexp::int(1)];
        let err = resolve_bound_arg(&args, 1, "m", TemplateInvariantKind::SubstBadIndex)
            .expect_err("idx == len must error");
        match err {
            LispError::TemplateInvariant { kind, .. } => {
                assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(1));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn resolve_bound_arg_empty_slice_with_any_idx_routes_to_error_arm() {
        // Boundary case: an empty `args_by_index` slice rejects every
        // idx (including 0). Pin that the helper's emission shape is
        // uniform regardless of which out-of-range idx fires the
        // rejection — `SubstBadIndex(0)` for an empty slice is the
        // bytecode-runtime mirror of a zero-arity macro template
        // referencing the 0-th param.
        let args: Vec<Sexp> = Vec::new();
        let err = resolve_bound_arg(&args, 0, "zero-arity", TemplateInvariantKind::SubstBadIndex)
            .expect_err("empty slice rejects every idx");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "zero-arity");
                assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(0));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn apply_compiled_subst_bad_idx_routes_through_resolve_bound_arg_with_subst_kind() {
        // End-to-end path-uniformity: a `Subst(99)` op against a
        // zero-arity macro routes the bytecode-runtime's bound-arg
        // lookup through `resolve_bound_arg` with the
        // `SubstBadIndex` constructor, emitting the structural
        // variant with `kind: SubstBadIndex(99)`. The pre-lift
        // sibling test `apply_compiled_subst_bad_idx_routes_through_
        // template_invariant_violation` pins that the same input
        // routes through `template_invariant_violation`; this test
        // pins that BOTH still hold under the post-lift composition
        // — `resolve_bound_arg` calls `template_invariant_violation`
        // internally on the rejection arm. A regression that drifts
        // ONE arm's projection from the other (e.g., swaps the
        // constructor at one call site, or short-circuits the
        // composition) would fail here.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Subst(99)],
        };
        let err = apply_compiled("test-macro", &MacroParams::default(), &tmpl, &[])
            .expect_err("bad idx must error");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "test-macro");
                assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(99));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn apply_compiled_splice_bad_idx_routes_through_resolve_bound_arg_with_splice_kind() {
        // Sibling end-to-end path-uniformity for the `Splice` arm:
        // the post-lift composition routes a `Splice(42)` op through
        // `resolve_bound_arg` with the `SpliceBadIndex` constructor,
        // emitting `kind: SpliceBadIndex(42)`. Together with the
        // `Subst` sibling test above, this pins the structural matrix
        // `{Subst, Splice} × resolve_bound_arg` end-to-end through
        // the public `apply_compiled` surface, so a regression that
        // drifts ONE arm's kind constructor (e.g., the `Splice` arm
        // accidentally emits `SubstBadIndex` after a copy-paste
        // refactor) fails-loudly here.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Splice(42)],
        };
        let err = apply_compiled("call-macro", &MacroParams::default(), &tmpl, &[])
            .expect_err("bad splice idx must error");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "call-macro");
                assert_eq!(kind, TemplateInvariantKind::SpliceBadIndex(42));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn apply_compiled_subst_in_range_routes_past_resolve_bound_arg_into_clone_and_push() {
        // Positive control: a `Subst(0)` op against a one-arg macro
        // routes through `resolve_bound_arg`'s success arm and the
        // `Subst` post-lookup verb (clone + push) emits the bound
        // value verbatim. Pin the post-lift composition's success
        // path: the clone-and-push semantics live at the call site
        // (NOT in `resolve_bound_arg`, which only borrows), and a
        // regression that drifts the borrow contract (e.g., the
        // helper clones internally + the call site clones again)
        // would still pass observationally but would regress the
        // hot-path allocation count.
        let params = MacroParams {
            required: vec!["x".into()],
            optional: Vec::new(),
            rest: None,
        };
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Subst(0)],
        };
        let out = apply_compiled("id", &params, &tmpl, &[Sexp::int(42)])
            .expect("in-range Subst must succeed");
        assert_eq!(out, Sexp::int(42));
    }

    // ── current_builder_mut: the bytecode-runtime top-of-stack projection ──
    //
    // `current_builder_mut(stack)` lifts the `stack.last_mut().unwrap()`
    // projection that appeared at FOUR sites inside `apply_compiled`'s
    // op-loop (Literal, Subst, Splice, post-EndList parent-fold) into ONE
    // named primitive. The expect message names the bytecode-runtime
    // invariant ("at least one stack frame during op-loop") so a
    // regression that drifts the loop's frame management (a new op that
    // pops without pushing, an early-return that bypasses EndList's
    // stack-check) surfaces a NAMED panic rather than a silent unwrap.
    // These tests pin the projection's contract directly; the existing
    // `apply_compiled_*` tests + the cross-strategy `expansion_layers_
    // agree_on_output_and_cache_wins` benchmark are the path-uniformity
    // guards proving the four sites still emit the canonical bytecode-
    // runtime output across the lift.

    #[test]
    fn current_builder_mut_returns_the_top_frame_reference() {
        // The simplest projection: on a single-frame stack, the helper
        // returns a `&mut Vec<Sexp>` pointing at THAT frame. Pin the
        // projection's identity end-to-end via a push that mutates
        // through the borrow and observe the original frame carries the
        // pushed value back.
        let mut stack: Vec<Vec<Sexp>> = vec![Vec::new()];
        current_builder_mut(&mut stack).push(Sexp::int(42));
        assert_eq!(stack.len(), 1);
        assert_eq!(stack[0], vec![Sexp::int(42)]);
    }

    #[test]
    fn current_builder_mut_targets_the_topmost_frame_on_a_multi_frame_stack() {
        // The projection MUST target the topmost frame, not the bottom
        // one — every `TemplateOp::BeginList` pushes a fresh frame the
        // subsequent ops emit into, and a regression that flipped the
        // projection to `first_mut` (or to a fixed bottom-frame
        // reference) would silently smear all op output into the
        // outermost result. Pin path-uniformity with the bytecode-
        // runtime's mid-list emission posture: with three frames on
        // the stack (one outer + two pending lists), the helper
        // returns a borrow into the third frame, leaving frames 0 and
        // 1 untouched.
        let mut stack: Vec<Vec<Sexp>> = vec![
            vec![Sexp::symbol("outer")],
            vec![Sexp::symbol("inner-a")],
            vec![Sexp::symbol("inner-b")],
        ];
        current_builder_mut(&mut stack).push(Sexp::int(99));
        assert_eq!(stack[0], vec![Sexp::symbol("outer")]);
        assert_eq!(stack[1], vec![Sexp::symbol("inner-a")]);
        assert_eq!(stack[2], vec![Sexp::symbol("inner-b"), Sexp::int(99)]);
    }

    #[test]
    fn current_builder_mut_is_pointer_equal_to_last_mut_unwrap() {
        // Structural identity binding the lift to its pre-lift inline
        // shape: `current_builder_mut(&mut stack)` IS
        // `stack.last_mut().unwrap()` — the same `&mut Vec<Sexp>`,
        // pointing at the same allocation. Pin pointer equality via
        // `std::ptr::eq` on the projected slice's `as_ptr()` to rule
        // out any allocation-shape drift across the lift.
        let mut stack: Vec<Vec<Sexp>> = vec![vec![Sexp::int(1), Sexp::int(2)]];
        let via_lift_ptr = current_builder_mut(&mut stack).as_ptr();
        let via_inline_ptr = stack.last_mut().unwrap().as_ptr();
        assert!(
            std::ptr::eq(via_lift_ptr, via_inline_ptr),
            "current_builder_mut must borrow the SAME frame as stack.last_mut().unwrap()"
        );
    }

    #[test]
    #[should_panic(
        expected = "bytecode-runtime invariant: at least one stack frame during op-loop"
    )]
    fn current_builder_mut_panics_with_named_invariant_on_empty_stack() {
        // The bytecode-runtime invariant is encoded in the expect
        // message: an empty stack at the projection boundary is
        // structurally unreachable inside `apply_compiled`'s op-loop
        // (the outermost frame is seeded at entry and every BeginList
        // / EndList pair preserves the count >= 1). Pin that the
        // NAMED invariant fires on the failure path so a regression
        // that drifts the loop's frame management surfaces a
        // diagnostic-grade panic rather than a silent unwrap over
        // `None`. Authoring tools / future debug-mode hooks can
        // pattern-match on the named invariant string instead of
        // tracking down an unnamed unwrap site.
        let mut empty: Vec<Vec<Sexp>> = Vec::new();
        let _ = current_builder_mut(&mut empty);
    }

    #[test]
    fn current_builder_mut_routes_apply_compiled_literal_emit() {
        // End-to-end path-uniformity guard: a single-op program
        // `TemplateOp::Literal(s)` routes its push through
        // `current_builder_mut(&mut stack)` and the literal lands in
        // the outermost frame. After the op-loop completes the outer
        // `stack.pop().FinalNoValue` gate sees a non-empty top frame
        // containing exactly one element, which `apply_compiled`'s
        // tail (`top.len() == 1 { top.remove(0) }`) projects back as
        // the bound value. Pre-lift the same emission ran through
        // `stack.last_mut().unwrap().push(s.clone())`; post-lift it
        // runs through `current_builder_mut(&mut stack).push(s.clone())`
        // — the byte-identical outcome pins that the Literal arm's
        // routing through the new projection preserves the bytecode-
        // runtime's emission shape.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Literal(Sexp::symbol("hello"))],
        };
        let out = apply_compiled("id", &MacroParams::default(), &tmpl, &[])
            .expect("literal-only template must succeed");
        assert_eq!(out, Sexp::symbol("hello"));
    }

    #[test]
    fn current_builder_mut_routes_apply_compiled_end_list_parent_fold() {
        // End-to-end path-uniformity guard for the post-EndList
        // parent-fold push: `(BeginList, Literal(a), Literal(b),
        // EndList)` builds an inner frame `[a, b]`, pops it on
        // EndList, then pushes `Sexp::List([a, b])` into the parent
        // (outer) frame via `current_builder_mut`. The outermost
        // `stack.pop()` then surfaces that list as the bound result.
        // Pre-lift the parent-fold push ran through
        // `stack.last_mut().unwrap().push(Sexp::List(items))`; post-
        // lift it runs through `current_builder_mut(&mut stack).
        // push(Sexp::List(items))` — pin the byte-identical outcome
        // so a regression that drifts the parent-fold target (e.g.,
        // pushes onto the just-popped frame's pointer instead of the
        // new top) fails loudly here.
        let tmpl = CompiledTemplate {
            ops: vec![
                TemplateOp::BeginList,
                TemplateOp::Literal(Sexp::symbol("a")),
                TemplateOp::Literal(Sexp::symbol("b")),
                TemplateOp::EndList,
            ],
        };
        let out = apply_compiled("id", &MacroParams::default(), &tmpl, &[])
            .expect("BeginList/EndList template must succeed");
        assert_eq!(out, Sexp::List(vec![Sexp::symbol("a"), Sexp::symbol("b")]));
    }

    #[test]
    fn current_builder_mut_routes_apply_compiled_subst_and_splice_emits() {
        // End-to-end path-uniformity guard for BOTH index-reading
        // arms routing through the lifted projection: a one-required +
        // one-rest macro `(call f &rest args)` with template
        // `(BeginList, Subst(0), Splice(1), EndList)` exercises both
        // Subst's clone-and-push AND Splice's splice-value-into
        // emit-paths against the current builder via
        // `current_builder_mut(&mut stack)`. The composed result is
        // `(foo 1 2 3)` — Subst lands the bound `f = foo` and
        // Splice flattens `args = (1 2 3)` — and the byte-identical
        // outcome pins that BOTH Subst and Splice arms' emits route
        // through the SHARED projection. Sibling to
        // `apply_compiled_splice_in_range_routes_past_resolve_bound
        // _arg_into_splice_value_into` which already exercises this
        // shape end-to-end; the addition here is the path-uniformity
        // anchor for the `current_builder_mut` lift specifically.
        let params = MacroParams {
            required: vec!["f".into()],
            optional: Vec::new(),
            rest: Some("args".into()),
        };
        let tmpl = CompiledTemplate {
            ops: vec![
                TemplateOp::BeginList,
                TemplateOp::Subst(0),
                TemplateOp::Splice(1),
                TemplateOp::EndList,
            ],
        };
        let out = apply_compiled(
            "call",
            &params,
            &tmpl,
            &[
                Sexp::symbol("foo"),
                Sexp::int(1),
                Sexp::int(2),
                Sexp::int(3),
            ],
        )
        .expect("Subst + Splice template must succeed");
        assert_eq!(
            out,
            Sexp::List(vec![
                Sexp::symbol("foo"),
                Sexp::int(1),
                Sexp::int(2),
                Sexp::int(3),
            ])
        );
    }

    #[test]
    fn apply_compiled_splice_in_range_routes_past_resolve_bound_arg_into_splice_value_into() {
        // Positive control for the `Splice` arm: a `&rest` macro that
        // splices a bound list routes through `resolve_bound_arg`'s
        // success arm and the `Splice` post-lookup verb
        // (`splice_value_into`) flattens the bound list into the
        // builder. Pin the composition's success path end-to-end:
        // the bound `Sexp::List([1, 2, 3])` at idx 1 flattens into
        // the outer builder's `(call 1 2 3)` shape — the same output
        // `rest_param_splices_with_at` pins through the public
        // surface, here pinned with the bytecode-runtime composition
        // exposed directly.
        let params = MacroParams {
            required: vec!["f".into()],
            optional: Vec::new(),
            rest: Some("args".into()),
        };
        let tmpl = CompiledTemplate {
            ops: vec![
                TemplateOp::BeginList,
                TemplateOp::Subst(0),
                TemplateOp::Splice(1),
                TemplateOp::EndList,
            ],
        };
        let out = apply_compiled(
            "call",
            &params,
            &tmpl,
            &[Sexp::symbol("foo"), Sexp::int(1), Sexp::int(2)],
        )
        .expect("in-range Splice must succeed");
        assert_eq!(
            out,
            Sexp::List(vec![Sexp::symbol("foo"), Sexp::int(1), Sexp::int(2)])
        );
    }

    // ── pop_builder_frame: the bytecode-runtime stack-frame consume ─────
    //
    // `pop_builder_frame(stack, macro_name, kind)` lifts the
    // `stack.pop().ok_or_else(|| template_invariant_violation(macro_name,
    // kind))?` chain that recurred at two sites inside `apply_compiled`
    // (the `EndList` arm + the post-loop final pop) into ONE named
    // primitive on the bytecode-runtime's stack-frame algebra. Sibling of
    // `current_builder_mut` (the top-frame-borrow projection — the same
    // `&mut Vec<Vec<Sexp>>` consumed at the borrow face) and
    // `resolve_bound_arg` (the bound-arg-by-index lookup primitive that
    // also routes through `TemplateInvariantKind` as the per-call-site
    // rejection identity). These tests pin the primitive's contract
    // directly; the existing `apply_compiled_*` tests are the path-
    // uniformity guards proving the two sites route through it without
    // behavior drift.

    #[test]
    fn pop_builder_frame_pops_top_frame_off_non_empty_stack() {
        // Happy path: a two-frame stack pops the topmost frame off and
        // returns it AS-IS while shrinking the stack by exactly one
        // element. Pin both the return value (the popped frame's
        // contents are byte-identical to what was pushed) AND the
        // mutation (`stack.len()` drops from 2 to 1).
        let mut stack: Vec<Vec<Sexp>> = vec![
            vec![Sexp::symbol("outer")],
            vec![Sexp::int(1), Sexp::int(2)],
        ];
        let popped =
            pop_builder_frame(&mut stack, "wrap", TemplateInvariantKind::EndListEmptyStack)
                .expect("non-empty stack must pop cleanly");
        assert_eq!(popped, vec![Sexp::int(1), Sexp::int(2)]);
        assert_eq!(stack.len(), 1);
        assert_eq!(stack[0], vec![Sexp::symbol("outer")]);
    }

    #[test]
    fn pop_builder_frame_emits_template_invariant_with_end_list_empty_stack_kind() {
        // Empty-stack rejection: an empty stack flows through the
        // `EndListEmptyStack` kind constructor into a structural
        // `LispError::TemplateInvariant { macro_name, kind:
        // EndListEmptyStack }` variant. Fail-before-pass-after: pre-lift
        // the same input would route through the inline
        // `stack.pop().ok_or_else(|| template_invariant_violation(_,
        // EndListEmptyStack))?` chain at the `EndList` arm; post-lift
        // it routes through ONE named primitive both pop-emitting
        // sites share, and a regression that drops the kind threading
        // (e.g. unifies both kinds into one constant) fails here.
        let mut empty: Vec<Vec<Sexp>> = Vec::new();
        let err = pop_builder_frame(&mut empty, "wrap", TemplateInvariantKind::EndListEmptyStack)
            .expect_err("empty stack must reject");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "wrap");
                assert_eq!(kind, TemplateInvariantKind::EndListEmptyStack);
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn pop_builder_frame_emits_template_invariant_with_final_no_value_kind() {
        // Path-uniformity across the closed-set of pop-emitting kinds:
        // the same primitive threads `FinalNoValue` verbatim through
        // its `TemplateInvariantKind` slot, with the macro_name
        // identity preserved across the call boundary. Sibling of the
        // `EndListEmptyStack` test above — together they pin the
        // primitive's closed-set posture (BOTH reachable
        // pop-emitting kinds route through the same primitive, neither
        // is hard-coded), so a future `TemplateInvariantKind` variant
        // added for a new pop-emitting op (e.g. a hypothetical
        // `EndManyEmptyStack`) extends the primitive's reachability
        // mechanically by passing the new kind through the same slot.
        let mut empty: Vec<Vec<Sexp>> = Vec::new();
        let err = pop_builder_frame(&mut empty, "id", TemplateInvariantKind::FinalNoValue)
            .expect_err("empty stack must reject");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "id");
                assert_eq!(kind, TemplateInvariantKind::FinalNoValue);
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn pop_builder_frame_threads_macro_name_through_variant_for_indexed_kinds() {
        // Closed-set posture check: even kinds the production
        // `apply_compiled` op-loop ROUTES through `resolve_bound_arg`
        // rather than `pop_builder_frame` (the indexed `SubstBadIndex(_)`
        // / `SpliceBadIndex(_)` siblings) MUST compose correctly with
        // this primitive's typed slot — they are NOT reachable here
        // from the production loop, but `TemplateInvariantKind` does
        // not distinguish "indexed" kinds from "stack-gate" kinds at
        // the helper's signature, so a regression that special-cases
        // one kind family would be a silent type-narrowing the closed-
        // set typed enum was lifted to prevent. Pin the universal
        // routing: ANY kind variant feeds through the primitive's
        // `kind` slot identically. Sibling assertion to
        // `template_invariant_violation_threads_subst_idx_through_typed_variant`
        // — same compose-the-kind-into-the-variant contract, one
        // composition step further down the substrate stack.
        let mut empty: Vec<Vec<Sexp>> = Vec::new();
        let err = pop_builder_frame(
            &mut empty,
            "compose",
            TemplateInvariantKind::SubstBadIndex(42),
        )
        .expect_err("empty stack must reject regardless of kind family");
        match err {
            LispError::TemplateInvariant { macro_name, kind } => {
                assert_eq!(macro_name, "compose");
                assert_eq!(kind, TemplateInvariantKind::SubstBadIndex(42));
            }
            other => panic!("expected LispError::TemplateInvariant, got {other:?}"),
        }
    }

    #[test]
    fn pop_builder_frame_is_byte_identical_to_inline_pop_then_template_invariant_violation() {
        // Structural-identity binding the lift to its pre-lift inline
        // shape: `pop_builder_frame(stack, macro_name, kind)` IS
        // `stack.pop().ok_or_else(|| template_invariant_violation(
        // macro_name, kind))?` — both reachable arms (success +
        // failure) must produce byte-identical outcomes. The success
        // arm checks the popped Vec contents AND the post-pop stack
        // length match the inline path; the failure arm checks the
        // emitted variant's identity AND its `macro_name` / `kind`
        // slots match the inline path. A regression that drifts the
        // primitive's projection (e.g. a `stack.swap_remove(_)` typo,
        // or a kind-rewrite at the helper boundary) fails on at least
        // one of the two arms.
        // Success arm:
        let mut stack_lift: Vec<Vec<Sexp>> = vec![vec![Sexp::symbol("a")], vec![Sexp::int(7)]];
        let mut stack_inline: Vec<Vec<Sexp>> = vec![vec![Sexp::symbol("a")], vec![Sexp::int(7)]];
        let via_lift = pop_builder_frame(
            &mut stack_lift,
            "macro",
            TemplateInvariantKind::EndListEmptyStack,
        )
        .expect("non-empty stack pops cleanly through lift");
        let via_inline = stack_inline.pop().ok_or_else(|| {
            template_invariant_violation("macro", TemplateInvariantKind::EndListEmptyStack)
        });
        assert_eq!(
            via_lift,
            via_inline.unwrap(),
            "popped frame must be byte-identical across lift vs inline"
        );
        assert_eq!(
            stack_lift.len(),
            stack_inline.len(),
            "post-pop stack length must be byte-identical across lift vs inline"
        );
        // Failure arm:
        let mut empty_lift: Vec<Vec<Sexp>> = Vec::new();
        let mut empty_inline: Vec<Vec<Sexp>> = Vec::new();
        let err_lift = pop_builder_frame(
            &mut empty_lift,
            "macro",
            TemplateInvariantKind::FinalNoValue,
        )
        .expect_err("empty stack rejects through lift");
        let err_inline = empty_inline
            .pop()
            .ok_or_else(|| {
                template_invariant_violation("macro", TemplateInvariantKind::FinalNoValue)
            })
            .expect_err("empty stack rejects through inline");
        match (err_lift, err_inline) {
            (
                LispError::TemplateInvariant {
                    macro_name: m_lift,
                    kind: k_lift,
                },
                LispError::TemplateInvariant {
                    macro_name: m_inline,
                    kind: k_inline,
                },
            ) => {
                assert_eq!(m_lift, m_inline);
                assert_eq!(k_lift, k_inline);
            }
            (l, i) => panic!(
                "expected LispError::TemplateInvariant on both arms, got lift={l:?}, inline={i:?}"
            ),
        }
    }

    #[test]
    fn pop_builder_frame_routes_apply_compiled_end_list_consume() {
        // End-to-end path-uniformity guard for the `EndList` arm: a
        // `(BeginList, Literal(x), EndList)` program pushes a child
        // frame, populates it with one literal, then routes the child
        // frame OUT of the stack via `pop_builder_frame` (kind
        // `EndListEmptyStack` — unreachable on this valid input, but
        // the kind threads through the primitive identically). The
        // post-pop verb (`Sexp::List(items)` push into the parent via
        // `current_builder_mut`) yields the same `Sexp::List([x])`
        // shape the consumer projected pre-lift. Pin the byte-
        // identical outcome so a regression that drifts the EndList
        // arm's routing (e.g. swaps the kind constructor, or routes
        // through a different stack-mutating primitive) fails loudly
        // here. Sibling of
        // `current_builder_mut_routes_apply_compiled_end_list_parent_fold`
        // — that test pins the parent-fold PUSH; this test pins the
        // child-frame POP that immediately precedes it. Together the
        // two close the EndList arm's path-uniformity across the
        // pop-then-push composition.
        let tmpl = CompiledTemplate {
            ops: vec![
                TemplateOp::BeginList,
                TemplateOp::Literal(Sexp::symbol("only")),
                TemplateOp::EndList,
            ],
        };
        let out = apply_compiled("id", &MacroParams::default(), &tmpl, &[])
            .expect("BeginList/EndList one-literal template must succeed");
        assert_eq!(out, Sexp::List(vec![Sexp::symbol("only")]));
    }

    #[test]
    fn pop_builder_frame_routes_apply_compiled_final_pop_consume() {
        // End-to-end path-uniformity guard for the post-loop final
        // pop: a single-op `Literal(s)` program emits `s` into the
        // outermost (seed) frame, then the post-loop tail routes the
        // seed frame OUT via `pop_builder_frame` (kind `FinalNoValue`
        // — unreachable on this valid input). The post-pop arity gate
        // (`top.len() == 1 { top.remove(0) }`) projects the literal
        // back as the bound value. Pre-lift the same emission ran
        // through the inline `stack.pop().ok_or_else(|| template_
        // invariant_violation(_, FinalNoValue))?` chain at the
        // post-loop tail; post-lift it routes through ONE named
        // primitive the EndList arm ALSO routes through, and the
        // single-literal outcome is byte-identical across both code
        // paths. Sibling of
        // `current_builder_mut_routes_apply_compiled_literal_emit` —
        // that test pins the EMIT into the seed frame; this test pins
        // the POP of the same seed frame at the post-loop tail.
        // Together the two close the Literal-only program's path-
        // uniformity across the emit-then-consume composition.
        let tmpl = CompiledTemplate {
            ops: vec![TemplateOp::Literal(Sexp::int(123))],
        };
        let out = apply_compiled("id", &MacroParams::default(), &tmpl, &[])
            .expect("literal-only template must succeed");
        assert_eq!(out, Sexp::int(123));
    }

    // ── MacroParams: the typed param-list primitive ─────────────────────
    //
    // `parse_params` now yields a `MacroParams { required, optional, rest }`
    // whose shape makes the canonical lambda-list ordering (required →
    // optional → rest, "&rest is last + at-most-one", "&optional at most
    // once") structural rather than a construction discipline a `Vec<Param>`
    // only happened to uphold. These tests pin the parser's mapping into the
    // typed shape, the flat-index contract `names()` exposes to the template
    // bytecode, and the single positional binder `bind()` both expansion
    // strategies now route through. The end-to-end `rest_param_splices_with_at`
    // and `compiled_template_matches_substitute_path` tests above are the
    // path-uniformity guards proving both strategies still agree.

    #[test]
    fn parse_params_maps_required_then_rest_into_typed_shape() {
        // `(a b &rest c)` — two required, one rest. The rest name lands in
        // the `Option`, never in `required`.
        let params = parse_params(&read("a b &rest c").unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: vec!["a".into(), "b".into()],
                optional: Vec::new(),
                rest: Some("c".into()),
            }
        );
    }

    #[test]
    fn parse_params_rest_absent_leaves_none() {
        // `(x y)` — no `&rest`, so `rest` is structurally `None`. There is
        // no representation in which a rest-less list carries a stray rest.
        let params = parse_params(&read("x y").unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: vec!["x".into(), "y".into()],
                optional: Vec::new(),
                rest: None,
            }
        );
    }

    #[test]
    fn parse_params_maps_optional_section_between_required_and_rest() {
        // `(a &optional b c &rest d)` — the canonical lambda-list order. `a`
        // is required, `b`/`c` are optional, `d` is rest. The `&optional`
        // marker switches collection from `required` to `optional`; `&rest`
        // remains terminal.
        let params = parse_params(&read("a &optional b c &rest d").unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: vec!["a".into()],
                optional: vec![OptionalParam::bare("b"), OptionalParam::bare("c")],
                rest: Some("d".into()),
            }
        );
    }

    #[test]
    fn parse_params_optional_with_no_rest_leaves_rest_none() {
        // `(&optional x)` — a leading `&optional` (zero required) with no
        // rest. `required` is empty, `x` is the sole optional, `rest` None.
        let params = parse_params(&read("&optional x").unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: Vec::new(),
                optional: vec![OptionalParam::bare("x")],
                rest: None,
            }
        );
    }

    #[test]
    fn parse_params_rejects_repeated_optional_marker() {
        // `(a &optional b &optional c)` — a second `&optional` is
        // unrepresentable (one flat optional section), so the gate REJECTS
        // rather than binding args to a marker symbol named `&optional`. The
        // two marker positions (1 and 3) are named.
        let err = parse_params(&read("a &optional b &optional c").unwrap())
            .expect_err("repeated &optional must error");
        assert!(
            matches!(
                err,
                LispError::OptionalMarkerRepeated {
                    first_position: 1,
                    second_position: 3,
                }
            ),
            "expected OptionalMarkerRepeated {{1, 3}}, got: {err:?}"
        );
    }

    #[test]
    fn parse_params_rejects_optional_after_rest_as_trailing_tokens() {
        // `(&rest xs &optional y)` — `&rest <name>` is terminal, so the
        // `&optional y` tail is REJECTED as trailing tokens (not silently
        // dropped, and not a repeated-optional error: the rest gate fires
        // first). Pins the interaction the prior run (3627426) signposted.
        let err = parse_params(&read("&rest xs &optional y").unwrap())
            .expect_err("tokens after &rest <name> must error");
        assert!(
            matches!(err, LispError::RestParamTrailingTokens { .. }),
            "expected RestParamTrailingTokens, got: {err:?}"
        );
    }

    #[test]
    fn names_are_required_then_optional_then_rest_in_flat_index_order() {
        // The flat-index contract the bytecode `Subst(idx)`/`Splice(idx)`
        // depends on: required names at 0.., then optional names, then the
        // rest name last.
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: vec![OptionalParam::bare("c")],
            rest: Some("d".into()),
        };
        assert_eq!(params.names(), vec!["a", "b", "c", "d"]);
        // Optional names occupy the indices immediately after the required run.
        assert_eq!(params.names()[params.required.len()], "c");
        // The rest name is last, after required + optional — i.e. at the
        // structural `fixed_arity()` boundary the typed primitive names.
        assert_eq!(params.names()[params.fixed_arity()], "d");
    }

    // ── `MacroParams::{REST_MARKER, OPTIONAL_MARKER,
    // LAMBDA_LIST_KEYWORD_LEAD}` — the typed CL lambda-list-keyword
    // marker algebra ────────────────────────────────────────────────
    //
    // The three `pub const`s close the Common-Lisp lambda-list keyword
    // family at the typed [`MacroParams`] algebra: `REST_MARKER` and
    // `OPTIONAL_MARKER` are the two `&'static str` markers the parser's
    // typed dispatch specialises on; `LAMBDA_LIST_KEYWORD_LEAD` is the
    // canonical `'&'` char shared as the LEAD byte of both markers.
    // Pre-lift the same two `&'static str` markers lived as two inline
    // `s == "..."` comparisons at `parse_params` — post-lift both
    // comparisons route through the typed constants so a delimiter swap
    // (e.g. a Racket-compat `#!rest` port, a Clojure-compat `&` port)
    // lands at ONE constant on the typed algebra.
    //
    // These pins cover: (a) the exact `&'static str` / `char` values,
    // (b) the structural round-trip law binding each `&'static str`
    // marker to its shared `char` LEAD byte, (c) the pairwise
    // disjointness of the two `&'static str` markers, (d) the cross-
    // axis disjointness of the `char` LEAD byte against every sibling
    // outer-marker `char` the substrate's other closed-set algebras
    // specialise on, and (e) the path-uniformity of `parse_params`
    // through the typed constants.

    #[test]
    fn macro_params_rest_marker_projects_canonical_ampersand_rest_str() {
        // Pins the constant's exact `&'static str` bytes so a typo
        // (`"&res"`, `"&Rest"`, `"&rst"`) or an accidental redefinition
        // surfaces immediately. Sibling-shape pin to
        // `macro_params_optional_marker_projects_canonical_ampersand_optional_str`
        // on the peer `&optional` axis.
        assert_eq!(
            MacroParams::REST_MARKER,
            "&rest",
            "MacroParams::REST_MARKER drifted from the substrate- \
             canonical CL lambda-list `&rest` marker — the parser's \
             `parse_params` rest-slot dispatch AND every downstream \
             authoring / rendering surface binds to this ONE typed \
             constant.",
        );
    }

    #[test]
    fn macro_params_optional_marker_projects_canonical_ampersand_optional_str() {
        // Pins the constant's exact `&'static str` bytes so a typo
        // (`"&opt"`, `"&Optional"`, `"&option"`) or an accidental
        // redefinition surfaces immediately. Sibling-shape pin to
        // `macro_params_rest_marker_projects_canonical_ampersand_rest_str`
        // on the peer `&rest` axis.
        assert_eq!(
            MacroParams::OPTIONAL_MARKER,
            "&optional",
            "MacroParams::OPTIONAL_MARKER drifted from the substrate- \
             canonical CL lambda-list `&optional` marker — the parser's \
             `parse_params` optional-section dispatch AND every \
             downstream authoring / rendering surface binds to this \
             ONE typed constant.",
        );
    }

    #[test]
    fn macro_params_lambda_list_keyword_lead_projects_canonical_ampersand_char() {
        // Pins the constant's exact `char` value so a typo (`'#'`,
        // `'@'`, `'!'`) or an accidental redefinition surfaces
        // immediately. Sibling-shape pin to
        // `atom_keyword_marker_lead_projects_canonical_colon_char`,
        // `atom_bool_literal_lead_projects_canonical_hash_char`,
        // `atom_str_delimiter_projects_canonical_double_quote_char`
        // on the peer per-role LEAD-byte axes across the substrate's
        // closed-set outer algebras.
        assert_eq!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            '&',
            "LAMBDA_LIST_KEYWORD_LEAD char drifted from the substrate- \
             canonical `&` LEAD byte — the CL lambda-list-keyword \
             family (REST_MARKER, OPTIONAL_MARKER) shares this ONE \
             typed constant as their common LEAD byte.",
        );
    }

    #[test]
    fn macro_params_rest_marker_prefixed_by_lambda_list_keyword_lead() {
        // STRUCTURAL ROUND-TRIP CONTRACT: the `&'static str` marker
        // `MacroParams::REST_MARKER` starts with the `char` LEAD byte
        // `MacroParams::LAMBDA_LIST_KEYWORD_LEAD` — the projection law
        // binding the two typed constants on the [`MacroParams`]
        // algebra. A regression that renames the `&'static str` (e.g.
        // to Racket's `"#!rest"` keyword-args) OR the `char` (e.g. to
        // `'#'` for the `#!` shebang lead) without updating the other
        // fails HERE. Sibling-shape pin to
        // `atom_keyword_marker_lead_prefixes_keyword_marker` on the
        // peer `Atom`-algebra Keyword-prefix LEAD-byte axis.
        assert!(
            MacroParams::REST_MARKER.starts_with(MacroParams::LAMBDA_LIST_KEYWORD_LEAD),
            "MacroParams::REST_MARKER `{}` does NOT start with \
             MacroParams::LAMBDA_LIST_KEYWORD_LEAD `{:?}` — the two \
             typed constants have drifted apart on the [`MacroParams`] \
             algebra; the CL lambda-list-keyword family disjointness \
             contract can no longer bind to ONE shared LEAD byte.",
            MacroParams::REST_MARKER,
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
        );
    }

    #[test]
    fn macro_params_optional_marker_prefixed_by_lambda_list_keyword_lead() {
        // STRUCTURAL ROUND-TRIP CONTRACT: peer to
        // `macro_params_rest_marker_prefixed_by_lambda_list_keyword_lead`
        // on the `&optional` axis. Both `&'static str` markers of the
        // CL lambda-list-keyword family MUST share the canonical `char`
        // LEAD byte so the typed-marker disjointness contract can bind
        // to ONE shared LEAD byte on the [`MacroParams`] algebra.
        assert!(
            MacroParams::OPTIONAL_MARKER.starts_with(MacroParams::LAMBDA_LIST_KEYWORD_LEAD),
            "MacroParams::OPTIONAL_MARKER `{}` does NOT start with \
             MacroParams::LAMBDA_LIST_KEYWORD_LEAD `{:?}` — the two \
             typed constants have drifted apart on the [`MacroParams`] \
             algebra; the CL lambda-list-keyword family disjointness \
             contract can no longer bind to ONE shared LEAD byte.",
            MacroParams::OPTIONAL_MARKER,
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
        );
    }

    #[test]
    fn macro_params_rest_and_optional_markers_pairwise_disjoint() {
        // PAIRWISE DISJOINTNESS PIN: the two `&'static str` markers on
        // the CL lambda-list-keyword algebra MUST differ so the
        // parser's typed dispatch cascade at `parse_params` (which
        // tests `REST_MARKER` FIRST, then `OPTIONAL_MARKER`) cannot
        // silently route both dispatches through the same arm. A
        // regression that aliases the two markers (e.g. both to
        // `"&rest"` after a typo) would silently drop the optional
        // section's structural distinction — every `&optional` name
        // would misclassify as a rest-slot marker.
        assert_ne!(
            MacroParams::REST_MARKER,
            MacroParams::OPTIONAL_MARKER,
            "REST_MARKER and OPTIONAL_MARKER collide — the parser's \
             typed dispatch cascade at `parse_params` can no longer \
             distinguish the rest-slot boundary from the optional- \
             section boundary.",
        );
    }

    #[test]
    fn macro_params_lambda_list_keyword_lead_distinct_from_every_other_algebra_marker() {
        // CROSS-AXIS DISJOINTNESS PIN: `MacroParams::LAMBDA_LIST_KEYWORD_LEAD`
        // MUST NOT alias any sibling outer-marker `char` on the
        // substrate's other closed-set algebras — the Atom-payload
        // markers (`STR_DELIMITER`, `STR_ESCAPE_LEAD`,
        // `KEYWORD_MARKER_LEAD`, `BOOL_LITERAL_LEAD`), the paired list
        // delimiters (`Sexp::LIST_OPEN` / `Sexp::LIST_CLOSE`), the
        // paired line-comment delimiters (`Sexp::COMMENT_LEAD` /
        // `Sexp::COMMENT_TERM`), every `QuoteForm::lead_char`
        // projection, AND `QuoteForm::SPLICE_DISCRIMINATOR`. A
        // collision would silently break the reader's outer dispatch:
        // an `&`-prefixed bare atom `&rest` / `&optional` would collide
        // with whichever marker it aliased. Sibling-shape pin to
        // `atom_keyword_marker_lead_distinct_from_every_other_algebra_marker`
        // on the peer `Atom`-algebra Keyword-prefix LEAD-byte axis —
        // pins the SAME shape on the CL lambda-list-keyword LEAD-byte
        // axis. A future outer-marker extension that collided with
        // `'&'` fails HERE at the cross-axis enumeration.
        use crate::ast::{Atom, QuoteForm, Sexp};

        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Atom::STR_DELIMITER,
            "LAMBDA_LIST_KEYWORD_LEAD collides with STR_DELIMITER — a \
             bare `&rest` at a param-list position would ambiguously \
             begin a lambda-list keyword AND open a string.",
        );
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Atom::STR_ESCAPE_LEAD,
            "LAMBDA_LIST_KEYWORD_LEAD collides with STR_ESCAPE_LEAD — \
             the reader's Str-escape lead byte would alias the CL \
             lambda-list-keyword LEAD byte.",
        );
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Atom::KEYWORD_MARKER_LEAD,
            "LAMBDA_LIST_KEYWORD_LEAD collides with KEYWORD_MARKER_LEAD \
             — a bare `&rest` at a param-list position would \
             ambiguously begin a lambda-list keyword AND begin an \
             `:foo` keyword.",
        );
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Atom::BOOL_LITERAL_LEAD,
            "LAMBDA_LIST_KEYWORD_LEAD collides with BOOL_LITERAL_LEAD — \
             a bare `&rest` at a param-list position would ambiguously \
             begin a lambda-list keyword AND classify as a Bool prefix.",
        );
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Sexp::LIST_OPEN,
            "LAMBDA_LIST_KEYWORD_LEAD collides with LIST_OPEN — a bare \
             `&rest` at a param-list position would ambiguously begin \
             a lambda-list keyword AND open a list.",
        );
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Sexp::LIST_CLOSE,
            "LAMBDA_LIST_KEYWORD_LEAD collides with LIST_CLOSE — a bare \
             `&rest` at a param-list position would ambiguously begin \
             a lambda-list keyword AND close a list.",
        );
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Sexp::COMMENT_LEAD,
            "LAMBDA_LIST_KEYWORD_LEAD collides with COMMENT_LEAD — a \
             bare `&rest` at a param-list position would ambiguously \
             begin a lambda-list keyword AND begin a comment.",
        );
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            Sexp::COMMENT_TERM,
            "LAMBDA_LIST_KEYWORD_LEAD collides with COMMENT_TERM — the \
             reader's line-comment discard loop would terminate on the \
             SAME byte the parser's lambda-list-keyword LEAD dispatch \
             binds to.",
        );
        for qf in QuoteForm::ALL {
            assert_ne!(
                MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
                qf.lead_char(),
                "LAMBDA_LIST_KEYWORD_LEAD collides with \
                 QuoteForm::{qf:?}'s lead_char — a bare `&rest` at a \
                 param-list position would ambiguously begin a lambda- \
                 list keyword AND begin a quote-family prefix.",
            );
        }
        assert_ne!(
            MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            QuoteForm::SPLICE_DISCRIMINATOR,
            "LAMBDA_LIST_KEYWORD_LEAD collides with \
             SPLICE_DISCRIMINATOR — the reader's `,@` splice-promotion \
             peek byte would alias the CL lambda-list-keyword LEAD \
             byte.",
        );
    }

    #[test]
    fn parse_params_recognizes_rest_marker_via_typed_constant() {
        // PATH-UNIFORMITY PIN: the parser's rest-slot dispatch at
        // `parse_params` MUST classify the typed constant
        // `MacroParams::REST_MARKER` as the rest-slot boundary —
        // authoring surfaces that assemble a param list through the
        // typed constant (rather than through an inline string literal
        // read from user source) must reach the SAME rest-slot binding
        // the reader-driven path does.
        //
        // The `read(REST_MARKER)` composition here is the load-bearing
        // structural link: we build the param-list source through the
        // typed constant, then parse it through the reader, then the
        // parser MUST bind `xs` at the `rest` slot. A regression that
        // drifts the parser's dispatch away from the typed constant
        // (e.g. re-inlines a string literal that goes stale against
        // the constant) fails HERE.
        let src = format!("a {} xs", MacroParams::REST_MARKER);
        let params = parse_params(&read(&src).unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: vec!["a".into()],
                optional: Vec::new(),
                rest: Some("xs".into()),
            },
            "parse_params dispatch drifted away from REST_MARKER — the \
             typed constant no longer routes to the rest-slot arm.",
        );
    }

    #[test]
    fn parse_params_recognizes_optional_marker_via_typed_constant() {
        // PATH-UNIFORMITY PIN: peer to
        // `parse_params_recognizes_rest_marker_via_typed_constant` on
        // the `&optional` axis. The parser's optional-section dispatch
        // at `parse_params` MUST classify the typed constant
        // `MacroParams::OPTIONAL_MARKER` as the section-switch
        // boundary that reroutes subsequent bare-symbol names from the
        // `required` bin to the `optional` bin.
        let src = format!("a {} b c", MacroParams::OPTIONAL_MARKER);
        let params = parse_params(&read(&src).unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: vec!["a".into()],
                optional: vec![OptionalParam::bare("b"), OptionalParam::bare("c")],
                rest: None,
            },
            "parse_params dispatch drifted away from OPTIONAL_MARKER — \
             the typed constant no longer routes to the optional- \
             section arm.",
        );
    }

    // ── `MacroParams::LAMBDA_LIST_KEYWORDS` + `is_lambda_list_keyword` —
    // the closed-set forced-arity ALL array + membership gate that closes
    // the CL lambda-list-keyword family at the typed [`MacroParams`]
    // algebra. Sibling posture to the closed set of `pub const ALL: [Self;
    // N]` forced-arity arrays across the substrate's other closed-set
    // outer algebras (`AtomKind::ALL`, `QuoteForm::ALL`, `SexpShape::ALL`,
    // `UnquoteForm::ALL`, `MacroDefHead::ALL`); a future third marker
    // (`&key`, `&aux`, `&body`) extends the array's arity + adds ONE `pub
    // const` for the marker and every downstream family-wide contract
    // sweep (LEAD-byte round-trip, pairwise disjointness, membership
    // gate) picks up the extension at ONE structural site.
    //
    // These pins cover: (a) the cardinality contract (the ALL array's
    // length matches the pre-lift per-role marker count), (b) the
    // ordering contract (each ALL entry matches its corresponding per-
    // role `pub const` by-index), (c) the family-wide structural round-
    // trip (every ALL element starts_with LEAD), (d) the family-wide
    // pairwise disjointness (every distinct ALL index pair yields
    // distinct markers), (e) the membership-gate acceptance side (every
    // ALL element classifies as `true`), and (f) the membership-gate
    // rejection side (the bare LEAD byte + unrecognised `&`-prefixed
    // names classify as `false`).
    //
    // Fail-before/pass-after: every test below references
    // `MacroParams::LAMBDA_LIST_KEYWORDS` or
    // `MacroParams::is_lambda_list_keyword`, which simply did not exist
    // on `MacroParams` before this lift — every assertion was a
    // compile-time error against the prior surface.

    #[test]
    fn macro_params_lambda_list_keywords_has_expected_cardinality() {
        // CARDINALITY PIN: the ALL array closes the family at exactly TWO
        // entries — the two `&'static str` markers the parser's typed
        // dispatch specialises on today (`&rest` + `&optional`). A future
        // third marker (`&key`, `&aux`, `&body`) extends this arity to
        // 3 AND every downstream family-wide contract sweep picks up the
        // extension at ONE structural site. A regression that drops a
        // marker from the ALL array (silently narrowing the family) OR
        // aliases two markers to the same index (silently narrowing the
        // typed dispatch) fails HERE at the cardinality contract before
        // the structural round-trip / pairwise-disjointness contracts
        // even fire.
        assert_eq!(
            MacroParams::LAMBDA_LIST_KEYWORDS.len(),
            2,
            "LAMBDA_LIST_KEYWORDS cardinality drifted from 2 — the CL \
             lambda-list-keyword family closure now names a different \
             number of markers than the two the parser's typed dispatch \
             specialises on.",
        );
    }

    #[test]
    fn macro_params_lambda_list_keywords_binds_per_role_markers_by_index() {
        // ORDERING PIN: each ALL entry matches its corresponding per-role
        // `pub const` by-index. A regression that swaps the ordering
        // (`[OPTIONAL_MARKER, REST_MARKER]` after a rebase) would keep
        // the cardinality + membership contracts intact but silently
        // reorder downstream consumers that iterate `LAMBDA_LIST_KEYWORDS`
        // in canonical order (a future authoring surface that renders
        // "supported CL lambda-list keywords: &rest, &optional" would
        // silently render "supported CL lambda-list keywords: &optional,
        // &rest" instead). Pins the array's declaration-order binding
        // structurally so a reorder fails HERE at each element rather
        // than only at consumer sites downstream.
        assert_eq!(
            MacroParams::LAMBDA_LIST_KEYWORDS[0],
            MacroParams::REST_MARKER,
            "LAMBDA_LIST_KEYWORDS[0] drifted from REST_MARKER — the ALL \
             array's declaration-order binding to the per-role `pub \
             const` broke at the rest-slot marker slot.",
        );
        assert_eq!(
            MacroParams::LAMBDA_LIST_KEYWORDS[1],
            MacroParams::OPTIONAL_MARKER,
            "LAMBDA_LIST_KEYWORDS[1] drifted from OPTIONAL_MARKER — the \
             ALL array's declaration-order binding to the per-role \
             `pub const` broke at the optional-section marker slot.",
        );
    }

    #[test]
    fn macro_params_every_lambda_list_keyword_prefixed_by_lambda_list_keyword_lead() {
        // FAMILY-WIDE STRUCTURAL ROUND-TRIP PIN: every element of the ALL
        // array MUST start with the canonical LEAD byte. Where the two
        // per-marker `_prefixed_by_lambda_list_keyword_lead` pins each
        // named ONE marker inline as a duplicate 3-line
        // `assert!(A.starts_with(LEAD), ...)` shape, this family-wide
        // sweep routes the SAME contract through the closed-set ALL
        // array — a future third marker (`&key`, `&aux`, `&body`)
        // extends the array AND is automatically covered by this sweep
        // without adding a third `_prefixed_by_...` per-marker pin. The
        // per-marker pins stay as fine-grained fail-loud sites; this
        // pin is the algebra-wide closure the family-extending refactor
        // routes through.
        for m in MacroParams::LAMBDA_LIST_KEYWORDS {
            assert!(
                m.starts_with(MacroParams::LAMBDA_LIST_KEYWORD_LEAD),
                "LAMBDA_LIST_KEYWORDS element `{m}` does NOT start with \
                 LAMBDA_LIST_KEYWORD_LEAD `{lead:?}` — the CL lambda- \
                 list-keyword family's structural round-trip contract \
                 no longer binds every marker to its shared LEAD byte.",
                lead = MacroParams::LAMBDA_LIST_KEYWORD_LEAD,
            );
        }
    }

    #[test]
    fn macro_params_lambda_list_keywords_pairwise_distinct() {
        // FAMILY-WIDE PAIRWISE DISJOINTNESS PIN: every distinct index pair
        // `(i, j)` in the ALL array yields distinct markers. Where the
        // pre-lift `_rest_and_optional_markers_pairwise_disjoint` pin
        // named the TWO markers as a hand-rolled `assert_ne!` pair, this
        // family-wide sweep routes the SAME contract through the closed-
        // set ALL array so a future third marker automatically extends
        // the sweep to `(3 * 2) / 2 == 3` distinct pairs without re-
        // deriving per-marker `assert_ne!` calls. The pre-lift pin
        // stays as the fine-grained fail-loud site; this pin is the
        // family-wide closure the algebra-extending refactor routes
        // through.
        for (i, a) in MacroParams::LAMBDA_LIST_KEYWORDS.iter().enumerate() {
            for (j, b) in MacroParams::LAMBDA_LIST_KEYWORDS.iter().enumerate() {
                if i == j {
                    continue;
                }
                assert_ne!(
                    a, b,
                    "LAMBDA_LIST_KEYWORDS[{i}] `{a}` collides with \
                     LAMBDA_LIST_KEYWORDS[{j}] `{b}` — the CL lambda- \
                     list-keyword family's pairwise disjointness \
                     contract no longer binds distinct index pairs \
                     to distinct markers.",
                );
            }
        }
    }

    #[test]
    fn macro_params_is_lambda_list_keyword_accepts_every_marker() {
        // ACCEPTANCE-SIDE MEMBERSHIP PIN: every element of the ALL array
        // MUST classify as `true` through the typed membership gate. The
        // gate is defined as `LAMBDA_LIST_KEYWORDS.contains(&s)`, so this
        // pin is the structural closure binding the gate's return value
        // to the ALL array's element set. A regression that specialises
        // the gate to a subset of the array (e.g. a `matches!(s,
        // "&rest")` inline that silently drops the `&optional` branch)
        // fails HERE at the ALL sweep. Sibling-shape acceptance sweep to
        // the closed-set `ClosedSet::parse_label` roundtrip pin — every
        // element of `Self::ALL` decodes through the projection back to
        // itself.
        for m in MacroParams::LAMBDA_LIST_KEYWORDS {
            assert!(
                MacroParams::is_lambda_list_keyword(m),
                "is_lambda_list_keyword rejected LAMBDA_LIST_KEYWORDS \
                 element `{m}` — the closed-set membership gate's \
                 acceptance side drifted from the ALL array.",
            );
        }
    }

    #[test]
    fn macro_params_is_lambda_list_keyword_rejects_bare_lead_byte() {
        // REJECTION-SIDE MEMBERSHIP PIN (LEAD byte alone): the bare LEAD
        // byte `"&"` MUST classify as `false`. A future Clojure-compat
        // port might land a bare `&` marker — but until such an
        // extension explicitly lands on the ALL array, the substrate
        // MUST NOT silently classify the LEAD byte alone as a
        // recognised CL lambda-list keyword. Pins the gate's
        // rejection-side contract against a plausible future
        // near-miss extension.
        let bare_lead: String = MacroParams::LAMBDA_LIST_KEYWORD_LEAD.to_string();
        assert!(
            !MacroParams::is_lambda_list_keyword(&bare_lead),
            "is_lambda_list_keyword accepted the bare LEAD byte `{bare_lead}` — \
             the closed-set membership gate silently classifies the bare `&` \
             LEAD byte as a recognised CL lambda-list keyword despite the ALL \
             array containing only the two suffixed markers.",
        );
    }

    #[test]
    fn macro_params_is_lambda_list_keyword_rejects_unrecognised_ampersand_prefixed_names() {
        // REJECTION-SIDE MEMBERSHIP PIN (unrecognised near-misses): the
        // three plausible future CL lambda-list keywords (`&key` for
        // keyword-args, `&aux` for auxiliaries, `&body` for the
        // docstring-carrying tail of `defmacro` bodies) MUST classify as
        // `false` UNTIL they explicitly land on the ALL array. Pins the
        // gate's conservative rejection contract — the closed-set
        // membership gate is not a "starts with `&`" heuristic; it is a
        // typed enumeration over the currently-recognised markers. A
        // regression that silently loosens the gate to a `starts_with`
        // check (dropping the closed-set discipline) fails HERE.
        for candidate in ["&key", "&aux", "&body"] {
            assert!(
                !MacroParams::is_lambda_list_keyword(candidate),
                "is_lambda_list_keyword accepted the unrecognised \
                 `&`-prefixed name `{candidate}` — the closed-set \
                 membership gate silently loosened its acceptance beyond \
                 the two markers the ALL array names today.",
            );
        }
    }

    #[test]
    fn macro_params_is_lambda_list_keyword_rejects_bare_identifiers_and_empty_string() {
        // REJECTION-SIDE MEMBERSHIP PIN (bare identifiers + empty): a
        // bare identifier (`"a"`, `"xs"`, `"foo"`) and the empty string
        // MUST classify as `false`. These are the shapes the parser's
        // bare-symbol dispatch cascade sees at `parse_params` when
        // walking a param list, so pinning them here binds the
        // membership gate's rejection contract to the parser's most
        // common non-marker input shapes.
        for candidate in ["a", "xs", "foo", ""] {
            assert!(
                !MacroParams::is_lambda_list_keyword(candidate),
                "is_lambda_list_keyword accepted the bare non-marker \
                 input `{candidate}` — the closed-set membership gate's \
                 rejection side no longer excludes bare identifiers \
                 the parser routes through the fall-through cascade.",
            );
        }
    }

    // ── fixed_arity: the rest-start / rest-less max-arity primitive ─────
    //
    // `fixed_arity()` lifts the `self.required.len() + self.optional.len()`
    // arithmetic that recurred three times inside `MacroParams::bind` — at
    // the `Vec::with_capacity` site (where it adds `usize::from(rest.is_some())`
    // to get the bound-values count), at the `rest_start` site (inside the
    // `if let Some(rest)` branch), and at the `expected` site (inside the
    // rest-less `else`). The latter two sites live in mutually-exclusive
    // branches yet name ONE structural concept; lifting them collapses the
    // arithmetic to one named primitive. These tests pin the primitive's
    // contract directly; the existing `bind_*` tests are the path-uniformity
    // guards proving `bind`'s sites route through the same value without
    // behavior drift.
    //
    // Fail-before/pass-after: every test below references
    // `params.fixed_arity()`, which simply did not exist on `MacroParams`
    // before this lift — every assertion's `expect: ___ == params.fixed_arity()`
    // line was a compile-time error against the prior surface.

    #[test]
    fn fixed_arity_is_zero_for_the_empty_param_list() {
        // `()` — a nullary macro has fixed arity 0, the rest-less binder
        // boundary at which the FIRST surplus arg already rejects.
        let params = MacroParams::default();
        assert_eq!(params.fixed_arity(), 0);
    }

    #[test]
    fn fixed_arity_counts_required_only_when_no_optional_or_rest() {
        // `(a b c)` — three required, no optional, no rest. fixed_arity is
        // exactly the required length.
        let params = MacroParams {
            required: vec!["a".into(), "b".into(), "c".into()],
            optional: Vec::new(),
            rest: None,
        };
        assert_eq!(params.fixed_arity(), 3);
    }

    #[test]
    fn fixed_arity_counts_optional_only_when_no_required_or_rest() {
        // `(&optional x y)` — two optional, no required. fixed_arity is the
        // optional length; the optional section participates in the fixed
        // run because supplied positional args bind to it.
        let params = MacroParams {
            required: Vec::new(),
            optional: vec![OptionalParam::bare("x"), OptionalParam::bare("y")],
            rest: None,
        };
        assert_eq!(params.fixed_arity(), 2);
    }

    #[test]
    fn fixed_arity_sums_required_and_optional_in_canonical_lambda_order() {
        // `(a b &optional c d e)` — two required + three optional, no rest.
        // fixed_arity is 5: the maximum arity a rest-less call can supply.
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: vec![
                OptionalParam::bare("c"),
                OptionalParam::bare("d"),
                OptionalParam::bare("e"),
            ],
            rest: None,
        };
        assert_eq!(params.fixed_arity(), 5);
    }

    #[test]
    fn fixed_arity_ignores_rest_slot_by_construction() {
        // `(a &optional b &rest r)` and `(a &optional b)` — identical fixed
        // arity (2). The `&rest` slot has NO maximum and is structurally
        // excluded from `fixed_arity`. Naming this invariant pins that a
        // regression that drifts the primitive to "required + optional +
        // rest.is_some() as usize" fails loudly here — that drift would
        // collapse `fixed_arity` into `names().len()`, losing the rest-start
        // vs total-bound-values distinction the typed shape relies on.
        let with_rest = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: Some("r".into()),
        };
        let without_rest = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: None,
        };
        assert_eq!(with_rest.fixed_arity(), without_rest.fixed_arity());
        assert_eq!(with_rest.fixed_arity(), 2);
    }

    #[test]
    fn fixed_arity_is_the_rest_start_index_in_names_when_rest_present() {
        // When `rest` is `Some`, `names()[fixed_arity()]` IS the rest name
        // — the rest-start reading of the primitive. Same arithmetic the
        // bytecode index would hit (`Subst(fixed_arity())` resolves to the
        // rest-bound `Sexp::List`).
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: vec![OptionalParam::bare("c")],
            rest: Some("r".into()),
        };
        assert_eq!(params.fixed_arity(), 3);
        assert_eq!(params.names()[params.fixed_arity()], "r");
    }

    #[test]
    fn fixed_arity_equals_names_length_when_rest_is_absent() {
        // When `rest` is `None`, `names().len() == fixed_arity()` — there
        // is no rest-name slot to extend the flat run past the fixed
        // boundary. Pins the structural identity
        // `names().len() == fixed_arity() + usize::from(rest.is_some())`
        // for the rest-less case; the rest-present case is pinned by the
        // sibling test above (where the boundary is the rest-name index,
        // i.e. one short of `names().len()`).
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: vec![OptionalParam::bare("c")],
            rest: None,
        };
        assert_eq!(params.names().len(), params.fixed_arity());
        assert_eq!(params.names().len(), 3);
    }

    #[test]
    fn fixed_arity_is_the_rest_less_surplus_rejection_boundary() {
        // The `expected` field of `TooManyMacroArgs` IS `fixed_arity()` —
        // the rest-less binder rejects iff `args.len() > fixed_arity()`.
        // This pin is the path-uniformity guard binding the typed primitive
        // to the binder's rejection contract: a regression that drifts
        // `bind`'s `expected` arithmetic from `fixed_arity()` would silently
        // surface a different boundary in the diagnostic without touching
        // the primitive — and this assertion fails loudly. Mirror of the
        // sibling rest-less surplus pin (`bind_rest_less_params_reject_
        // surplus_args`); this test pins WHAT the `expected` slot's value
        // structurally IS, that pin checks the variant SHAPE.
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: vec![OptionalParam::bare("c")],
            rest: None,
        };
        assert_eq!(params.fixed_arity(), 3);
        let err = params
            .bind(
                "m",
                &[Sexp::int(1), Sexp::int(2), Sexp::int(3), Sexp::int(4)],
            )
            .expect_err("4 args against fixed_arity 3 must reject");
        match err {
            LispError::TooManyMacroArgs {
                expected,
                got,
                macro_name,
            } => {
                assert_eq!(expected, params.fixed_arity());
                assert_eq!(got, 4);
                assert_eq!(macro_name, "m");
            }
            other => panic!("expected TooManyMacroArgs, got {other:?}"),
        }
    }

    #[test]
    fn fixed_arity_is_the_rest_start_index_consumed_by_bind() {
        // When `rest` is `Some`, `bind` collects `args[fixed_arity()..]`
        // into the rest's `Sexp::List`. Pin that the rest list contents
        // are exactly the suffix beginning at `fixed_arity()` — the
        // primitive's rest-start reading IS the slice index the binder
        // consumes. A regression that drifts `bind`'s rest-collection
        // slice from `fixed_arity()` would surface as a misaligned rest
        // list (off-by-one in either direction) and this assertion fails
        // loudly. Sibling of `fixed_arity_is_the_rest_less_surplus_
        // rejection_boundary` on the rest-PRESENT branch.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: Some("r".into()),
        };
        assert_eq!(params.fixed_arity(), 2);
        let args = [Sexp::int(1), Sexp::int(2), Sexp::int(3), Sexp::int(4)];
        let vals = params.bind("m", &args).unwrap();
        // Bound vec: [a=1, b=2, r=(3 4)] — the rest list IS args[fixed_arity()..].
        let rest_expected: Vec<Sexp> = args[params.fixed_arity()..].to_vec();
        assert_eq!(vals.last().unwrap(), &Sexp::List(rest_expected));
    }

    #[test]
    fn bind_rest_present_at_exact_fixed_arity_yields_empty_rest_list() {
        // Exactly-saturated rest-present call: `args.len() == fixed_arity()`.
        // The rest slot collects the empty slice; bind succeeds, never
        // misaligning to an off-by-one underflow. Pin the boundary on the
        // rest-PRESENT path — the rest-less mirror is
        // `too_many_macro_args_does_not_fire_at_exact_max_arity` above.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: Some("r".into()),
        };
        assert_eq!(params.fixed_arity(), 2);
        let vals = params
            .bind("m", &[Sexp::int(1), Sexp::int(2)])
            .expect("rest-present at exact fixed_arity must bind cleanly");
        assert_eq!(vals, vec![Sexp::int(1), Sexp::int(2), Sexp::List(vec![])]);
    }

    #[test]
    fn bind_threads_required_positionally_and_collects_rest_as_list() {
        // `(a b &rest c)` bound to `1 2 3 4`: a=1, b=2, c=(3 4). The bound
        // vec is parallel to `names()`, so the rest list sits at the rest's
        // flat index.
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: Vec::new(),
            rest: Some("c".into()),
        };
        let vals = params
            .bind(
                "m",
                &[Sexp::int(1), Sexp::int(2), Sexp::int(3), Sexp::int(4)],
            )
            .unwrap();
        assert_eq!(
            vals,
            vec![
                Sexp::int(1),
                Sexp::int(2),
                Sexp::List(vec![Sexp::int(3), Sexp::int(4)]),
            ]
        );
    }

    #[test]
    fn bind_supplied_optional_takes_its_positional_arg() {
        // `(a &optional b)` bound to `1 2`: a=1, b=2. A supplied optional
        // behaves exactly like a positional — only its ABSENCE differs.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: None,
        };
        let vals = params.bind("m", &[Sexp::int(1), Sexp::int(2)]).unwrap();
        assert_eq!(vals, vec![Sexp::int(1), Sexp::int(2)]);
    }

    #[test]
    fn bind_unsupplied_optional_defaults_to_nil() {
        // `(a &optional b c)` bound to just `1`: a=1, then b and c run out of
        // args and bind to `Sexp::Nil` — CL's default for an `&optional` with
        // no supplied default-form. The bound vec is still parallel to
        // `names()`, so the template's `,b` / `,c` resolve to nil, not a
        // missing-arg error.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b"), OptionalParam::bare("c")],
            rest: None,
        };
        let vals = params.bind("m", &[Sexp::int(1)]).unwrap();
        assert_eq!(vals, vec![Sexp::int(1), Sexp::Nil, Sexp::Nil]);
    }

    #[test]
    fn bind_rest_collects_args_beyond_required_and_optional() {
        // `(a &optional b &rest c)` bound to `1 2 3 4`: a=1, b=2 (supplied),
        // c=(3 4). The rest starts AFTER the required+optional run, so the
        // optional's supplied arg is not swept into the rest.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: Some("c".into()),
        };
        let vals = params
            .bind(
                "m",
                &[Sexp::int(1), Sexp::int(2), Sexp::int(3), Sexp::int(4)],
            )
            .unwrap();
        assert_eq!(
            vals,
            vec![
                Sexp::int(1),
                Sexp::int(2),
                Sexp::List(vec![Sexp::int(3), Sexp::int(4)]),
            ]
        );
    }

    #[test]
    fn bind_unsupplied_optional_then_empty_rest() {
        // `(a &optional b &rest c)` bound to just `1`: a=1, b=nil (absent),
        // c=() (nothing left). Both the optional default AND the empty-rest
        // contract hold in the same bind.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: Some("c".into()),
        };
        let vals = params.bind("m", &[Sexp::int(1)]).unwrap();
        assert_eq!(vals, vec![Sexp::int(1), Sexp::Nil, Sexp::List(vec![])]);
    }

    #[test]
    fn bind_rest_with_no_remaining_args_is_the_empty_list() {
        // Exactly-saturated required args + a rest that captures nothing →
        // the rest binds to the empty list, never errors. Mirrors the
        // splice contract `,@()` contributes nothing.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: Vec::new(),
            rest: Some("c".into()),
        };
        let vals = params.bind("m", &[Sexp::int(1)]).unwrap();
        assert_eq!(vals, vec![Sexp::int(1), Sexp::List(vec![])]);
    }

    #[test]
    fn bind_missing_required_errors_before_any_rest_collection() {
        // A required name with no arg at its position is a
        // `MissingMacroArg` — the gate fires during the required walk,
        // before the rest is ever collected.
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: Vec::new(),
            rest: Some("c".into()),
        };
        let err = params
            .bind("m", &[Sexp::int(1)])
            .expect_err("missing required `b` must error");
        assert!(
            matches!(err, LispError::MissingMacroArg { .. }),
            "expected MissingMacroArg, got: {err:?}"
        );
    }

    #[test]
    fn bind_missing_required_errors_even_with_optional_present() {
        // An absent REQUIRED arg errors even when the param list has an
        // optional section: the required walk fires `MissingMacroArg` before
        // the optional arm (which would otherwise default to nil) is reached.
        // Required absence is an error; optional absence is a nil default.
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: vec![OptionalParam::bare("c")],
            rest: None,
        };
        let err = params
            .bind("m", &[Sexp::int(1)])
            .expect_err("missing required `b` must error before optional defaulting");
        assert!(
            matches!(err, LispError::MissingMacroArg { .. }),
            "expected MissingMacroArg, got: {err:?}"
        );
    }

    #[test]
    fn bind_rest_less_params_reject_surplus_args() {
        // The rest-less binder REJECTS surplus call args via the
        // structural `TooManyMacroArgs { macro_name, expected, got }`
        // rejection — the call-site mirror of `RestParamTrailingTokens`
        // (the definition-site rejection lifted at the parse_params
        // boundary). Closes the asymmetry where the typed-entry
        // macro-call-gate rejected too-few-args loudly
        // (`MissingMacroArg`) but silently truncated too-many. `expected`
        // is the rest-less binder's fixed maximum arity
        // (`required.len() + optional.len()`); `got` is the actual
        // call-site arg count.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: Vec::new(),
            rest: None,
        };
        let err = params
            .bind("m", &[Sexp::int(1), Sexp::int(2)])
            .expect_err("rest-less surplus must error");
        match err {
            LispError::TooManyMacroArgs {
                macro_name,
                expected,
                got,
            } => {
                assert_eq!(macro_name, "m");
                assert_eq!(expected, 1);
                assert_eq!(got, 2);
            }
            other => panic!("expected TooManyMacroArgs, got: {other:?}"),
        }
    }

    // ── OptionalParam: per-param default forms — `&optional (x DEFAULT)` ──
    //
    // The `&optional` section now admits both bare-symbol entries (`x`) AND
    // list-form entries (`(x DEFAULT)`). The typed `OptionalParam.default:
    // Option<Sexp>` slot makes the per-param default a FIELD on each
    // optional entry, not a discipline a sibling `Vec<Sexp>` would have had
    // to maintain in lock-step with `Vec<String>`. These tests pin: the
    // parser admits both shapes side-by-side; the four malformed list-spec
    // shapes (empty / missing-default / extra-elements / non-symbol-name)
    // are rejected via `OptionalParamMalformed` with the typed
    // `OptionalParamMalformedReason`; the binder consults the default form
    // when the arg is absent and ignores it when supplied; and the end-to-
    // end expansion agrees between the bytecode and substitute strategies
    // (invariant 2 — free middle).

    #[test]
    fn parse_params_admits_optional_list_spec_with_default() {
        // `(a &optional (b 5))` — one bare optional becomes
        // `OptionalParam { name: "b", default: Some(Int(5)) }`. The
        // surrounding `MacroParams` shape is otherwise identical.
        let params = parse_params(&read("a &optional (b 5)").unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: vec!["a".into()],
                optional: vec![OptionalParam::with_default("b", Sexp::int(5))],
                rest: None,
            }
        );
    }

    #[test]
    fn parse_params_mixes_bare_and_list_optional_specs_side_by_side() {
        // `(a &optional b (c "x") d (e 9) &rest r)` — the optional section
        // interleaves bare and list-form specs. Each lands in its own
        // `OptionalParam` entry; `names()` still yields the flat
        // required-then-optional-then-rest order.
        let params =
            parse_params(&read("a &optional b (c \"x\") d (e 9) &rest r").unwrap()).unwrap();
        assert_eq!(
            params,
            MacroParams {
                required: vec!["a".into()],
                optional: vec![
                    OptionalParam::bare("b"),
                    OptionalParam::with_default("c", Sexp::string("x")),
                    OptionalParam::bare("d"),
                    OptionalParam::with_default("e", Sexp::int(9)),
                ],
                rest: Some("r".into()),
            }
        );
        assert_eq!(params.names(), vec!["a", "b", "c", "d", "e", "r"]);
    }

    #[test]
    fn parse_params_admits_arbitrary_sexp_as_optional_default_form() {
        // `(&optional (x (list 1 2)))` — the default form is itself a list.
        // Without an evaluator, the literal Sexp is parked verbatim into
        // `default`; the binder produces it for any absent call.
        let params = parse_params(&read("&optional (x (list 1 2))").unwrap()).unwrap();
        let want_default = Sexp::List(vec![Sexp::symbol("list"), Sexp::int(1), Sexp::int(2)]);
        assert_eq!(
            params,
            MacroParams {
                required: Vec::new(),
                optional: vec![OptionalParam::with_default("x", want_default)],
                rest: None,
            }
        );
    }

    #[test]
    fn parse_params_rejects_empty_list_optional_spec() {
        // `(&optional ())` — a zero-element list is the empty-list rejection.
        // Without the gate the loop would `as_symbol()` on a `Sexp::List` and
        // fall through to `NonSymbolParam`, which mis-classifies the failure
        // (this is a malformed DEFAULT-FORM spec, not a "param must be a
        // symbol" rejection).
        let err = parse_params(&read("&optional ()").unwrap())
            .expect_err("empty list optional spec must error");
        assert!(
            matches!(
                err,
                LispError::OptionalParamMalformed {
                    position: 1,
                    reason: crate::error::OptionalParamMalformedReason::EmptyList,
                    ..
                }
            ),
            "expected OptionalParamMalformed{{EmptyList, position: 1}}, got: {err:?}"
        );
    }

    #[test]
    fn parse_params_rejects_one_element_optional_list_as_missing_default() {
        // `(&optional (x))` — a one-element list. REJECTED with reason
        // `MissingDefault` rather than reinterpreted as `&optional x`, because
        // a parenthesized single-element spec is structurally ambiguous and
        // the bare-symbol form `x` IS the canonical "no default" shape.
        let err = parse_params(&read("&optional (x)").unwrap())
            .expect_err("one-element list optional spec must error");
        assert!(
            matches!(
                err,
                LispError::OptionalParamMalformed {
                    position: 1,
                    reason: crate::error::OptionalParamMalformedReason::MissingDefault,
                    ..
                }
            ),
            "expected OptionalParamMalformed{{MissingDefault, position: 1}}, got: {err:?}"
        );
    }

    #[test]
    fn parse_params_rejects_three_or_more_element_optional_list_as_extra_elements() {
        // `(&optional (x 5 6))` — a three-element list. CL's `(name default
        // supplied-p)` shape is not yet supported (no evaluator → no
        // supplied-p variable binding), so the third element is structurally
        // surplus. REJECTED with reason `ExtraElements{length: 3}`.
        let err = parse_params(&read("&optional (x 5 6)").unwrap())
            .expect_err("three-element list optional spec must error");
        assert!(
            matches!(
                err,
                LispError::OptionalParamMalformed {
                    position: 1,
                    reason: crate::error::OptionalParamMalformedReason::ExtraElements { length: 3 },
                    ..
                }
            ),
            "expected OptionalParamMalformed{{ExtraElements{{3}}, position: 1}}, got: {err:?}"
        );
    }

    #[test]
    fn parse_params_rejects_non_symbol_name_in_optional_list_spec() {
        // `(&optional (5 default))` — the name slot must be a symbol; a
        // numeric literal is REJECTED with reason `NonSymbolName`. Without
        // this branch the gate would silently populate
        // `OptionalParam.name` from a stringified non-symbol value (`"5"`),
        // breaking the invariant that param names are symbols.
        let err = parse_params(&read("&optional (5 default)").unwrap())
            .expect_err("non-symbol-name optional spec must error");
        assert!(
            matches!(
                err,
                LispError::OptionalParamMalformed {
                    position: 1,
                    reason: crate::error::OptionalParamMalformedReason::NonSymbolName,
                    ..
                }
            ),
            "expected OptionalParamMalformed{{NonSymbolName, position: 1}}, got: {err:?}"
        );
    }

    #[test]
    fn parse_params_rejects_list_in_required_section_as_non_symbol_param() {
        // `((a 5))` — a list in the REQUIRED section is NOT a default-form
        // spec; default forms are an optional-section affordance. The gate
        // must fall through to `NonSymbolParam` (parity with the prior
        // behavior on lists in the required section), not silently admit
        // the list as a default-form spec.
        let err =
            parse_params(&read("(a 5)").unwrap()).expect_err("list in required section must error");
        assert!(
            matches!(err, LispError::NonSymbolParam { position: 0, .. }),
            "expected NonSymbolParam{{position: 0}}, got: {err:?}"
        );
    }

    #[test]
    fn bind_unsupplied_optional_with_default_takes_the_default() {
        // `(a &optional (b 5))` bound to just `1`: a=1, b=5 (the declared
        // default), not nil. The default form is consulted ONLY when the
        // call ran out of args.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::with_default("b", Sexp::int(5))],
            rest: None,
        };
        let vals = params.bind("m", &[Sexp::int(1)]).unwrap();
        assert_eq!(vals, vec![Sexp::int(1), Sexp::int(5)]);
    }

    #[test]
    fn bind_supplied_optional_with_default_takes_the_arg_not_the_default() {
        // `(&optional (b 5))` bound to `42`: b=42, NOT the default. A
        // supplied optional ALWAYS takes its arg; the default is the
        // absence-only fallback. Pins that the default form does not
        // shadow a supplied call arg.
        let params = MacroParams {
            required: Vec::new(),
            optional: vec![OptionalParam::with_default("b", Sexp::int(5))],
            rest: None,
        };
        let vals = params.bind("m", &[Sexp::int(42)]).unwrap();
        assert_eq!(vals, vec![Sexp::int(42)]);
    }

    #[test]
    fn bind_mixes_supplied_unsupplied_default_and_nil_floor() {
        // `(a &optional (b 5) c (d "z"))` bound to just `1`: a=1, b=5
        // (default), c=nil (bare floor), d="z" (default). The three
        // absence cases coexist in one bind: per-default fill, nil floor,
        // and a tail with a literal-string default.
        let params = MacroParams {
            required: vec!["a".into()],
            optional: vec![
                OptionalParam::with_default("b", Sexp::int(5)),
                OptionalParam::bare("c"),
                OptionalParam::with_default("d", Sexp::string("z")),
            ],
            rest: None,
        };
        let vals = params.bind("m", &[Sexp::int(1)]).unwrap();
        assert_eq!(
            vals,
            vec![Sexp::int(1), Sexp::int(5), Sexp::Nil, Sexp::string("z")]
        );
    }

    // ── OptionalParam::resolved_default: the absent-call binder accessor ──
    //
    // `resolved_default` lifts the `param.default.clone().unwrap_or(Sexp::Nil)`
    // two-arm fallback that previously inlined at `MacroParams::bind`'s
    // optional arm into ONE named accessor on the typed `OptionalParam`.
    // The constructor pair `bare` / `with_default` defines the typed
    // shapes of the `default` slot; this accessor names the symmetric
    // bound-value projection both shapes yield at the absence boundary.
    // Tests pin: (a) `bare(name).resolved_default()` is the `Sexp::Nil`
    // no-default floor; (b) `with_default(name, d).resolved_default()` is
    // `d.clone()`; (c) the projection is `Clone`-stable across repeated
    // calls (the typed `default` field is not consumed); (d) path-
    // uniformity at the binder — `bind`'s optional arm routes through
    // `resolved_default` for both shapes; (e) end-to-end through both
    // expansion strategies, the absent-call binding agrees.

    #[test]
    fn resolved_default_is_nil_for_bare_optional() {
        // `OptionalParam::bare(name).default` is `None`, so
        // `resolved_default()` projects to `Sexp::Nil` — the CL
        // `&optional` no-default-form floor. Fail-before/pass-after: this
        // assert is meaningless pre-lift because the helper does not
        // exist; post-lift it pins the typed accessor's `Sexp::Nil` arm
        // at the named primitive. Sibling of `bare` itself: the
        // constructor defines the shape (`default: None`); the accessor
        // names the bound-value projection of that shape.
        let p = OptionalParam::bare("x");
        assert_eq!(p.resolved_default(), Sexp::Nil);
    }

    #[test]
    fn resolved_default_clones_declared_default_for_with_default_optional() {
        // `OptionalParam::with_default(name, d).default` is `Some(d)`, so
        // `resolved_default()` projects to `d.clone()` — the declared
        // default form. Sibling of the bare-floor pin: the closed-set
        // `default: Option<Sexp>` slot's two shapes correspond 1:1 with
        // the two arms of `resolved_default`. Pins the closed-set
        // exhaustive coverage of `Option<Sexp>` × `{Some, None}`.
        let p = OptionalParam::with_default("x", Sexp::int(5));
        assert_eq!(p.resolved_default(), Sexp::int(5));
    }

    #[test]
    fn resolved_default_clones_arbitrary_sexp_default_form() {
        // The declared default can be any `Sexp` — a literal list, a
        // keyword, a string, a quasi-quoted form — because v0 has no
        // evaluator and the typed slot parks the literal verbatim. Pin
        // that `resolved_default()` is faithful to the parked literal
        // regardless of shape: a regression that special-cases an arm
        // (e.g., projecting `Sexp::List(_)` to `Sexp::Nil`, or "normalizing"
        // a `Sexp::Quote`) fails here. The accessor is exactly
        // `default.clone()` for the `Some` arm — no shape rewriting.
        let arbitrary = Sexp::List(vec![Sexp::symbol("list"), Sexp::int(1), Sexp::int(2)]);
        let p = OptionalParam::with_default("x", arbitrary.clone());
        assert_eq!(p.resolved_default(), arbitrary);
    }

    #[test]
    fn resolved_default_is_clone_stable_across_repeated_calls() {
        // The accessor takes `&self` and projects through `Clone`, so
        // repeated calls yield IDENTICAL values — the typed `default`
        // field is not consumed. Pins that the accessor is idempotent
        // for the same `OptionalParam`, which is the contract the binder
        // relies on across multiple `bind` invocations of the same
        // macro: every call that leaves the optional unfilled yields
        // the SAME bound value, never a partially-consumed shape. A
        // regression that converted the accessor to `self.default.take()`
        // (consuming the field) would still type-check at the call site
        // but would silently desync repeated absent-call bindings; this
        // test catches that drift.
        let p = OptionalParam::with_default("x", Sexp::string("hi"));
        let first = p.resolved_default();
        let second = p.resolved_default();
        assert_eq!(first, second);
        assert_eq!(first, Sexp::string("hi"));
    }

    #[test]
    fn resolved_default_is_the_binders_absent_optional_projection() {
        // Path-uniformity pin at the binder boundary: `MacroParams::bind`'s
        // optional arm consults `param.resolved_default()` for any
        // absent slot. Two-arm coverage: a bare optional (`b`) binds to
        // `Sexp::Nil` via the `None` arm; a with-default optional
        // (`(c 5)`) binds to `Sexp::int(5)` via the `Some` arm. The
        // single bind call exercises both arms in one walk, and the
        // bound values vec is parallel to `names()` so position
        // checking pins the arm-to-slot mapping. A regression that
        // re-inlines the two-arm fallback at the binder, drifting it
        // independently from the accessor, would still type-check but
        // a future shape change to `resolved_default` (e.g., adding a
        // typed `&supplied-p` companion slot) would silently desync
        // the binder from the accessor — this test catches that drift.
        let params = MacroParams {
            required: Vec::new(),
            optional: vec![
                OptionalParam::bare("b"),
                OptionalParam::with_default("c", Sexp::int(5)),
            ],
            rest: None,
        };
        // Empty args → both optionals are absent → both arms fire.
        let vals = params.bind("m", &[]).unwrap();
        assert_eq!(vals.len(), 2);
        assert_eq!(vals[0], OptionalParam::bare("b").resolved_default());
        assert_eq!(
            vals[1],
            OptionalParam::with_default("c", Sexp::int(5)).resolved_default()
        );
        // And the absolute identities pin the projection's arms:
        assert_eq!(vals[0], Sexp::Nil);
        assert_eq!(vals[1], Sexp::int(5));
    }

    #[test]
    fn resolved_default_is_path_uniform_across_bytecode_and_substitute() {
        // End-to-end path-uniformity: a macro with both an `&optional
        // (g "hi")` (with-default) and an `&optional h` (bare) param
        // expands the same way under bytecode AND substitute
        // strategies, because both strategies route through the SHARED
        // `MacroParams::bind` which now consults `resolved_default`
        // for absent slots. Pins that the accessor's contract is
        // structurally observable at the strategy boundary — a
        // regression that bifurcated the accessor's behavior between
        // the two paths (impossible, since they share `bind`) would
        // surface here.
        let src = r#"
            (defmacro greet (n &optional (g "hi") h)
              `(list ,g ,n ,h))
            (greet world)
        "#;
        let expected = vec![Sexp::List(vec![
            Sexp::symbol("list"),
            Sexp::string("hi"),
            Sexp::symbol("world"),
            Sexp::Nil,
        ])];
        let bytecode = Expander::new().expand_program(read(src).unwrap()).unwrap();
        let substitute = Expander::new_substitute_only()
            .expand_program(read(src).unwrap())
            .unwrap();
        assert_eq!(
            bytecode, expected,
            "bytecode resolved_default expansion drifted"
        );
        assert_eq!(
            substitute, expected,
            "substitute resolved_default expansion drifted"
        );
        assert_eq!(
            bytecode, substitute,
            "the two strategies disagree on resolved_default expansion"
        );
    }

    #[test]
    fn resolved_default_supplied_optional_does_not_consult_accessor() {
        // A SUPPLIED optional binds to its CALL ARG, never to the
        // accessor's projection. Pins the contract: `resolved_default`
        // is the absence-only fallback; a present arg shadows the
        // accessor at the binder. Sibling negative control to
        // `resolved_default_is_the_binders_absent_optional_projection`:
        // that test exercises the absence arm at every slot; this test
        // exercises the presence arm at every slot and proves the
        // accessor's `Sexp::int(5)` projection is NOT consulted when
        // the optional is supplied with `Sexp::int(42)`. A regression
        // that wired the binder to always consult the accessor (the
        // wrong direction — the default would shadow supplied args) is
        // caught here.
        let params = MacroParams {
            required: Vec::new(),
            optional: vec![OptionalParam::with_default("b", Sexp::int(5))],
            rest: None,
        };
        let vals = params.bind("m", &[Sexp::int(42)]).unwrap();
        assert_eq!(vals, vec![Sexp::int(42)]);
        // And the accessor's would-be projection IS NOT the bound value:
        let p = OptionalParam::with_default("b", Sexp::int(5));
        assert_ne!(vals[0], p.resolved_default());
    }

    #[test]
    fn optional_default_macro_expands_end_to_end_under_both_strategies() {
        // The end-to-end path: a macro with `&optional (g "hi")` expands to
        // the default literal when unsupplied, and to the supplied arg when
        // present. Both the bytecode and substitute strategies must agree
        // (invariant 2 — free middle); they share `MacroParams::bind`, so
        // the default arm lands once in `bind` and both strategies inherit
        // it unable to drift. This is the test the prior run (611a682)
        // signposted as the next-change-that-benefits.
        let src = r#"
            (defmacro greet (n &optional (g "hi"))
              `(list ,g ,n))
            (greet world)
            (greet world there)
        "#;
        let expected = vec![
            Sexp::List(vec![
                Sexp::symbol("list"),
                Sexp::string("hi"),
                Sexp::symbol("world"),
            ]),
            Sexp::List(vec![
                Sexp::symbol("list"),
                Sexp::symbol("there"),
                Sexp::symbol("world"),
            ]),
        ];
        let bytecode = Expander::new().expand_program(read(src).unwrap()).unwrap();
        let substitute = Expander::new_substitute_only()
            .expand_program(read(src).unwrap())
            .unwrap();
        assert_eq!(
            bytecode, expected,
            "bytecode optional-default expansion drifted"
        );
        assert_eq!(
            substitute, expected,
            "substitute optional-default expansion drifted"
        );
        assert_eq!(
            bytecode, substitute,
            "the two strategies disagree on optional-default expansion"
        );
    }

    #[test]
    fn optional_macro_expands_end_to_end_under_both_strategies() {
        // The end-to-end path: a macro with an `&optional` param expands
        // correctly whether the optional is supplied or defaulted, and the
        // bytecode and substitute strategies agree (invariant 2 — free
        // middle). `,b` resolves to the supplied arg when present, to
        // `Sexp::Nil` when absent (CL's `&optional` default).
        let src = "(defmacro pair (a &optional b) `(cons ,a ,b)) (pair 1 2) (pair 3)";
        // (cons 1 2) — optional supplied; (cons 3 <Nil>) — optional defaulted.
        // The defaulted slot is the canonical `Sexp::Nil`, distinct in the AST
        // from a reader-produced empty list `()` even though both Display as
        // `()`.
        let expected = vec![
            Sexp::List(vec![Sexp::symbol("cons"), Sexp::int(1), Sexp::int(2)]),
            Sexp::List(vec![Sexp::symbol("cons"), Sexp::int(3), Sexp::Nil]),
        ];
        let bytecode = Expander::new().expand_program(read(src).unwrap()).unwrap();
        let substitute = Expander::new_substitute_only()
            .expand_program(read(src).unwrap())
            .unwrap();
        assert_eq!(bytecode, expected, "bytecode optional expansion drifted");
        assert_eq!(
            substitute, expected,
            "substitute optional expansion drifted"
        );
        assert_eq!(
            bytecode, substitute,
            "the two strategies disagree on optional expansion"
        );
    }

    // ── MacroDef::template_body: the shared body-projection primitive ──
    //
    // `template_body` lifts the `match &def.body { Sexp::Quasiquote(inner)
    // => inner.as_ref(), other => other }` inline peel — present
    // byte-identically at the bytecode (`compile_template`) AND substitute
    // (`apply`'s fallback) path entries — into ONE named projection both
    // strategies share. The existing `compiled_template_matches_substitute
    // _path` and `expansion_layers_agree_on_output_and_cache_wins` tests
    // are the path-uniformity guards covering the SHARED-PROJECTION shape;
    // the four tests below pin the projection's contract DIRECTLY:
    // (a) a quasi-quoted body unwraps to the inner; (b) a non-quasi-quoted
    // body returns the body verbatim; (c) the borrow is rooted in the
    // body field (single-level peel); (d) the projection is the same
    // `&Sexp` both strategies route on (so a regression that drifts the
    // body-peel from one strategy to the other becomes a type-level
    // change at this helper, not a silent two-site divergence).

    #[test]
    fn template_body_unwraps_outer_quasiquote_to_inner() {
        // The canonical authoring shape: `(defmacro f (a) `(list ,a))` —
        // the reader wraps the `` ` `` form into `Sexp::Quasiquote(inner)`,
        // and `template_body` peels the outer marker. The returned `&Sexp`
        // is the inner walker-payload both expansion strategies consume.
        let inner = Sexp::List(vec![
            Sexp::symbol("list"),
            Sexp::Unquote(Box::new(Sexp::symbol("a"))),
        ]);
        let def = MacroDef {
            name: "f".into(),
            params: MacroParams::default(),
            body: Sexp::Quasiquote(Box::new(inner.clone())),
        };
        assert_eq!(def.template_body(), &inner);
    }

    #[test]
    fn template_body_returns_non_quasiquote_body_verbatim() {
        // A body authored WITHOUT the outer `` ` `` affordance — a bare
        // `Sexp::List` body — returns verbatim. The "other" arm of the
        // legacy match. Pin parity with the pre-lift code path so a
        // regression that drifts the body-peel into "always peel
        // something" (which would break literal-body macros) fails here.
        let body = Sexp::List(vec![Sexp::symbol("list"), Sexp::int(1)]);
        let def = MacroDef {
            name: "f".into(),
            params: MacroParams::default(),
            body: body.clone(),
        };
        assert_eq!(def.template_body(), &body);
        // Atom bodies too — the projection is a single-arm match, not a
        // recursive descent. A `Sexp::Atom` body is its own template payload.
        let atom_def = MacroDef {
            name: "g".into(),
            params: MacroParams::default(),
            body: Sexp::symbol("nil-template"),
        };
        assert_eq!(atom_def.template_body(), &Sexp::symbol("nil-template"));
    }

    #[test]
    fn template_body_peels_single_level_only() {
        // A nested `` ``form `` body — `Sexp::Quasiquote(Box::new(
        // Sexp::Quasiquote(...)))` — unwraps ONE outer quasi-quote and
        // returns the inner `Sexp::Quasiquote(...)` as-is. The v0 module
        // preamble declares "Nested quasi-quotes: Not yet supported"; the
        // single-level peel matches the legacy inline match's posture
        // (which only matched ONE outer `Sexp::Quasiquote(_)` arm, not a
        // recursive loop). A regression that drifts to a recursive peel
        // would project too far and the inner `Sexp::Quasiquote` marker —
        // which the substitute walker treats as an atomic leaf returned
        // verbatim (line ~830, `Sexp::Quote(_) | Sexp::Quasiquote(_)
        // => Ok(form.clone())`) — would silently disappear from the
        // expansion's emitted form. Pin the single-level contract here.
        let inner_payload = Sexp::List(vec![Sexp::symbol("list"), Sexp::int(7)]);
        let inner_qq = Sexp::Quasiquote(Box::new(inner_payload.clone()));
        let def = MacroDef {
            name: "nested".into(),
            params: MacroParams::default(),
            body: Sexp::Quasiquote(Box::new(inner_qq.clone())),
        };
        // Outer peel returns the INNER quasi-quote, NOT its inner payload.
        assert_eq!(def.template_body(), &inner_qq);
        assert_ne!(def.template_body(), &inner_payload);
    }

    #[test]
    fn template_body_returns_quote_form_verbatim_distinct_from_quasiquote() {
        // A `Sexp::Quote(_)` body — not a `Sexp::Quasiquote(_)` — returns
        // verbatim through the "other" arm. The two close-cousin shapes
        // share an outer-marker character (`'` vs `` ` ``) at the reader
        // boundary but differ semantically: a `Quote` body is a literal
        // template (no substitution semantics), a `Quasiquote` body is a
        // substitution-walker entry. A regression that conflated the two
        // — peeling Quote as if it were Quasiquote — would silently turn
        // every quoted-body macro into a template-walked macro. Pin the
        // discrimination.
        let inner = Sexp::List(vec![Sexp::symbol("opaque"), Sexp::int(42)]);
        let body = Sexp::Quote(Box::new(inner.clone()));
        let def = MacroDef {
            name: "quoted".into(),
            params: MacroParams::default(),
            body: body.clone(),
        };
        assert_eq!(def.template_body(), &body);
        // The inner is NOT what comes back — only Quasiquote-bodied macros
        // would peel to the inner.
        assert_ne!(def.template_body(), &inner);
    }

    #[test]
    fn template_body_is_the_shared_projection_both_strategies_walk() {
        // End-to-end path-uniformity at the projection boundary: a macro
        // authored with the canonical quasi-quoted body expands
        // IDENTICALLY under bytecode and substitute strategies because
        // both route their walker's body through `template_body()` — the
        // SAME `&Sexp` projection. Sibling of
        // `compiled_template_matches_substitute_path` (which observes
        // agreement on the EMITTED form); this test pins agreement on
        // the projection ENTRY: `compile_template` and the substitute
        // fallback now consume the same `&Sexp` (`def.template_body()`),
        // never a divergent inline match the two paths could regress
        // independently.
        let src = "(defmacro wrap (x) `(list ,x ,x)) (wrap 5)";
        let expected = vec![Sexp::List(vec![
            Sexp::symbol("list"),
            Sexp::int(5),
            Sexp::int(5),
        ])];
        let bytecode = Expander::new().expand_program(read(src).unwrap()).unwrap();
        let substitute = Expander::new_substitute_only()
            .expand_program(read(src).unwrap())
            .unwrap();
        assert_eq!(bytecode, expected, "bytecode body-projection drifted");
        assert_eq!(substitute, expected, "substitute body-projection drifted");
        assert_eq!(
            bytecode, substitute,
            "the two strategies disagree on the body-projection's emission"
        );
    }

    // ── Expander::expand: macro-call dispatch routes through `as_call_to_any` ──
    //
    // `expand` lifts its macro-call recognition to route through the
    // substrate's typed-decoded call decomposition: `as_call_to_any(|h|
    // self.macros.get(h))` answers "is this form an invocation of any
    // registered macro?" in ONE structural query on the Sexp algebra,
    // and a HashMap-backed lookup as its classifier. Sibling consumer to
    // `macro_def_from` (the typed-macro-definition dispatcher already
    // routing through `as_call_to_any(MacroDefHead::from_keyword)` with
    // a closed-set enum classifier). With both in place, BOTH dispatch
    // sites in the macro expander project through the SAME family
    // primitive — each binding the classifier that fits its candidate
    // set. The tests below pin the consumer's path-uniformity contract
    // at the new boundary: a hand-rolled `as_call_to_any(|h| macros.get
    // (h))` dispatch observes the SAME `(def, args)` decomposition the
    // `Expander::expand` consumer routes through.

    #[test]
    fn expand_routes_macro_call_dispatch_observably_through_as_call_to_any() {
        // Structural identity: on a registered-macro call, the consumer's
        // expansion is observably equivalent to: classify the form via
        // `as_call_to_any(|h| macros.get(h))` → some `(def, args)` →
        // apply the def to args. Pin path-uniformity: a hand-rolled
        // `as_call_to_any` lookup against the same registry the expander
        // walks produces the SAME `MacroDef` reference for the SAME
        // input form. A regression that drifts the consumer back to an
        // inline `as_list + as_call + macros.get` chain (which would
        // fragment the family adoption) is caught structurally — the
        // hand-rolled `as_call_to_any` and the consumer's dispatch must
        // observe the same decomposition.
        let mut e = Expander::new();
        e.expand_program(read("(defmacro wrap (x) `(list ,x ,x))").unwrap())
            .unwrap();
        let call_form = parse("(wrap 42)");

        // Hand-rolled family-primitive lookup mirrors the lifted consumer.
        let (def_via_family, args_via_family) = call_form
            .as_call_to_any(|h| e.macros.get(h))
            .expect("registered macro call must decompose via as_call_to_any");
        assert_eq!(def_via_family.name, "wrap");
        assert_eq!(args_via_family, &[Sexp::int(42)]);

        // Consumer's expand observes the SAME decomposition: the expanded
        // form is `(list 42 42)`, derived from the SAME def + args the
        // hand-rolled lookup found. Path-uniform with the family
        // primitive at the dispatch boundary.
        let expanded = e.expand(&call_form).unwrap();
        assert_eq!(
            expanded,
            Sexp::List(vec![Sexp::symbol("list"), Sexp::int(42), Sexp::int(42)])
        );
    }

    #[test]
    fn expand_skips_non_macro_call_into_children_walk_via_family_primitive_none() {
        // Path-uniformity for the non-registered-head path: `as_call_to_any
        // (|h| macros.get(h))` returns `None` for a call whose head ISN'T
        // a registered macro, and the consumer falls through to the
        // children-walk (which expands any nested macro calls). Pin
        // both halves: the hand-rolled lookup returns `None`, AND the
        // consumer's expand walks into the children. A regression that
        // accidentally short-circuits the children-walk for non-macro
        // calls (e.g. by treating `as_call_to_any` = `None` as
        // "non-expandable" globally) would fail here.
        let mut e = Expander::new();
        e.expand_program(read("(defmacro wrap (x) `(list ,x ,x))").unwrap())
            .unwrap();
        let outer = parse("(foo (wrap 5))");

        // Hand-rolled family-primitive lookup rejects the outer head.
        assert!(outer.as_call_to_any(|h| e.macros.get(h)).is_none());

        // Consumer walks children — the inner `(wrap 5)` IS a macro call
        // and expands to `(list 5 5)`; the outer `foo` head is preserved.
        let expanded = e.expand(&outer).unwrap();
        assert_eq!(
            expanded,
            Sexp::List(vec![
                Sexp::symbol("foo"),
                Sexp::List(vec![Sexp::symbol("list"), Sexp::int(5), Sexp::int(5)]),
            ])
        );
    }

    #[test]
    fn expand_non_call_shapes_route_past_family_primitive_into_fallthrough_clone() {
        // Path-uniformity for the non-call path: every shape `as_call`
        // rejects (atoms across all 6 kinds, Nil, Quote-family wrappers)
        // ALSO routes past `as_call_to_any` into the `as_list()`
        // fallthrough, where the not-a-list arm returns `form.clone()`
        // verbatim. Pin both halves: the hand-rolled lookup rejects
        // every non-call shape regardless of decoder, AND the consumer
        // preserves each shape unchanged. A regression that drifts the
        // consumer's dispatch order (e.g. checking `as_list()` BEFORE
        // `as_call_to_any` in a way that mis-handles Quote-family
        // wrappers) would fail here.
        let e = Expander::new();
        let shapes = [
            Sexp::symbol("foo"),
            Sexp::int(5),
            Sexp::keyword("k"),
            Sexp::string("s"),
            Sexp::boolean(true),
            Sexp::float(1.5),
            Sexp::Nil,
            Sexp::Quote(Box::new(Sexp::symbol("x"))),
            Sexp::Quasiquote(Box::new(Sexp::symbol("x"))),
            Sexp::Unquote(Box::new(Sexp::symbol("x"))),
            Sexp::UnquoteSplice(Box::new(Sexp::symbol("x"))),
        ];
        for s in &shapes {
            // Hand-rolled family-primitive lookup rejects non-call shapes
            // even for a promiscuous decoder — the call-shape gate fires
            // BEFORE the decoder runs.
            assert!(
                s.as_call_to_any(|_h: &str| Some(0_u8)).is_none(),
                "non-call shape must yield None for as_call_to_any: {s}"
            );
            // Consumer preserves the shape verbatim — the not-a-list
            // arm at the fallthrough returns `form.clone()`.
            assert_eq!(
                e.expand(s).unwrap(),
                s.clone(),
                "non-call shape must round-trip unchanged through expand: {s}"
            );
        }
    }

    #[test]
    fn expand_empty_list_routes_past_family_primitive_into_children_walk() {
        // The empty list `()` has no operator and no children. Pin that
        // `as_call_to_any` rejects it (no head to feed the decoder), the
        // consumer falls through to `as_list()` which returns `Some(&[])`,
        // and the children-walk emits `Sexp::List(vec![])` (an empty
        // list, not `form.clone()` of `Sexp::List(vec![])` — both happen
        // to be observationally identical, but the path is the
        // children-walk arm, NOT the not-a-list arm). Path-uniformity
        // gate for the singleton-list edge case the `compile_named_from_
        // forms` rejection chain relies on `as_call_to(KEYWORD)` to yield
        // `Some(&[])` for — same posture, different family member.
        let e = Expander::new();
        let empty = Sexp::List(vec![]);

        // Hand-rolled family-primitive lookup rejects the empty list.
        assert!(empty.as_call_to_any(|_h: &str| Some(())).is_none());

        // Consumer walks children (zero of them) — output is the empty
        // list, same as input.
        assert_eq!(e.expand(&empty).unwrap(), Sexp::List(vec![]));
    }

    // ── Expander::expand_and_collect_calls_to: program-level walk ───────
    //
    // `expand_and_collect_calls_to(forms, keyword, project)` composes the
    // expander's program-level expansion (`expand_program`) with the
    // substrate's slice-side typed-keyword projection (`iter_calls_to`)
    // and a caller-supplied per-form mapper into ONE method on the
    // `Expander` surface. Both `compile_typed::<T>` and
    // `compile_named_from_forms::<T>` (compile.rs) route through it; the
    // tests below pin its contract directly. The existing compile.rs
    // dispatch tests are the path-uniformity guards proving the two
    // production sites route through it without behavior drift.

    #[test]
    fn expand_and_collect_calls_to_yields_projection_for_every_matching_form_in_source_order() {
        // Three forms — two match `defmonitor`, one matches `defalert`.
        // The mapper records `args.len()` from each matching form's tail.
        // Pin: only the two `defmonitor` matches flow through `project`,
        // in source order (so the recorded lengths are 2, 1).
        let forms = vec![
            Sexp::List(vec![
                Sexp::symbol("defmonitor"),
                Sexp::keyword("name"),
                Sexp::string("first"),
            ]),
            Sexp::List(vec![
                Sexp::symbol("defalert"),
                Sexp::keyword("name"),
                Sexp::string("not-a-match"),
            ]),
            Sexp::List(vec![Sexp::symbol("defmonitor"), Sexp::keyword("solo")]),
        ];
        let mut e = Expander::new();
        let lengths: Vec<usize> = e
            .expand_and_collect_calls_to(forms, "defmonitor", |args| Ok(args.len()))
            .expect("matching forms must compose");
        assert_eq!(lengths, vec![2, 1]);
    }

    #[test]
    fn expand_and_collect_calls_to_skips_non_matching_forms_without_invoking_project() {
        // Path-uniformity for the soft-projection posture inherited from
        // `iter_calls_to`: non-matching forms are skipped silently, and
        // `project` is never invoked on them. Pin via a counter the
        // closure increments per invocation — the counter is the
        // observable that distinguishes "skipped silently" from
        // "projected to a no-op".
        let forms = vec![
            Sexp::symbol("bare-atom"),
            Sexp::List(vec![Sexp::symbol("defalert"), Sexp::int(1)]),
            Sexp::List(vec![Sexp::int(5), Sexp::symbol("not-symbol-head")]),
            Sexp::List(vec![]),
            Sexp::Nil,
        ];
        let mut count = 0usize;
        let mut e = Expander::new();
        let out: Vec<()> = e
            .expand_and_collect_calls_to(forms, "defmonitor", |_args| {
                count += 1;
                Ok(())
            })
            .expect("non-matching-only slice must collect to empty Vec");
        assert!(out.is_empty(), "no matching forms — empty Vec, got {out:?}");
        assert_eq!(count, 0, "project must never run for non-matching forms");
    }

    #[test]
    fn expand_and_collect_calls_to_short_circuits_on_project_error_at_first_failure() {
        // Three matching forms; the closure errors on the SECOND. Pin: the
        // collect's `Result<Vec<_>, _>` short-circuit fires at the second
        // form's error, the third form's `project` is NEVER invoked, and
        // the returned error is exactly the one the closure raised. This
        // mirrors `compile_named_from_forms`'s short-circuit on the first
        // `NamedFormMissingName` / `NamedFormNonSymbolName` / typed-entry
        // kwargs rejection.
        let forms = vec![
            Sexp::List(vec![Sexp::symbol("defmonitor"), Sexp::int(1)]),
            Sexp::List(vec![Sexp::symbol("defmonitor"), Sexp::int(2)]),
            Sexp::List(vec![Sexp::symbol("defmonitor"), Sexp::int(3)]),
        ];
        let mut seen = Vec::new();
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_calls_to::<(), _>(forms, "defmonitor", |args| {
                let n = args[0].as_int().expect("test args are ints");
                seen.push(n);
                if n == 2 {
                    Err(LispError::Compile {
                        form: "test".to_string(),
                        message: "stop at two".to_string(),
                    })
                } else {
                    Ok(())
                }
            })
            .expect_err("project's error must short-circuit collect");
        // Only the first two forms were ever projected — the third
        // never reached `project`.
        assert_eq!(seen, vec![1, 2]);
        assert!(
            matches!(err, LispError::Compile { ref message, .. } if message == "stop at two"),
            "short-circuit must propagate the project's error verbatim, got {err:?}"
        );
    }

    #[test]
    fn expand_and_collect_calls_to_short_circuits_on_expand_program_error_before_project_runs() {
        // The `expand_program` step runs BEFORE `iter_calls_to` walks
        // anything — so an `expand_program` error (e.g., a malformed
        // `defmacro` head) must short-circuit the entire composition
        // and `project` must NEVER run. Pin via the closure-running
        // counter: an error from the FIRST step never invokes `project`.
        // `(defmacro 5 (x) `,x)` — the macro NAME slot is an int, not a
        // symbol; `macro_def_from`'s `defmacro_non_symbol_name` rejection
        // fires during `expand_program`.
        let forms = read("(defmacro 5 (x) `,x) (defmonitor :name \"x\")").unwrap();
        let mut count = 0usize;
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_calls_to::<(), _>(forms, "defmonitor", |_args| {
                count += 1;
                Ok(())
            })
            .expect_err("expand_program error must short-circuit before project");
        assert_eq!(
            count, 0,
            "project must never run when expand_program errors"
        );
        // Sanity: the error IS the expand_program-stage rejection, NOT
        // a project-stage error (path-uniformity for the ordering).
        let rendered = format!("{err}");
        assert!(
            rendered.contains("NAME") || rendered.contains("symbol"),
            "error must be the defmacro-NAME-not-a-symbol rejection, got: {rendered}"
        );
    }

    #[test]
    fn expand_and_collect_calls_to_yields_empty_vec_for_empty_forms_input() {
        // Boundary: empty forms slice yields zero items regardless of
        // keyword. Pin the degenerate boundary — empty in, empty out —
        // and the closure is never invoked. Sibling of
        // `iter_calls_to_yields_nothing_for_empty_slice` in ast.rs,
        // one level up the composition: the program-level walk is
        // fused-empty when `expand_program` yields an empty `Vec<Sexp>`.
        let mut count = 0usize;
        let mut e = Expander::new();
        let out: Vec<()> = e
            .expand_and_collect_calls_to(Vec::new(), "anything", |_args| {
                count += 1;
                Ok(())
            })
            .expect("empty forms is not an error");
        assert!(out.is_empty());
        assert_eq!(count, 0);
    }

    #[test]
    fn expand_and_collect_calls_to_expands_macros_before_filtering_by_keyword() {
        // Critical ordering: `expand_program` runs BEFORE the keyword
        // filter, so a `defmacro` whose expansion produces a form with
        // a matching head IS visible to `project`. Pin the pipeline
        // order: `(defmacro emit-monitor (n) `(defmonitor :name ,n))
        //         (emit-monitor "alpha") (defmonitor :name "beta")`
        // expands the macro call to `(defmonitor :name "alpha")` and
        // the keyword walk then sees TWO `defmonitor` forms (the
        // macro-emitted one AND the directly-authored one). A
        // pre-expansion filter would miss the macro-emitted form.
        let forms = read(
            "(defmacro emit-monitor (n) `(defmonitor :name ,n))
             (emit-monitor \"alpha\")
             (defmonitor :name \"beta\")",
        )
        .unwrap();
        let mut e = Expander::new();
        let names: Vec<String> = e
            .expand_and_collect_calls_to(forms, "defmonitor", |args| {
                // Each defmonitor form's tail is `(:name "X")`; project
                // the second element's string to capture the name.
                Ok(args[1].as_string().unwrap().to_string())
            })
            .expect("macroexpanded + directly-authored forms must both flow");
        assert_eq!(names, vec!["alpha".to_string(), "beta".to_string()]);
    }

    #[test]
    fn expand_and_collect_calls_to_threads_keyword_argument_verbatim_into_filter() {
        // The `keyword` argument flows straight into `iter_calls_to`'s
        // head-comparison gate — a regression that drifts the keyword
        // (e.g., uses `T::KEYWORD` from a different `T` at the helper,
        // or lowercases / trims the keyword en route) fails here. Pin
        // by passing TWO different keywords against the SAME forms
        // input and asserting each picks up only its matching forms.
        let forms = vec![
            Sexp::List(vec![Sexp::symbol("defmonitor"), Sexp::int(1)]),
            Sexp::List(vec![Sexp::symbol("defalert"), Sexp::int(2)]),
            Sexp::List(vec![Sexp::symbol("defmonitor"), Sexp::int(3)]),
            Sexp::List(vec![Sexp::symbol("defnotify"), Sexp::int(4)]),
        ];

        let mut e = Expander::new();
        let monitors: Vec<i64> = e
            .expand_and_collect_calls_to(forms.clone(), "defmonitor", |args| {
                Ok(args[0].as_int().unwrap())
            })
            .unwrap();
        assert_eq!(monitors, vec![1, 3]);

        let mut e2 = Expander::new();
        let alerts: Vec<i64> = e2
            .expand_and_collect_calls_to(forms.clone(), "defalert", |args| {
                Ok(args[0].as_int().unwrap())
            })
            .unwrap();
        assert_eq!(alerts, vec![2]);

        // A keyword nothing matches collects to the empty Vec — same
        // shape as the empty-forms case at the slice level.
        let mut e3 = Expander::new();
        let none: Vec<i64> = e3
            .expand_and_collect_calls_to(forms, "missing-keyword", |args| {
                Ok(args[0].as_int().unwrap())
            })
            .unwrap();
        assert!(none.is_empty());
    }

    #[test]
    fn expand_and_collect_calls_to_matches_inlined_expand_program_plus_iter_calls_to_path() {
        // Structural identity: for any (forms, keyword, project) triple
        // whose pieces succeed, the method's result equals the inlined
        // pre-lift pipeline `expand_program + iter_calls_to + map +
        // collect`. Pin shape AND ordering on a mixed forms input
        // (matching + non-matching + macroexpand-emitted matches) so a
        // regression that drifts the method's pipeline from the inlined
        // closed-form fails here. This is the lift's load-bearing
        // path-uniformity gate — the SAME assertion that holds for
        // both production consumers (compile.rs) holds at the
        // primitive's contract level.
        let src = "(defmacro emit-foo (n) `(foo :idx ,n))
                   (foo :idx 1)
                   (emit-foo 2)
                   (bar :idx 99)
                   (foo :idx 3)";
        let forms = read(src).unwrap();

        // Inlined pre-lift pipeline.
        let mut exp_inline = Expander::new();
        let expanded = exp_inline.expand_program(forms.clone()).unwrap();
        let via_inline: Vec<i64> = crate::ast::iter_calls_to(&expanded, "foo")
            .map(|args| -> Result<i64> { Ok(args[1].as_int().unwrap()) })
            .collect::<Result<Vec<_>>>()
            .unwrap();

        // Method pipeline.
        let mut exp_method = Expander::new();
        let via_method: Vec<i64> = exp_method
            .expand_and_collect_calls_to(forms, "foo", |args| Ok(args[1].as_int().unwrap()))
            .unwrap();

        assert_eq!(via_inline, via_method);
        assert_eq!(via_inline, vec![1, 2, 3]);
    }

    // ── Expander::expand_and_collect_calls_to_any: typed-decoded sibling ──
    //
    // The typed-decoded classifier sibling of `expand_and_collect_calls_to`:
    // composes `expand_program` with `iter_calls_to_any` and a per-form
    // mapper that receives BOTH the typed witness AND the args tail.
    // Closes the (keyword, classifier) 2×2 of expander-surface
    // compose-on-iter projections at the typed-decoded corner the prior
    // runs' slice-side `iter_calls_to_any` lift left open. The keyword
    // sibling now ROUTES through this primitive via a constant-classifier
    // composition — the tests below pin both the typed-decoded primitive's
    // contract directly AND the routing identity binding the keyword
    // sibling to it.
    //
    // The existing `expand_and_collect_calls_to_*` tests above remain
    // load-bearing — they pin the keyword sibling's contract through
    // its ROUTED implementation, so a regression that drifts the routing
    // composition surfaces at the existing keyword tests too.

    #[test]
    fn expand_and_collect_calls_to_any_yields_decoded_pair_for_every_matching_form_in_source_order()
    {
        // The typed-decoded primitive's happy path: a closed-set
        // classifier decodes head symbols to a typed enum, and the
        // per-form projection receives `(decoded, args)` for every
        // matched form in source order. Sweep across THREE distinct
        // classifier outcomes — `Foo` / `Bar` / `Baz` — interleaved with
        // a non-matching form to pin both the typed-witness threading
        // AND the source-order yield AND the rejection of non-classifier
        // forms in ONE assertion. The decoder runs once per call form
        // (`FnMut`); the projection runs once per matched form.
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        enum Op {
            Foo,
            Bar,
            Baz,
        }
        let src = "(foo 1)
                   (bar 2)
                   (other 99)
                   (baz 3)
                   (foo 4)";
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let pairs: Vec<(Op, i64)> = e
            .expand_and_collect_calls_to_any(
                forms,
                |h| match h {
                    "foo" => Some(Op::Foo),
                    "bar" => Some(Op::Bar),
                    "baz" => Some(Op::Baz),
                    _ => None,
                },
                |op, args| Ok((op, args[0].as_int().unwrap())),
            )
            .unwrap();
        assert_eq!(
            pairs,
            vec![(Op::Foo, 1), (Op::Bar, 2), (Op::Baz, 3), (Op::Foo, 4),],
        );
    }

    #[test]
    fn expand_and_collect_calls_to_any_skips_non_matching_forms_without_invoking_project() {
        // The soft-projection contract — every shape `iter_calls_to_any`
        // rejects (non-list, empty list, list whose head is not a
        // symbol, list whose head decodes through the classifier to
        // `None`) skips the projection silently. Pin a deliberately-
        // panicking projection so the assertion fires loudly if a
        // non-matching form reaches it. The decoder accepts only
        // `"defmonitor"`; every other shape (atom, list whose head is a
        // keyword, list whose head is a symbol the decoder rejects)
        // short-circuits before the projection runs.
        let src = r#":bare-keyword
                     "bare-string"
                     42
                     ()
                     (foo bar)
                     (defmonitor :name "matches")"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let lengths: Vec<usize> = e
            .expand_and_collect_calls_to_any(
                forms,
                |h| (h == "defmonitor").then_some(()),
                |(), args| {
                    // The projection must run EXACTLY once — for the
                    // single matched form. Any non-matching form that
                    // reaches the projection panics here.
                    assert_eq!(args.len(), 2, "projection ran on non-matching form");
                    Ok(args.len())
                },
            )
            .unwrap();
        assert_eq!(lengths, vec![2]);
    }

    #[test]
    fn expand_and_collect_calls_to_any_short_circuits_on_project_error_at_first_failure() {
        // The Result projection's short-circuit contract — when the
        // projection returns `Err` on a matched form, the walk
        // short-circuits and subsequent matched forms are NOT projected.
        // Pin the source-order short-circuit via a counter the
        // projection increments before deciding to fail: the counter
        // sits at exactly the index of the failing form (the second
        // match), proving the third match never reached the projection.
        let src = "(foo 1) (foo 2) (foo 3)";
        let forms = read(src).unwrap();
        let mut count = 0usize;
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_calls_to_any::<i64, _, _, ()>(
                forms,
                |h| (h == "foo").then_some(()),
                |(), args| {
                    count += 1;
                    let v = args[0].as_int().unwrap();
                    if v == 2 {
                        return Err(crate::error::LispError::Missing("test-failure"));
                    }
                    Ok(v)
                },
            )
            .expect_err("projection must short-circuit on first Err");
        assert_eq!(
            count, 2,
            "projection must have run on first AND failing form, then stopped",
        );
        // Sanity: the error is the project-stage rejection — the same
        // typed `LispError` the projection returned, propagated verbatim.
        assert!(
            matches!(err, crate::error::LispError::Missing("test-failure")),
            "expected the projection's typed Err verbatim, got {err:?}",
        );
    }

    #[test]
    fn expand_and_collect_calls_to_any_expands_macros_before_filtering_by_classifier() {
        // Ordering contract — `expand_program` runs BEFORE
        // `iter_calls_to_any` walks the slice. A `(defmacro …)` form
        // that emits a classifier-decoded body must have its expanded
        // body decoded by the classifier (not the unexpanded macro-call
        // head). Pin the ordering with a macro `(emit-foo n)` that
        // expands to `(foo :idx n)` — the classifier sees the expanded
        // `foo` head, not `emit-foo`. Mirrors the parallel keyword test
        // `expand_and_collect_calls_to_expands_macros_before_filtering_by_keyword`
        // — the SAME composition contract holds on the typed-decoded
        // sibling.
        let src = "(defmacro emit-foo (n) `(foo :idx ,n))
                   (foo :idx 1)
                   (emit-foo 2)
                   (bar :idx 99)
                   (foo :idx 3)";
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        // Classifier returns `()` for "foo" only; the keyword sibling's
        // routing identity is the same composition we exercise here
        // directly.
        let idxs: Vec<i64> = e
            .expand_and_collect_calls_to_any(
                forms,
                |h| (h == "foo").then_some(()),
                |(), args| Ok(args[1].as_int().unwrap()),
            )
            .unwrap();
        // 1 from the literal call, 2 from the macro-emitted call, 3 from
        // the final literal call. The macro-emitted `(foo :idx 2)` is
        // present BECAUSE `expand_program` ran first.
        assert_eq!(idxs, vec![1, 2, 3]);
    }

    #[test]
    fn expand_and_collect_calls_to_any_admits_fnmut_classifier_maintaining_state_across_walk() {
        // The `FnMut` constraint — the slice walk calls the classifier
        // once per call form, and a decoder that captures mutable state
        // (a counter, a registry cache, a visited-set) maintains that
        // state across the walk. Pin the `FnMut` contract with a counter
        // closure that increments per shape-gate-passing form (calls
        // whose head is a symbol), asserting the counter equals the
        // total call count regardless of whether the classifier accepts
        // each form. Mirrors the parallel slice-side test
        // `iter_calls_to_any_admits_fnmut_classifier_maintaining_state_across_batch_walk`
        // — the SAME `FnMut` contract holds on the expander surface.
        let src = "(foo 1) (bar 2) (foo 3) (bar 4) (foo 5)";
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let mut classifier_calls = 0usize;
        let projected: Vec<i64> = e
            .expand_and_collect_calls_to_any(
                forms,
                |h| {
                    classifier_calls += 1;
                    (h == "foo").then_some(())
                },
                |(), args| Ok(args[0].as_int().unwrap()),
            )
            .unwrap();
        assert_eq!(
            classifier_calls, 5,
            "classifier must run once per call form (5 forms, all calls with symbol heads)",
        );
        assert_eq!(
            projected,
            vec![1, 3, 5],
            "projection must run only for classifier-accepted forms in source order",
        );
    }

    #[test]
    fn expand_and_collect_calls_to_routes_through_expand_and_collect_calls_to_any_via_constant_classifier_composition(
    ) {
        // Structural identity: the keyword sibling
        // `expand_and_collect_calls_to` ROUTES through the typed-decoded
        // primitive via a constant-classifier composition — the
        // post-lift composition law binding the two siblings:
        //
        //   expand_and_collect_calls_to(forms, k, p) ==
        //       expand_and_collect_calls_to_any(forms,
        //           |h| (h == k).then_some(()),
        //           |(), args| p(args))
        //
        // Pin shape AND ordering across THREE representative keyword
        // values: one that matches multiple forms, one that matches
        // none, one that matches exactly one form. Same mixed input
        // (literal + macroexpand-emitted + non-matching) the keyword
        // path-uniformity test exercises, so the routing identity holds
        // on the SAME input shape the keyword sibling's contract pins.
        let src = "(defmacro emit-foo (n) `(foo :idx ,n))
                   (foo :idx 1)
                   (emit-foo 2)
                   (bar :idx 99)
                   (foo :idx 3)";
        let forms = read(src).unwrap();

        for keyword in ["foo", "bar", "absent"] {
            let mut exp_keyword = Expander::new();
            let via_keyword: Vec<i64> = exp_keyword
                .expand_and_collect_calls_to(forms.clone(), keyword, |args| {
                    Ok(args[1].as_int().unwrap())
                })
                .unwrap();
            let mut exp_classifier = Expander::new();
            let via_classifier: Vec<i64> = exp_classifier
                .expand_and_collect_calls_to_any(
                    forms.clone(),
                    |h| (h == keyword).then_some(()),
                    |(), args| Ok(args[1].as_int().unwrap()),
                )
                .unwrap();
            assert_eq!(
                via_keyword, via_classifier,
                "routing identity drifted for keyword {keyword:?}",
            );
        }
    }

    #[test]
    fn expand_and_collect_calls_to_any_short_circuits_on_expand_program_error_before_project_runs()
    {
        // The expand_program-stage short-circuit contract — when
        // `expand_program` rejects (e.g. a `(defmacro …)` form whose
        // param list is malformed), the walk short-circuits BEFORE the
        // classifier or projection runs. Pin the ordering with a
        // deliberately-panicking classifier AND projection: any
        // post-expand-program execution fires the panic. Mirrors the
        // parallel keyword test
        // `expand_and_collect_calls_to_short_circuits_on_expand_program_error_before_project_runs`
        // — the SAME composition contract holds on the typed-decoded
        // sibling.
        // `(defmacro 5 (x) `,x)` — macro NAME slot is an int, not a
        // symbol; `macro_def_from`'s `defmacro_non_symbol_name` rejection
        // fires during `expand_program`. Same rejection shape the
        // parallel keyword test uses, so the ordering contract observed
        // here is structurally identical to the keyword sibling's.
        let forms = read("(defmacro 5 (x) `,x) (foo :idx 1)").unwrap();
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_calls_to_any::<(), _, _, ()>(
                forms,
                |_h| -> Option<()> {
                    panic!("classifier must not run when expand_program errors");
                },
                |(), _args| {
                    panic!("project must not run when expand_program errors");
                },
            )
            .expect_err("expand_program error must short-circuit before classifier or project");
        // Sanity: the error IS an expand_program-stage rejection — not a
        // classifier or projection error — so the ordering is observable.
        let rendered = format!("{err}");
        assert!(
            rendered.contains("NAME") || rendered.contains("symbol"),
            "expected expand_program-stage `defmacro-NAME-not-a-symbol` rejection, got {rendered:?}",
        );
    }

    // ── Expander::expand_source_and_collect_calls_to: from-source walk ──
    //
    // The from-source sibling of `expand_and_collect_calls_to`: composes
    // `crate::reader::read(src)?` with the from-forms primitive in ONE
    // method on the `Expander` surface. All four typed-program dispatchers
    // (free-function `compile_typed` / `compile_named`, preloaded-expander
    // `RealizedCompiler::compile_typed` / `compile_named`) route through
    // it; the tests below pin its contract directly. The existing
    // compile.rs + compiler_spec.rs dispatch tests are the path-uniformity
    // guards proving the four production sites route through it without
    // behavior drift.

    #[test]
    fn expand_source_and_collect_calls_to_routes_through_reader_then_expand_and_collect() {
        // Happy path: a source string with three top-level forms (two
        // matching `defmonitor`, one matching `defalert`) flows through
        // `read` then through the from-forms primitive. Pin the SAME
        // emission shape the from-forms test pins for the matching
        // sub-set, sourced from a `&str` rather than a `Vec<Sexp>`.
        let src = r#"(defmonitor :name "first")
                     (defalert :name "not-a-match")
                     (defmonitor :solo)"#;
        let mut e = Expander::new();
        let lengths: Vec<usize> = e
            .expand_source_and_collect_calls_to(src, "defmonitor", |args| Ok(args.len()))
            .expect("matching forms must compose");
        assert_eq!(lengths, vec![2, 1]);
    }

    #[test]
    fn expand_source_and_collect_calls_to_short_circuits_on_reader_error_before_expand_program() {
        // The reader runs BEFORE `expand_program` — so a reader error (an
        // unterminated string, an unbalanced paren, an unknown escape)
        // must short-circuit the entire composition and `expand_program`
        // / the keyword filter / `project` must NEVER run. Pin the
        // ordering: an unbalanced open-paren is rejected by the reader
        // at parse time, never reaches the from-forms primitive.
        let mut count = 0usize;
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_calls_to::<(), _>(
                "(defmonitor :name \"unbalanced",
                "defmonitor",
                |_args| {
                    count += 1;
                    Ok(())
                },
            )
            .expect_err("reader error must short-circuit before expand_program");
        assert_eq!(
            count, 0,
            "project must never run when reader errors at parse time"
        );
        // Sanity: the error IS a reader-stage rejection — the rendered
        // diagnostic mentions the lexer's gate, not the expander's or
        // projector's (path-uniformity for the read-then-walk ordering).
        let rendered = format!("{err}");
        assert!(
            rendered.to_lowercase().contains("string")
                || rendered.to_lowercase().contains("paren")
                || rendered.to_lowercase().contains("eof")
                || rendered.to_lowercase().contains("unexpected")
                || rendered.to_lowercase().contains("unterminated")
                || rendered.to_lowercase().contains("unclosed"),
            "error must be the reader-stage rejection, got: {rendered}"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_short_circuits_on_expand_program_error_before_project_runs(
    ) {
        // Reader succeeds, but `expand_program` rejects a malformed
        // `defmacro` head (NAME slot is an int, not a symbol). Pin the
        // ordering: `expand_program` rejects BEFORE the keyword filter
        // walks anything, `project` must NEVER run. Sibling of the
        // from-forms test of the same name — one level up the
        // composition (sourced from `&str` rather than `Vec<Sexp>`).
        let mut count = 0usize;
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_calls_to::<(), _>(
                "(defmacro 5 (x) `,x) (defmonitor :name \"x\")",
                "defmonitor",
                |_args| {
                    count += 1;
                    Ok(())
                },
            )
            .expect_err("expand_program error must short-circuit before project");
        assert_eq!(
            count, 0,
            "project must never run when expand_program errors"
        );
        let rendered = format!("{err}");
        assert!(
            rendered.contains("NAME") || rendered.contains("symbol"),
            "error must be the defmacro-NAME-not-a-symbol rejection, got: {rendered}"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_short_circuits_on_project_error_at_first_failure() {
        // Reader + `expand_program` both succeed; the per-form `project`
        // errors on the SECOND matched form. Pin: the collect's short-
        // circuit fires at the second match's error, the third match's
        // `project` is NEVER invoked, and the returned error is exactly
        // the one the closure raised. Mirrors `compile_named`'s
        // short-circuit on the first `NamedFormMissingName` /
        // `NamedFormNonSymbolName` / typed-entry rejection — sourced
        // from `&str`.
        let src = "(defmonitor :idx 1) (defmonitor :idx 2) (defmonitor :idx 3)";
        let mut seen = Vec::new();
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_calls_to::<(), _>(src, "defmonitor", |args| {
                let n = args[1].as_int().expect("test args are ints");
                seen.push(n);
                if n == 2 {
                    Err(LispError::Compile {
                        form: "test".to_string(),
                        message: "stop at two".to_string(),
                    })
                } else {
                    Ok(())
                }
            })
            .expect_err("project's error must short-circuit collect");
        assert_eq!(seen, vec![1, 2]);
        assert!(
            matches!(err, LispError::Compile { ref message, .. } if message == "stop at two"),
            "short-circuit must propagate the project's error verbatim, got {err:?}"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_yields_empty_vec_for_empty_source() {
        // Boundary: empty source string yields zero items regardless of
        // keyword. Pin the degenerate boundary — empty in, empty out —
        // and the closure is never invoked. Sibling of the from-forms
        // test of the same name, one level up the composition: the
        // from-source posture is fused-empty when `read` yields an
        // empty `Vec<Sexp>` (which, fed into `expand_program`, yields
        // an empty `Vec<Sexp>`, which iter_calls_to walks to zero
        // matches).
        let mut count = 0usize;
        let mut e = Expander::new();
        let out: Vec<()> = e
            .expand_source_and_collect_calls_to("", "anything", |_args| {
                count += 1;
                Ok(())
            })
            .expect("empty source is not an error");
        assert!(out.is_empty());
        assert_eq!(count, 0);
    }

    #[test]
    fn expand_source_and_collect_calls_to_expands_macros_before_filtering_by_keyword() {
        // Critical ordering preserved across the from-source posture:
        // `defmacro` source registers in `expand_program`, its call
        // sites expand to the matching keyword, AND the keyword walk
        // sees both the macro-emitted form and any directly-authored
        // matches in source order. Sibling of the from-forms test of
        // the same name, sourced from `&str`.
        let src = "(defmacro emit-monitor (n) `(defmonitor :name ,n))
                   (emit-monitor \"alpha\")
                   (defmonitor :name \"beta\")";
        let mut e = Expander::new();
        let names: Vec<String> = e
            .expand_source_and_collect_calls_to(src, "defmonitor", |args| {
                Ok(args[1].as_string().unwrap().to_string())
            })
            .expect("macroexpanded + directly-authored forms must both flow");
        assert_eq!(names, vec!["alpha".to_string(), "beta".to_string()]);
    }

    #[test]
    fn expand_source_and_collect_calls_to_matches_inlined_read_plus_expand_and_collect_path() {
        // Structural identity: for any (src, keyword, project) triple
        // whose pieces succeed, the from-source method's result equals
        // the inlined pre-lift pipeline `read + expand_and_collect_
        // calls_to`. Pin shape AND ordering on a mixed source
        // (matching + non-matching + macroexpand-emitted matches) so a
        // regression that drifts the method's pipeline from the
        // inlined closed-form fails here. This is the lift's
        // load-bearing path-uniformity gate — the SAME assertion that
        // holds for all four production consumers (free-function
        // `compile_typed`/`compile_named` + `RealizedCompiler::compile_typed`/`compile_named`)
        // holds at the primitive's contract level.
        let src = "(defmacro emit-foo (n) `(foo :idx ,n))
                   (foo :idx 1)
                   (emit-foo 2)
                   (bar :idx 99)
                   (foo :idx 3)";

        // Inlined pre-lift pipeline.
        let mut exp_inline = Expander::new();
        let inline_forms = read(src).unwrap();
        let via_inline: Vec<i64> = exp_inline
            .expand_and_collect_calls_to(inline_forms, "foo", |args| Ok(args[1].as_int().unwrap()))
            .unwrap();

        // From-source method pipeline.
        let mut exp_method = Expander::new();
        let via_method: Vec<i64> = exp_method
            .expand_source_and_collect_calls_to(src, "foo", |args| Ok(args[1].as_int().unwrap()))
            .unwrap();

        assert_eq!(via_inline, via_method);
        assert_eq!(via_inline, vec![1, 2, 3]);
    }

    #[test]
    fn expand_source_and_collect_calls_to_threads_keyword_argument_verbatim_into_filter() {
        // The `keyword` argument flows straight into the from-forms
        // primitive's head-comparison gate, which inherits from
        // `iter_calls_to` — a regression that drifts the keyword (e.g.,
        // lowercases / trims it en route through the read step) fails
        // here. Pin by passing TWO different keywords against the SAME
        // source and asserting each picks up only its matching forms.
        let src = "(defmonitor :idx 1) (defalert :idx 2) (defmonitor :idx 3) (defnotify :idx 4)";

        let mut e1 = Expander::new();
        let monitors: Vec<i64> = e1
            .expand_source_and_collect_calls_to(src, "defmonitor", |args| {
                Ok(args[1].as_int().unwrap())
            })
            .unwrap();
        assert_eq!(monitors, vec![1, 3]);

        let mut e2 = Expander::new();
        let alerts: Vec<i64> = e2
            .expand_source_and_collect_calls_to(src, "defalert", |args| {
                Ok(args[1].as_int().unwrap())
            })
            .unwrap();
        assert_eq!(alerts, vec![2]);

        let mut e3 = Expander::new();
        let none: Vec<i64> = e3
            .expand_source_and_collect_calls_to(src, "missing-keyword", |args| {
                Ok(args[1].as_int().unwrap())
            })
            .unwrap();
        assert!(none.is_empty());
    }

    #[test]
    fn expand_source_and_collect_calls_to_skips_non_matching_forms_without_invoking_project() {
        // Path-uniformity for the soft-projection posture inherited
        // from `iter_calls_to`: non-matching forms in the source are
        // skipped silently, and `project` is never invoked on them.
        // Sibling of the from-forms test of the same name, sourced
        // from `&str` with a mix of atoms-and-lists that the reader
        // emits at the top level.
        let src = "bare-atom (defalert :idx 1) (defnotify :idx 2)";
        let mut count = 0usize;
        let mut e = Expander::new();
        let out: Vec<()> = e
            .expand_source_and_collect_calls_to(src, "defmonitor", |_args| {
                count += 1;
                Ok(())
            })
            .expect("non-matching-only source must collect to empty Vec");
        assert!(out.is_empty(), "no matching forms — empty Vec, got {out:?}");
        assert_eq!(count, 0, "project must never run for non-matching forms");
    }

    // ── Expander::expand_source_and_collect_calls_to_any — from-source × classifier ─
    //
    // The from-source posture of the typed-decoded classifier sibling on
    // the `Expander` surface — closes the (from-forms, from-source) ×
    // (keyword, classifier) 2×2 of compose-on-iter projections at the
    // from-source classifier corner the prior runs left open. The
    // pre-existing `expand_source_and_collect_calls_to` (from-source ×
    // keyword) is the constant-classifier projection of this primitive:
    // its body composes this function with a `|h| (h == keyword).
    // then_some(())` decoder, so the from-source pipeline lives at ONE
    // site. These tests pin both the typed-decoded primitive's contract
    // directly AND the post-lift routing of
    // `expand_source_and_collect_calls_to` through it.

    #[test]
    fn expand_source_and_collect_calls_to_any_yields_decoded_pair_for_every_matching_form_in_source_order(
    ) {
        // Happy path: a source string with four top-level forms (two
        // matching "foo", one matching "bar", one rejected-head
        // "defmonitor") flows through `read` → `expand_program` → the
        // typed-decoded classifier walk. The closed-set classifier
        // `Op::from_keyword` admits "foo" and "bar" but rejects
        // "defmonitor". Pin the typed-decoded yield shape (decoded
        // witness alongside args tail) AND source-order preservation
        // sourced from `&str` rather than a pre-parsed `Vec<Sexp>`.
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum Op {
            Foo,
            Bar,
        }
        fn op_from_keyword(head: &str) -> Option<Op> {
            match head {
                "foo" => Some(Op::Foo),
                "bar" => Some(Op::Bar),
                _ => None,
            }
        }
        let src = r#"(foo :idx 1)
                     (defmonitor :idx 99)
                     (bar :idx 2)
                     (foo :idx 3)"#;
        let mut e = Expander::new();
        let yielded: Vec<(Op, i64)> = e
            .expand_source_and_collect_calls_to_any(src, op_from_keyword, |op, args| {
                Ok((op, args[1].as_int().expect("test args are ints")))
            })
            .expect("matching forms must compose through from-source classifier walk");
        assert_eq!(
            yielded,
            vec![(Op::Foo, 1), (Op::Bar, 2), (Op::Foo, 3)],
            "yields must be in source order, decoded witness paired with per-form mapper output"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_any_short_circuits_on_reader_error_before_classifier_runs(
    ) {
        // The reader runs BEFORE `expand_program` AND BEFORE the
        // classifier — so a reader error (an unterminated string)
        // short-circuits the entire composition and both the classifier
        // AND `project` must NEVER run. Pin the ordering with BOTH
        // decoder and projection explicitly panicking — any post-reader
        // execution fires the panic. Sibling of
        // `expand_source_and_collect_calls_to_short_circuits_on_reader_error_before_expand_program`
        // one corner over in the 2×2 (the classifier version of the
        // same ordering pin).
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_calls_to_any::<(), _, _, ()>(
                "(defmonitor :name \"unbalanced",
                |_h: &str| -> Option<()> {
                    panic!("classifier must not run when reader errors at parse time")
                },
                |(), _args| -> Result<()> { panic!("project must not run when reader errors") },
            )
            .expect_err("reader error must short-circuit before classifier");
        // Sanity: the error is a reader-stage rejection.
        let rendered = format!("{err}");
        assert!(
            rendered.to_lowercase().contains("string")
                || rendered.to_lowercase().contains("paren")
                || rendered.to_lowercase().contains("eof")
                || rendered.to_lowercase().contains("unexpected")
                || rendered.to_lowercase().contains("unterminated")
                || rendered.to_lowercase().contains("unclosed"),
            "error must be the reader-stage rejection, got: {rendered}"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_any_short_circuits_on_expand_program_error_before_classifier_runs(
    ) {
        // Reader succeeds, but `expand_program` rejects a malformed
        // `defmacro` head (NAME slot is an int, not a symbol). Pin the
        // ordering: `expand_program` rejects BEFORE the classifier walks
        // anything, both decoder AND `project` must NEVER run. Sibling
        // of the keyword-from-source variant — one corner over in the
        // 2×2 with both classifier and projection explicitly panicking.
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_calls_to_any::<(), _, _, ()>(
                "(defmacro 5 (x) `,x) (defmonitor :name \"x\")",
                |_h: &str| -> Option<()> {
                    panic!("classifier must not run when expand_program errors")
                },
                |(), _args| -> Result<()> {
                    panic!("project must not run when expand_program errors")
                },
            )
            .expect_err("expand_program error must short-circuit before classifier");
        let rendered = format!("{err}");
        assert!(
            rendered.contains("NAME") || rendered.contains("symbol"),
            "error must be the defmacro-NAME-not-a-symbol rejection, got: {rendered}"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_any_skips_non_matching_forms_without_invoking_project() {
        // Path-uniformity for the soft-projection posture inherited
        // from `iter_calls_to_any`: forms whose head the classifier
        // rejects are skipped silently, and `project` is never invoked
        // on them. Pin via an explicitly-panicking projection across a
        // mix of forms (atom, list-with-non-symbol-head, list with
        // unrecognized-by-classifier symbol head). A regression that
        // wrongly invokes `project` on a rejected form fires the panic.
        let src = r#"bare-atom
                     (5 :not-a-symbol-head)
                     (defmonitor :name "decoder-rejects-me")"#;
        let mut e = Expander::new();
        // The closed-set classifier admits NOTHING in this source.
        let out: Vec<()> = e
            .expand_source_and_collect_calls_to_any::<(), _, _, ()>(
                src,
                |_h: &str| -> Option<()> { None },
                |(), _args| -> Result<()> {
                    panic!("project must not run for classifier-rejected forms")
                },
            )
            .expect("classifier-rejects-all source must collect to empty Vec");
        assert!(
            out.is_empty(),
            "no classifier-accepted forms — empty Vec, got {out:?}"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_any_short_circuits_on_project_error_at_first_failure() {
        // Reader + `expand_program` + classifier all succeed; the
        // per-form `project` errors on the SECOND matched form. Pin: the
        // collect's short-circuit fires at the second match's error, the
        // third match's `project` is NEVER invoked, and the returned
        // error is exactly the one the closure raised. Sibling of the
        // keyword-from-source variant — one corner over in the 2×2.
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum Op {
            Foo,
        }
        fn op_from_keyword(head: &str) -> Option<Op> {
            (head == "foo").then_some(Op::Foo)
        }
        let src = "(foo :idx 1) (foo :idx 2) (foo :idx 3)";
        let mut seen = Vec::new();
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_calls_to_any::<(), _, _, _>(
                src,
                op_from_keyword,
                |_op: Op, args: &[Sexp]| -> Result<()> {
                    let n = args[1].as_int().expect("test args are ints");
                    seen.push(n);
                    if n == 2 {
                        Err(LispError::Compile {
                            form: "test".to_string(),
                            message: "stop at two".to_string(),
                        })
                    } else {
                        Ok(())
                    }
                },
            )
            .expect_err("project's error must short-circuit collect");
        assert_eq!(seen, vec![1, 2], "third match's project must never run");
        assert!(
            matches!(err, LispError::Compile { ref message, .. } if message == "stop at two"),
            "short-circuit must propagate the project's error verbatim, got {err:?}"
        );
    }

    #[test]
    fn expand_source_and_collect_calls_to_routes_through_expand_source_and_collect_calls_to_any_via_constant_classifier_composition(
    ) {
        // The post-lift composition law binding the keyword-from-source
        // sibling to the typed-decoded primitive:
        //   `expand_source_and_collect_calls_to(src, k, project) ==
        //    expand_source_and_collect_calls_to_any(src,
        //        |h| (h == k).then_some(()),
        //        |(), args| project(args))`
        // Pin shape AND ordering across THREE representative keywords
        // (matching some, matching exactly one, matching none) on the
        // SAME mixed source the keyword path-uniformity test exercises.
        // A regression that re-implements the keyword-from-source filter
        // as a parallel `read + expand_and_collect_calls_to` pipeline
        // (rather than routing through the typed-decoded primitive)
        // fails the value pin.
        let src = "(defmacro emit-foo (n) `(foo :idx ,n))
                   (foo :idx 1)
                   (emit-foo 2)
                   (bar :idx 99)
                   (foo :idx 3)";
        for k in ["foo", "bar", "missing"] {
            let mut e_keyword = Expander::new();
            let via_keyword: Vec<i64> = e_keyword
                .expand_source_and_collect_calls_to(src, k, |args| Ok(args[1].as_int().unwrap()))
                .unwrap();

            let mut e_classifier = Expander::new();
            let via_classifier: Vec<i64> = e_classifier
                .expand_source_and_collect_calls_to_any(
                    src,
                    |h: &str| (h == k).then_some(()),
                    |(), args: &[Sexp]| Ok(args[1].as_int().unwrap()),
                )
                .unwrap();

            assert_eq!(
                via_keyword, via_classifier,
                "keyword from-source path must equal classifier from-source path for {k:?}"
            );
        }
    }

    #[test]
    fn expand_source_and_collect_calls_to_any_expands_macros_before_filtering_by_classifier() {
        // Critical ordering preserved across the typed-decoded
        // from-source posture: `defmacro` source registers in
        // `expand_program`, its call sites expand to a classifier-
        // accepted form, AND the classifier walk sees both the
        // macro-emitted form and any directly-authored matches in
        // source order. Sibling of the keyword-from-source ordering
        // test, one corner over in the 2×2.
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        enum Op {
            Foo,
        }
        fn op_from_keyword(head: &str) -> Option<Op> {
            (head == "foo").then_some(Op::Foo)
        }
        let src = "(defmacro emit-foo (n) `(foo :name ,n))
                   (emit-foo \"alpha\")
                   (foo :name \"beta\")";
        let mut e = Expander::new();
        let names: Vec<(Op, String)> = e
            .expand_source_and_collect_calls_to_any(src, op_from_keyword, |op, args| {
                Ok((op, args[1].as_string().unwrap().to_string()))
            })
            .expect("macroexpanded + directly-authored forms must both flow through classifier");
        assert_eq!(
            names,
            vec![
                (Op::Foo, "alpha".to_string()),
                (Op::Foo, "beta".to_string()),
            ]
        );
    }

    // ── expand_source_program — from-source × yield-all primitive ───
    //
    // Closes the 2×2 program-level walk family on the `Expander` surface:
    // from-forms × yield-all (`expand_program`), from-forms × keyword-
    // projected (`expand_and_collect_calls_to`), from-source × keyword-
    // projected (`expand_source_and_collect_calls_to`), AND now
    // from-source × yield-all (`expand_source_program`). Pins (a) the
    // happy path (mixed forms flow through reader then expand_program),
    // (b) reader-stage short-circuit (no expand_program side-effects),
    // (c) expand_program-stage short-circuit (defmacro-NAME-not-symbol
    // is rejected at its offending form), (d) defmacro absorption (the
    // primitive's side-effect on `self.macros` matches the from-forms
    // posture's side-effect verbatim), (e) the empty-source boundary,
    // and (f) structural identity vs. the inlined pre-lift `read +
    // expand_program` pipeline (path-uniformity gate).

    #[test]
    fn expand_source_program_routes_through_reader_then_expand_program() {
        // Happy path: a source string with mixed forms (a `defmacro`
        // definition, a `defmonitor` form, a plain symbol literal) flows
        // through `read` then through the from-forms primitive. Pin the
        // SAME emission shape the from-forms test pins, sourced from a
        // `&str` rather than a `Vec<Sexp>`.
        let src = r#"(defmacro id (x) `,x)
                     (defmonitor :name "alpha")
                     bare-symbol"#;
        let mut e = Expander::new();
        let out = e
            .expand_source_program(src)
            .expect("mixed forms must compose");
        // `(defmacro id …)` is consumed as a side-effect (registers `id`
        // in `e.macros`), so the returned `Vec<Sexp>` contains the
        // remaining two top-level forms in source order.
        assert_eq!(out.len(), 2);
        assert_eq!(
            out[0].as_call_to("defmonitor").map(<[_]>::len),
            Some(2),
            "first surviving form is the defmonitor with two args, got: {:?}",
            out[0]
        );
        assert_eq!(
            out[1].as_symbol(),
            Some("bare-symbol"),
            "second surviving form is the bare symbol literal, got: {:?}",
            out[1]
        );
        // The defmacro side-effect landed in the expander's macro table.
        assert!(
            e.has("id"),
            "defmacro must register `id` in the expander's macro table"
        );
    }

    #[test]
    fn expand_source_program_short_circuits_on_reader_error_before_expand_program() {
        // The reader runs BEFORE `expand_program` — so a reader error (an
        // unterminated string, an unbalanced paren) must short-circuit
        // the entire composition and `expand_program` must NEVER run.
        // Pin the ordering: a `defmacro` BEFORE the unterminated string
        // is NOT registered, because the reader fails at parse time
        // before `expand_program` sees any form.
        let mut e = Expander::new();
        let err = e
            .expand_source_program(r#"(defmacro should-not-register (x) `,x) "unterminated"#)
            .expect_err("reader error must short-circuit before expand_program");
        // Sanity: the error IS a reader-stage rejection.
        let rendered = format!("{err}").to_lowercase();
        assert!(
            rendered.contains("string")
                || rendered.contains("paren")
                || rendered.contains("eof")
                || rendered.contains("unexpected")
                || rendered.contains("unterminated")
                || rendered.contains("unclosed"),
            "error must be the reader-stage rejection, got: {err}"
        );
        // Path-uniformity gate: the `defmacro` lexically BEFORE the
        // unterminated string must NOT have been absorbed — `read`'s
        // failure short-circuits the entire pipeline before
        // `expand_program` walks any forms.
        assert!(
            !e.has("should-not-register"),
            "reader-stage rejection must short-circuit BEFORE expand_program registers any defmacro"
        );
    }

    #[test]
    fn expand_source_program_short_circuits_on_expand_program_error() {
        // Reader succeeds, but `expand_program` rejects a malformed
        // `defmacro` head (NAME slot is an int, not a symbol). Pin the
        // ordering: the expand_program-stage rejection bubbles up
        // verbatim, sourced from `&str` rather than `Vec<Sexp>`.
        let mut e = Expander::new();
        let err = e
            .expand_source_program("(defmacro 5 (x) `,x)")
            .expect_err("expand_program error must propagate");
        let rendered = format!("{err}");
        assert!(
            rendered.contains("NAME") || rendered.contains("symbol"),
            "error must be the defmacro-NAME-not-a-symbol rejection, got: {rendered}"
        );
    }

    #[test]
    fn expand_source_program_yields_empty_vec_for_empty_source() {
        // Boundary: empty source string yields zero items. Pin the
        // degenerate boundary — empty in, empty out — sibling of the
        // from-source × keyword-projected test of the same name, one
        // level down the composition (no keyword filter).
        let mut e = Expander::new();
        let out = e
            .expand_source_program("")
            .expect("empty source is not an error");
        assert!(
            out.is_empty(),
            "empty source must yield empty Vec, got: {out:?}"
        );
    }

    #[test]
    fn expand_source_program_absorbs_defmacro_and_expands_subsequent_calls() {
        // Critical pipeline order: a `defmacro` in the source registers
        // AND a subsequent call to it expands AND the expanded form
        // surfaces in the returned Vec. Sourced from `&str`, the
        // from-source posture preserves the side-effect-then-expansion
        // semantics of the from-forms primitive verbatim.
        let src = r#"(defmacro emit-monitor (n) `(defmonitor :name ,n))
                     (emit-monitor "alpha")
                     (emit-monitor "beta")"#;
        let mut e = Expander::new();
        let out = e
            .expand_source_program(src)
            .expect("defmacro absorption then expansion must compose");
        // Two surviving forms (the `defmacro` itself is consumed as a
        // side-effect), each expanded to a `(defmonitor :name "<n>")`.
        assert_eq!(out.len(), 2, "expected two expanded forms, got: {out:?}");
        for (i, expected_name) in [(0, "alpha"), (1, "beta")] {
            let args = out[i]
                .as_call_to("defmonitor")
                .unwrap_or_else(|| panic!("form {i} must be defmonitor, got: {:?}", out[i]));
            assert_eq!(args[0].as_keyword(), Some("name"));
            assert_eq!(args[1].as_string(), Some(expected_name));
        }
        // The macro is now in the table — a subsequent call would
        // expand against this SAME expander.
        assert!(e.has("emit-monitor"));
    }

    #[test]
    fn expand_source_program_matches_inlined_read_plus_expand_program_path() {
        // Structural identity: for any `src` whose pieces succeed, the
        // from-source method's result equals the inlined pre-lift
        // pipeline `read + expand_program`. Pin shape AND ordering on a
        // mixed source (defmacro definition + macro call + plain form)
        // so a regression that drifts the method's pipeline from the
        // inlined closed-form fails here. This is the lift's
        // load-bearing path-uniformity gate — the SAME assertion holds
        // for both production consumers (`RealizedCompiler::compile` +
        // `realize_in_memory`'s `:macros` loop) at the primitive's
        // contract level.
        let src = r#"(defmacro id (x) `,x)
                     (id (foo 1 2))
                     (bar)"#;

        // Inlined pre-lift pipeline.
        let mut e_inline = Expander::new();
        let inline_forms = read(src).unwrap();
        let via_inline = e_inline
            .expand_program(inline_forms)
            .expect("inlined pipeline must succeed");

        // From-source method pipeline.
        let mut e_method = Expander::new();
        let via_method = e_method
            .expand_source_program(src)
            .expect("from-source method pipeline must succeed");

        assert_eq!(
            via_inline, via_method,
            "from-source method must emit byte-identical result to inlined read+expand_program"
        );
        // Both pipelines registered the same defmacro side-effect.
        assert_eq!(e_inline.has("id"), e_method.has("id"));
        assert!(e_method.has("id"));
    }

    #[test]
    fn expand_source_program_preserves_defmacro_absorption_across_repeated_calls() {
        // Per-`&mut self` absorption posture pin: a `defmacro` registered
        // in call 1 SURVIVES into call 2 on the SAME `Expander`. This is
        // the load-bearing semantic `realize_in_memory`'s per-spec-macro
        // build-up depends on — every iteration's `expand_source_program(
        // macro_src)?` lands its `defmacro` heads into the SAME mutable
        // `preloaded` expander, so a follow-up `:macros` source can
        // invoke macros defined in earlier ones.
        let mut e = Expander::new();
        let _ = e
            .expand_source_program("(defmacro outer (n) `(inner ,n))")
            .unwrap();
        assert!(e.has("outer"));
        // Call 2: defines `inner` AND invokes `outer`, which expands to
        // `(inner <n>)`. The expansion proves call 1's `outer` survived
        // into call 2's expansion.
        let out = e
            .expand_source_program("(defmacro inner (x) `(wrapped ,x)) (outer 42)")
            .unwrap();
        assert_eq!(out.len(), 1, "call 2 yields one expanded form");
        // (outer 42) → (inner 42) → (wrapped 42)
        let args = out[0]
            .as_call_to("wrapped")
            .expect("nested expansion must reach `wrapped`");
        assert_eq!(args[0].as_int(), Some(42));
    }

    // ── Expander::register_macro_def: the macro-registration primitive ──
    //
    // `register_macro_def(&mut self, def: MacroDef) -> Result<()>` lifts
    // the byte-identical two-step block —
    //
    //   if self.compile_templates {
    //       self.templates.insert(def.name.clone(), compile_template(&def)?);
    //   }
    //   self.macros.insert(def.name.clone(), def);
    //
    // — that lived inline at `with_macros` (the bulk-from-iterator
    // constructor) AND `expand_program`'s `(defmacro …)`-head arm (the
    // program-walk-time registration site) into ONE named method on the
    // `Expander` surface. The tests below pin:
    //
    //   (a) the bytecode-default expander (`Expander::new()`) populates
    //       BOTH `macros` AND `templates` keyed by `def.name`,
    //   (b) the substitute-only expander (`Expander::new_substitute_only()`)
    //       populates `macros` but SKIPS `templates` — the
    //       `compile_templates: false` gate fires structurally,
    //   (c) a template that fails to compile (`,foo` against `params:
    //       []`) short-circuits BEFORE `self.macros.insert` runs, so the
    //       failed registration leaves both tables untouched — no
    //       partial-write window in which `self.macros.has(name)` is
    //       true but `self.templates.has(name)` is missing,
    //   (d) `with_macros([def])` and `register_macro_def(def)` on a fresh
    //       expander produce structurally identical state (both tables'
    //       sets of keys + the same `MacroDef` body under each key),
    //   (e) `expand_program` of one `(defmacro …)` form and
    //       `register_macro_def` of the parsed `MacroDef` produce
    //       structurally identical state — closing path-uniformity
    //       across the lift's two consumers AT the registration site.
    //
    // The tests bind on `Expander::has(name)` / `Expander::len()` for
    // the macros table and on bytecode-vs-substitute output equivalence
    // (a registered macro must expand to the SAME result regardless of
    // whether the bytecode path's `self.templates` entry exists) for the
    // templates table.

    fn macro_def_id() -> MacroDef {
        // `(defmacro id (x) `,x)` — the simplest well-formed MacroDef:
        // one required param, a single-symbol unquote body. Compiles to
        // a valid `CompiledTemplate` (no unbound vars), so
        // `register_macro_def` succeeds on every Expander posture.
        MacroDef {
            name: "id".into(),
            params: MacroParams {
                required: vec!["x".into()],
                optional: vec![],
                rest: None,
            },
            // ` ` quasi-quoted `,x` — `Quasiquote(Unquote(Symbol("x")))`.
            body: Sexp::Quasiquote(Box::new(Sexp::Unquote(Box::new(Sexp::symbol("x"))))),
        }
    }

    fn macro_def_bad_template() -> MacroDef {
        // `(defmacro bad () `,unbound)` — a quasi-quote body with `,unbound`
        // against an EMPTY required-params list. `compile_template`
        // rejects it with `UnboundTemplateVar` because `unbound` is not
        // in `params.names()`. Used to exercise the
        // `compile_template`-failed-but-self.macros-still-pristine
        // path-uniformity pin.
        MacroDef {
            name: "bad".into(),
            params: MacroParams::default(),
            body: Sexp::Quasiquote(Box::new(Sexp::Unquote(Box::new(Sexp::symbol("unbound"))))),
        }
    }

    #[test]
    fn register_macro_def_bytecode_default_populates_macros_and_templates() {
        // The bytecode-default `Expander::new()` carries
        // `compile_templates: true`; `register_macro_def` MUST populate
        // BOTH `self.macros` (the substitute path's registry) AND
        // `self.templates` (the bytecode path's pre-compiled bytecode
        // index) keyed by `def.name`. Fail-before-pass-after: this
        // assert requires the new method to exist AND to compose the
        // two side-effects in canonical order on a single-call
        // registration — pre-lift `register_macro_def` did not exist.
        let mut e = Expander::new();
        e.register_macro_def(macro_def_id())
            .expect("well-formed MacroDef must register");
        assert!(
            e.has("id"),
            "self.macros must carry the registered name after register_macro_def"
        );
        assert!(
            e.templates.contains_key("id"),
            "self.templates must carry the compiled bytecode under the bytecode-default posture"
        );
        // The registered macro must expand correctly through the
        // bytecode strategy — proves the inserted template is the right
        // bytecode for the body.
        let out = e
            .expand_program(read("(id 42)").unwrap())
            .expect("registered macro must expand");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], Sexp::int(42));
    }

    #[test]
    fn register_macro_def_substitute_only_skips_templates() {
        // `Expander::new_substitute_only()` carries `compile_templates:
        // false`; `register_macro_def` MUST populate `self.macros` for
        // the substitute path but SKIP `self.templates` (no bytecode
        // pre-compile). Pin the `compile_templates: false` gate fires
        // structurally — a regression that drifts the conditional from
        // the registration primitive (e.g. a future emitter that
        // unconditionally pre-compiles) would silently double the
        // benchmark baseline's allocation footprint.
        let mut e = Expander::new_substitute_only();
        e.register_macro_def(macro_def_id())
            .expect("well-formed MacroDef must register under substitute-only");
        assert!(
            e.has("id"),
            "self.macros must carry the registered name even under substitute-only"
        );
        assert!(
            !e.templates.contains_key("id"),
            "self.templates MUST be empty under compile_templates: false — the gate fires"
        );
        // The registered macro must still expand correctly through the
        // substitute strategy — proves the inserted MacroDef is the
        // right body for substitute-walking.
        let out = e
            .expand_program(read("(id 42)").unwrap())
            .expect("registered macro must expand via substitute path");
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], Sexp::int(42));
    }

    #[test]
    fn register_macro_def_template_compile_failure_leaves_both_tables_pristine() {
        // The structural ordering pin: when `compile_template(&def)?`
        // rejects (e.g. `,unbound` against empty params), the `?` MUST
        // short-circuit BEFORE `self.macros.insert(def.name.clone(),
        // def)` runs, so a failed registration leaves BOTH tables
        // exactly as they were. Without this ordering a future
        // bytecode-strategy lookup would resolve `self.macros.get(name)`
        // (the body was inserted) AND find `self.templates.get(name)`
        // returning `None` (the pre-compile failed), silently coercing
        // the macro onto the substitute fallback path despite
        // `compile_templates: true`. The lift preserves the pre-lift
        // ordering (`compile_template` precedes `self.macros.insert`)
        // structurally — the test pins it across the lift.
        let mut e = Expander::new();
        let err = e
            .register_macro_def(macro_def_bad_template())
            .expect_err("unbound-template body must reject");
        // The rejection is the structural variant the bytecode
        // strategy's template-gate emits.
        assert!(
            matches!(err, LispError::UnboundTemplateVar { .. }),
            "expected UnboundTemplateVar, got: {err:?}"
        );
        // Both tables MUST be pristine — no partial write.
        assert!(
            !e.has("bad"),
            "self.macros must be untouched after compile_template failure"
        );
        assert!(
            !e.templates.contains_key("bad"),
            "self.templates must be untouched after compile_template failure"
        );
    }

    #[test]
    fn with_macros_routes_through_register_macro_def_path_uniformity() {
        // Path-uniformity pin across the bulk-constructor consumer:
        // `with_macros([def])` MUST produce the same final state as
        // `Expander::new()` + `register_macro_def(def)`. A regression
        // that drifts the constructor's per-MacroDef inline block from
        // the registration primitive (e.g. a future emitter that
        // re-inlines the two-step block at `with_macros` rather than
        // delegating) would fail loudly here.
        let mut via_register = Expander::new();
        via_register
            .register_macro_def(macro_def_id())
            .expect("register must succeed");
        let mut via_with_macros =
            Expander::with_macros([macro_def_id()]).expect("with_macros must succeed");
        assert_eq!(via_register.len(), via_with_macros.len());
        assert!(via_register.has("id"));
        assert!(via_with_macros.has("id"));
        // Both tables key on the same set across both postures.
        assert_eq!(
            via_register.templates.contains_key("id"),
            via_with_macros.templates.contains_key("id"),
            "self.templates key-presence must agree across with_macros and register_macro_def"
        );
        // Both registered expanders expand the registered macro
        // identically — the strongest behavioral parity.
        let out_a = via_register
            .expand_program(read("(id 99)").unwrap())
            .unwrap();
        let out_b = via_with_macros
            .expand_program(read("(id 99)").unwrap())
            .unwrap();
        assert_eq!(out_a, out_b);
        assert_eq!(out_a, vec![Sexp::int(99)]);
    }

    #[test]
    fn expand_program_routes_through_register_macro_def_path_uniformity() {
        // Path-uniformity pin across the program-walk consumer:
        // `expand_program` of `(defmacro id (x) `,x)` MUST produce the
        // same final state as a direct
        // `register_macro_def(macro_def_id())`. A regression that
        // drifts `expand_program`'s `(defmacro …)`-head arm from the
        // registration primitive (e.g. a future emitter that re-inlines
        // the two-step block at `expand_program` rather than delegating)
        // would fail loudly here.
        let mut via_register = Expander::new();
        via_register
            .register_macro_def(macro_def_id())
            .expect("register must succeed");
        let mut via_expand_program = Expander::new();
        let yielded = via_expand_program
            .expand_program(read("(defmacro id (x) `,x)").unwrap())
            .expect("expand_program of one defmacro must succeed");
        // expand_program drops the (defmacro …) form from its returned
        // Vec<Sexp> (defmacro is a definition, not a program form), so
        // the yielded list is empty — pin the side-effect-only posture.
        assert!(
            yielded.is_empty(),
            "(defmacro …) is a side-effect-only top-level form; expand_program yields nothing"
        );
        assert!(via_register.has("id"));
        assert!(via_expand_program.has("id"));
        assert_eq!(via_register.len(), via_expand_program.len());
        // Both tables key on the same set across both postures.
        assert_eq!(
            via_register.templates.contains_key("id"),
            via_expand_program.templates.contains_key("id"),
            "self.templates key-presence must agree across expand_program and register_macro_def"
        );
        // Both registered expanders expand the registered macro
        // identically — the strongest behavioral parity, closing
        // path-uniformity across BOTH consumers (with_macros above,
        // expand_program here) at ONE primitive.
        let out_a = via_register
            .expand_program(read("(id 7)").unwrap())
            .unwrap();
        let out_b = via_expand_program
            .expand_program(read("(id 7)").unwrap())
            .unwrap();
        assert_eq!(out_a, out_b);
        assert_eq!(out_a, vec![Sexp::int(7)]);
    }

    // ── as_unquote: path-uniformity across the three substitute / compile_node sites ──
    //
    // The new typed-marker projection `Sexp::as_unquote` lifts the
    // (Sexp::Unquote/UnquoteSplice variant, UnquoteForm::Unquote/Splice
    // literal) pair into ONE structural query. These tests pin behavioral
    // parity end-to-end across BOTH expansion strategies:
    //   * `compile_node` — the bytecode-template strategy's typed marker
    //     dispatch routes through as_unquote at the compile step.
    //   * `substitute` (top-level + list-inner) — the substitute-walker
    //     fallback strategy's typed marker dispatch routes through
    //     as_unquote at both per-form sites.
    // The structural invariant the prior runs' `expansion_layers_agree_on_
    // output_and_cache_wins` benchmark observes — bytecode AND substitute
    // produce byte-identical output — is anchored here at the macro-template
    // level for every distinct unquote-family shape the substitute and
    // bytecode strategies discriminate.

    #[test]
    fn bytecode_and_substitute_agree_on_unquote_substitution_routed_through_as_unquote() {
        // A template body whose only marker is a top-level `,x`. Both
        // expansion strategies route through `as_unquote` (compile_node for
        // bytecode, substitute for the fallback walker), each pairing
        // Sexp::Unquote ↔ UnquoteForm::Unquote at ONE typed projection.
        // Pin byte-identical output across both strategies — the
        // structural-invariant the new projection's lift was designed to
        // make load-bearing structural rather than per-site discipline.
        let src = "(defmacro id (x) ,x) (id 42)";
        let mut bc = Expander::new();
        let mut sub = Expander::new_substitute_only();
        let out_bc = bc.expand_program(read(src).unwrap()).unwrap();
        let out_sub = sub.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out_bc, out_sub, "strategies diverged on `,x` template");
        assert_eq!(out_bc, vec![Sexp::int(42)]);
    }

    #[test]
    fn bytecode_and_substitute_agree_on_unquote_splice_routed_through_as_unquote() {
        // A template body whose marker is a list-inner `,@xs`. The substitute
        // strategy's list-inner Splice arm routes through `as_unquote`
        // matching Some((UnquoteForm::Splice, inner)); the bytecode strategy's
        // compile_node Splice arm routes through `as_unquote` matching the
        // same. Pin byte-identical output across both strategies for the
        // splice path — the projection's typed-marker pairing
        // Sexp::UnquoteSplice ↔ UnquoteForm::Splice is structurally
        // identical at every consumer post-lift.
        let src = "(defmacro wrap (xs) (list 0 ,@xs 99)) (wrap (1 2 3))";
        let mut bc = Expander::new();
        let mut sub = Expander::new_substitute_only();
        let out_bc = bc.expand_program(read(src).unwrap()).unwrap();
        let out_sub = sub.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out_bc, out_sub, "strategies diverged on `,@xs` template");
        let expected = Sexp::List(vec![
            Sexp::symbol("list"),
            Sexp::int(0),
            Sexp::int(1),
            Sexp::int(2),
            Sexp::int(3),
            Sexp::int(99),
        ]);
        assert_eq!(out_bc, vec![expected]);
    }

    #[test]
    fn substitute_splice_outside_list_routes_through_as_unquote_typed_marker() {
        // The substitute strategy's top-level `,@x` arm rejects with
        // LispError::SpliceOutsideList (a splice marker with no containing
        // list to flatten into). Pre-lift the arm was
        // `Sexp::UnquoteSplice(inner) => Err(splice_outside_list(inner))`;
        // post-lift the arm routes through `as_unquote` matching
        // Some((UnquoteForm::Splice, inner)) and dispatches on the typed
        // marker. Pin path-uniformity: the rejection MUST fire identically
        // through the new projection. The substitute-only strategy bypasses
        // the bytecode path, exposing this gate directly.
        //
        // `(defmacro bad (xs) ,@xs) (bad (1 2 3))` — the body is a bare
        // `,@xs` at top level (NOT wrapped in a containing list), so the
        // substitute fallback's top-level Splice arm fires.
        let src = "(defmacro bad (xs) ,@xs) (bad (1 2 3))";
        let mut sub = Expander::new_substitute_only();
        let err = sub.expand_program(read(src).unwrap()).unwrap_err();
        assert!(
            matches!(err, crate::error::LispError::SpliceOutsideList { .. }),
            "expected SpliceOutsideList through as_unquote, got: {err:?}"
        );
    }

    #[test]
    fn as_unquote_threads_typed_marker_into_unbound_template_var_rejection() {
        // A `,unbound` template body — the inner symbol isn't a param —
        // fires gate-2 (must-be-bound-in-scope). The typed marker
        // `UnquoteForm::Unquote` MUST thread through `as_unquote` →
        // `resolve_unquote_in_params(inner, params, form)` → gate-2's
        // rejection-builder. Pre-lift the marker was bound at the per-arm
        // literal `UnquoteForm::Unquote`; post-lift it's bound at the
        // typed projection. Pin: the rejection's `prefix` slot is
        // UnquoteForm::Unquote, structurally derived from the typed
        // projection's typed marker, NOT a literal at the arm body.
        let src = "(defmacro bad (x) ,unbound)";
        let mut bc = Expander::new();
        let err = bc.expand_program(read(src).unwrap()).unwrap_err();
        match err {
            crate::error::LispError::UnboundTemplateVar { prefix, .. } => {
                assert_eq!(
                    prefix,
                    UnquoteForm::Unquote,
                    "typed marker drifted from UnquoteForm::Unquote at gate-2"
                );
            }
            other => panic!("expected UnboundTemplateVar, got: {other:?}"),
        }
        // Sibling negative control: `,@unbound` inside a containing list
        // threads UnquoteForm::Splice through the same projection. The
        // splice MUST be inside a list — `compile_template` rejects
        // top-level `,@X` bodies with SpliceOutsideList before compile_node
        // runs, so the typed-marker dispatch on Splice is observable only
        // for well-positioned splice bodies. Closes path-uniformity across
        // BOTH typed marker variants at the compile path.
        let src_splice = "(defmacro bad (x) (foo ,@unbound))";
        let mut bc2 = Expander::new();
        let err_splice = bc2.expand_program(read(src_splice).unwrap()).unwrap_err();
        match err_splice {
            crate::error::LispError::UnboundTemplateVar { prefix, .. } => {
                assert_eq!(
                    prefix,
                    UnquoteForm::Splice,
                    "typed marker drifted from UnquoteForm::Splice at gate-2"
                );
            }
            other => panic!("expected UnboundTemplateVar, got: {other:?}"),
        }
    }

    // ── compile_template + contains_unquote path-uniformity through as_unquote ──
    //
    // The prior `as_unquote` projection lift (eb00684) routed `compile_node`'s
    // two arms and `substitute`'s top-level + list-inner arms through the
    // typed-marker projection but LEFT `compile_template`'s top-level
    // splice-outside-list gate and `contains_unquote`'s family check inline
    // matching `Sexp::UnquoteSplice(inner)` / `Sexp::Unquote(_) |
    // Sexp::UnquoteSplice(_)`. After this lift both production sites route
    // through `as_unquote`: `compile_template` matches `Some((UnquoteForm::
    // Splice, inner))` (same shape as `substitute`'s list-inner Splice arm),
    // `contains_unquote` uses `as_unquote().is_some()` for the family check.
    // Every production-site recognizer of an unquote-family wrapper now
    // shares ONE typed-marker projection — the (Sexp variant, UnquoteForm
    // variant) pairing for `,@-outside-list` is bound at ONE structural
    // query across all FOUR reachable splice-recognition sites, and a future
    // regression that drifts the marker pairing at any production site
    // becomes a type error at the helper boundary rather than a silent
    // per-site divergence.

    #[test]
    fn compile_template_splice_outside_list_routes_through_as_unquote_typed_marker() {
        // The bytecode path's `compile_template` gate pre-rejects top-level
        // `,@X` bodies via `as_unquote()` matching `Some((UnquoteForm::Splice,
        // inner))`. Pre-lift the arm was `if let Sexp::UnquoteSplice(inner) =
        // body` — the LAST production-site inline `Sexp::UnquoteSplice(_)`
        // match outside the projection itself. Post-lift the (Sexp variant,
        // UnquoteForm variant) pairing for the splice-outside-list gate is
        // bound at ONE projection function across all three reachable
        // emission sites (compile_template top-level, substitute top-level,
        // substitute list-inner). Path-uniformity guard at the new boundary:
        // the bytecode-path compile-time gate now routes through the same
        // shape `substitute`'s list-inner Splice arm uses.
        //
        // `(defmacro bad (xs) \`,@xs)` — the body's outer quasi-quote is
        // peeled by `template_body`, leaving `,@xs` at top level for
        // `compile_template` to gate before `compile_node` walks anything.
        // The bytecode strategy is default-on (`Expander::new()` sets
        // `compile_templates: true`), so the gate fires at
        // `register_macro_def` time.
        let mut e = Expander::new();
        let err = e
            .expand_program(read("(defmacro bad (xs) `,@xs)").unwrap())
            .expect_err("compile_template must reject top-level ,@X via as_unquote");
        assert!(
            matches!(err, crate::error::LispError::SpliceOutsideList { .. }),
            "expected SpliceOutsideList through as_unquote, got: {err:?}"
        );
    }

    #[test]
    fn compile_template_accepts_top_level_unquote_through_as_unquote_typed_marker() {
        // Negative control on the typed-marker dispatch at `compile_template`'s
        // top-level gate. A top-level `,X` body (Unquote, NOT Splice) is a
        // valid template — `compile_node` lowers it to a single `Subst(idx)`
        // op. The new `Some((UnquoteForm::Splice, inner))` pattern at the
        // gate MUST NOT fire on the Unquote variant — only Splice — so the
        // typed marker is observably load-bearing: a regression that drifts
        // the pattern from `UnquoteForm::Splice` to the wider
        // `Some((_, inner))` would mis-reject `(defmacro id (x) ,x)` here.
        //
        // `(defmacro id (x) ,x) (id 42)` — `id`'s body is bare `,x` at top
        // level; `compile_template` admits it via the typed-marker gate,
        // `compile_node` emits `Subst(0)`, and the call expands to `42`.
        let src = "(defmacro id (x) ,x) (id 42)";
        let mut e = Expander::new();
        let expanded = e
            .expand_program(read(src).unwrap())
            .expect("top-level ,X body must compile through as_unquote-typed gate");
        assert_eq!(expanded, vec![Sexp::int(42)]);
    }

    #[test]
    fn contains_unquote_routes_through_as_unquote_for_unquote_family_recognition() {
        // The fast-path optimizer in `compile_node` short-circuits on
        // `contains_unquote(node)` — true iff the subtree carries an
        // unquote-family wrapper. Pre-lift the family check inlined
        // `Sexp::Unquote(_) | Sexp::UnquoteSplice(_) => true`; post-lift it
        // routes through `as_unquote().is_some()`. Pin path-uniformity at
        // the family-recognition boundary: every production-site unquote
        // recognizer (compile_template's gate, compile_node's per-arm
        // dispatch, substitute's top-level + list-inner arms, AND this
        // fast-path predicate) now shares ONE typed-marker projection.
        //
        // Both variants must trigger the fast-path bail — the optimizer's
        // gate keys on the family, not the inner. The recursion into
        // Quote/Quasiquote/List subtrees ALSO observes the same family
        // gate at every level, so a `,@xs` buried under a `\`...` outer
        // wrapper still fires it.
        let bare_unquote = Sexp::Unquote(Box::new(Sexp::symbol("x")));
        let bare_splice = Sexp::UnquoteSplice(Box::new(Sexp::symbol("xs")));
        let nested = Sexp::Quasiquote(Box::new(Sexp::List(vec![
            Sexp::symbol("foo"),
            Sexp::UnquoteSplice(Box::new(Sexp::symbol("xs"))),
        ])));
        // The projection's `is_some()` face MUST agree with the pre-lift
        // `matches!()` discriminant on every variant — closed-set guarantee
        // shared with `as_unquote`'s contract pin in `ast.rs`.
        assert!(super::contains_unquote(&bare_unquote));
        assert!(super::contains_unquote(&bare_splice));
        assert!(super::contains_unquote(&nested));
        // Negative control: shapes the projection rejects (Nil, Atom,
        // bare List, Quote-family without inner unquote) must NOT trigger
        // the fast-path bail — the projection's None face stays observably
        // distinct from its Some face.
        assert!(!super::contains_unquote(&Sexp::Nil));
        assert!(!super::contains_unquote(&Sexp::symbol("plain")));
        assert!(!super::contains_unquote(&Sexp::int(5)));
        assert!(!super::contains_unquote(&Sexp::List(vec![
            Sexp::symbol("plain"),
            Sexp::int(1),
        ])));
        assert!(!super::contains_unquote(&Sexp::Quote(Box::new(
            Sexp::symbol("inert")
        ))));
    }

    #[test]
    fn contains_unquote_routes_quote_family_through_as_quote_form_typed_marker() {
        // Pin the lift: `contains_unquote`'s quote-family recognition
        // now routes through `Sexp::as_quote_form` (the 4-of-4 wrapper
        // projection) AND `QuoteForm::as_unquote_form` (the 2-of-4
        // substitution-subset gate) at ONE site — not through the pair
        // of `as_unquote().is_some()` + inline
        // `Sexp::Quote(inner) | Sexp::Quasiquote(inner)` arm. The
        // path-uniformity assertion: for every quote-family wrapper, the
        // function's behavior agrees with the manual composition through
        // the two typed-marker projections. A regression that re-inlines
        // either arm (e.g. drops the `as_unquote_form().is_some()` gate
        // and just returns true for any `as_quote_form().is_some()`, or
        // restores the per-variant `Quote | Quasiquote` arm) drifts from
        // this composition and surfaces here.
        use crate::ast::QuoteForm;

        // Sweep every QuoteForm variant under both axes:
        //   * unquote-only-inner (inner = symbol):
        //       Unquote(s)        → true via `as_unquote_form() == Some`
        //       UnquoteSplice(s)  → true via `as_unquote_form() == Some`
        //       Quote(s)          → false (inner has no unquote, recurses to false)
        //       Quasiquote(s)     → false (same)
        //   * unquote-inner-inside-quote-wrapper:
        //       Quote(Unquote(s)) → true (Quote arm recurses via `as_quote_form`,
        //                                 inner `Unquote` returns true through the
        //                                 SAME projection — both arms share the
        //                                 ONE typed-marker site post-lift)
        let inner_plain = Sexp::symbol("x");
        let inner_unquote = Sexp::Unquote(Box::new(Sexp::symbol("x")));

        for qf in QuoteForm::ALL {
            let wrapped_plain = match qf {
                QuoteForm::Quote => Sexp::Quote(Box::new(inner_plain.clone())),
                QuoteForm::Quasiquote => Sexp::Quasiquote(Box::new(inner_plain.clone())),
                QuoteForm::Unquote => Sexp::Unquote(Box::new(inner_plain.clone())),
                QuoteForm::UnquoteSplice => Sexp::UnquoteSplice(Box::new(inner_plain.clone())),
            };
            // Path-uniformity: behavior derives from the manual two-marker
            // composition through `as_quote_form` + `as_unquote_form`.
            // The substitution-subset gate (`as_unquote_form().is_some()`)
            // returns true for Unquote/UnquoteSplice and false for
            // Quote/Quasiquote — directly encoding the 2-of-4 partition.
            let via_manual =
                qf.as_unquote_form().is_some() || super::contains_unquote(&inner_plain);
            assert_eq!(
                super::contains_unquote(&wrapped_plain),
                via_manual,
                "contains_unquote drifted from as_quote_form + as_unquote_form composition for {qf:?}"
            );

            let wrapped_unquote = match qf {
                QuoteForm::Quote => Sexp::Quote(Box::new(inner_unquote.clone())),
                QuoteForm::Quasiquote => Sexp::Quasiquote(Box::new(inner_unquote.clone())),
                QuoteForm::Unquote => Sexp::Unquote(Box::new(inner_unquote.clone())),
                QuoteForm::UnquoteSplice => Sexp::UnquoteSplice(Box::new(inner_unquote.clone())),
            };
            // EVERY quote-family wrapper around an inner `Unquote` must
            // contain unquote — either the outer projects as `Some` on
            // the substitution subset (Unquote/UnquoteSplice arms), OR
            // the outer is Quote/Quasiquote and the recursion into the
            // inner re-fires the projection. The pre-lift Quote arm
            // recursed via the inline `Sexp::Quote(inner)` match;
            // post-lift the SAME recursion fires via `as_quote_form`'s
            // typed projection. Both yield `true`.
            assert!(
                super::contains_unquote(&wrapped_unquote),
                "contains_unquote missed an inner Unquote under {qf:?} — \
                 the quote-family recursion through as_quote_form drifted"
            );
        }

        // Negative control: a non-quote-family wrapper (List, Atom,
        // Nil) must NOT route through `as_quote_form` at all. The
        // `if let Some(...) = node.as_quote_form()` gate stays `None`
        // and falls through to the List/_  arms. This is the structural
        // partition: the projection's `None` face MUST agree with
        // `!matches!(node, Sexp::Quote(_) | Sexp::Quasiquote(_) |
        // Sexp::Unquote(_) | Sexp::UnquoteSplice(_))`.
        let nested_in_list = Sexp::List(vec![
            Sexp::symbol("outer"),
            Sexp::Quasiquote(Box::new(Sexp::Unquote(Box::new(Sexp::symbol("x"))))),
        ]);
        assert!(
            super::contains_unquote(&nested_in_list),
            "contains_unquote failed to descend into a List subtree containing a \
             Quasiquote(Unquote(_)) — list recursion arm drifted"
        );
    }

    // ── expand_and_collect_named_calls_to_any (from-forms × named ────
    // × typed-decoded classifier) ─────────────────────────────────────
    //
    // The (named NAME-then-kwargs × typed-decoded classifier) cell of
    // the dispatcher matrix on the `Expander` surface — pre-lift the
    // matrix had the bare-kwargs row closed (expand_and_collect_calls_to
    // + expand_and_collect_calls_to_any) AND the constant-keyword
    // column closed on the named axis (expand_to_named +
    // expand_source_to_named) but the (named × classifier) cell was
    // open — every consumer that wanted to walk a program by typed-
    // decoded classifier AND extract the NAME slot per matched form
    // had to compose `expand_and_collect_calls_to_any` with
    // `split_name_slot` inline. Post-lift the cell is ONE named primitive
    // on the `Expander` surface, and the constant-`T::KEYWORD` named
    // sibling routes through it as the (constant-classifier × named)
    // specialization.
    //
    // The tests below pin: (a) the happy path yields the decoded triple
    // `(T, &str, &[Sexp])` for every matched form in source order; (b)
    // non-matching forms are skipped (soft-projection contract inherited
    // from the typed-decoded primitive); (c) the `NamedFormMissingName`
    // variant fires for matched forms with no NAME slot, threading the
    // classifier-supplied `&'static str` keyword; (d) the
    // `NamedFormNonSymbolName` variant fires for matched forms with a
    // non-symbol-or-string NAME slot, again threading the classifier-
    // supplied keyword; (e) the projection's `Err` short-circuits at
    // the first failing matched form; (f) `expand_program` runs BEFORE
    // the classifier filter walks — a `(defmacro …)` emitting a named
    // form is decoded by the classifier on the EXPANDED head, not the
    // macro-call head; (g) the from-source sibling agrees with `read +
    // from-forms` on the same source.

    #[test]
    fn expand_and_collect_named_calls_to_any_yields_decoded_triple_for_every_matching_form_in_source_order(
    ) {
        // The typed-decoded named primitive's happy path: a closed-set
        // classifier decodes head symbols to a typed enum PAIRED with
        // its canonical static keyword, and the per-form projection
        // receives `(decoded, name, spec_args)` for every matched form
        // in source order. Sweep across TWO distinct classifier outcomes
        // — `Monitor` / `Notify` — interleaved with a non-matching form
        // to pin the typed-witness threading AND the NAME-slot
        // projection AND the source-order yield AND the rejection of
        // non-classifier forms in ONE assertion.
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        enum Kind {
            Monitor,
            Notify,
        }
        let src = r#"(defmonitor cpu :threshold 80)
                     (other-form 99)
                     (defnotify email :to "ops@example.com")
                     (defmonitor mem :threshold 90)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let rows: Vec<(Kind, String, usize)> = e
            .expand_and_collect_named_calls_to_any(
                forms,
                |h| match h {
                    "defmonitor" => Some((Kind::Monitor, "defmonitor")),
                    "defnotify" => Some((Kind::Notify, "defnotify")),
                    _ => None,
                },
                |kind, name, spec_args| Ok((kind, name.to_string(), spec_args.len())),
            )
            .unwrap();
        assert_eq!(
            rows,
            vec![
                (Kind::Monitor, "cpu".to_string(), 2),
                (Kind::Notify, "email".to_string(), 2),
                (Kind::Monitor, "mem".to_string(), 2),
            ],
        );
    }

    #[test]
    fn expand_and_collect_named_calls_to_any_skips_non_matching_forms_without_invoking_project() {
        // Soft-projection contract — every shape the typed-decoded
        // primitive rejects (non-list, empty list, list whose head is
        // not a symbol, list whose head decodes to `None`) skips the
        // projection silently. The named gate inside the wrapper
        // projection runs ONLY for classifier-matched forms; a non-
        // matching form that reaches the projection panics here.
        let src = r#":bare-keyword
                     "bare-string"
                     42
                     ()
                     (foo bar)
                     (defmonitor cpu :threshold 80)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let names: Vec<String> = e
            .expand_and_collect_named_calls_to_any(
                forms,
                |h| (h == "defmonitor").then_some(((), "defmonitor")),
                |(), name, _args| Ok(name.to_string()),
            )
            .unwrap();
        assert_eq!(names, vec!["cpu".to_string()]);
    }

    #[test]
    fn expand_and_collect_named_calls_to_any_emits_named_form_missing_name_through_classifier_keyword(
    ) {
        // `(defmonitor)` matches the classifier but has no NAME slot —
        // `split_name_slot` fires `NamedFormMissingName { keyword:
        // "defmonitor" }`. The classifier's `&'static str` keyword is
        // threaded VERBATIM through the named gate; a regression that
        // hardcodes a different keyword (e.g. the matched head text or
        // a default) would fail the structural variant identity
        // assertion. Fail-before-pass-after: pre-lift the primitive did
        // not exist; the inline `expand_and_collect_calls_to_any +
        // split_name_slot` composition at the consumer site was the
        // only path, with the keyword bound at the consumer's call
        // boundary rather than at the named primitive's body.
        let forms = read("(defmonitor)").unwrap();
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_named_calls_to_any::<(), _, _, ()>(
                forms,
                |h| (h == "defmonitor").then_some(((), "defmonitor")),
                |(), _name, _args| Ok(()),
            )
            .unwrap_err();
        assert!(
            matches!(
                err,
                crate::error::LispError::NamedFormMissingName {
                    keyword: "defmonitor"
                }
            ),
            "expected NamedFormMissingName with classifier-supplied keyword, got: {err:?}"
        );
    }

    #[test]
    fn expand_and_collect_named_calls_to_any_emits_named_form_non_symbol_name_through_classifier_keyword(
    ) {
        // `(defmonitor 42 :threshold 80)` matches the classifier but
        // the NAME slot is an int — `split_name_slot` fires
        // `NamedFormNonSymbolName { keyword: "defmonitor", got:
        // SexpShape::Int }`. The classifier's `&'static str` keyword is
        // threaded through the structural rejection variant verbatim,
        // and the typed `SexpShape` projection on the offending slot
        // is preserved across the named primitive.
        let forms = read("(defmonitor 42 :threshold 80)").unwrap();
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_named_calls_to_any::<(), _, _, ()>(
                forms,
                |h| (h == "defmonitor").then_some(((), "defmonitor")),
                |(), _name, _args| Ok(()),
            )
            .unwrap_err();
        assert!(
            matches!(
                err,
                crate::error::LispError::NamedFormNonSymbolName {
                    keyword: "defmonitor",
                    got: crate::error::SexpShape::Int,
                }
            ),
            "expected NamedFormNonSymbolName with classifier-supplied keyword + SexpShape::Int, got: {err:?}"
        );
    }

    #[test]
    fn expand_and_collect_named_calls_to_any_short_circuits_on_project_error_at_first_failure() {
        // Result projection's short-circuit contract — when the
        // projection returns `Err` on a matched named form, the walk
        // stops and subsequent matched forms are NOT projected. Pin
        // source-order short-circuit via a counter the projection
        // increments before deciding to fail: the counter sits at
        // exactly the index of the failing form (second match),
        // proving the third match never reached the projection.
        let forms = read("(defmon a :x 1) (defmon b :x 2) (defmon c :x 3)").unwrap();
        let mut count = 0usize;
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_named_calls_to_any::<String, _, _, ()>(
                forms,
                |h| (h == "defmon").then_some(((), "defmon")),
                |(), name, _args| {
                    count += 1;
                    if name == "b" {
                        return Err(crate::error::LispError::Missing("test-failure"));
                    }
                    Ok(name.to_string())
                },
            )
            .expect_err("projection must short-circuit on first Err");
        assert_eq!(
            count, 2,
            "projection must have run on first matched form AND the failing form, then stopped"
        );
        assert!(
            matches!(err, crate::error::LispError::Missing("test-failure")),
            "expected the projection's typed Err verbatim, got: {err:?}"
        );
    }

    #[test]
    fn expand_and_collect_named_calls_to_any_expands_macros_before_filtering_by_classifier() {
        // Ordering contract — `expand_program` runs BEFORE the
        // typed-decoded named walk. A `(defmacro …)` form that emits a
        // classifier-decoded named form must have its EXPANDED head
        // decoded by the classifier, not the macro-call head. Pin the
        // ordering with a macro `(emit-mon n thr)` expanding to
        // `(defmonitor ,n :threshold ,thr)` — the classifier sees the
        // expanded `defmonitor` head and the NAME slot's symbol value
        // from the macro arg.
        let src = r#"(defmacro emit-mon (n thr) `(defmonitor ,n :threshold ,thr))
                     (defmonitor cpu :threshold 80)
                     (emit-mon mem 90)
                     (other-form 99)
                     (emit-mon disk 70)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let names: Vec<String> = e
            .expand_and_collect_named_calls_to_any(
                forms,
                |h| (h == "defmonitor").then_some(((), "defmonitor")),
                |(), name, _args| Ok(name.to_string()),
            )
            .unwrap();
        // `cpu` from the literal call, `mem` from the first macro
        // emit, `disk` from the second macro emit. The macro-emitted
        // forms are present BECAUSE `expand_program` ran first.
        assert_eq!(names, vec!["cpu", "mem", "disk"]);
    }

    #[test]
    fn expand_source_and_collect_named_calls_to_any_matches_inlined_read_plus_from_forms_path() {
        // From-source posture parity: feeding source through
        // `expand_source_and_collect_named_calls_to_any` is byte-
        // identical to feeding `read(src)?` through the from-forms
        // sibling on a fresh expander, because the from-source posture
        // is `read(src)? + from-forms` by construction. A regression
        // that drifts the from-source posture's pipeline from the
        // from-forms posture's pipeline would fail here.
        let src = r#"(defmonitor cpu :threshold 80)
                     (defmonitor mem :threshold 90)"#;
        let via_src: Vec<String> = Expander::new()
            .expand_source_and_collect_named_calls_to_any(
                src,
                |h| (h == "defmonitor").then_some(((), "defmonitor")),
                |(), name, _args| Ok(name.to_string()),
            )
            .unwrap();
        let forms = read(src).unwrap();
        let via_forms: Vec<String> = Expander::new()
            .expand_and_collect_named_calls_to_any(
                forms,
                |h| (h == "defmonitor").then_some(((), "defmonitor")),
                |(), name, _args| Ok(name.to_string()),
            )
            .unwrap();
        assert_eq!(via_src, via_forms);
        assert_eq!(via_src, vec!["cpu".to_string(), "mem".to_string()]);
    }

    #[test]
    fn expand_source_and_collect_named_calls_to_any_short_circuits_on_reader_error_before_classifier_runs(
    ) {
        // `?`-routing through `read` short-circuits BEFORE the
        // classifier or the named gate runs. Unbalanced paren — reader
        // error fires; classifier panic-decoder MUST NOT execute,
        // proving the read step gates the entire pipeline.
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_named_calls_to_any::<(), _, _, ()>(
                "(defmonitor cpu :threshold 80",
                |_h| panic!("classifier must not run when reader fails"),
                |(), _name, _args| Ok(()),
            )
            .unwrap_err();
        // The named gate's variants MUST NOT fire — the reader error
        // is structurally distinct.
        assert!(
            !matches!(
                err,
                crate::error::LispError::NamedFormMissingName { .. }
                    | crate::error::LispError::NamedFormNonSymbolName { .. }
            ),
            "expected reader error, not named-gate variant; got: {err:?}"
        );
    }

    // ── expand_and_collect_named_calls_to (from-forms × named × ──────
    // constant-keyword × untyped R) ─────────────────────────────────
    //
    // The (named NAME-then-kwargs × constant-keyword × untyped `R`)
    // cell of the `Expander` typed-walk family — pre-lift the cell was
    // reachable ONLY through `expand_to_named<T>` with the
    // `T: TataraDomain` parameter baking BOTH the `T::KEYWORD` filter
    // AND the `T::compile_from_args`-based projection through
    // `expand_and_collect_calls_to(forms, T::KEYWORD,
    // named_form_projection::<T>)`. Post-lift the cell surfaces as ONE
    // method that takes the keyword and the `(name, args) -> R`
    // projection as caller-supplied parameters, AND
    // `expand_to_named<T>` routes through it as the typed
    // `T::KEYWORD`-constant specialization — so the named-form
    // `split_name_slot` composition lives at ONE site
    // (`expand_and_collect_named_calls_to_any` body) post-lift rather
    // than at TWO sites pre-lift (the bare-kwargs path through
    // `named_form_projection<T>` AND the classifier path).
    //
    // The tests below pin: (a) the happy path yields the `(name, args)`
    // pair for every matched form in source order; (b) non-matching
    // forms are skipped (soft-projection contract inherited from the
    // named typed-decoded primitive); (c) the `NamedFormMissingName`
    // variant fires for matched forms with no NAME slot, threading the
    // primitive's `&'static str` keyword; (d) the
    // `NamedFormNonSymbolName` variant fires for matched forms with a
    // non-symbol-or-string NAME slot, again threading the primitive's
    // keyword; (e) the projection's `Err` short-circuits at the first
    // failing matched form; (f) `expand_program` runs BEFORE the
    // keyword filter walks — a `(defmacro …)` emitting a named form
    // has its EXPANDED head matched by the constant-keyword filter,
    // not the macro-call head; (g) the from-source sibling agrees with
    // `read + from-forms` on the same source; (h) the constant-
    // classifier composition law binds the runtime-keyword cell
    // (`expand_and_collect_named_calls_to`) to the typed-decoded
    // classifier cell (`expand_and_collect_named_calls_to_any`) via a
    // constant-classifier decoder.

    #[test]
    fn expand_and_collect_named_calls_to_yields_name_and_args_for_every_matching_form_in_source_order(
    ) {
        // The constant-keyword named primitive's happy path: a runtime
        // `&'static str` keyword filters matched forms, and the per-
        // form projection receives `(name, spec_args)` for every
        // matched form in source order. Three matched forms
        // interleaved with a non-matcher pin the source-order yield,
        // the NAME-slot projection, AND the rejection of non-keyword
        // forms in ONE assertion.
        let src = r#"(defmonitor cpu :threshold 80)
                     (other-form 99)
                     (defmonitor mem :threshold 90 :unit "MiB")
                     (defmonitor disk :threshold 70)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let rows: Vec<(String, usize)> = e
            .expand_and_collect_named_calls_to(forms, "defmonitor", |name, spec_args| {
                Ok((name.to_string(), spec_args.len()))
            })
            .unwrap();
        assert_eq!(
            rows,
            vec![
                ("cpu".to_string(), 2),
                ("mem".to_string(), 4),
                ("disk".to_string(), 2),
            ],
        );
    }

    #[test]
    fn expand_and_collect_named_calls_to_skips_non_matching_forms_without_invoking_project() {
        // Soft-projection contract — every shape the named typed-
        // decoded primitive rejects (non-list, empty list, list whose
        // head is not a symbol, list whose head doesn't match the
        // constant keyword) skips the projection silently. The named
        // gate inside the wrapper projection runs ONLY for matched
        // forms; a non-matching form that reaches the projection
        // panics here.
        let src = r#":bare-keyword
                     "bare-string"
                     42
                     ()
                     (foo bar)
                     (defmonitor cpu :threshold 80)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let names: Vec<String> = e
            .expand_and_collect_named_calls_to(forms, "defmonitor", |name, _args| {
                Ok(name.to_string())
            })
            .unwrap();
        assert_eq!(names, vec!["cpu".to_string()]);
    }

    #[test]
    fn expand_and_collect_named_calls_to_emits_named_form_missing_name_through_primitive_keyword() {
        // The named-form gate's missing-NAME variant must thread the
        // primitive's `&'static str` keyword (NOT a hardcoded literal,
        // NOT the projection's own copy) — the `NamedFormMissingName
        // { keyword }` slot inside `split_name_slot` is bound at the
        // call site BY THE PRIMITIVE itself, via the constant-
        // classifier decoder threading `((), keyword)` into
        // `expand_and_collect_named_calls_to_any`.
        let src = r#"(defmonitor)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_named_calls_to::<(), _>(forms, "defmonitor", |_name, _args| Ok(()))
            .unwrap_err();
        assert!(
            matches!(
                err,
                crate::error::LispError::NamedFormMissingName {
                    keyword: "defmonitor"
                }
            ),
            "expected NamedFormMissingName threading the primitive's keyword; got: {err:?}",
        );
    }

    #[test]
    fn expand_and_collect_named_calls_to_emits_named_form_non_symbol_name_through_primitive_keyword(
    ) {
        // The named-form gate's non-symbol-NAME variant must thread
        // the primitive's `&'static str` keyword AND the typed-shape
        // witness (`SexpShape::Int` for an integer NAME slot). The
        // shape projection through `split_name_slot`'s
        // `as_symbol_or_string()` gate fires on the first matched
        // form whose NAME slot is not a symbol or string.
        let src = r#"(defmonitor 42 :threshold 80)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_named_calls_to::<(), _>(forms, "defmonitor", |_name, _args| Ok(()))
            .unwrap_err();
        match err {
            crate::error::LispError::NamedFormNonSymbolName { keyword, got } => {
                assert_eq!(keyword, "defmonitor");
                assert_eq!(got, crate::error::SexpShape::Int);
            }
            other => panic!(
                "expected NamedFormNonSymbolName threading the primitive's keyword + Int shape; got: {other:?}",
            ),
        }
    }

    #[test]
    fn expand_and_collect_named_calls_to_short_circuits_on_project_error_at_first_failure() {
        // `Iterator::collect::<Result<Vec<R>, _>>()` short-circuits at
        // the first failing projection. The second matched form's
        // projection error MUST fire AND the third matched form's
        // projection MUST NOT run. Pin both halves with a counter +
        // a fail-on-call sentinel.
        let src = r#"(defmonitor cpu :threshold 80)
                     (defmonitor mem :threshold 90)
                     (defmonitor disk :threshold 70)"#;
        let forms = read(src).unwrap();
        let mut count: usize = 0;
        let mut e = Expander::new();
        let err = e
            .expand_and_collect_named_calls_to::<String, _>(forms, "defmonitor", |name, _args| {
                count += 1;
                if name == "mem" {
                    Err(crate::error::LispError::Compile {
                        form: "test".into(),
                        message: format!("rejecting at NAME={name}"),
                    })
                } else {
                    Ok(name.to_string())
                }
            })
            .unwrap_err();
        assert_eq!(count, 2, "third matched form must not be projected");
        match err {
            crate::error::LispError::Compile { message, .. } => {
                assert!(message.contains("NAME=mem"));
            }
            other => panic!("expected projection-driven Compile error; got: {other:?}"),
        }
    }

    #[test]
    fn expand_and_collect_named_calls_to_expands_macros_before_filtering_by_keyword() {
        // Ordering contract — `expand_program` runs BEFORE the
        // constant-keyword named walk. A `(defmacro …)` form that
        // emits a matched named form must have its EXPANDED head
        // matched by the constant-keyword filter, not the macro-call
        // head. Pin the ordering with a macro `(emit-mon n thr)`
        // expanding to `(defmonitor ,n :threshold ,thr)` — the
        // constant-keyword filter matches the expanded `defmonitor`
        // head and the NAME slot projects the symbol-author value.
        let src = r#"(defmacro emit-mon (n thr) `(defmonitor ,n :threshold ,thr))
                     (defmonitor cpu :threshold 80)
                     (emit-mon mem 90)
                     (other-form 99)
                     (emit-mon disk 70)"#;
        let forms = read(src).unwrap();
        let mut e = Expander::new();
        let names: Vec<String> = e
            .expand_and_collect_named_calls_to(forms, "defmonitor", |name, _args| {
                Ok(name.to_string())
            })
            .unwrap();
        // `cpu` from the literal call, `mem` from the first macro
        // emit, `disk` from the second macro emit. The macro-emitted
        // forms are present BECAUSE `expand_program` ran first.
        assert_eq!(names, vec!["cpu", "mem", "disk"]);
    }

    #[test]
    fn expand_source_and_collect_named_calls_to_matches_inlined_read_plus_from_forms_path() {
        // From-source posture parity: feeding source through
        // `expand_source_and_collect_named_calls_to` is byte-identical
        // to feeding `read(src)?` through the from-forms sibling on a
        // fresh expander, because the from-source posture is
        // `read(src)? + from-forms` by construction. A regression that
        // drifts the from-source posture's pipeline from the from-
        // forms posture's pipeline would fail here.
        let src = r#"(defmonitor cpu :threshold 80)
                     (defmonitor mem :threshold 90)"#;
        let via_src: Vec<String> = Expander::new()
            .expand_source_and_collect_named_calls_to(src, "defmonitor", |name, _args| {
                Ok(name.to_string())
            })
            .unwrap();
        let forms = read(src).unwrap();
        let via_forms: Vec<String> = Expander::new()
            .expand_and_collect_named_calls_to(forms, "defmonitor", |name, _args| {
                Ok(name.to_string())
            })
            .unwrap();
        assert_eq!(via_src, via_forms);
        assert_eq!(via_src, vec!["cpu".to_string(), "mem".to_string()]);
    }

    #[test]
    fn expand_source_and_collect_named_calls_to_short_circuits_on_reader_error_before_named_gate_runs(
    ) {
        // `?`-routing through `read` short-circuits BEFORE the
        // constant-keyword filter, the named gate, or the projection
        // runs. Unbalanced paren — reader error fires; the projection
        // panic-payload MUST NOT execute, proving the read step gates
        // the entire pipeline.
        let mut e = Expander::new();
        let err = e
            .expand_source_and_collect_named_calls_to::<(), _>(
                "(defmonitor cpu :threshold 80",
                "defmonitor",
                |_name, _args| panic!("projection must not run when reader fails"),
            )
            .unwrap_err();
        // The named gate's variants MUST NOT fire — the reader error
        // is structurally distinct.
        assert!(
            !matches!(
                err,
                crate::error::LispError::NamedFormMissingName { .. }
                    | crate::error::LispError::NamedFormNonSymbolName { .. }
            ),
            "expected reader error, not named-gate variant; got: {err:?}",
        );
    }

    #[test]
    fn expand_and_collect_named_calls_to_routes_through_classifier_via_constant_decoder_composition(
    ) {
        // Composition-identity test pinning the runtime-keyword named
        // cell (`expand_and_collect_named_calls_to`) to the typed-
        // decoded named-classifier cell
        // (`expand_and_collect_named_calls_to_any`) via the constant-
        // classifier decoder shape. Post-lift the identity:
        //
        //   expand_and_collect_named_calls_to(forms, kw, project) ==
        //       expand_and_collect_named_calls_to_any(forms,
        //           |h| (h == kw).then_some(((), kw)),
        //           |(), name, args| project(name, args))
        //
        // Pinning the identity here makes the typed-decoded named-
        // classifier primitive the CANONICAL composition point the
        // runtime-keyword sibling routes through — parallel to how
        // `expand_and_collect_calls_to` routes through
        // `expand_and_collect_calls_to_any` via a `|h| (h == k).
        // then_some(())` decoder on the bare-kwargs axis. A future
        // regression that drifts ONE cell's NAME-slot rejection chain
        // from the other becomes loudly visible at this assertion.
        let src = r#"(defmonitor cpu :threshold 80)
                     (other-form 99)
                     (defmonitor mem :threshold 90)"#;
        let forms = read(src).unwrap();
        let via_constant_keyword: Vec<(String, usize)> = Expander::new()
            .expand_and_collect_named_calls_to(forms.clone(), "defmonitor", |name, args| {
                Ok((name.to_string(), args.len()))
            })
            .unwrap();
        let via_classifier: Vec<(String, usize)> = Expander::new()
            .expand_and_collect_named_calls_to_any(
                forms,
                |h| (h == "defmonitor").then_some(((), "defmonitor")),
                |(), name, args| Ok((name.to_string(), args.len())),
            )
            .unwrap();
        assert_eq!(via_constant_keyword, via_classifier);
        assert_eq!(
            via_constant_keyword,
            vec![("cpu".to_string(), 2), ("mem".to_string(), 2)],
        );
    }

    #[test]
    fn expand_to_named_routes_through_expand_and_collect_named_calls_to_via_constant_keyword_composition(
    ) {
        // End-to-end path-uniformity: `Expander::expand_to_named<T>`
        // (the typed constant-keyword named cell) must yield the same
        // payload as `expand_and_collect_named_calls_to(forms,
        // T::KEYWORD, |name, args| { T::compile_from_args(args)? +
        // NamedDefinition })` — the lift's structural identity.
        //
        // Pre-lift `expand_to_named<T>` routed through
        // `expand_and_collect_calls_to(forms, T::KEYWORD,
        // named_form_projection::<T>)` (the bare-kwargs constant
        // primitive with `named_form_projection<T>` doing the NAME
        // extraction internally). Post-lift `expand_to_named<T>`
        // routes through the named constant-keyword primitive (which
        // itself routes through the classifier primitive via a
        // constant-classifier decoder) — so the `split_name_slot`
        // composition lives at ONE site (the `_any` primitive body)
        // post-lift rather than at TWO sites.
        use crate::compile::NamedDefinition;
        use crate::compiler_spec::CompilerSpec;
        let src = r#"(defcompiler alpha-compiler :name "x" :dialect "standard")
                     (defcompiler beta-compiler  :name "y" :dialect "standard")"#;
        let forms = read(src).unwrap();
        let via_expand_to_named = Expander::new()
            .expand_to_named::<CompilerSpec>(forms.clone())
            .unwrap();
        let via_named_constant: Vec<NamedDefinition<CompilerSpec>> = Expander::new()
            .expand_and_collect_named_calls_to(forms, "defcompiler", |name, spec_args| {
                let spec =
                    <CompilerSpec as crate::domain::TataraDomain>::compile_from_args(spec_args)?;
                Ok(NamedDefinition {
                    name: name.to_string(),
                    spec,
                })
            })
            .unwrap();
        assert_eq!(via_expand_to_named.len(), 2);
        assert_eq!(via_expand_to_named.len(), via_named_constant.len());
        for (a, b) in via_expand_to_named.iter().zip(via_named_constant.iter()) {
            assert_eq!(a.name, b.name, "NAME slot must agree across cells");
            assert_eq!(a.spec.name, b.spec.name, ":name spec must agree");
        }
        assert_eq!(via_expand_to_named[0].name, "alpha-compiler");
        assert_eq!(via_expand_to_named[0].spec.name, "x");
        assert_eq!(via_expand_to_named[1].name, "beta-compiler");
        assert_eq!(via_expand_to_named[1].spec.name, "y");
    }

    // ── ExpansionDepthExceeded: runaway macro rejected instead of aborting ──

    #[test]
    fn expander_default_max_expansion_depth_is_the_module_constant() {
        // Both constructors seed `max_expansion_depth` from the module
        // constant — a regression that drifts one constructor's default
        // from the constant (e.g. a hardcoded `256` at ONE site with the
        // other left uninitialized after a `Default` derive addition)
        // fails this pin.
        assert_eq!(
            Expander::new().max_expansion_depth(),
            DEFAULT_MAX_EXPANSION_DEPTH
        );
        assert_eq!(
            Expander::new_substitute_only().max_expansion_depth(),
            DEFAULT_MAX_EXPANSION_DEPTH
        );
        assert_eq!(DEFAULT_MAX_EXPANSION_DEPTH, 256);
    }

    #[test]
    fn set_max_expansion_depth_takes_effect_on_subsequent_expand() {
        let mut e = Expander::new();
        e.set_max_expansion_depth(7);
        assert_eq!(e.max_expansion_depth(), 7);
    }

    #[test]
    fn expand_recursive_macro_rejects_at_depth_limit_bytecode_path() {
        // `(defmacro loop (x) `(loop ,x))` applied to `(loop hello)`
        // pre-lift stack-overflowed the process — a below-floor abort.
        // Post-lift the expander returns a typed
        // `LispError::ExpansionDepthExceeded` at the ceiling with
        // `macro_name` populated from the offending call's head.
        let mut e = Expander::new();
        e.set_max_expansion_depth(4);
        let forms = read("(defmacro loop (x) `(loop ,x)) (loop hello)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::ExpansionDepthExceeded { macro_name, limit } => {
                assert_eq!(macro_name, "loop");
                assert_eq!(limit, 4);
            }
            other => panic!("expected ExpansionDepthExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn expand_recursive_macro_rejects_at_depth_limit_substitute_path() {
        // The substitute strategy shares the same `expand` outer walker
        // with the bytecode strategy, so the ceiling fires at the SAME
        // gate regardless of which apply-layer is active. The pin makes
        // that shared-outer-walker property structural: a regression
        // that ever branches the depth guard on strategy (e.g. moves it
        // into `apply_compiled` alone) fails this test on the
        // substitute expander.
        let mut e = Expander::new_substitute_only();
        e.set_max_expansion_depth(4);
        let forms = read("(defmacro loop (x) `(loop ,x)) (loop hello)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::ExpansionDepthExceeded { macro_name, limit } => {
                assert_eq!(macro_name, "loop");
                assert_eq!(limit, 4);
            }
            other => panic!("expected ExpansionDepthExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn expand_lawful_nested_macros_within_ceiling_succeed() {
        // Lawful nested macros (`(twice (twice hey))`) accrete depth in
        // the low single digits because the tree-child arm doesn't
        // count — only the post-apply re-expansion path bumps the
        // counter. A ceiling of 3 is enough for a two-deep nested
        // expansion. This pin is the fail-before/pass-after negative
        // control for the recursive-macro rejection tests above: the
        // depth counter must NOT reject lawful macro-nesting within
        // the ceiling, and only reject the runaway shape.
        let mut e = Expander::new();
        e.set_max_expansion_depth(3);
        let forms = read(
            "(defmacro twice (x) `(list ,x ,x))
             (twice (twice hey))",
        )
        .unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(list (list hey hey) (list hey hey))"));
    }

    #[test]
    fn expand_depth_ceiling_ignores_lawful_tree_nesting_depth() {
        // A macro-free lawful deep tree — five levels of plain nesting —
        // is expanded at a ceiling well below the tree's height. The
        // tree-child arm does not accrete depth, so tree height is
        // orthogonal to the ceiling; only macro re-expansion counts.
        // A regression that ever bumps depth on tree-child descent
        // fails this pin.
        let mut e = Expander::new();
        e.set_max_expansion_depth(2);
        let forms = read("(a (b (c (d (e f)))))").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(a (b (c (d (e f)))))"));
    }

    #[test]
    fn expansion_depth_exceeded_position_is_none() {
        // The variant joins the non-positional cohort — the offending
        // macro's byte offset is not what a runaway diagnostic anchors
        // to; the OFFENDING MACRO NAME (`macro_name`) is. This pin
        // keeps the variant in the `position() -> None` cohort so a
        // future span-carrying edit lands the field in ONE place
        // across every non-positional variant simultaneously.
        let err = LispError::ExpansionDepthExceeded {
            macro_name: "loop".to_string(),
            limit: 256,
        };
        assert_eq!(err.position(), None);
    }

    #[test]
    fn expansion_depth_exceeded_display_matches_typed_variant_shape() {
        // Display projection carries both `macro_name` and `limit`, so
        // authoring surfaces that substring-grep the rendered
        // diagnostic (`tatara-check`, REPL, LSP) see BOTH halves at
        // the variant boundary and never need to substring-parse
        // free-form text to recover the identity of the offending
        // macro or the ceiling it breached.
        let err = LispError::ExpansionDepthExceeded {
            macro_name: "loop".to_string(),
            limit: 256,
        };
        let rendered = err.to_string();
        assert!(rendered.contains("loop"), "rendered: {rendered}");
        assert!(rendered.contains("256"), "rendered: {rendered}");
        assert!(
            rendered.contains("macro expansion depth exceeded"),
            "rendered: {rendered}"
        );
    }

    // ── max_cache_entries: bounded-memoization ceiling ──────────────────

    #[test]
    fn expander_default_max_cache_entries_is_the_module_constant() {
        // Both cache-enabling constructors seed `max_cache_entries` from
        // the module constant — a regression that drifts one
        // constructor's default from the constant (e.g. a hardcoded
        // `8192` at ONE site with the other left uninitialized after a
        // `Default` derive addition) fails this pin. The peer
        // constructor `new_substitute_only` seeds the same ceiling so
        // the field stays initialized under `#[derive(Clone)]` (a
        // zero-initialized clone would be a silent bifurcation of the
        // cache-ceiling surface).
        assert_eq!(
            Expander::new().max_cache_entries(),
            DEFAULT_MAX_CACHE_ENTRIES
        );
        assert_eq!(
            Expander::new_substitute_only().max_cache_entries(),
            DEFAULT_MAX_CACHE_ENTRIES
        );
        assert_eq!(DEFAULT_MAX_CACHE_ENTRIES, 8192);
    }

    #[test]
    fn set_max_cache_entries_takes_effect_on_subsequent_expand() {
        // Setter mirrors accessor — a regression that ever forgets to
        // write through to the field, or writes to a shadow field the
        // accessor does not read, fails this pin.
        let mut e = Expander::new();
        e.set_max_cache_entries(7);
        assert_eq!(e.max_cache_entries(), 7);
    }

    #[test]
    fn expand_cache_size_is_bounded_by_max_cache_entries() {
        // Five distinct `(name, args)` pairs expanded against a cache
        // ceiling of `2` populate the cache with EXACTLY the first two
        // insertions and skip the remaining three. Every expansion
        // still returns the correct result — the cache is a pure
        // PERFORMANCE optimization; the ceiling gates memoization,
        // never correctness. LOAD-BEARING true-arm catch on the
        // bounded-cache contract: a regression that ignored the
        // ceiling (unbounded insert) would land `cache_size() == 5`
        // here; a regression that skipped insertion entirely (broken
        // cache) would still see correct expansion output but would
        // fail the interior `cache_size() == 2` pin.
        let mut e = Expander::new();
        e.set_max_cache_entries(2);
        let src = "
            (defmacro id (x) `,x)
            (id one)
            (id two)
            (id three)
            (id four)
            (id five)
        ";
        let out = e.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out.len(), 5);
        assert_eq!(out[0], parse("one"));
        assert_eq!(out[1], parse("two"));
        assert_eq!(out[2], parse("three"));
        assert_eq!(out[3], parse("four"));
        assert_eq!(out[4], parse("five"));
        assert_eq!(
            e.cache_size(),
            2,
            "cache grew past the max_cache_entries ceiling",
        );
    }

    #[test]
    fn expand_zero_cache_ceiling_disables_caching_effectively() {
        // Zero ceiling admits every fresh `(name, args)` pair through
        // the compute path and never grows the cache — the same
        // observable behavior as `set_cache_enabled(false)` but
        // reached through the ceiling knob. Correctness is preserved:
        // the miss path always recomputes the same value the cache
        // would have returned, so an operator that dials the ceiling
        // to `0` (e.g. to hunt a cache-related regression) never
        // bifurcates the output surface. Peer to
        // `set_max_expansion_depth(0)` one RESOURCE axis over — both
        // ceilings admit the zero endpoint as a well-defined
        // extremum.
        let mut e = Expander::new();
        e.set_max_cache_entries(0);
        let src = "
            (defmacro id (x) `,x)
            (id one)
            (id two)
        ";
        let out = e.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(out[0], parse("one"));
        assert_eq!(out[1], parse("two"));
        assert_eq!(
            e.cache_size(),
            0,
            "zero cache ceiling grew the cache — the ceiling must be respected on every insert",
        );
    }

    #[test]
    fn expand_cached_hits_survive_past_the_ceiling() {
        // Once a `(name, args)` pair sits IN the cache under the
        // ceiling, subsequent calls hit it — the ceiling only gates
        // NEW-KEY inserts, never lookups. This test seeds the cache
        // with two entries under a ceiling of `2`, then re-issues the
        // SAME calls to prove the cached hits still fire (cache_size
        // stays at `2` because no new keys are inserted, and the
        // expansion output is stable). LOAD-BEARING true-arm catch
        // that the ceiling gates the INSERT path alone — a regression
        // that ever refused cache LOOKUPS at the ceiling would
        // silently bifurcate correctness on the second call.
        let mut e = Expander::new();
        e.set_max_cache_entries(2);
        let src = "
            (defmacro id (x) `,x)
            (id one)
            (id two)
            (id one)
            (id two)
        ";
        let out = e.expand_program(read(src).unwrap()).unwrap();
        assert_eq!(out.len(), 4);
        assert_eq!(out[0], parse("one"));
        assert_eq!(out[1], parse("two"));
        assert_eq!(out[2], parse("one"));
        assert_eq!(out[3], parse("two"));
        assert_eq!(
            e.cache_size(),
            2,
            "cache grew past the max_cache_entries ceiling on repeated (name, args) pairs",
        );
    }

    #[test]
    fn clear_cache_reopens_the_insert_path_after_the_ceiling_was_hit() {
        // After the cache reaches its ceiling and subsequent inserts
        // are skipped, `clear_cache` empties the memo and RE-OPENS the
        // insert path — the next expansion populates the freshly-
        // empty cache without operator intervention on the ceiling
        // itself. The pin binds the operator-facing recovery path
        // documented on [`DEFAULT_MAX_CACHE_ENTRIES`]: "skip cache
        // insertion until the operator clears the cache via
        // [`Expander::clear_cache`]".
        let mut e = Expander::new();
        e.set_max_cache_entries(1);
        let src_fill = "
            (defmacro id (x) `,x)
            (id one)
            (id two)
        ";
        let _ = e.expand_program(read(src_fill).unwrap()).unwrap();
        assert_eq!(e.cache_size(), 1, "cache did not stop at the ceiling");
        e.clear_cache();
        assert_eq!(e.cache_size(), 0, "clear_cache did not empty the memo");
        let out = e
            .expand_program(read("(defmacro id (x) `,x) (id three)").unwrap())
            .unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], parse("three"));
        assert_eq!(
            e.cache_size(),
            1,
            "clear_cache did not re-open the insert path — the cache should have accepted the fresh (id, three) pair",
        );
    }

    // ── max_expansion_size: bounded-output ceiling ─────────────────────

    #[test]
    fn expander_default_max_expansion_size_is_the_module_constant() {
        // Both constructors seed `max_expansion_size` from the module
        // constant — a regression that drifts one constructor's
        // default from the constant (e.g. a hardcoded `65_536` at
        // ONE site with the other left uninitialized after a
        // `Default` derive addition) fails this pin. Peer to the
        // `max_expansion_depth` + `max_cache_entries` default-
        // coherence pins one RESOURCE-DIMENSION axis over.
        assert_eq!(
            Expander::new().max_expansion_size(),
            DEFAULT_MAX_EXPANSION_SIZE
        );
        assert_eq!(
            Expander::new_substitute_only().max_expansion_size(),
            DEFAULT_MAX_EXPANSION_SIZE
        );
        assert_eq!(DEFAULT_MAX_EXPANSION_SIZE, 65_536);
    }

    #[test]
    fn set_max_expansion_size_takes_effect_on_subsequent_expand() {
        // Setter mirrors accessor — a regression that ever forgets to
        // write through to the field, or writes to a shadow field the
        // accessor does not read, fails this pin. Peer to the
        // setter/accessor coherence pins on the depth + cache axes.
        let mut e = Expander::new();
        e.set_max_expansion_size(64);
        assert_eq!(e.max_expansion_size(), 64);
    }

    #[test]
    fn expand_expansion_bomb_rejects_at_size_limit_bytecode_path() {
        // `(defmacro bomb (x) `(list ,x ,x ,x ,x))` applied to
        // `(bomb hey)` produces `(list hey hey hey hey)` — 6 nodes
        // (outer List + 5 children). With a ceiling of `4` this
        // crosses the OUTPUT-SIZE threshold at the first apply and
        // the expander returns a typed
        // `LispError::ExpansionSizeExceeded` with `macro_name`,
        // `size`, and `limit` all populated. Pre-lift the runaway
        // just accumulated in a growing tree until the process
        // heap ran out; post-lift the rejection sits at the same
        // call boundary as every other macro-expansion failure.
        let mut e = Expander::new();
        e.set_max_expansion_size(4);
        let forms = read("(defmacro bomb (x) `(list ,x ,x ,x ,x)) (bomb hey)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::ExpansionSizeExceeded {
                macro_name,
                size,
                limit,
            } => {
                assert_eq!(macro_name, "bomb");
                assert_eq!(size, 6);
                assert_eq!(limit, 4);
            }
            other => panic!("expected ExpansionSizeExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn expand_expansion_bomb_rejects_at_size_limit_substitute_path() {
        // The substitute strategy shares the same `expand_with_depth`
        // outer walker with the bytecode strategy, so the ceiling
        // fires at the SAME gate regardless of which apply-layer is
        // active. The pin makes that shared-outer-walker property
        // structural: a regression that ever branches the size guard
        // on strategy (e.g. moves it into `apply_compiled` alone)
        // fails this test on the substitute expander. Peer to
        // `expand_recursive_macro_rejects_at_depth_limit_substitute_path`
        // one RESOURCE axis over.
        let mut e = Expander::new_substitute_only();
        e.set_max_expansion_size(4);
        let forms = read("(defmacro bomb (x) `(list ,x ,x ,x ,x)) (bomb hey)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::ExpansionSizeExceeded {
                macro_name,
                size,
                limit,
            } => {
                assert_eq!(macro_name, "bomb");
                assert_eq!(size, 6);
                assert_eq!(limit, 4);
            }
            other => panic!("expected ExpansionSizeExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn expand_lawful_output_within_size_ceiling_succeeds() {
        // `(defmacro twice (x) `(list ,x ,x))` applied to `(twice hey)`
        // produces `(list hey hey)` — 4 nodes. With a ceiling of `4`
        // the output sits AT the ceiling (`<=` admits equality; only
        // `>` rejects), so the expansion succeeds. Fail-before/pass-
        // after negative control for the bomb rejection tests: a
        // regression that ever rejected at-ceiling output would fail
        // this pin. Peer to `expand_lawful_nested_macros_within_ceiling_succeed`
        // one RESOURCE axis over.
        let mut e = Expander::new();
        e.set_max_expansion_size(4);
        let forms = read("(defmacro twice (x) `(list ,x ,x)) (twice hey)").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(list hey hey)"));
    }

    #[test]
    fn expand_size_ceiling_ignores_lawful_tree_nesting_size() {
        // A macro-free lawful large tree is NOT gated by the size
        // ceiling — the ceiling gates macro-`apply` outputs alone,
        // not tree-child descents through non-macro forms. A `usize::MAX`
        // ceiling would trivially admit anything; this pin uses a
        // deliberately small ceiling of `4` on a tree with 6 nodes
        // to catch a regression that ever bumps the ceiling on tree
        // descent. A tree-only walk should NEVER fire the ceiling.
        // Peer to `expand_depth_ceiling_ignores_lawful_tree_nesting_depth`
        // one RESOURCE axis over.
        let mut e = Expander::new();
        e.set_max_expansion_size(4);
        // `(a (b (c d)))` — 6 nodes, no macros. Passes cleanly.
        let forms = read("(a (b (c d)))").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(a (b (c d)))"));
    }

    #[test]
    fn expansion_size_exceeded_position_is_none() {
        // The variant joins the non-positional cohort — the offending
        // macro's byte offset is not what an expansion-bomb diagnostic
        // anchors to; the (offending macro name, observed size,
        // configured ceiling) triple is. This pin keeps the variant
        // in the `position() -> None` cohort so a future span-carrying
        // edit lands the field in ONE place across every non-positional
        // variant simultaneously. Peer to
        // `expansion_depth_exceeded_position_is_none` one RESOURCE
        // axis over.
        let err = LispError::ExpansionSizeExceeded {
            macro_name: "bomb".to_string(),
            size: 512,
            limit: 256,
        };
        assert_eq!(err.position(), None);
    }

    #[test]
    fn expansion_size_exceeded_display_matches_typed_variant_shape() {
        // Display projection carries `macro_name`, `size`, AND
        // `limit`, so authoring surfaces that substring-grep the
        // rendered diagnostic (`tatara-check`, REPL, LSP) see ALL
        // THREE halves at the variant boundary and never need to
        // substring-parse free-form text to recover the identity of
        // the offending macro, the observed size, or the ceiling it
        // breached. Peer to `expansion_depth_exceeded_display_matches_typed_variant_shape`
        // one RESOURCE axis over.
        let err = LispError::ExpansionSizeExceeded {
            macro_name: "bomb".to_string(),
            size: 512,
            limit: 256,
        };
        let rendered = err.to_string();
        assert!(rendered.contains("bomb"), "rendered: {rendered}");
        assert!(rendered.contains("512"), "rendered: {rendered}");
        assert!(rendered.contains("256"), "rendered: {rendered}");
        assert!(
            rendered.contains("macro expansion output size exceeded"),
            "rendered: {rendered}"
        );
    }

    #[test]
    fn expand_size_ceiling_names_the_offending_macro_in_a_nested_expansion() {
        // A lawful outer macro that expands to a call of a bomb inner
        // macro rejects at the INNER call — `macro_name` at the
        // variant boundary is the name of the macro whose `apply`
        // output crossed the ceiling, not the outermost caller.
        // Load-bearing name-provenance pin: an operator whose bomb
        // sits N levels deep in a compose chain needs to see the
        // INNER macro's name in the diagnostic, not the wrapping
        // shape. A regression that ever populates `macro_name` from
        // the outermost caller's head fails this pin.
        let mut e = Expander::new();
        e.set_max_expansion_size(4);
        // `wrapper` re-expands into `bomb`; `bomb` produces a size-6
        // output that crosses the ceiling. Expected: the diagnostic
        // names `bomb`, not `wrapper`.
        let src = "
            (defmacro bomb (x) `(list ,x ,x ,x ,x))
            (defmacro wrapper (x) `(bomb ,x))
            (wrapper hey)
        ";
        let err = e.expand_program(read(src).unwrap()).unwrap_err();
        match err {
            LispError::ExpansionSizeExceeded {
                macro_name,
                size,
                limit,
            } => {
                assert_eq!(macro_name, "bomb");
                assert_eq!(size, 6);
                assert_eq!(limit, 4);
            }
            other => panic!("expected ExpansionSizeExceeded, got: {other:?}"),
        }
    }

    // ── max_macro_body_size: REGISTRATION-time body-size ceiling ──────
    // Peer to depth (recursion length) + cache (memoization width) +
    // expansion size (single-`apply` OUTPUT size) one PIPELINE-STAGE
    // axis over — the three prior guards fire at EXPAND time; this
    // one fires at REGISTER time. Closes the expander's RESOURCE
    // surface at a fourth typed dimension across two pipeline stages.

    #[test]
    fn expander_default_max_macro_body_size_is_the_module_constant() {
        // Both constructors seed `max_macro_body_size` from the
        // module constant — a regression that drifts one
        // constructor's default from the constant (e.g. a hardcoded
        // `16_384` at ONE site with the other left uninitialized
        // after a `Default` derive addition) fails this pin. Peer
        // to the `expander_default_max_expansion_{depth,size}_is_the_module_constant`
        // pins one PIPELINE-STAGE axis over.
        assert_eq!(
            Expander::new().max_macro_body_size(),
            DEFAULT_MAX_MACRO_BODY_SIZE
        );
        assert_eq!(
            Expander::new_substitute_only().max_macro_body_size(),
            DEFAULT_MAX_MACRO_BODY_SIZE
        );
        assert_eq!(DEFAULT_MAX_MACRO_BODY_SIZE, 16_384);
    }

    #[test]
    fn set_max_macro_body_size_takes_effect_on_subsequent_register() {
        // Setter mirrors accessor — a regression that ever forgets to
        // write through to the field, or writes to a shadow field the
        // accessor does not read, fails this pin. Peer to the
        // setter/accessor coherence pins on the depth + cache +
        // expansion-size axes.
        let mut e = Expander::new();
        e.set_max_macro_body_size(64);
        assert_eq!(e.max_macro_body_size(), 64);
    }

    #[test]
    fn register_macro_body_bomb_rejects_at_body_size_limit_bytecode_path() {
        // `(defmacro huge (x) `(list a b c d e))` has body
        // `` `(list a b c d e) `` — a `Sexp::Quasiquote` wrapping a
        // list of 6 nodes (outer List + 5 children); the outer
        // quasi-quote wrapper adds one → 8 nodes total for
        // `def.body.node_count()`. With a ceiling of `4` this
        // crosses the REGISTRATION-time BODY-SIZE threshold and the
        // expander returns a typed `LispError::MacroBodySizeExceeded`
        // with `macro_name`, `size`, and `limit` all populated. Peer
        // to `expand_expansion_bomb_rejects_at_size_limit_bytecode_path`
        // one PIPELINE-STAGE axis over.
        let mut e = Expander::new();
        e.set_max_macro_body_size(4);
        let forms = read("(defmacro huge (x) `(list a b c d e))").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::MacroBodySizeExceeded {
                macro_name,
                size,
                limit,
            } => {
                assert_eq!(macro_name, "huge");
                assert_eq!(size, 8);
                assert_eq!(limit, 4);
            }
            other => panic!("expected MacroBodySizeExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn register_macro_body_bomb_rejects_at_body_size_limit_substitute_path() {
        // The substitute strategy shares the same
        // `register_macro_def` outer registration entry with the
        // bytecode strategy, so the REGISTRATION-time BODY-SIZE
        // ceiling fires at the SAME gate regardless of which
        // apply-layer is active. The pin makes that shared-registration
        // property structural: a regression that ever branches the
        // body-size guard on strategy (e.g. moves it into the
        // `compile_templates` arm alone) fails this test on the
        // substitute expander. Peer to
        // `expand_expansion_bomb_rejects_at_size_limit_substitute_path`
        // one PIPELINE-STAGE axis over.
        let mut e = Expander::new_substitute_only();
        e.set_max_macro_body_size(4);
        let forms = read("(defmacro huge (x) `(list a b c d e))").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::MacroBodySizeExceeded {
                macro_name,
                size,
                limit,
            } => {
                assert_eq!(macro_name, "huge");
                assert_eq!(size, 8);
                assert_eq!(limit, 4);
            }
            other => panic!("expected MacroBodySizeExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn register_macro_body_at_ceiling_admits() {
        // `(defmacro twice (x) `(list ,x))` has body
        // `` `(list ,x) `` — `Sexp::Quasiquote` wrapping a 3-node
        // list (List + `list` atom + `,x` unquote which is
        // 1 + inner atom = 2 nodes) = 1 + (1 + 1 + 2) = 5 nodes.
        // With a ceiling of `5` the body sits AT the ceiling
        // (`<=` admits equality; only `>` rejects), so the
        // registration succeeds and the subsequent expansion
        // proceeds normally. Fail-before/pass-after negative
        // control for the body-bomb rejection tests: a regression
        // that ever rejected at-ceiling bodies would fail this pin.
        let mut e = Expander::new();
        e.set_max_macro_body_size(5);
        let forms = read("(defmacro twice (x) `(list ,x)) (twice hey)").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(list hey)"));
    }

    #[test]
    fn register_failure_leaves_both_tables_pristine() {
        // A rejected registration MUST leave BOTH `self.macros`
        // AND `self.templates` exactly as they were — no
        // partial-write window in which one table carries the
        // over-ceiling entry while the other does not, or in
        // which the template pre-compile already ran. This pin
        // catches a regression that ever moves the body-size
        // gate below `self.templates.insert` or below
        // `self.macros.insert`.
        let mut e = Expander::new();
        e.set_max_macro_body_size(4);
        let forms = read("(defmacro huge (x) `(list a b c d e))").unwrap();
        assert!(e.expand_program(forms).is_err());
        assert!(
            !e.has("huge"),
            "macros table must stay pristine after rejection"
        );
        assert_eq!(e.len(), 0);
    }

    #[test]
    fn macro_body_size_exceeded_position_is_none() {
        // The variant joins the non-positional cohort — the
        // offending macro's byte offset is not what a body-bomb
        // diagnostic anchors to; the (offending macro name,
        // observed body size, configured ceiling) triple is.
        // This pin keeps the variant in the `position() -> None`
        // cohort so a future span-carrying edit lands the field
        // in ONE place across every non-positional variant
        // simultaneously. Peer to
        // `expansion_{depth,size}_exceeded_position_is_none` one
        // PIPELINE-STAGE axis over.
        let err = LispError::MacroBodySizeExceeded {
            macro_name: "huge".to_string(),
            size: 512,
            limit: 256,
        };
        assert_eq!(err.position(), None);
    }

    #[test]
    fn macro_body_size_exceeded_display_matches_typed_variant_shape() {
        // Display projection carries `macro_name`, `size`, AND
        // `limit`, so authoring surfaces that substring-grep the
        // rendered diagnostic (`tatara-check`, REPL, LSP) see
        // ALL THREE halves at the variant boundary and never need
        // to substring-parse free-form text to recover the
        // identity of the offending macro, the observed body
        // size, or the ceiling it breached. Peer to
        // `expansion_size_exceeded_display_matches_typed_variant_shape`
        // one PIPELINE-STAGE axis over.
        let err = LispError::MacroBodySizeExceeded {
            macro_name: "huge".to_string(),
            size: 512,
            limit: 256,
        };
        let rendered = err.to_string();
        assert!(rendered.contains("huge"), "rendered: {rendered}");
        assert!(rendered.contains("512"), "rendered: {rendered}");
        assert!(rendered.contains("256"), "rendered: {rendered}");
        assert!(
            rendered.contains("macro body size exceeded"),
            "rendered: {rendered}"
        );
    }

    #[test]
    fn lawful_macro_body_within_ceiling_registers_and_expands() {
        // A lawful hand-authored macro body sits well below any
        // realistic ceiling — the default `DEFAULT_MAX_MACRO_BODY_SIZE`
        // is deliberately generous so operators never brush it on
        // real authoring workloads. This pin locks the default
        // ceiling's non-interference posture: a regression that
        // ever lowered the default enough to reject the reference
        // `(defmacro when (cond x) `(if ,cond ,x))` shape would
        // fail here.
        let mut e = Expander::new();
        let forms = read(
            "(defmacro when (cond x) `(if ,cond ,x))
             (when #t hey)",
        )
        .unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(if #t hey)"));
    }

    #[test]
    fn register_macro_def_direct_call_respects_body_size_ceiling() {
        // `register_macro_def` is the substrate primitive both
        // `expand_program`'s `defmacro` recognition AND
        // `with_macros`'s bulk load route through. The body-size
        // ceiling fires on the primitive itself, not on any one
        // consumer — a regression that ever moved the gate into
        // `expand_program`'s arm alone would fail this pin.
        let mut e = Expander::new();
        e.set_max_macro_body_size(4);
        let def = MacroDef {
            name: "huge".to_string(),
            params: MacroParams {
                required: vec!["x".to_string()],
                optional: Vec::new(),
                rest: None,
            },
            body: Sexp::List(vec![
                Sexp::Atom(crate::ast::Atom::Symbol("a".to_string())),
                Sexp::Atom(crate::ast::Atom::Symbol("b".to_string())),
                Sexp::Atom(crate::ast::Atom::Symbol("c".to_string())),
                Sexp::Atom(crate::ast::Atom::Symbol("d".to_string())),
                Sexp::Atom(crate::ast::Atom::Symbol("e".to_string())),
            ]),
        };
        // Body node_count: List(5 atoms) = 1 + 5 = 6 nodes.
        let err = e.register_macro_def(def).unwrap_err();
        match err {
            LispError::MacroBodySizeExceeded {
                macro_name,
                size,
                limit,
            } => {
                assert_eq!(macro_name, "huge");
                assert_eq!(size, 6);
                assert_eq!(limit, 4);
            }
            other => panic!("expected MacroBodySizeExceeded, got: {other:?}"),
        }
        assert!(!e.has("huge"));
    }

    // ── max_registered_macros: REGISTRATION-time table-count ceiling ──
    // Peer to body-size (REGISTER-time SIZE) one RESOURCE-DIMENSION
    // axis over — where body-size bounds a per-registration SIZE,
    // this ceiling bounds cumulative registration COUNT. Peer to
    // cache-entries (EXPAND-time COUNT) one PIPELINE-STAGE axis over
    // — the two entry-count guards close the two pipeline stages
    // symmetrically. Closes the expander's RESOURCE surface at a
    // FIFTH typed dimension across two pipeline stages: the
    // REGISTER-time face is now a two-dimensional (size × count)
    // closure symmetric with the EXPAND-time (depth + count + size)
    // triple.

    #[test]
    fn expander_default_max_registered_macros_is_the_module_constant() {
        // Both constructors seed `max_registered_macros` from the
        // module constant — a regression that drifts one
        // constructor's default from the constant (e.g. a hardcoded
        // `4096` at ONE site with the other left uninitialized
        // after a `Default` derive addition) fails this pin. Peer
        // to the four prior default-coherence pins on depth,
        // cache-entries, expansion-size, and body-size.
        assert_eq!(
            Expander::new().max_registered_macros(),
            DEFAULT_MAX_REGISTERED_MACROS
        );
        assert_eq!(
            Expander::new_substitute_only().max_registered_macros(),
            DEFAULT_MAX_REGISTERED_MACROS
        );
        assert_eq!(DEFAULT_MAX_REGISTERED_MACROS, 4096);
    }

    #[test]
    fn set_max_registered_macros_takes_effect_on_subsequent_register() {
        // Setter mirrors accessor — a regression that ever forgets
        // to write through to the field, or writes to a shadow
        // field the accessor does not read, fails this pin. Peer
        // to the four prior setter/accessor coherence pins.
        let mut e = Expander::new();
        e.set_max_registered_macros(64);
        assert_eq!(e.max_registered_macros(), 64);
    }

    #[test]
    fn register_fresh_macro_past_table_ceiling_rejects_bytecode_path() {
        // With a ceiling of `2`, the first two fresh registrations
        // land in the table and the third fresh key rejects with
        // `LispError::RegisteredMacrosExceeded { macro_name: "c",
        // count: 2, limit: 2 }`. `count` is the pre-insert table
        // length (which equals `limit` at rejection in the common
        // case); `macro_name` is the OFFENDING call's name (the
        // fresh key we could not admit), not the outermost caller.
        let mut e = Expander::new();
        e.set_max_registered_macros(2);
        let forms = read(
            "(defmacro a (x) `(list ,x))
             (defmacro b (x) `(list ,x))
             (defmacro c (x) `(list ,x))",
        )
        .unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::RegisteredMacrosExceeded {
                macro_name,
                count,
                limit,
            } => {
                assert_eq!(macro_name, "c");
                assert_eq!(count, 2);
                assert_eq!(limit, 2);
            }
            other => panic!("expected RegisteredMacrosExceeded, got: {other:?}"),
        }
        // First two admitted; third rejected leaves the table at
        // its pre-third-call size.
        assert!(e.has("a"));
        assert!(e.has("b"));
        assert!(!e.has("c"));
        assert_eq!(e.len(), 2);
    }

    #[test]
    fn register_fresh_macro_past_table_ceiling_rejects_substitute_path() {
        // The substitute strategy shares the same
        // `register_macro_def` outer registration entry with the
        // bytecode strategy, so the REGISTRATION-time TABLE-COUNT
        // ceiling fires at the SAME gate regardless of which
        // apply-layer is active. The pin makes that shared-
        // registration property structural: a regression that ever
        // branches the table-count guard on strategy (e.g. moves
        // it into the `compile_templates` arm alone) fails this
        // test on the substitute expander. Peer to the four prior
        // shared-registration pins.
        let mut e = Expander::new_substitute_only();
        e.set_max_registered_macros(2);
        let forms = read(
            "(defmacro a (x) `(list ,x))
             (defmacro b (x) `(list ,x))
             (defmacro c (x) `(list ,x))",
        )
        .unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::RegisteredMacrosExceeded {
                macro_name,
                count,
                limit,
            } => {
                assert_eq!(macro_name, "c");
                assert_eq!(count, 2);
                assert_eq!(limit, 2);
            }
            other => panic!("expected RegisteredMacrosExceeded, got: {other:?}"),
        }
        assert!(e.has("a"));
        assert!(e.has("b"));
        assert!(!e.has("c"));
        assert_eq!(e.len(), 2);
    }

    #[test]
    fn register_overwrite_of_existing_key_at_table_ceiling_admits() {
        // OVERWRITES (a re-registration of an already-registered
        // key) do not grow the table and MUST be admitted at any
        // ceiling — operators redefining a macro at capacity is a
        // legitimate authoring pattern. This pin catches a
        // regression that ever treats overwrites the same as fresh
        // keys (a `contains_key` check that inverts, or a
        // `set_max_registered_macros(0)` that would reject even
        // pre-registered overwrites).
        let mut e = Expander::new();
        // Land two macros with a permissive ceiling.
        e.expand_program(
            read(
                "(defmacro a (x) `(list ,x))
                 (defmacro b (x) `(list ,x))",
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(e.len(), 2);
        // Drop the ceiling to exactly the current size — a fresh
        // third key would now reject, but an overwrite of `a` MUST
        // admit.
        e.set_max_registered_macros(2);
        let forms = read("(defmacro a (x y) `(pair ,x ,y))").unwrap();
        e.expand_program(forms).unwrap();
        assert_eq!(e.len(), 2, "overwrite must not grow the table");
        // Re-expand a call to `a` — the NEW definition (two
        // required params) is active, and the OLD definition (one
        // required param) is gone. Under the new definition,
        // `(a 1 2)` expands to `(pair 1 2)`.
        let expanded = e.expand_program(read("(a foo bar)").unwrap()).unwrap();
        assert_eq!(expanded[0], parse("(pair foo bar)"));
    }

    #[test]
    fn register_at_table_ceiling_admits_up_to_but_not_past() {
        // Fail-before/pass-after negative control on the exact
        // boundary: with a ceiling of `3`, exactly three fresh keys
        // admit and the fourth rejects. A regression that ever
        // shifted the boundary by one (e.g. keyed on `>` instead of
        // `>=`, or checked `len() > cap` before insert instead of
        // `len() >= cap`) would fail one of the two arms — either
        // the third admission or the fourth rejection.
        let mut e = Expander::new();
        e.set_max_registered_macros(3);
        // Three fresh keys admit.
        e.expand_program(
            read(
                "(defmacro a (x) `(list ,x))
                 (defmacro b (x) `(list ,x))
                 (defmacro c (x) `(list ,x))",
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(e.len(), 3);
        // Fourth fresh key rejects.
        let err = e
            .expand_program(read("(defmacro d (x) `(list ,x))").unwrap())
            .unwrap_err();
        match err {
            LispError::RegisteredMacrosExceeded {
                macro_name,
                count,
                limit,
            } => {
                assert_eq!(macro_name, "d");
                assert_eq!(count, 3);
                assert_eq!(limit, 3);
            }
            other => panic!("expected RegisteredMacrosExceeded, got: {other:?}"),
        }
        // Table stays at pre-rejection size — no partial write.
        assert_eq!(e.len(), 3);
        assert!(!e.has("d"));
    }

    #[test]
    fn register_table_ceiling_leaves_both_tables_pristine_on_rejection() {
        // A rejected registration MUST leave BOTH `self.macros` AND
        // `self.templates` exactly as they were — no partial-write
        // window in which one table carries the over-ceiling entry
        // while the other does not, or in which the template
        // pre-compile already ran. Table-count gate fires BEFORE
        // body-size gate walks the body AND BEFORE any insert lands,
        // so a regression that ever moved the table-count gate
        // below `self.templates.insert` or below
        // `self.macros.insert` would fail this pin. Peer to
        // `register_failure_leaves_both_tables_pristine` on the
        // body-size axis.
        let mut e = Expander::new();
        e.set_max_registered_macros(1);
        // Land one macro at ceiling.
        e.expand_program(read("(defmacro a (x) `(list ,x))").unwrap())
            .unwrap();
        assert!(e.has("a"));
        // Reject a fresh second key.
        let err = e
            .expand_program(read("(defmacro b (x) `(list ,x))").unwrap())
            .unwrap_err();
        assert!(matches!(err, LispError::RegisteredMacrosExceeded { .. }));
        // Table stays at pre-rejection state — `b` is NOT present
        // in either self.macros OR self.templates.
        assert_eq!(e.len(), 1);
        assert!(e.has("a"));
        assert!(!e.has("b"));
        // Expanding a call to `a` still works (templates table for
        // `a` untouched by the failed `b` registration).
        let expanded = e.expand_program(read("(a hey)").unwrap()).unwrap();
        assert_eq!(expanded[0], parse("(list hey)"));
    }

    #[test]
    fn set_max_registered_macros_zero_rejects_every_fresh_registration() {
        // Zero ceiling is the "contract-test that this expander
        // accepts no new macros" posture — every fresh key rejects
        // at the first `defmacro` because `0 >= 0`. Peer to the
        // depth-ceiling zero-admits-and-rejects-every-macro-call
        // pin one RESOURCE axis over.
        let mut e = Expander::new();
        e.set_max_registered_macros(0);
        let err = e
            .expand_program(read("(defmacro a (x) `(list ,x))").unwrap())
            .unwrap_err();
        match err {
            LispError::RegisteredMacrosExceeded {
                macro_name,
                count,
                limit,
            } => {
                assert_eq!(macro_name, "a");
                assert_eq!(count, 0);
                assert_eq!(limit, 0);
            }
            other => panic!("expected RegisteredMacrosExceeded, got: {other:?}"),
        }
        assert!(e.is_empty());
    }

    #[test]
    fn registered_macros_exceeded_position_is_none() {
        // The variant joins the non-positional cohort — the
        // offending macro's byte offset is not what a table-count
        // diagnostic anchors to; the (offending fresh macro name,
        // observed table count, configured ceiling) triple is.
        // This pin keeps the variant in the `position() -> None`
        // cohort so a future span-carrying edit lands the field
        // in ONE place across every non-positional variant
        // simultaneously. Peer to the four prior
        // `*_exceeded_position_is_none` pins on the resource-
        // ceiling cohort.
        let err = LispError::RegisteredMacrosExceeded {
            macro_name: "fresh-1000".to_string(),
            count: 4096,
            limit: 4096,
        };
        assert_eq!(err.position(), None);
    }

    #[test]
    fn registered_macros_exceeded_display_matches_typed_variant_shape() {
        // Display projection carries `macro_name`, `count`, AND
        // `limit`, so authoring surfaces that substring-grep the
        // rendered diagnostic (`tatara-check`, REPL, LSP) see ALL
        // THREE halves at the variant boundary and never need to
        // substring-parse free-form text to recover the identity
        // of the offending fresh key, the observed table count, or
        // the ceiling it breached. Peer to the four prior
        // `*_exceeded_display_matches_typed_variant_shape` pins.
        let err = LispError::RegisteredMacrosExceeded {
            macro_name: "fresh-1000".to_string(),
            count: 4096,
            limit: 4096,
        };
        let rendered = err.to_string();
        assert!(rendered.contains("fresh-1000"), "rendered: {rendered}");
        assert!(rendered.contains("4096"), "rendered: {rendered}");
        assert!(
            rendered.contains("registered macros count exceeded"),
            "rendered: {rendered}"
        );
    }

    #[test]
    fn lawful_typescape_within_ceiling_registers_and_expands() {
        // A lawful hand-authored typescape (a handful of macros)
        // sits well below any realistic ceiling — the default
        // `DEFAULT_MAX_REGISTERED_MACROS` is deliberately generous
        // so operators never brush it on real authoring workloads.
        // This pin locks the default ceiling's non-interference
        // posture: a regression that ever lowered the default
        // enough to reject a small typescape would fail here. Peer
        // to `lawful_macro_body_within_ceiling_registers_and_expands`.
        let mut e = Expander::new();
        let forms = read(
            "(defmacro when (cond x) `(if ,cond ,x))
             (defmacro twice (x) `(list ,x ,x))
             (defmacro pair (x y) `(list ,x ,y))
             (when #t (twice hey))",
        )
        .unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(if #t (list hey hey))"));
        assert_eq!(e.len(), 3);
    }

    #[test]
    fn register_macro_def_direct_call_respects_table_ceiling() {
        // `register_macro_def` is the substrate primitive both
        // `expand_program`'s `defmacro` recognition AND
        // `with_macros`'s bulk load route through. The table-count
        // ceiling fires on the primitive itself, not on any one
        // consumer — a regression that ever moved the gate into
        // `expand_program`'s arm alone would fail this pin. Peer
        // to `register_macro_def_direct_call_respects_body_size_ceiling`
        // one RESOURCE-DIMENSION axis over.
        let mut e = Expander::new();
        e.set_max_registered_macros(1);
        let def_a = MacroDef {
            name: "a".to_string(),
            params: MacroParams {
                required: vec!["x".to_string()],
                optional: Vec::new(),
                rest: None,
            },
            body: Sexp::Atom(crate::ast::Atom::Symbol("y".to_string())),
        };
        let def_b = MacroDef {
            name: "b".to_string(),
            params: MacroParams {
                required: vec!["x".to_string()],
                optional: Vec::new(),
                rest: None,
            },
            body: Sexp::Atom(crate::ast::Atom::Symbol("y".to_string())),
        };
        // First admits — table sits at ceiling.
        e.register_macro_def(def_a).unwrap();
        assert!(e.has("a"));
        assert_eq!(e.len(), 1);
        // Second rejects — fresh key past ceiling.
        let err = e.register_macro_def(def_b).unwrap_err();
        match err {
            LispError::RegisteredMacrosExceeded {
                macro_name,
                count,
                limit,
            } => {
                assert_eq!(macro_name, "b");
                assert_eq!(count, 1);
                assert_eq!(limit, 1);
            }
            other => panic!("expected RegisteredMacrosExceeded, got: {other:?}"),
        }
        assert!(!e.has("b"));
        assert_eq!(e.len(), 1);
    }

    #[test]
    fn register_macro_def_direct_call_admits_overwrite_at_table_ceiling() {
        // Direct `register_macro_def` calls must ALSO admit
        // overwrites at ceiling — the overwrite discipline lives
        // on the primitive, not on `expand_program`'s arm alone.
        // Sibling of the source-level overwrite admission test.
        let mut e = Expander::new();
        e.set_max_registered_macros(1);
        let def_a_v1 = MacroDef {
            name: "a".to_string(),
            params: MacroParams {
                required: vec!["x".to_string()],
                optional: Vec::new(),
                rest: None,
            },
            body: Sexp::Atom(crate::ast::Atom::Symbol("y".to_string())),
        };
        let def_a_v2 = MacroDef {
            name: "a".to_string(),
            params: MacroParams {
                required: vec!["x".to_string(), "y".to_string()],
                optional: Vec::new(),
                rest: None,
            },
            body: Sexp::Atom(crate::ast::Atom::Symbol("z".to_string())),
        };
        e.register_macro_def(def_a_v1).unwrap();
        assert_eq!(e.len(), 1);
        // Overwrite of `a` at ceiling admits — no growth.
        e.register_macro_def(def_a_v2).unwrap();
        assert_eq!(e.len(), 1);
    }

    // ── `MacroParams::total_arity` — the total-slots projection ──
    //
    // `total_arity()` names `required.len() + optional.len() +
    // rest.is_some() as usize` on the typed `MacroParams` algebra —
    // the `Vec`-free peer of `names().len()` AND the axis both
    // `MacroParams::bind`'s `Vec::with_capacity` hint AND the
    // REGISTER-time arity-ceiling gate consult. These pins cover:
    // structural identity vs. `names().len()`, the
    // `fixed_arity + rest.is_some() as usize` decomposition, and the
    // three canonical shapes (empty, all-required, mixed with rest).
    #[test]
    fn macro_params_total_arity_matches_names_len() {
        // The structural identity `total_arity() == names().len()`
        // — the `Vec`-free primitive's projection equals the flat-
        // index list's length. A regression that ever miscounts
        // one slot (drops rest, double-counts optional) fails this
        // pin. Sibling to `fixed_arity`'s peer-arithmetic pins.
        let params = MacroParams {
            required: vec!["a".into(), "b".into()],
            optional: vec![OptionalParam::bare("c"), OptionalParam::bare("d")],
            rest: Some("e".into()),
        };
        assert_eq!(params.total_arity(), params.names().len());
        assert_eq!(params.total_arity(), 5);
    }

    #[test]
    fn macro_params_total_arity_equals_fixed_arity_plus_rest_bit() {
        // The `fixed_arity + rest.is_some() as usize` decomposition
        // — pins the composition on the [`MacroParams`] algebra so
        // a future consumer that wants "total slots" via
        // `fixed_arity + rest?` binds to the same arithmetic
        // `total_arity` names.
        let rest_none = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: None,
        };
        assert_eq!(rest_none.total_arity(), rest_none.fixed_arity());
        assert_eq!(rest_none.total_arity(), 2);
        let rest_some = MacroParams {
            required: vec!["a".into()],
            optional: vec![OptionalParam::bare("b")],
            rest: Some("r".into()),
        };
        assert_eq!(rest_some.total_arity(), rest_some.fixed_arity() + 1);
        assert_eq!(rest_some.total_arity(), 3);
    }

    #[test]
    fn macro_params_total_arity_is_zero_for_the_empty_param_list() {
        // Nullary macro edge: `(defmacro nullary () BODY)` has
        // `total_arity() == 0`. Under a `set_max_macro_arity(0)`
        // ceiling the arity gate keys on `>` (equality admits), so
        // this nullary registration succeeds while any non-nullary
        // one rejects — the exact contract the arity-gate
        // zero-admits-nullary test below relies on.
        let params = MacroParams::default();
        assert_eq!(params.total_arity(), 0);
    }

    // ── max_macro_arity: REGISTRATION-time param-count ceiling ──
    // Peer to body-size (REGISTER-time BODY SIZE) one RESOURCE-
    // DIMENSION axis over — where body-size bounds a per-registration
    // BODY node count, this ceiling bounds a per-registration PARAM
    // slot count. Peer to registered-macros (REGISTER-time TABLE
    // COUNT) one RESOURCE-DIMENSION axis over — where
    // registered-macros bounds cumulative registration COUNT, this
    // ceiling bounds a per-registration PARAM-LIST WIDTH. Together
    // the three REGISTER-time ceilings close the (per-body SIZE,
    // per-body ARITY, per-table COUNT) three-corner surface.

    #[test]
    fn expander_default_max_macro_arity_is_the_module_constant() {
        // Both constructors seed `max_macro_arity` from the module
        // constant — a regression that drifts one constructor's
        // default from the constant (e.g. a hardcoded `128` at ONE
        // site with the other left uninitialized after a `Default`
        // derive addition) fails this pin. Peer to the five prior
        // default-coherence pins on depth, cache-entries,
        // expansion-size, body-size, and registered-macros.
        assert_eq!(Expander::new().max_macro_arity(), DEFAULT_MAX_MACRO_ARITY);
        assert_eq!(
            Expander::new_substitute_only().max_macro_arity(),
            DEFAULT_MAX_MACRO_ARITY
        );
        assert_eq!(DEFAULT_MAX_MACRO_ARITY, 128);
    }

    #[test]
    fn set_max_macro_arity_takes_effect_on_subsequent_register() {
        // Setter mirrors accessor — a regression that ever forgets to
        // write through to the field, or writes to a shadow field the
        // accessor does not read, fails this pin. Peer to the five
        // prior setter/accessor coherence pins.
        let mut e = Expander::new();
        e.set_max_macro_arity(16);
        assert_eq!(e.max_macro_arity(), 16);
    }

    #[test]
    fn register_arity_bomb_rejects_at_arity_limit_bytecode_path() {
        // `(defmacro huge (a b c) `,a)` declares 3 required params.
        // Under `set_max_macro_arity(2)` the arity gate fires:
        // 3 > 2 → `LispError::MacroArityExceeded { macro_name: "huge",
        // arity: 3, limit: 2 }`. `arity` is the observed
        // `def.params.total_arity()`, NOT `required.len()` alone —
        // even an optional-only or rest-only overrun trips the gate
        // (pinned separately). Peer to the register-time body-size
        // rejection tests one RESOURCE-DIMENSION axis over.
        let mut e = Expander::new();
        e.set_max_macro_arity(2);
        let forms = read("(defmacro huge (a b c) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::MacroArityExceeded {
                macro_name,
                arity,
                limit,
            } => {
                assert_eq!(macro_name, "huge");
                assert_eq!(arity, 3);
                assert_eq!(limit, 2);
            }
            other => panic!("expected MacroArityExceeded, got: {other:?}"),
        }
        assert!(!e.has("huge"));
    }

    #[test]
    fn register_arity_bomb_rejects_at_arity_limit_substitute_path() {
        // The substitute strategy shares the same
        // `register_macro_def` outer registration entry with the
        // bytecode strategy, so the REGISTRATION-time ARITY ceiling
        // fires at the SAME gate regardless of which apply-layer is
        // active. Peer to
        // `register_arity_bomb_rejects_at_arity_limit_bytecode_path`.
        let mut e = Expander::new_substitute_only();
        e.set_max_macro_arity(2);
        let forms = read("(defmacro huge (a b c) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::MacroArityExceeded {
                macro_name,
                arity,
                limit,
            } => {
                assert_eq!(macro_name, "huge");
                assert_eq!(arity, 3);
                assert_eq!(limit, 2);
            }
            other => panic!("expected MacroArityExceeded, got: {other:?}"),
        }
        assert!(!e.has("huge"));
    }

    #[test]
    fn register_arity_gate_counts_optional_slots() {
        // `(defmacro foo (a &optional b c) `,a)` has 1 required + 2
        // optional + 0 rest = arity 3 via `total_arity`. Under a
        // ceiling of `2` the gate rejects, matching the required-only
        // arity-bomb — the arity axis is `total_arity()`, not
        // `required.len()`. A regression that drops the optional slots
        // from the arity computation would ADMIT this shape and fail
        // this pin.
        let mut e = Expander::new();
        e.set_max_macro_arity(2);
        let forms = read("(defmacro foo (a &optional b c) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::MacroArityExceeded {
                macro_name,
                arity,
                limit,
            } => {
                assert_eq!(macro_name, "foo");
                assert_eq!(arity, 3);
                assert_eq!(limit, 2);
            }
            other => panic!("expected MacroArityExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn register_arity_gate_counts_rest_slot() {
        // `(defmacro spread (a b &rest r) `,a)` has 2 required + 0
        // optional + 1 rest = arity 3 via `total_arity`. Under a
        // ceiling of `2` the gate rejects, matching the required-only
        // arity-bomb — the arity axis includes the rest slot as ONE
        // named param, not zero. A regression that drops the rest slot
        // from the arity computation would ADMIT this shape and fail
        // this pin.
        let mut e = Expander::new();
        e.set_max_macro_arity(2);
        let forms = read("(defmacro spread (a b &rest r) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        match err {
            LispError::MacroArityExceeded {
                macro_name,
                arity,
                limit,
            } => {
                assert_eq!(macro_name, "spread");
                assert_eq!(arity, 3);
                assert_eq!(limit, 2);
            }
            other => panic!("expected MacroArityExceeded, got: {other:?}"),
        }
    }

    #[test]
    fn register_arity_at_ceiling_admits() {
        // `(defmacro pair (x y) `(list ,x ,y))` has 2 required = arity
        // 2 via `total_arity`. Under a ceiling of `2` the arity gate
        // keys on `>` (equality admits; only strict overrun rejects),
        // so the registration succeeds and the expansion proceeds
        // normally. Fail-before/pass-after negative control on the
        // exact boundary: a regression that ever shifted the boundary
        // by one (e.g. keyed on `>=` instead of `>`) would fail this
        // pin. Peer to `register_macro_body_at_ceiling_admits` on the
        // body-size axis.
        let mut e = Expander::new();
        e.set_max_macro_arity(2);
        let forms = read("(defmacro pair (x y) `(list ,x ,y)) (pair a b)").unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(list a b)"));
        assert_eq!(e.len(), 1);
    }

    #[test]
    fn register_arity_ceiling_leaves_both_tables_pristine_on_rejection() {
        // A rejected arity-gated registration MUST leave BOTH
        // `self.macros` AND `self.templates` exactly as they were —
        // no partial-write window in which one table carries the
        // over-ceiling entry while the other does not, or in which
        // the template pre-compile already ran. Arity gate fires
        // BEFORE the body-size gate walks the body AND BEFORE any
        // insert lands, so a regression that ever moved the arity
        // gate below `self.templates.insert` or below
        // `self.macros.insert` would fail this pin. Peer to
        // `register_failure_leaves_both_tables_pristine` (body-size)
        // and `register_table_ceiling_leaves_both_tables_pristine_on_rejection`
        // (table-count).
        let mut e = Expander::new();
        e.set_max_macro_arity(1);
        let forms = read("(defmacro huge (a b c) `,a)").unwrap();
        assert!(e.expand_program(forms).is_err());
        assert!(
            !e.has("huge"),
            "macros table must stay pristine after rejection"
        );
        assert_eq!(e.len(), 0);
        // Expanding a NEW lawful macro afterwards still works — the
        // failed arity-gate rejection has not corrupted expander
        // state.
        let out = e
            .expand_program(read("(defmacro id (x) `,x) (id hey)").unwrap())
            .unwrap();
        assert_eq!(out[0], parse("hey"));
    }

    #[test]
    fn set_max_macro_arity_zero_rejects_every_non_nullary_registration() {
        // Zero ceiling is the "contract-test that this expander
        // accepts only nullary macros" posture — every fresh
        // non-nullary key rejects at the arity gate because
        // `total_arity() > 0`, while nullary `(defmacro nullary ()
        // BODY)` still admits (its arity is exactly 0, and only
        // strict overrun rejects). Peer to the body-size zero-rejects-
        // every-non-empty-body pin one RESOURCE-DIMENSION axis over
        // (though body-size zero rejects even nullary-body shapes,
        // since `Sexp::Nil::node_count() == 1 > 0`; arity zero
        // preserves the nullary registration surface).
        let mut e = Expander::new();
        e.set_max_macro_arity(0);
        // Nullary admits — arity 0 <= 0.
        e.expand_program(read("(defmacro nullary () `unit)").unwrap())
            .unwrap();
        assert!(e.has("nullary"));
        // Non-nullary rejects — arity 1 > 0.
        let err = e
            .expand_program(read("(defmacro id (x) `,x)").unwrap())
            .unwrap_err();
        match err {
            LispError::MacroArityExceeded {
                macro_name,
                arity,
                limit,
            } => {
                assert_eq!(macro_name, "id");
                assert_eq!(arity, 1);
                assert_eq!(limit, 0);
            }
            other => panic!("expected MacroArityExceeded, got: {other:?}"),
        }
        assert!(!e.has("id"));
    }

    #[test]
    fn macro_arity_exceeded_position_is_none() {
        // The variant joins the non-positional cohort — the offending
        // macro's byte offset is not what an arity-bomb diagnostic
        // anchors to; the (macro name, observed arity, configured
        // ceiling) triple is. This pin keeps the variant in the
        // `position() -> None` cohort so a future span-carrying edit
        // lands the field in ONE place across every non-positional
        // variant simultaneously. Peer to the five prior
        // `*_exceeded_position_is_none` pins on the resource-ceiling
        // cohort.
        let err = LispError::MacroArityExceeded {
            macro_name: "huge".to_string(),
            arity: 512,
            limit: 128,
        };
        assert_eq!(err.position(), None);
    }

    #[test]
    fn macro_arity_exceeded_display_matches_typed_variant_shape() {
        // Display projection carries `macro_name`, `arity`, AND
        // `limit`, so authoring surfaces that substring-grep the
        // rendered diagnostic (`tatara-check`, REPL, LSP) see ALL
        // THREE halves at the variant boundary and never need to
        // substring-parse free-form text to recover the identity of
        // the offending macro, the observed arity, or the ceiling it
        // breached. Peer to the five prior
        // `*_exceeded_display_matches_typed_variant_shape` pins.
        let err = LispError::MacroArityExceeded {
            macro_name: "huge".to_string(),
            arity: 512,
            limit: 128,
        };
        let rendered = err.to_string();
        assert!(rendered.contains("huge"), "rendered: {rendered}");
        assert!(rendered.contains("512"), "rendered: {rendered}");
        assert!(rendered.contains("128"), "rendered: {rendered}");
        assert!(
            rendered.contains("macro arity exceeded"),
            "rendered: {rendered}"
        );
    }

    #[test]
    fn lawful_macro_arity_within_ceiling_registers_and_expands() {
        // A lawful hand-authored macro arity sits well below any
        // realistic ceiling — the default `DEFAULT_MAX_MACRO_ARITY`
        // is deliberately generous so operators never brush it on
        // real authoring workloads. This pin locks the default
        // ceiling's non-interference posture: a regression that
        // ever lowered the default enough to reject the reference
        // multi-slot `(defmacro when (cond x) …)` shape would fail
        // here. Peer to `lawful_macro_body_within_ceiling_registers_and_expands`
        // and `lawful_typescape_within_ceiling_registers_and_expands`.
        let mut e = Expander::new();
        let forms = read(
            "(defmacro when (cond x) `(if ,cond ,x))
             (defmacro triple (x y z) `(list ,x ,y ,z))
             (when #t (triple a b c))",
        )
        .unwrap();
        let out = e.expand_program(forms).unwrap();
        assert_eq!(out[0], parse("(if #t (list a b c))"));
    }

    #[test]
    fn register_macro_def_direct_call_respects_arity_ceiling() {
        // `register_macro_def` is the substrate primitive both
        // `expand_program`'s `defmacro` recognition AND `with_macros`'s
        // bulk load route through. The arity ceiling fires on the
        // primitive itself, not on any one consumer — a regression
        // that ever moved the gate into `expand_program`'s arm alone
        // would fail this pin. Peer to
        // `register_macro_def_direct_call_respects_body_size_ceiling`
        // AND `register_macro_def_direct_call_respects_table_ceiling`
        // one RESOURCE-DIMENSION axis over.
        let mut e = Expander::new();
        e.set_max_macro_arity(2);
        let def = MacroDef {
            name: "huge".to_string(),
            params: MacroParams {
                required: vec!["a".to_string(), "b".to_string(), "c".to_string()],
                optional: Vec::new(),
                rest: None,
            },
            body: Sexp::Atom(crate::ast::Atom::Symbol("a".to_string())),
        };
        // Arity 3 > ceiling 2 — rejected before body-size gate.
        let err = e.register_macro_def(def).unwrap_err();
        match err {
            LispError::MacroArityExceeded {
                macro_name,
                arity,
                limit,
            } => {
                assert_eq!(macro_name, "huge");
                assert_eq!(arity, 3);
                assert_eq!(limit, 2);
            }
            other => panic!("expected MacroArityExceeded, got: {other:?}"),
        }
        assert!(!e.has("huge"));
    }

    #[test]
    fn arity_gate_fires_before_body_size_gate() {
        // ORDERING PIN — the arity gate fires BEFORE the body-size
        // gate. With both `set_max_macro_arity(1)` AND
        // `set_max_macro_body_size(2)` set below a shape that violates
        // BOTH ceilings — `(defmacro dual (a b) `(list ,a ,b))` has
        // arity 2 AND body node count > 2 — the arity gate's
        // rejection wins, so the returned variant is
        // `MacroArityExceeded`, not `MacroBodySizeExceeded`. A
        // regression that ever swapped the two gates' order would fail
        // this pin. The ordering isn't cosmetic: arity is O(1)
        // (three-arm addition on `def.params` fields), body-size is
        // O(body_nodes) (`def.body.node_count()` walks the AST), so
        // the O(1)-first order minimises the cost of rejecting the
        // worst case (a large-body large-arity macro).
        let mut e = Expander::new();
        e.set_max_macro_arity(1);
        e.set_max_macro_body_size(2);
        let forms = read("(defmacro dual (a b) `(list ,a ,b))").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(err, LispError::MacroArityExceeded { .. }),
            "arity gate must fire before body-size gate; got: {err:?}"
        );
    }

    #[test]
    fn arity_gate_fires_after_table_count_gate() {
        // ORDERING PIN — the table-count gate fires BEFORE the arity
        // gate. Under `set_max_registered_macros(1)` at capacity AND
        // `set_max_macro_arity(1)`, a fresh over-arity registration
        // trips the table-count gate FIRST (its `HashMap::len`
        // comparison is O(1) cache-friendly and gates cumulative
        // registration cost); the arity gate is O(1) but on `def`,
        // not on shared state, so it sits AFTER the table-count gate
        // on the O(1)-first ordering of the REGISTER-time chain. A
        // regression that ever swapped the two would fail this pin.
        let mut e = Expander::new();
        e.set_max_registered_macros(1);
        e.set_max_macro_arity(1);
        // Land one macro at table ceiling.
        e.expand_program(read("(defmacro anchor (x) `,x)").unwrap())
            .unwrap();
        assert_eq!(e.len(), 1);
        // Fresh registration with BOTH violations — table-count wins.
        let forms = read("(defmacro huge (a b c) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(err, LispError::RegisteredMacrosExceeded { .. }),
            "table-count gate must fire before arity gate; got: {err:?}"
        );
    }

    // ── ResourceLimits: bundled resource-ceiling snapshot ────────────

    #[test]
    fn default_resource_limits_binds_each_field_to_matching_module_constant() {
        // Pin the (constant × aggregation) corner: the const-form
        // aggregate MUST bind every field to its individually-defined
        // module constant. A re-tuning of ONE module constant
        // (e.g. `DEFAULT_MAX_EXPANSION_DEPTH` raised from 256 to 512)
        // has to propagate through the aggregate at ONE site; this
        // test fires the divergence loudly if a future edit sets a
        // module constant to a fresh value but forgets to update the
        // matching aggregate slot. Field-by-field equality carries
        // the message better than one deep-equality assertion.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.max_expansion_depth,
            DEFAULT_MAX_EXPANSION_DEPTH
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.max_cache_entries,
            DEFAULT_MAX_CACHE_ENTRIES
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.max_expansion_size,
            DEFAULT_MAX_EXPANSION_SIZE
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.max_macro_body_size,
            DEFAULT_MAX_MACRO_BODY_SIZE
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.max_registered_macros,
            DEFAULT_MAX_REGISTERED_MACROS
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.max_macro_arity,
            DEFAULT_MAX_MACRO_ARITY
        );
    }

    #[test]
    fn resource_limits_default_impl_matches_const_form() {
        // The two projections of the shipped posture — the `const`
        // form [`DEFAULT_RESOURCE_LIMITS`] and the runtime
        // `Default::default()` form — must reach the SAME value. Pins
        // that a future edit which flips one to a new default cannot
        // silently drift the other.
        assert_eq!(ResourceLimits::default(), DEFAULT_RESOURCE_LIMITS);
    }

    #[test]
    fn expander_new_resource_limits_matches_shipped_defaults() {
        // Fresh-expander posture on the bundled-getter surface — the
        // six ceilings [`Expander::new`] seeds MUST snapshot to
        // [`DEFAULT_RESOURCE_LIMITS`] verbatim. Peer of the six
        // individual `expander_default_max_*_is_the_module_constant`
        // pins one AGGREGATION axis over — where each individual
        // pin catches ONE field drift, this pin catches ANY of the
        // six drifting AND the snapshot projection itself losing a
        // field.
        assert_eq!(Expander::new().resource_limits(), DEFAULT_RESOURCE_LIMITS);
    }

    #[test]
    fn expander_new_substitute_only_resource_limits_matches_shipped_defaults() {
        // Substitute-only expander seeds the SAME six ceilings from
        // the SAME module constants as [`Expander::new`] — the two
        // constructors share the resource-ceiling posture even
        // though they diverge on `compile_templates` +
        // `cache_enabled`. Pins that a future constructor which
        // forgets to seed one of the six ceilings from its module
        // constant fails loudly through the bundled getter.
        assert_eq!(
            Expander::new_substitute_only().resource_limits(),
            DEFAULT_RESOURCE_LIMITS
        );
    }

    #[test]
    fn resource_limits_snapshot_reflects_each_individual_setter() {
        // Coherence pin between the six individual setters and the
        // bundled getter — flipping ONE ceiling via its individual
        // setter must project through [`Expander::resource_limits`]
        // to the SAME value the individual getter returns. A
        // regression that leaves ONE field out of the snapshot
        // projection (a copy-paste omission in the struct literal
        // constructor) fires here. Distinct low-non-default values
        // so a stray field carrying the default fails loudly.
        let mut e = Expander::new();
        e.set_max_expansion_depth(3);
        e.set_max_cache_entries(5);
        e.set_max_expansion_size(7);
        e.set_max_macro_body_size(11);
        e.set_max_registered_macros(13);
        e.set_max_macro_arity(17);
        let snap = e.resource_limits();
        assert_eq!(snap.max_expansion_depth, 3);
        assert_eq!(snap.max_cache_entries, 5);
        assert_eq!(snap.max_expansion_size, 7);
        assert_eq!(snap.max_macro_body_size, 11);
        assert_eq!(snap.max_registered_macros, 13);
        assert_eq!(snap.max_macro_arity, 17);
        // And the individual getters see the same values — the
        // snapshot is a projection, not a divergent copy.
        assert_eq!(e.max_expansion_depth(), 3);
        assert_eq!(e.max_cache_entries(), 5);
        assert_eq!(e.max_expansion_size(), 7);
        assert_eq!(e.max_macro_body_size(), 11);
        assert_eq!(e.max_registered_macros(), 13);
        assert_eq!(e.max_macro_arity(), 17);
    }

    #[test]
    fn set_resource_limits_bulk_propagates_every_field_to_individual_getters() {
        // Sibling pin to `resource_limits_snapshot_reflects_...` on the
        // WRITE axis — bulk-setting via [`Expander::set_resource_limits`]
        // must reach every individual `max_*` getter. A regression
        // that drops one field from the destructuring assignment in
        // the bulk setter fires here. Distinct low-non-default values
        // so a stray field carrying the previous value fails loudly.
        let mut e = Expander::new();
        e.set_resource_limits(ResourceLimits {
            max_expansion_depth: 2,
            max_cache_entries: 4,
            max_expansion_size: 8,
            max_macro_body_size: 16,
            max_registered_macros: 32,
            max_macro_arity: 64,
        });
        assert_eq!(e.max_expansion_depth(), 2);
        assert_eq!(e.max_cache_entries(), 4);
        assert_eq!(e.max_expansion_size(), 8);
        assert_eq!(e.max_macro_body_size(), 16);
        assert_eq!(e.max_registered_macros(), 32);
        assert_eq!(e.max_macro_arity(), 64);
    }

    #[test]
    fn resource_limits_round_trip_through_bundled_getter_and_setter_is_identity() {
        // Round-trip theorem — for any starting expander, the
        // composition `set_resource_limits(resource_limits())` is
        // the identity on the resource-ceiling surface. This is the
        // ONE typed statement that pins the (getter, setter) pair as
        // strict projections of the same six-field surface, no
        // hidden lossy field, no ordering asymmetry between the
        // struct literal and the destructuring pattern.
        let mut e = Expander::new();
        e.set_max_expansion_depth(9);
        e.set_max_cache_entries(19);
        e.set_max_expansion_size(29);
        e.set_max_macro_body_size(39);
        e.set_max_registered_macros(49);
        e.set_max_macro_arity(59);
        let snap = e.resource_limits();
        // Reset to defaults so any leftover state would show up in
        // the post-round-trip snapshot as the default rather than
        // the intended value.
        e.set_resource_limits(ResourceLimits::default());
        assert_eq!(e.resource_limits(), DEFAULT_RESOURCE_LIMITS);
        // Apply the captured snapshot — the expander must land at
        // the same six values `snap` recorded.
        e.set_resource_limits(snap);
        assert_eq!(e.resource_limits(), snap);
    }

    #[test]
    fn resource_limits_struct_update_syntax_overrides_one_ceiling() {
        // The `Copy` posture on [`ResourceLimits`] gives callers the
        // cheap ergonomic of a struct-update literal — take the
        // shipped posture and override ONE ceiling — that a chain of
        // six independent setters cannot express in ONE typed expression.
        // Pins the intended use-shape so a future refactor which
        // removes `Copy` from the struct fails to compile at THIS
        // site rather than at every downstream consumer.
        let mut e = Expander::new();
        e.set_resource_limits(ResourceLimits {
            max_macro_arity: 4,
            ..DEFAULT_RESOURCE_LIMITS
        });
        // Overridden field carries the fresh value.
        assert_eq!(e.max_macro_arity(), 4);
        // Every other field carries the shipped default — the
        // struct-update literal is a full projection, not a
        // selective mutation.
        assert_eq!(e.max_expansion_depth(), DEFAULT_MAX_EXPANSION_DEPTH);
        assert_eq!(e.max_cache_entries(), DEFAULT_MAX_CACHE_ENTRIES);
        assert_eq!(e.max_expansion_size(), DEFAULT_MAX_EXPANSION_SIZE);
        assert_eq!(e.max_macro_body_size(), DEFAULT_MAX_MACRO_BODY_SIZE);
        assert_eq!(e.max_registered_macros(), DEFAULT_MAX_REGISTERED_MACROS);
    }

    #[test]
    fn expander_default_derives_resource_limits_from_bundled_field_default() {
        // Post the [`Expander::limits`]-field consolidation the derived
        // `Default` on [`Expander`] projects through [`ResourceLimits`]'s
        // own `Default` — which returns [`DEFAULT_RESOURCE_LIMITS`] — so
        // `Expander::default().resource_limits()` lands at the shipped
        // ceiling posture verbatim. Pre-consolidation the six independent
        // `max_*: usize` fields defaulted to the bare `usize` zero, so
        // `Expander::default()` yielded a below-floor posture with every
        // ceiling clamped to `0` — a shape no consumer wanted and every
        // test path avoided by routing through [`Expander::new`] instead.
        // The consolidation is what turned that latent below-floor
        // derived-`Default` shape into a lawful shipped posture on the
        // structural axis. Peer of
        // `expander_new_resource_limits_matches_shipped_defaults` one
        // CONSTRUCTOR axis over — where that test pins the explicit
        // [`Expander::new`] constructor, this test pins the derived-
        // [`Default`] constructor route to the SAME six values through
        // the SAME bundled projection. Sibling of
        // `resource_limits_default_impl_matches_const_form` one
        // TYPE-LEVEL axis over — that test pins [`ResourceLimits::default`]
        // to [`DEFAULT_RESOURCE_LIMITS`]; this test pins [`Expander`]'s
        // derived `Default` to project through it.
        assert_eq!(
            Expander::default().resource_limits(),
            DEFAULT_RESOURCE_LIMITS
        );
    }

    #[test]
    fn resource_limits_bulk_setter_keeps_the_arity_gate_in_effect() {
        // Behavioral pin — the bundled setter is not a decorative
        // getter/setter pair; the six ceilings it propagates must
        // reach the SAME check sites the individual setters do. Set
        // `max_macro_arity` to 1 via the bulk setter and confirm the
        // arity gate fires on a two-arg macro registration. A
        // regression that wired the bulk setter to a shadow field
        // rather than the actual `Expander` state fails here.
        let mut e = Expander::new();
        e.set_resource_limits(ResourceLimits {
            max_macro_arity: 1,
            ..DEFAULT_RESOURCE_LIMITS
        });
        let forms = read("(defmacro two (a b) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(
                err,
                LispError::MacroArityExceeded {
                    arity: 2,
                    limit: 1,
                    ..
                }
            ),
            "bulk-set arity ceiling must reach the register-time gate; got: {err:?}"
        );
    }

    // ── Expander::with_limits — at-construction resource-posture ───────

    #[test]
    fn expander_with_limits_seeds_the_provided_resource_posture() {
        // Round-trip pin at CONSTRUCTION time — the bundle the caller
        // passes into [`Expander::with_limits`] MUST project back
        // through [`Expander::resource_limits`] verbatim. Peer of the
        // `set_resource_limits(l); resource_limits() == l` round-trip
        // one CONSTRUCTOR-STAGE axis over — that pin covers the
        // POST-construction assignment; this pin covers the
        // AT-construction assignment. A regression that dropped the
        // `limits` argument on the floor (a copy-paste that left
        // `limits: DEFAULT_RESOURCE_LIMITS` in the struct literal
        // instead of `limits`) fires here on every non-default field.
        // Distinct low-non-default values so a stray field defaulting
        // fails loudly.
        let want = ResourceLimits {
            max_expansion_depth: 3,
            max_cache_entries: 5,
            max_expansion_size: 7,
            max_macro_body_size: 11,
            max_registered_macros: 13,
            max_macro_arity: 17,
        };
        assert_eq!(Expander::with_limits(want).resource_limits(), want);
    }

    #[test]
    fn expander_with_default_limits_agrees_with_new_on_resource_posture() {
        // Delegation identity — [`Expander::new`] delegates to
        // [`Expander::with_limits`] with [`DEFAULT_RESOURCE_LIMITS`] so
        // the two constructors MUST agree on the resource-ceiling
        // projection. Pins the "no drift between the two paths to a
        // fresh default-posture expander" theorem: a future refactor
        // that breaks the delegation (an inline field literal reappearing
        // in [`Expander::new`], an accidental hardcoded const at ONE
        // site with the other unchanged) fires here. Peer of
        // `resource_limits_default_impl_matches_const_form` one
        // TYPE-LEVEL axis over — that test pins the two projections of
        // the shipped posture on [`ResourceLimits`] itself; this test
        // pins the two constructor paths on [`Expander`] to reach the
        // SAME six values through the SAME bundle.
        assert_eq!(
            Expander::with_limits(DEFAULT_RESOURCE_LIMITS).resource_limits(),
            Expander::new().resource_limits()
        );
    }

    #[test]
    fn expander_with_limits_composes_with_struct_update_override() {
        // The `Copy` posture on [`ResourceLimits`] lets a caller compose
        // "the shipped posture with ONE ceiling overridden" as ONE
        // struct-update literal AND thread that composition through
        // [`Expander::with_limits`] as ONE typed call — the ergonomic
        // shape that six independent setter invocations cannot express
        // in ONE expression. Overridden ceiling carries the fresh value,
        // every other ceiling carries its shipped default. A future
        // refactor that removes `Copy` from [`ResourceLimits`] fails to
        // compile at THIS site rather than at every downstream consumer.
        let e = Expander::with_limits(ResourceLimits {
            max_macro_arity: 4,
            ..DEFAULT_RESOURCE_LIMITS
        });
        assert_eq!(e.max_macro_arity(), 4);
        assert_eq!(e.max_expansion_depth(), DEFAULT_MAX_EXPANSION_DEPTH);
        assert_eq!(e.max_cache_entries(), DEFAULT_MAX_CACHE_ENTRIES);
        assert_eq!(e.max_expansion_size(), DEFAULT_MAX_EXPANSION_SIZE);
        assert_eq!(e.max_macro_body_size(), DEFAULT_MAX_MACRO_BODY_SIZE);
        assert_eq!(e.max_registered_macros(), DEFAULT_MAX_REGISTERED_MACROS);
    }

    #[test]
    fn expander_with_limits_carries_the_new_execution_strategy() {
        // The (compile_templates, cache_enabled) execution-strategy pair
        // MUST carry the [`Expander::new`] default posture — bytecode +
        // cache both on — regardless of which resource posture the
        // caller passes in. Cache-count observation is the least-
        // invasive check available on the public surface: a fresh
        // `with_limits` expander that expands a repeat-call site must
        // populate at least one cache entry (bytecode + cache both on),
        // and a substitute-only sibling would leave `cache_size()` at
        // zero even after every call site expanded. A regression that
        // wired the wrong execution strategy into `with_limits`
        // (compile_templates: false, cache_enabled: false) fires here.
        let mut e = Expander::with_limits(DEFAULT_RESOURCE_LIMITS);
        let forms = read(
            "(defmacro id (x) `,x)
             (id one)
             (id one)",
        )
        .unwrap();
        e.expand_program(forms).unwrap();
        assert!(
            e.cache_size() >= 1,
            "with_limits carries the bytecode+cache strategy; cache_size must be >= 1 after repeat calls, got {}",
            e.cache_size()
        );
    }

    #[test]
    fn expander_with_limits_fires_the_arity_gate_from_construction() {
        // Behavioral pin — the at-construction bundle assignment MUST
        // reach the SAME check sites the individual + bulk POST-
        // construction setters do. Construct an expander with
        // `max_macro_arity: 1` directly and confirm the arity gate
        // fires on a two-arg macro registration. Sibling of
        // `resource_limits_bulk_setter_keeps_the_arity_gate_in_effect`
        // one CONSTRUCTOR-STAGE axis over — that pin covers the POST-
        // construction setter reaching the gate; this pin covers the
        // AT-construction assignment reaching the SAME gate through
        // the SAME `self.limits.max_macro_arity` load. A regression
        // that wired `with_limits` to a shadow field rather than
        // `self.limits` fails here.
        let mut e = Expander::with_limits(ResourceLimits {
            max_macro_arity: 1,
            ..DEFAULT_RESOURCE_LIMITS
        });
        let forms = read("(defmacro two (a b) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(
                err,
                LispError::MacroArityExceeded {
                    arity: 2,
                    limit: 1,
                    ..
                }
            ),
            "at-construction arity ceiling must reach the register-time gate; got: {err:?}"
        );
    }

    // ── UNBOUNDED_RESOURCE_LIMITS — ceiling-lifted preset posture ──────

    #[test]
    fn unbounded_resource_limits_binds_every_ceiling_to_usize_max() {
        // Field-level pin — the ceiling-lifted preset carries
        // [`usize::MAX`] on every axis of the six-field surface. Pinned
        // as six independent field asserts (rather than one struct
        // equality) so a drift on ONE field carries a distinct-name
        // failure that names the drifting axis. A future extension
        // that adds a SEVENTH ceiling requires an additional field
        // assert here in lockstep with the const literal — rustc's
        // field-exhaustiveness on the const forces the new field to
        // appear, and this pin exercises it.
        assert_eq!(UNBOUNDED_RESOURCE_LIMITS.max_expansion_depth, usize::MAX);
        assert_eq!(UNBOUNDED_RESOURCE_LIMITS.max_cache_entries, usize::MAX);
        assert_eq!(UNBOUNDED_RESOURCE_LIMITS.max_expansion_size, usize::MAX);
        assert_eq!(UNBOUNDED_RESOURCE_LIMITS.max_macro_body_size, usize::MAX);
        assert_eq!(UNBOUNDED_RESOURCE_LIMITS.max_registered_macros, usize::MAX);
        assert_eq!(UNBOUNDED_RESOURCE_LIMITS.max_macro_arity, usize::MAX);
    }

    #[test]
    fn unbounded_resource_limits_disagrees_with_default_on_every_ceiling() {
        // Structural-distinctness pin — the two constants
        // [`DEFAULT_RESOURCE_LIMITS`] and [`UNBOUNDED_RESOURCE_LIMITS`]
        // sit at DISTINCT points on the posture axis of the (posture ×
        // aggregation) grid, and the disagreement is EXHAUSTIVE on the
        // six-field surface — every shipped `DEFAULT_MAX_*` module
        // constant is a concrete positive value strictly less than
        // [`usize::MAX`]. Pins that a future re-tuning which cranked one
        // shipped default up to [`usize::MAX`] (collapsing the two
        // presets on that field) fires here loudly rather than
        // silently letting the two presets become indistinguishable
        // on that axis. A regression which flipped ONE unbounded-const
        // field back to its default value also fires here — either
        // half of the disagreement breaks the theorem.
        assert_ne!(
            UNBOUNDED_RESOURCE_LIMITS.max_expansion_depth,
            DEFAULT_RESOURCE_LIMITS.max_expansion_depth
        );
        assert_ne!(
            UNBOUNDED_RESOURCE_LIMITS.max_cache_entries,
            DEFAULT_RESOURCE_LIMITS.max_cache_entries
        );
        assert_ne!(
            UNBOUNDED_RESOURCE_LIMITS.max_expansion_size,
            DEFAULT_RESOURCE_LIMITS.max_expansion_size
        );
        assert_ne!(
            UNBOUNDED_RESOURCE_LIMITS.max_macro_body_size,
            DEFAULT_RESOURCE_LIMITS.max_macro_body_size
        );
        assert_ne!(
            UNBOUNDED_RESOURCE_LIMITS.max_registered_macros,
            DEFAULT_RESOURCE_LIMITS.max_registered_macros
        );
        assert_ne!(
            UNBOUNDED_RESOURCE_LIMITS.max_macro_arity,
            DEFAULT_RESOURCE_LIMITS.max_macro_arity
        );
    }

    #[test]
    fn expander_with_unbounded_limits_projects_through_resource_limits_getter() {
        // Round-trip pin at CONSTRUCTION time — an expander built at
        // the ceiling-lifted preset MUST project back through
        // [`Expander::resource_limits`] to the SAME constant verbatim.
        // Peer of `expander_with_limits_seeds_the_provided_resource_posture`
        // one PRESET-POSTURE axis over — that pin exercises the
        // constructor's carry via a distinct-low-value bundle; this
        // pin exercises it via the ceiling-lifted preset constant.
        // Cross-pin the six-field snapshot equals the ceiling-lifted
        // constant so a regression that broke either the constant OR
        // the constructor's carry fires here.
        assert_eq!(
            Expander::with_limits(UNBOUNDED_RESOURCE_LIMITS).resource_limits(),
            UNBOUNDED_RESOURCE_LIMITS
        );
    }

    #[test]
    fn expander_with_unbounded_limits_admits_a_body_over_the_default_size_ceiling() {
        // Behavioral pin — the ceiling-lifted preset MUST reach the
        // register-time body-size gate as an actually-lifted ceiling.
        // Register a macro whose body node count strictly exceeds
        // [`DEFAULT_MAX_MACRO_BODY_SIZE`] (a body which under the
        // shipped default would fail [`register_macro_def`] with a
        // [`LispError::MacroBodySizeExceeded`]) and confirm the
        // registration succeeds under the ceiling-lifted preset. Only
        // the body-size ceiling being lifted lets a body of that
        // magnitude land; the arity ceiling is left at 1 param via
        // struct-update override to prove the preset's other five
        // ceilings STILL project cleanly at [`usize::MAX`] alongside
        // the ceiling under test. A regression that failed to lift
        // ONE ceiling across the preset (a stale `DEFAULT_MAX_*` field
        // in the const literal) fires here on the axis it dropped.
        let mut e = Expander::with_limits(UNBOUNDED_RESOURCE_LIMITS);
        // Build a huge quasi-quoted list body: `(k k k k k … k) whose
        // node_count() eclipses DEFAULT_MAX_MACRO_BODY_SIZE = 16384.
        let mut body = String::from("(defmacro huge (k) `(");
        for _ in 0..(DEFAULT_MAX_MACRO_BODY_SIZE + 1) {
            body.push_str(",k ");
        }
        body.push_str("))");
        let forms = read(&body).unwrap();
        e.expand_program(forms)
            .expect("unbounded body-size ceiling must admit a body over the default limit");
        assert!(e.has("huge"));
    }

    #[test]
    fn expander_with_unbounded_limits_admits_arity_over_the_default_arity_ceiling() {
        // Behavioral pin sibling of the body-size pin above one
        // RESOURCE-DIMENSION axis over on the REGISTER-time surface —
        // the ceiling-lifted preset MUST also reach the arity gate as
        // an actually-lifted ceiling. Register a macro whose param
        // list strictly exceeds [`DEFAULT_MAX_MACRO_ARITY`] (a
        // 129-slot lambda list which under the shipped default fails
        // with [`LispError::MacroArityExceeded`]) and confirm the
        // registration succeeds under the ceiling-lifted preset.
        use std::fmt::Write as _;
        let mut e = Expander::with_limits(UNBOUNDED_RESOURCE_LIMITS);
        let mut src = String::from("(defmacro many-arity (");
        for i in 0..(DEFAULT_MAX_MACRO_ARITY + 1) {
            write!(src, "a-{i} ").unwrap();
        }
        src.push_str(") `,a-0)");
        let forms = read(&src).unwrap();
        e.expand_program(forms)
            .expect("unbounded arity ceiling must admit a param list over the default limit");
        assert!(e.has("many-arity"));
    }

    #[test]
    fn unbounded_resource_limits_composes_via_struct_update_to_isolate_one_ceiling() {
        // Ergonomic pin — the `Copy` posture on [`ResourceLimits`] lets
        // a caller build "every ceiling lifted EXCEPT this ONE" as ONE
        // struct-update literal on the ceiling-lifted preset AND thread
        // that composition through [`Expander::with_limits`] as ONE
        // typed call. This is the "only THIS ceiling gates" fixture
        // shape a chain of six independent setters cannot express in
        // ONE expression, and the shape the last commit named as a
        // future benefit of the (getter, setter, at-construction)
        // three-corner face closing at ONE bundle.
        //
        // Set only `max_macro_arity: 1`; confirm the arity gate fires
        // on a two-arg registration while the five other lifted
        // ceilings project through the getter as [`usize::MAX`]. A
        // regression that broke the ceiling-lifted preset would EITHER
        // fail to project [`usize::MAX`] on one of the five other
        // fields OR fail to gate the isolated arity ceiling at 1.
        let mut e = Expander::with_limits(ResourceLimits {
            max_macro_arity: 1,
            ..UNBOUNDED_RESOURCE_LIMITS
        });
        assert_eq!(e.max_macro_arity(), 1);
        assert_eq!(e.max_expansion_depth(), usize::MAX);
        assert_eq!(e.max_cache_entries(), usize::MAX);
        assert_eq!(e.max_expansion_size(), usize::MAX);
        assert_eq!(e.max_macro_body_size(), usize::MAX);
        assert_eq!(e.max_registered_macros(), usize::MAX);
        let forms = read("(defmacro two (a b) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(
                err,
                LispError::MacroArityExceeded {
                    arity: 2,
                    limit: 1,
                    ..
                }
            ),
            "struct-update override on the ceiling-lifted preset must \
             leave the isolated arity ceiling gating; got: {err:?}"
        );
    }

    #[test]
    fn unbounded_resource_limits_carries_through_the_bulk_setter() {
        // Coherence pin between the AT-construction constructor and
        // the POST-construction bulk setter — both paths that reach the
        // ceiling-lifted preset must land at the SAME six values on
        // the expander state. Pre-lift a caller wanting the unbounded
        // posture composed six individual setter invocations at the
        // call site; post-lift both `Expander::with_limits(UNBOUNDED_
        // RESOURCE_LIMITS)` and `e.set_resource_limits(UNBOUNDED_
        // RESOURCE_LIMITS)` reach the SAME snapshot through the SAME
        // constant. A regression that wired the bulk setter to a
        // shadow field, or the ceiling-lifted preset to a stale field
        // literal, fires here on the constructor-vs-setter identity.
        let a = Expander::with_limits(UNBOUNDED_RESOURCE_LIMITS);
        let mut b = Expander::new();
        b.set_resource_limits(UNBOUNDED_RESOURCE_LIMITS);
        assert_eq!(a.resource_limits(), b.resource_limits());
        assert_eq!(a.resource_limits(), UNBOUNDED_RESOURCE_LIMITS);
    }

    // ── ResourceLimits::strictest / ::most_permissive — meet/join ──────

    /// A hand-authored asymmetric posture used across the lattice-law
    /// tests. Every field is a distinct positive value strictly less
    /// than [`usize::MAX`] and distinct from every corresponding
    /// [`DEFAULT_MAX_*`] module constant, so composition witnesses
    /// (meet, join, absorption, distributivity) discriminate across
    /// all three postures unambiguously.
    const HAND_AUTHORED_MID_POSTURE: ResourceLimits = ResourceLimits {
        max_expansion_depth: 7,
        max_cache_entries: 11,
        max_expansion_size: 13,
        max_macro_body_size: 17,
        max_registered_macros: 19,
        max_macro_arity: 23,
    };

    /// A second asymmetric posture whose per-axis values are on both
    /// sides of `HAND_AUTHORED_MID_POSTURE`'s values — three axes
    /// smaller (so the meet picks THIS posture on those axes and the
    /// join picks `MID` on those axes) and three axes larger (mirror).
    /// Together the two postures exercise every ordering combination
    /// on the six-axis pointwise `min`/`max` cascade.
    const HAND_AUTHORED_OTHER_POSTURE: ResourceLimits = ResourceLimits {
        max_expansion_depth: 3,   // smaller than MID's 7
        max_cache_entries: 29,    // larger  than MID's 11
        max_expansion_size: 5,    // smaller than MID's 13
        max_macro_body_size: 31,  // larger  than MID's 17
        max_registered_macros: 2, // smaller than MID's 19
        max_macro_arity: 41,      // larger  than MID's 23
    };

    #[test]
    fn resource_limits_strictest_of_default_and_unbounded_projects_the_default() {
        // Concrete-preset pin — the meet of the (shipped default,
        // ceiling-lifted unbounded) preset pair is the DEFAULT preset
        // structurally: every `DEFAULT_MAX_*` module constant is a
        // concrete positive value strictly less than [`usize::MAX`],
        // so on every axis the pointwise-`min` picks the DEFAULT side.
        // Peer of `most_permissive_of_default_and_unbounded_projects_the_unbounded`
        // one COMBINATOR axis over on the same shipped-preset-pair
        // surface.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.strictest(UNBOUNDED_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.strictest(DEFAULT_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn resource_limits_most_permissive_of_default_and_unbounded_projects_the_unbounded() {
        // Concrete-preset pin — the join of the (shipped default,
        // ceiling-lifted unbounded) preset pair is the UNBOUNDED
        // preset structurally: every axis's pointwise-`max` picks the
        // [`usize::MAX`] side over any concrete default. Peer of
        // `strictest_of_default_and_unbounded_projects_the_default`.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.most_permissive(UNBOUNDED_RESOURCE_LIMITS),
            UNBOUNDED_RESOURCE_LIMITS,
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.most_permissive(DEFAULT_RESOURCE_LIMITS),
            UNBOUNDED_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn resource_limits_strictest_takes_pointwise_min_on_every_axis() {
        // Field-level pin — the meet operation projects the pointwise
        // `min` across the six-field surface. Pinned as six
        // independent field asserts (rather than one struct equality)
        // so a drift on ONE axis carries a distinct-name failure that
        // names the drifting axis; a future SEVENTH ceiling extension
        // requires an additional field assert here in lockstep.
        let m = HAND_AUTHORED_MID_POSTURE.strictest(HAND_AUTHORED_OTHER_POSTURE);
        assert_eq!(m.max_expansion_depth, 3);
        assert_eq!(m.max_cache_entries, 11);
        assert_eq!(m.max_expansion_size, 5);
        assert_eq!(m.max_macro_body_size, 17);
        assert_eq!(m.max_registered_macros, 2);
        assert_eq!(m.max_macro_arity, 23);
    }

    #[test]
    fn resource_limits_most_permissive_takes_pointwise_max_on_every_axis() {
        // Field-level pin — the join operation projects the pointwise
        // `max` across the six-field surface. Pinned as six
        // independent field asserts so a drift on ONE axis carries a
        // distinct-name failure that names the drifting axis.
        let j = HAND_AUTHORED_MID_POSTURE.most_permissive(HAND_AUTHORED_OTHER_POSTURE);
        assert_eq!(j.max_expansion_depth, 7);
        assert_eq!(j.max_cache_entries, 29);
        assert_eq!(j.max_expansion_size, 13);
        assert_eq!(j.max_macro_body_size, 31);
        assert_eq!(j.max_registered_macros, 19);
        assert_eq!(j.max_macro_arity, 41);
    }

    #[test]
    fn resource_limits_strictest_is_idempotent() {
        // Lattice law — `a ∧ a = a`. Every posture is a fixed point of
        // its own meet with itself; a regression that changed the
        // per-axis primitive to something other than pointwise `min`
        // (a `min - 1` off-by-one, or an arbitrary tie-breaker on
        // equal values) fires here.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.strictest(DEFAULT_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.strictest(UNBOUNDED_RESOURCE_LIMITS),
            UNBOUNDED_RESOURCE_LIMITS,
        );
        assert_eq!(
            HAND_AUTHORED_MID_POSTURE.strictest(HAND_AUTHORED_MID_POSTURE),
            HAND_AUTHORED_MID_POSTURE,
        );
    }

    #[test]
    fn resource_limits_most_permissive_is_idempotent() {
        // Lattice law — `a ∨ a = a`. Sibling of the strictest
        // idempotence pin one COMBINATOR axis over.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.most_permissive(DEFAULT_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.most_permissive(UNBOUNDED_RESOURCE_LIMITS),
            UNBOUNDED_RESOURCE_LIMITS,
        );
        assert_eq!(
            HAND_AUTHORED_MID_POSTURE.most_permissive(HAND_AUTHORED_MID_POSTURE),
            HAND_AUTHORED_MID_POSTURE,
        );
    }

    #[test]
    fn resource_limits_strictest_is_commutative() {
        // Lattice law — `a ∧ b = b ∧ a`. Pointwise `min` is symmetric
        // on every axis, so the composition inherits commutativity
        // structurally. A regression that broke ordering (e.g. a
        // per-axis "prefer left on tie") fires here.
        assert_eq!(
            HAND_AUTHORED_MID_POSTURE.strictest(HAND_AUTHORED_OTHER_POSTURE),
            HAND_AUTHORED_OTHER_POSTURE.strictest(HAND_AUTHORED_MID_POSTURE),
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.strictest(HAND_AUTHORED_MID_POSTURE),
            HAND_AUTHORED_MID_POSTURE.strictest(DEFAULT_RESOURCE_LIMITS),
        );
    }

    #[test]
    fn resource_limits_most_permissive_is_commutative() {
        // Lattice law — `a ∨ b = b ∨ a`. Sibling of the strictest
        // commutativity pin one COMBINATOR axis over.
        assert_eq!(
            HAND_AUTHORED_MID_POSTURE.most_permissive(HAND_AUTHORED_OTHER_POSTURE),
            HAND_AUTHORED_OTHER_POSTURE.most_permissive(HAND_AUTHORED_MID_POSTURE),
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.most_permissive(HAND_AUTHORED_MID_POSTURE),
            HAND_AUTHORED_MID_POSTURE.most_permissive(DEFAULT_RESOURCE_LIMITS),
        );
    }

    #[test]
    fn resource_limits_strictest_is_associative() {
        // Lattice law — `(a ∧ b) ∧ c = a ∧ (b ∧ c)`. Pointwise `min`
        // is associative on every axis, so the composition inherits
        // associativity structurally. A regression that broke
        // grouping (e.g. an accidental accumulator that skewed the
        // order of `min` invocations) fires here.
        let a = DEFAULT_RESOURCE_LIMITS;
        let b = HAND_AUTHORED_MID_POSTURE;
        let c = HAND_AUTHORED_OTHER_POSTURE;
        assert_eq!(a.strictest(b).strictest(c), a.strictest(b.strictest(c)));
    }

    #[test]
    fn resource_limits_most_permissive_is_associative() {
        // Lattice law — `(a ∨ b) ∨ c = a ∨ (b ∨ c)`. Sibling of the
        // strictest associativity pin one COMBINATOR axis over.
        let a = DEFAULT_RESOURCE_LIMITS;
        let b = HAND_AUTHORED_MID_POSTURE;
        let c = HAND_AUTHORED_OTHER_POSTURE;
        assert_eq!(
            a.most_permissive(b).most_permissive(c),
            a.most_permissive(b.most_permissive(c)),
        );
    }

    #[test]
    fn resource_limits_meet_and_join_satisfy_absorption() {
        // Lattice absorption identities — `a ∧ (a ∨ b) = a` AND
        // `a ∨ (a ∧ b) = a`. Together with commutativity, idempotence,
        // and associativity they define the lattice axioms; the two
        // absorption laws are the operator PAIR's interlock (each
        // undoes the other's contribution on the shared operand).
        // Any per-axis primitive pair for which `min(a, max(a, b)) = a`
        // AND `max(a, min(a, b)) = a` inherits this at the pointwise
        // composition; pointwise-`min`/`max` on [`usize`] satisfy both.
        let a = HAND_AUTHORED_MID_POSTURE;
        let b = HAND_AUTHORED_OTHER_POSTURE;
        assert_eq!(a.strictest(a.most_permissive(b)), a);
        assert_eq!(a.most_permissive(a.strictest(b)), a);
    }

    #[test]
    fn resource_limits_meet_distributes_over_join() {
        // Distributive-lattice pin — `a ∧ (b ∨ c) = (a ∧ b) ∨ (a ∧ c)`.
        // Pointwise-`min` distributes over pointwise-`max` on [`usize`]
        // on every axis, so the composition inherits distributivity
        // structurally. A regression that broke the pointwise
        // structure (e.g. a per-axis operation that used SUBTRACTION
        // rather than MIN/MAX) fires here — subtraction does NOT
        // distribute over addition and would break the law on the
        // asymmetric-posture witness pair.
        let a = DEFAULT_RESOURCE_LIMITS;
        let b = HAND_AUTHORED_MID_POSTURE;
        let c = HAND_AUTHORED_OTHER_POSTURE;
        assert_eq!(
            a.strictest(b.most_permissive(c)),
            a.strictest(b).most_permissive(a.strictest(c)),
        );
    }

    #[test]
    fn resource_limits_join_distributes_over_meet() {
        // Distributive-lattice pin, sibling of the meet-over-join
        // distributivity pin one COMBINATOR axis over — `a ∨ (b ∧ c) =
        // (a ∨ b) ∧ (a ∨ c)`. In a distributive lattice BOTH
        // distributivity identities hold; pin both so a regression
        // that broke ONE without the other cannot slip through.
        let a = DEFAULT_RESOURCE_LIMITS;
        let b = HAND_AUTHORED_MID_POSTURE;
        let c = HAND_AUTHORED_OTHER_POSTURE;
        assert_eq!(
            a.most_permissive(b.strictest(c)),
            a.most_permissive(b).strictest(a.most_permissive(c)),
        );
    }

    #[test]
    fn resource_limits_strictest_is_dominated_by_both_operands_pointwise() {
        // Meet-lower-bound pin — the meet lies at or below BOTH
        // operands on every axis. This is the structural GLB property
        // of the meet in the pointwise partial order (tighter-first):
        // any admissible input under the meet is admissible under
        // both operands, so the meet's ceiling must not exceed either
        // operand's ceiling on any axis.
        let a = HAND_AUTHORED_MID_POSTURE;
        let b = HAND_AUTHORED_OTHER_POSTURE;
        let m = a.strictest(b);
        assert!(m.max_expansion_depth <= a.max_expansion_depth);
        assert!(m.max_expansion_depth <= b.max_expansion_depth);
        assert!(m.max_cache_entries <= a.max_cache_entries);
        assert!(m.max_cache_entries <= b.max_cache_entries);
        assert!(m.max_expansion_size <= a.max_expansion_size);
        assert!(m.max_expansion_size <= b.max_expansion_size);
        assert!(m.max_macro_body_size <= a.max_macro_body_size);
        assert!(m.max_macro_body_size <= b.max_macro_body_size);
        assert!(m.max_registered_macros <= a.max_registered_macros);
        assert!(m.max_registered_macros <= b.max_registered_macros);
        assert!(m.max_macro_arity <= a.max_macro_arity);
        assert!(m.max_macro_arity <= b.max_macro_arity);
    }

    #[test]
    fn resource_limits_most_permissive_dominates_both_operands_pointwise() {
        // Join-upper-bound pin — the join lies at or above BOTH
        // operands on every axis. Sibling of the strictest-lower-
        // bound pin one COMBINATOR axis over; the structural LUB
        // property of the join in the pointwise partial order.
        let a = HAND_AUTHORED_MID_POSTURE;
        let b = HAND_AUTHORED_OTHER_POSTURE;
        let j = a.most_permissive(b);
        assert!(j.max_expansion_depth >= a.max_expansion_depth);
        assert!(j.max_expansion_depth >= b.max_expansion_depth);
        assert!(j.max_cache_entries >= a.max_cache_entries);
        assert!(j.max_cache_entries >= b.max_cache_entries);
        assert!(j.max_expansion_size >= a.max_expansion_size);
        assert!(j.max_expansion_size >= b.max_expansion_size);
        assert!(j.max_macro_body_size >= a.max_macro_body_size);
        assert!(j.max_macro_body_size >= b.max_macro_body_size);
        assert!(j.max_registered_macros >= a.max_registered_macros);
        assert!(j.max_registered_macros >= b.max_registered_macros);
        assert!(j.max_macro_arity >= a.max_macro_arity);
        assert!(j.max_macro_arity >= b.max_macro_arity);
    }

    #[test]
    fn resource_limits_strictest_composes_at_compile_time_via_const_fn() {
        // Const-fn pin — the meet is evaluable in const context, so a
        // caller can stitch a new `pub const` preset from two shipped
        // presets without deferring the composition to runtime. Pinned
        // as a `const` binding at the item level so the compiler
        // exercises the const-fn path structurally; the runtime
        // assertion is redundant for a `const` value that already
        // evaluated at compile time, but pins the identity as a typed
        // theorem alongside every OTHER `strictest` pin above.
        const DEFAULT_TIGHTENED_BY_MID: ResourceLimits =
            DEFAULT_RESOURCE_LIMITS.strictest(HAND_AUTHORED_MID_POSTURE);
        assert_eq!(
            DEFAULT_TIGHTENED_BY_MID.max_expansion_depth,
            min_usize(
                DEFAULT_RESOURCE_LIMITS.max_expansion_depth,
                HAND_AUTHORED_MID_POSTURE.max_expansion_depth,
            ),
        );
        // Extra check: the composition MUST project the MID posture's
        // small value on every axis where MID is smaller than DEFAULT
        // — MID's per-axis values (7, 11, 13, 17, 19, 23) are all
        // strictly less than every `DEFAULT_MAX_*` constant, so the
        // meet projects MID verbatim.
        assert_eq!(DEFAULT_TIGHTENED_BY_MID, HAND_AUTHORED_MID_POSTURE);
    }

    #[test]
    fn resource_limits_most_permissive_composes_at_compile_time_via_const_fn() {
        // Const-fn pin sibling of the strictest const-composition pin
        // one COMBINATOR axis over — the join is also `const fn`, so
        // a caller can stitch a new `pub const` preset via the LUB
        // combinator at compile time.
        const DEFAULT_LOOSENED_BY_UNBOUNDED: ResourceLimits =
            DEFAULT_RESOURCE_LIMITS.most_permissive(UNBOUNDED_RESOURCE_LIMITS);
        assert_eq!(DEFAULT_LOOSENED_BY_UNBOUNDED, UNBOUNDED_RESOURCE_LIMITS);
    }

    // ── ResourceLimits::leq — pointwise partial order ─────────────────

    #[test]
    fn resource_limits_leq_is_pointwise_field_conjunction() {
        // Field-level pin — the leq relation projects the pointwise
        // `<=` conjunction across the six-field surface. `LOOSER` is
        // `MID + 1` on every axis, so `MID.leq(LOOSER)` holds; a
        // per-axis tighten on ANY field alone flips the relation to
        // false. Pinned as six independent tighten-per-axis asserts so
        // a drift on ONE axis carries a distinct-name failure that
        // names the drifting axis; a future SEVENTH ceiling extension
        // requires an additional per-axis tighten assert here in
        // lockstep.
        const LOOSER: ResourceLimits = ResourceLimits {
            max_expansion_depth: HAND_AUTHORED_MID_POSTURE.max_expansion_depth + 1,
            max_cache_entries: HAND_AUTHORED_MID_POSTURE.max_cache_entries + 1,
            max_expansion_size: HAND_AUTHORED_MID_POSTURE.max_expansion_size + 1,
            max_macro_body_size: HAND_AUTHORED_MID_POSTURE.max_macro_body_size + 1,
            max_registered_macros: HAND_AUTHORED_MID_POSTURE.max_registered_macros + 1,
            max_macro_arity: HAND_AUTHORED_MID_POSTURE.max_macro_arity + 1,
        };
        assert!(HAND_AUTHORED_MID_POSTURE.leq(LOOSER));
        assert!(!LOOSER.leq(HAND_AUTHORED_MID_POSTURE));

        // Per-axis exceed pins: raise MID's field ONE axis above LOOSER
        // on that axis; the leq must flip to false. Every other axis
        // stays at MID, so LOOSER still dominates on those axes —
        // isolating the single-axis violation.
        let exceed_depth = ResourceLimits {
            max_expansion_depth: LOOSER.max_expansion_depth + 1,
            ..HAND_AUTHORED_MID_POSTURE
        };
        assert!(!exceed_depth.leq(LOOSER));
        let exceed_cache = ResourceLimits {
            max_cache_entries: LOOSER.max_cache_entries + 1,
            ..HAND_AUTHORED_MID_POSTURE
        };
        assert!(!exceed_cache.leq(LOOSER));
        let exceed_expansion = ResourceLimits {
            max_expansion_size: LOOSER.max_expansion_size + 1,
            ..HAND_AUTHORED_MID_POSTURE
        };
        assert!(!exceed_expansion.leq(LOOSER));
        let exceed_body = ResourceLimits {
            max_macro_body_size: LOOSER.max_macro_body_size + 1,
            ..HAND_AUTHORED_MID_POSTURE
        };
        assert!(!exceed_body.leq(LOOSER));
        let exceed_registered = ResourceLimits {
            max_registered_macros: LOOSER.max_registered_macros + 1,
            ..HAND_AUTHORED_MID_POSTURE
        };
        assert!(!exceed_registered.leq(LOOSER));
        let exceed_arity = ResourceLimits {
            max_macro_arity: LOOSER.max_macro_arity + 1,
            ..HAND_AUTHORED_MID_POSTURE
        };
        assert!(!exceed_arity.leq(LOOSER));
    }

    #[test]
    fn resource_limits_leq_is_reflexive() {
        // Partial-order law — `a ≤ a` for every posture. Reflexivity
        // is the identity axiom on any lattice's underlying partial
        // order; a regression that changed the per-axis primitive to
        // strict `<` (or that added an accidental "prefer other on
        // tie" branch) fires here on every shipped posture.
        assert!(DEFAULT_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS));
        assert!(UNBOUNDED_RESOURCE_LIMITS.leq(UNBOUNDED_RESOURCE_LIMITS));
        assert!(HAND_AUTHORED_MID_POSTURE.leq(HAND_AUTHORED_MID_POSTURE));
        assert!(HAND_AUTHORED_OTHER_POSTURE.leq(HAND_AUTHORED_OTHER_POSTURE));
    }

    #[test]
    fn resource_limits_leq_is_antisymmetric() {
        // Partial-order law — `a ≤ b ∧ b ≤ a ⇒ a = b`. The mutual-
        // dominance witness on a partial order pins the two operands
        // to structural equality. On the pointwise `<=` composition
        // this holds because `a.max_X <= b.max_X && b.max_X <= a.max_X
        // ⇒ a.max_X == b.max_X` on every axis, and struct equality
        // is field-conjunction. Sibling to reflexivity one AXIOM axis
        // over on the partial-order axiom surface.
        //
        // Two distinct constructions of the SAME six-field posture
        // (one via struct literal, one via `..DEFAULT_RESOURCE_LIMITS`
        // spread of the shipped preset) — mutual leq holds; struct
        // equality holds; antisymmetry pin closes.
        let a = DEFAULT_RESOURCE_LIMITS;
        let b = ResourceLimits {
            max_expansion_depth: DEFAULT_RESOURCE_LIMITS.max_expansion_depth,
            max_cache_entries: DEFAULT_RESOURCE_LIMITS.max_cache_entries,
            max_expansion_size: DEFAULT_RESOURCE_LIMITS.max_expansion_size,
            max_macro_body_size: DEFAULT_RESOURCE_LIMITS.max_macro_body_size,
            max_registered_macros: DEFAULT_RESOURCE_LIMITS.max_registered_macros,
            max_macro_arity: DEFAULT_RESOURCE_LIMITS.max_macro_arity,
        };
        assert!(a.leq(b));
        assert!(b.leq(a));
        assert_eq!(a, b);
    }

    #[test]
    fn resource_limits_leq_is_transitive() {
        // Partial-order law — `a ≤ b ∧ b ≤ c ⇒ a ≤ c`. Transitivity
        // is the composition axiom on any lattice's partial order.
        // Pointwise `<=` on [`usize`] is transitive per axis, so the
        // six-field conjunction inherits it structurally.
        //
        // Chain witness: MID's every-axis `+1` shift is LOOSER, and
        // LOOSER's every-axis `+1` shift is LOOSEST; the chain MID
        // ≤ LOOSER ≤ LOOSEST implies MID ≤ LOOSEST.
        const LOOSER: ResourceLimits = ResourceLimits {
            max_expansion_depth: HAND_AUTHORED_MID_POSTURE.max_expansion_depth + 1,
            max_cache_entries: HAND_AUTHORED_MID_POSTURE.max_cache_entries + 1,
            max_expansion_size: HAND_AUTHORED_MID_POSTURE.max_expansion_size + 1,
            max_macro_body_size: HAND_AUTHORED_MID_POSTURE.max_macro_body_size + 1,
            max_registered_macros: HAND_AUTHORED_MID_POSTURE.max_registered_macros + 1,
            max_macro_arity: HAND_AUTHORED_MID_POSTURE.max_macro_arity + 1,
        };
        const LOOSEST: ResourceLimits = ResourceLimits {
            max_expansion_depth: LOOSER.max_expansion_depth + 1,
            max_cache_entries: LOOSER.max_cache_entries + 1,
            max_expansion_size: LOOSER.max_expansion_size + 1,
            max_macro_body_size: LOOSER.max_macro_body_size + 1,
            max_registered_macros: LOOSER.max_registered_macros + 1,
            max_macro_arity: LOOSER.max_macro_arity + 1,
        };
        assert!(HAND_AUTHORED_MID_POSTURE.leq(LOOSER));
        assert!(LOOSER.leq(LOOSEST));
        assert!(HAND_AUTHORED_MID_POSTURE.leq(LOOSEST));
    }

    #[test]
    fn resource_limits_leq_of_default_and_unbounded_is_a_strict_order() {
        // Concrete-preset pin — the leq relation on the shipped
        // preset pair is STRICT: DEFAULT ≤ UNBOUNDED holds (every
        // `DEFAULT_MAX_*` module constant is a concrete positive
        // value at most [`usize::MAX`]) AND UNBOUNDED ≤ DEFAULT
        // fails (every `DEFAULT_MAX_*` is strictly less than
        // [`usize::MAX`], so on every axis [`usize::MAX`] exceeds
        // the matching default). Peer of
        // `strictest_of_default_and_unbounded_projects_the_default`
        // one PRIMITIVE-KIND axis over on the same shipped-preset-
        // pair surface: where the meet composition projects DEFAULT,
        // this relation asserts DEFAULT is the tighter of the two.
        assert!(DEFAULT_RESOURCE_LIMITS.leq(UNBOUNDED_RESOURCE_LIMITS));
        assert!(!UNBOUNDED_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_leq_is_not_total_on_asymmetric_postures() {
        // Partial-order NON-total pin — the two hand-authored asymmetric
        // postures have MID smaller on three axes (depth, expansion,
        // registered) and OTHER smaller on the other three (cache,
        // body, arity); neither dominates the other, so BOTH
        // directions of the leq relation fail. The pin discriminates
        // a regression that promoted `leq` from partial to total
        // (e.g. an accidental `||` swap in the conjunction, which
        // would make every pair comparable).
        assert!(!HAND_AUTHORED_MID_POSTURE.leq(HAND_AUTHORED_OTHER_POSTURE));
        assert!(!HAND_AUTHORED_OTHER_POSTURE.leq(HAND_AUTHORED_MID_POSTURE));
    }

    #[test]
    fn resource_limits_leq_agrees_with_meet() {
        // Lattice cross-check axiom — `a ≤ b ⇔ a ⊓ b = a`. Every
        // classification lattice one crate over
        // (`tatara-lattice/src/lib.rs`'s preamble) declares this
        // agreement axiom binding the partial order to the meet
        // combinator, and the default-impl body on
        // `tatara_lattice::Lattice::leq` derives `leq` FROM `meet`
        // through it. This pin discharges the same axiom on the
        // ResourceLimits algebra as a two-direction structural
        // equality across the strict-order preset pair AND the
        // reflexivity witness.
        //
        // Forward (a ≤ b ⇒ a ⊓ b = a):
        assert!(DEFAULT_RESOURCE_LIMITS.leq(UNBOUNDED_RESOURCE_LIMITS));
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.strictest(UNBOUNDED_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        // Reverse (a ⊓ b = a ⇒ a ≤ b), reflexivity witness:
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.strictest(DEFAULT_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        assert!(DEFAULT_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS));

        // Non-agreement witness — the incomparable asymmetric postures
        // have meet distinct from EITHER operand, and leq false in
        // both directions; agreement holds on the negative side too.
        assert!(!HAND_AUTHORED_MID_POSTURE.leq(HAND_AUTHORED_OTHER_POSTURE));
        assert_ne!(
            HAND_AUTHORED_MID_POSTURE.strictest(HAND_AUTHORED_OTHER_POSTURE),
            HAND_AUTHORED_MID_POSTURE,
        );
    }

    #[test]
    fn resource_limits_leq_agrees_with_join() {
        // Lattice cross-check axiom, sibling of the meet-agreement
        // pin one COMBINATOR axis over — `a ≤ b ⇔ a ⊔ b = b`.
        //
        // Forward (a ≤ b ⇒ a ⊔ b = b):
        assert!(DEFAULT_RESOURCE_LIMITS.leq(UNBOUNDED_RESOURCE_LIMITS));
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.most_permissive(UNBOUNDED_RESOURCE_LIMITS),
            UNBOUNDED_RESOURCE_LIMITS,
        );
        // Reverse (a ⊔ b = b ⇒ a ≤ b), reflexivity witness:
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.most_permissive(DEFAULT_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        assert!(DEFAULT_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS));

        // Non-agreement witness — the incomparable asymmetric postures
        // have join distinct from EITHER operand.
        assert!(!HAND_AUTHORED_MID_POSTURE.leq(HAND_AUTHORED_OTHER_POSTURE));
        assert_ne!(
            HAND_AUTHORED_MID_POSTURE.most_permissive(HAND_AUTHORED_OTHER_POSTURE),
            HAND_AUTHORED_OTHER_POSTURE,
        );
    }

    #[test]
    fn resource_limits_strictest_is_leq_both_operands() {
        // Meet-lower-bound pin, typed lattice-relation companion to
        // `resource_limits_strictest_is_dominated_by_both_operands_pointwise`
        // one PRIMITIVE-KIND axis over — where the per-axis pin
        // discharged the six independent `<=` asserts inline, this pin
        // routes through the typed `leq` primitive, so the
        // greatest-lower-bound property is stated in the LATTICE
        // vocabulary (meet-is-leq-both-operands) rather than the
        // six-fold field-conjunction vocabulary.
        let a = HAND_AUTHORED_MID_POSTURE;
        let b = HAND_AUTHORED_OTHER_POSTURE;
        let m = a.strictest(b);
        assert!(m.leq(a));
        assert!(m.leq(b));
    }

    #[test]
    fn resource_limits_most_permissive_is_geq_both_operands() {
        // Join-upper-bound pin, typed lattice-relation companion to
        // `resource_limits_most_permissive_dominates_both_operands_pointwise`
        // one PRIMITIVE-KIND axis over. Stated in the LATTICE
        // vocabulary as `a ≤ a ⊔ b ∧ b ≤ a ⊔ b` — sibling of the
        // meet-lower-bound pin one COMBINATOR axis over.
        let a = HAND_AUTHORED_MID_POSTURE;
        let b = HAND_AUTHORED_OTHER_POSTURE;
        let j = a.most_permissive(b);
        assert!(a.leq(j));
        assert!(b.leq(j));
    }

    #[test]
    fn resource_limits_leq_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the leq relation is evaluable in const
        // context, so a caller can pin a preset-relation identity at
        // compile time. Sibling of the const-fn composition pins on
        // `strictest` / `most_permissive` one PRIMITIVE-KIND axis
        // over: those two operations compose two presets into a
        // const-time third, and this operation decides a const-time
        // yes/no on two presets. `const _: ()` at item scope is a
        // compile-time proof — the compiler rejects the module if
        // either identity does not hold; a runtime `assert!` over the
        // same expression would fire at test time on the same value
        // clippy's `assertions_on_constants` correctly names as a
        // redundant late check on a compile-time constant.
        //
        // Strict-order preset-pair pin — DEFAULT ≤ UNBOUNDED (every
        // `DEFAULT_MAX_*` module constant is at most [`usize::MAX`]):
        const _: () = assert!(DEFAULT_RESOURCE_LIMITS.leq(UNBOUNDED_RESOURCE_LIMITS));
        // Reverse direction fails — [`usize::MAX`] exceeds every
        // concrete `DEFAULT_MAX_*` constant, so the partial order is
        // STRICT on the shipped preset pair:
        const _: () = assert!(!UNBOUNDED_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS));
    }

    // ── EMPTY_RESOURCE_LIMITS — bounded-lattice bottom preset ─────────

    #[test]
    fn empty_resource_limits_binds_every_ceiling_to_zero() {
        // Field-level pin — the zero preset carries `0` on every axis
        // of the six-field surface. Pinned as six independent field
        // asserts (rather than one struct equality) so a drift on ONE
        // field carries a distinct-name failure that names the drifting
        // axis. A future extension that adds a SEVENTH ceiling requires
        // an additional field assert here in lockstep with the const
        // literal — rustc's field-exhaustiveness on the const forces
        // the new field to appear, and this pin exercises the seed
        // value. Structural peer of
        // `unbounded_resource_limits_binds_every_ceiling_to_usize_max`
        // one LATTICE-POLE axis over on the (bottom, top)
        // bounded-lattice preset-pair surface.
        assert_eq!(EMPTY_RESOURCE_LIMITS.max_expansion_depth, 0);
        assert_eq!(EMPTY_RESOURCE_LIMITS.max_cache_entries, 0);
        assert_eq!(EMPTY_RESOURCE_LIMITS.max_expansion_size, 0);
        assert_eq!(EMPTY_RESOURCE_LIMITS.max_macro_body_size, 0);
        assert_eq!(EMPTY_RESOURCE_LIMITS.max_registered_macros, 0);
        assert_eq!(EMPTY_RESOURCE_LIMITS.max_macro_arity, 0);
    }

    #[test]
    fn empty_resource_limits_disagrees_with_default_on_every_ceiling() {
        // Structural-distinctness pin — the two constants
        // [`DEFAULT_RESOURCE_LIMITS`] and [`EMPTY_RESOURCE_LIMITS`] sit
        // at DISTINCT points on the preset-posture axis, and the
        // disagreement is EXHAUSTIVE on the six-field surface — every
        // shipped `DEFAULT_MAX_*` module constant is a concrete
        // strictly-positive value, so every axis distinguishes DEFAULT
        // from the all-zero bottom. Peer of
        // `unbounded_resource_limits_disagrees_with_default_on_every_ceiling`
        // one LATTICE-POLE axis over.
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_expansion_depth,
            DEFAULT_RESOURCE_LIMITS.max_expansion_depth
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_cache_entries,
            DEFAULT_RESOURCE_LIMITS.max_cache_entries
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_expansion_size,
            DEFAULT_RESOURCE_LIMITS.max_expansion_size
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_macro_body_size,
            DEFAULT_RESOURCE_LIMITS.max_macro_body_size
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_registered_macros,
            DEFAULT_RESOURCE_LIMITS.max_registered_macros
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_macro_arity,
            DEFAULT_RESOURCE_LIMITS.max_macro_arity
        );
    }

    #[test]
    fn empty_resource_limits_disagrees_with_unbounded_on_every_ceiling() {
        // Diagonal-distinctness pin — the (BOTTOM, TOP) preset pair
        // disagrees on every axis (`0 != usize::MAX` on every field).
        // Structural companion to the DEFAULT-vs-EMPTY and
        // UNBOUNDED-vs-DEFAULT disagreement pins one PRESET-PAIR axis
        // over — together the three pin the six-field surface at the
        // full diagonal of the (EMPTY, DEFAULT, UNBOUNDED) triple.
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_expansion_depth,
            UNBOUNDED_RESOURCE_LIMITS.max_expansion_depth
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_cache_entries,
            UNBOUNDED_RESOURCE_LIMITS.max_cache_entries
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_expansion_size,
            UNBOUNDED_RESOURCE_LIMITS.max_expansion_size
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_macro_body_size,
            UNBOUNDED_RESOURCE_LIMITS.max_macro_body_size
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_registered_macros,
            UNBOUNDED_RESOURCE_LIMITS.max_registered_macros
        );
        assert_ne!(
            EMPTY_RESOURCE_LIMITS.max_macro_arity,
            UNBOUNDED_RESOURCE_LIMITS.max_macro_arity
        );
    }

    #[test]
    fn empty_resource_limits_is_the_join_identity() {
        // Lattice-identity law — `a ⊔ ⊥ = a`. Every posture's
        // pointwise `max` against 0 returns the posture verbatim, so
        // [`EMPTY_RESOURCE_LIMITS`] acts as the identity element of
        // the join monoid. Peer of
        // `empty_resource_limits_is_the_meet_annihilator` one
        // COMBINATOR axis over on the (meet, join) surface.
        //
        // Cross-preset exhaustion — verify the identity against every
        // named preset (DEFAULT, UNBOUNDED, both hand-authored
        // asymmetric postures) so a regression that broke ONE axis of
        // the algebra fires here on the operand whose field crosses
        // that axis's boundary.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.most_permissive(EMPTY_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        assert_eq!(
            EMPTY_RESOURCE_LIMITS.most_permissive(DEFAULT_RESOURCE_LIMITS),
            DEFAULT_RESOURCE_LIMITS,
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.most_permissive(EMPTY_RESOURCE_LIMITS),
            UNBOUNDED_RESOURCE_LIMITS,
        );
        assert_eq!(
            EMPTY_RESOURCE_LIMITS.most_permissive(UNBOUNDED_RESOURCE_LIMITS),
            UNBOUNDED_RESOURCE_LIMITS,
        );
        assert_eq!(
            HAND_AUTHORED_MID_POSTURE.most_permissive(EMPTY_RESOURCE_LIMITS),
            HAND_AUTHORED_MID_POSTURE,
        );
        assert_eq!(
            HAND_AUTHORED_OTHER_POSTURE.most_permissive(EMPTY_RESOURCE_LIMITS),
            HAND_AUTHORED_OTHER_POSTURE,
        );
        // Idempotence at the identity itself — sibling witness of the
        // `most_permissive_is_idempotent` general pin one PRESET axis
        // over.
        assert_eq!(
            EMPTY_RESOURCE_LIMITS.most_permissive(EMPTY_RESOURCE_LIMITS),
            EMPTY_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn empty_resource_limits_is_the_meet_annihilator() {
        // Lattice-annihilator law — `a ⊓ ⊥ = ⊥`. Every posture's
        // pointwise `min` against 0 returns 0 on every axis, so
        // [`EMPTY_RESOURCE_LIMITS`] acts as the annihilator (absorbing
        // element) of the meet operation. Peer of
        // `empty_resource_limits_is_the_join_identity` one COMBINATOR
        // axis over — the identity on one side of the bounded lattice
        // is the annihilator on the other side.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.strictest(EMPTY_RESOURCE_LIMITS),
            EMPTY_RESOURCE_LIMITS,
        );
        assert_eq!(
            EMPTY_RESOURCE_LIMITS.strictest(DEFAULT_RESOURCE_LIMITS),
            EMPTY_RESOURCE_LIMITS,
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.strictest(EMPTY_RESOURCE_LIMITS),
            EMPTY_RESOURCE_LIMITS,
        );
        assert_eq!(
            EMPTY_RESOURCE_LIMITS.strictest(UNBOUNDED_RESOURCE_LIMITS),
            EMPTY_RESOURCE_LIMITS,
        );
        assert_eq!(
            HAND_AUTHORED_MID_POSTURE.strictest(EMPTY_RESOURCE_LIMITS),
            EMPTY_RESOURCE_LIMITS,
        );
        assert_eq!(
            HAND_AUTHORED_OTHER_POSTURE.strictest(EMPTY_RESOURCE_LIMITS),
            EMPTY_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn empty_resource_limits_is_the_lattice_minimum() {
        // Partial-order minimum law — `⊥ ≤ a` for every `a`. Every
        // posture's field is a `usize` and `0 <= x` holds for every
        // `usize x`, so [`EMPTY_RESOURCE_LIMITS`] sits at or below
        // every posture on every axis of the pointwise `<=` conjunction.
        // Peer of the UNBOUNDED-is-maximum property on the
        // partial-order face one LATTICE-POLE axis over — those two
        // pin the (min, max) bounds of the bounded lattice.
        assert!(EMPTY_RESOURCE_LIMITS.leq(EMPTY_RESOURCE_LIMITS));
        assert!(EMPTY_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS));
        assert!(EMPTY_RESOURCE_LIMITS.leq(UNBOUNDED_RESOURCE_LIMITS));
        assert!(EMPTY_RESOURCE_LIMITS.leq(HAND_AUTHORED_MID_POSTURE));
        assert!(EMPTY_RESOURCE_LIMITS.leq(HAND_AUTHORED_OTHER_POSTURE));
        // Reverse direction FAILS on every non-EMPTY preset (each has
        // at least one field strictly greater than 0). The partial
        // order is STRICT between EMPTY and every other named preset,
        // structurally exhausting the diagonal of the
        // (EMPTY, DEFAULT, UNBOUNDED, MID, OTHER) 5-preset ordering
        // face at the BOTTOM row.
        assert!(!DEFAULT_RESOURCE_LIMITS.leq(EMPTY_RESOURCE_LIMITS));
        assert!(!UNBOUNDED_RESOURCE_LIMITS.leq(EMPTY_RESOURCE_LIMITS));
        assert!(!HAND_AUTHORED_MID_POSTURE.leq(EMPTY_RESOURCE_LIMITS));
        assert!(!HAND_AUTHORED_OTHER_POSTURE.leq(EMPTY_RESOURCE_LIMITS));
    }

    #[test]
    fn empty_resource_limits_composes_at_compile_time_via_const_fn() {
        // Const-fn pin — the bounded-lattice identity + annihilator +
        // minimum laws hold at COMPILE time. Sibling of
        // `resource_limits_leq_evaluates_at_compile_time_via_const_fn`
        // one LATTICE-STRUCTURE axis over — that pin fixed the strict
        // order of the (DEFAULT, UNBOUNDED) preset pair at compile
        // time; this pin fixes the bounded-lattice pole role of the
        // (EMPTY, UNBOUNDED) preset pair. `const _: ()` at item scope
        // is a compile-time proof — a regression that broke either
        // identity element or the bottom-is-minimum invariant fires at
        // rustc time, not test-run time.
        //
        // Bottom-is-minimum: EMPTY ≤ DEFAULT ≤ UNBOUNDED (the
        // three-preset ordering chain on the shipped preset diagonal).
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.leq(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.leq(UNBOUNDED_RESOURCE_LIMITS));
        // Reverse strictness — neither DEFAULT nor UNBOUNDED sits
        // below EMPTY (each has a strictly-positive field).
        const _: () = assert!(!DEFAULT_RESOURCE_LIMITS.leq(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(!UNBOUNDED_RESOURCE_LIMITS.leq(EMPTY_RESOURCE_LIMITS));
        // Join-identity + meet-annihilator laws cross-pinned through
        // the `leq` primitive at const time — the round-trip identity
        // (`a ⊔ ⊥ = a ⇔ ⊥ ≤ a`, `a ⊓ ⊥ = ⊥ ⇔ ⊥ ≤ a`) means the two
        // leq asserts above discharge both algebraic laws by the
        // `leq_agrees_with_meet` + `leq_agrees_with_join` lattice
        // cross-check axiom already pinned in this cohort.
    }

    #[test]
    fn empty_resource_limits_seeds_most_permissive_fold_over_slice() {
        // Fold-identity behavioral pin — a slice of postures folded
        // through [`ResourceLimits::most_permissive`] with EMPTY as
        // the seed produces the pointwise least upper bound across
        // the slice on every axis. The join-identity property
        // (`a.most_permissive(EMPTY) == a`) guarantees the seed
        // contributes nothing to the fold's result — every field's
        // pointwise `max` against the seed's `0` returns the field's
        // value verbatim, so the fold reduces to the joined-across-
        // -operands upper bound. This is the destination usage the
        // constant's docstring names as its fold-identity role.
        //
        // A regression that seeded from ANY non-empty posture (e.g.
        // `DEFAULT_RESOURCE_LIMITS`) would inflate the fold's result
        // on every axis where the seed's field exceeds the pointwise
        // max of the slice — fires as a distinct-axis inequality here.
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        let joined = postures
            .iter()
            .copied()
            .fold(EMPTY_RESOURCE_LIMITS, ResourceLimits::most_permissive);
        // Every operand is `leq` the joined result — the least
        // upper bound dominates each contributor on every axis.
        assert!(HAND_AUTHORED_MID_POSTURE.leq(joined));
        assert!(HAND_AUTHORED_OTHER_POSTURE.leq(joined));
        assert!(DEFAULT_RESOURCE_LIMITS.leq(joined));
        // Field-level pin — each axis is the pointwise `max` of the
        // three sources' values. Six independent field asserts so a
        // drift on ONE axis carries a distinct-name failure.
        assert_eq!(
            joined.max_expansion_depth,
            HAND_AUTHORED_MID_POSTURE
                .max_expansion_depth
                .max(HAND_AUTHORED_OTHER_POSTURE.max_expansion_depth)
                .max(DEFAULT_RESOURCE_LIMITS.max_expansion_depth),
        );
        assert_eq!(
            joined.max_cache_entries,
            HAND_AUTHORED_MID_POSTURE
                .max_cache_entries
                .max(HAND_AUTHORED_OTHER_POSTURE.max_cache_entries)
                .max(DEFAULT_RESOURCE_LIMITS.max_cache_entries),
        );
        assert_eq!(
            joined.max_expansion_size,
            HAND_AUTHORED_MID_POSTURE
                .max_expansion_size
                .max(HAND_AUTHORED_OTHER_POSTURE.max_expansion_size)
                .max(DEFAULT_RESOURCE_LIMITS.max_expansion_size),
        );
        assert_eq!(
            joined.max_macro_body_size,
            HAND_AUTHORED_MID_POSTURE
                .max_macro_body_size
                .max(HAND_AUTHORED_OTHER_POSTURE.max_macro_body_size)
                .max(DEFAULT_RESOURCE_LIMITS.max_macro_body_size),
        );
        assert_eq!(
            joined.max_registered_macros,
            HAND_AUTHORED_MID_POSTURE
                .max_registered_macros
                .max(HAND_AUTHORED_OTHER_POSTURE.max_registered_macros)
                .max(DEFAULT_RESOURCE_LIMITS.max_registered_macros),
        );
        assert_eq!(
            joined.max_macro_arity,
            HAND_AUTHORED_MID_POSTURE
                .max_macro_arity
                .max(HAND_AUTHORED_OTHER_POSTURE.max_macro_arity)
                .max(DEFAULT_RESOURCE_LIMITS.max_macro_arity),
        );
        // Empty-slice edge case — folding over an EMPTY slice returns
        // the seed verbatim (the identity element as the null aggregate).
        // A wrapper-type approach (`Option<ResourceLimits>` for the
        // aggregate) would need a distinct absent branch here; the
        // typed identity-element approach resolves it structurally.
        let empty_slice: [ResourceLimits; 0] = [];
        assert_eq!(
            empty_slice
                .iter()
                .copied()
                .fold(EMPTY_RESOURCE_LIMITS, ResourceLimits::most_permissive),
            EMPTY_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn unbounded_resource_limits_seeds_strictest_fold_over_slice() {
        // Dual fold-identity pin — a slice of postures folded through
        // [`ResourceLimits::strictest`] with UNBOUNDED as the seed
        // produces the pointwise greatest lower bound across the slice
        // on every axis. Peer of the EMPTY-seeds-most_permissive-fold
        // pin one COMBINATOR axis over — the identity element for
        // meet is the join's ANNIHILATOR (`UNBOUNDED`), and the
        // identity element for join is the meet's annihilator
        // (`EMPTY`); the two together bind the bounded-lattice's
        // aggregation surface at BOTH poles.
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        let met = postures
            .iter()
            .copied()
            .fold(UNBOUNDED_RESOURCE_LIMITS, ResourceLimits::strictest);
        // The greatest lower bound sits `leq` every operand.
        assert!(met.leq(HAND_AUTHORED_MID_POSTURE));
        assert!(met.leq(HAND_AUTHORED_OTHER_POSTURE));
        assert!(met.leq(DEFAULT_RESOURCE_LIMITS));
        // Field-level pin — each axis is the pointwise `min` of the
        // three sources' values (the UNBOUNDED seed's `usize::MAX`
        // never wins the min against a concrete positive value).
        assert_eq!(
            met.max_expansion_depth,
            HAND_AUTHORED_MID_POSTURE
                .max_expansion_depth
                .min(HAND_AUTHORED_OTHER_POSTURE.max_expansion_depth)
                .min(DEFAULT_RESOURCE_LIMITS.max_expansion_depth),
        );
        assert_eq!(
            met.max_cache_entries,
            HAND_AUTHORED_MID_POSTURE
                .max_cache_entries
                .min(HAND_AUTHORED_OTHER_POSTURE.max_cache_entries)
                .min(DEFAULT_RESOURCE_LIMITS.max_cache_entries),
        );
        assert_eq!(
            met.max_expansion_size,
            HAND_AUTHORED_MID_POSTURE
                .max_expansion_size
                .min(HAND_AUTHORED_OTHER_POSTURE.max_expansion_size)
                .min(DEFAULT_RESOURCE_LIMITS.max_expansion_size),
        );
        assert_eq!(
            met.max_macro_body_size,
            HAND_AUTHORED_MID_POSTURE
                .max_macro_body_size
                .min(HAND_AUTHORED_OTHER_POSTURE.max_macro_body_size)
                .min(DEFAULT_RESOURCE_LIMITS.max_macro_body_size),
        );
        assert_eq!(
            met.max_registered_macros,
            HAND_AUTHORED_MID_POSTURE
                .max_registered_macros
                .min(HAND_AUTHORED_OTHER_POSTURE.max_registered_macros)
                .min(DEFAULT_RESOURCE_LIMITS.max_registered_macros),
        );
        assert_eq!(
            met.max_macro_arity,
            HAND_AUTHORED_MID_POSTURE
                .max_macro_arity
                .min(HAND_AUTHORED_OTHER_POSTURE.max_macro_arity)
                .min(DEFAULT_RESOURCE_LIMITS.max_macro_arity),
        );
        // Empty-slice edge — folding over an empty slice returns the
        // UNBOUNDED seed verbatim (the meet-identity as the null
        // aggregate). Symmetric to the EMPTY-seed empty-slice pin.
        let empty_slice: [ResourceLimits; 0] = [];
        assert_eq!(
            empty_slice
                .iter()
                .copied()
                .fold(UNBOUNDED_RESOURCE_LIMITS, ResourceLimits::strictest),
            UNBOUNDED_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn resource_limits_strictest_of_empty_slice_returns_the_meet_identity() {
        // Null-aggregate pin — the N-ary meet over an empty slice is
        // the meet-identity element [`UNBOUNDED_RESOURCE_LIMITS`]. The
        // typed identity-element approach resolves the empty-input case
        // at the algebra layer; a wrapper-type approach
        // (`Option<ResourceLimits>` for the aggregate) would need a
        // distinct absent branch here, and a panic-on-empty seed-from-
        // -first-element approach would abort the caller.
        assert_eq!(ResourceLimits::strictest_of(&[]), UNBOUNDED_RESOURCE_LIMITS,);
    }

    #[test]
    fn resource_limits_most_permissive_of_empty_slice_returns_the_join_identity() {
        // Null-aggregate dual pin — the N-ary join over an empty slice
        // is the join-identity element [`EMPTY_RESOURCE_LIMITS`]. Peer
        // to `strictest_of_empty_slice` one COMBINATOR axis over on the
        // (N-ary meet, N-ary join) surface — the identity element for
        // join is the meet's ANNIHILATOR and vice versa; the two
        // together bind both bounded-lattice poles as null aggregates.
        assert_eq!(
            ResourceLimits::most_permissive_of(&[]),
            EMPTY_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn resource_limits_strictest_of_single_element_returns_the_element_verbatim() {
        // Meet-identity absorption pin at N=1 — the N-ary meet of ONE
        // input is the input verbatim, since the meet-identity seed
        // (`UNBOUNDED_RESOURCE_LIMITS`) satisfies
        // `UNBOUNDED.strictest(a) == a` by the pointwise `min` behavior
        // against [`usize::MAX`]. This is the identity-law-at-N=1
        // pin: the fold's seed does not distort the 1-input case.
        assert_eq!(
            ResourceLimits::strictest_of(&[HAND_AUTHORED_MID_POSTURE]),
            HAND_AUTHORED_MID_POSTURE,
        );
        assert_eq!(
            ResourceLimits::strictest_of(&[HAND_AUTHORED_OTHER_POSTURE]),
            HAND_AUTHORED_OTHER_POSTURE,
        );
        assert_eq!(
            ResourceLimits::strictest_of(&[DEFAULT_RESOURCE_LIMITS]),
            DEFAULT_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn resource_limits_most_permissive_of_single_element_returns_the_element_verbatim() {
        // Join-identity absorption pin at N=1 — dual of
        // `strictest_of_single_element`, using the join-identity seed
        // (`EMPTY_RESOURCE_LIMITS`) whose per-axis `0` satisfies
        // `EMPTY.most_permissive(a) == a` against any non-zero value.
        assert_eq!(
            ResourceLimits::most_permissive_of(&[HAND_AUTHORED_MID_POSTURE]),
            HAND_AUTHORED_MID_POSTURE,
        );
        assert_eq!(
            ResourceLimits::most_permissive_of(&[HAND_AUTHORED_OTHER_POSTURE]),
            HAND_AUTHORED_OTHER_POSTURE,
        );
        assert_eq!(
            ResourceLimits::most_permissive_of(&[DEFAULT_RESOURCE_LIMITS]),
            DEFAULT_RESOURCE_LIMITS,
        );
    }

    #[test]
    fn resource_limits_strictest_of_two_elements_reduces_to_pairwise_strictest() {
        // N=2 reduction pin — the N-ary meet on a 2-element slice
        // reduces to the pairwise combinator, since
        // `UNBOUNDED.strictest(a).strictest(b) == a.strictest(b)`. The
        // strictest_of(&[a, b]) call MUST agree with a.strictest(b) on
        // every input pair the algebra distinguishes.
        assert_eq!(
            ResourceLimits::strictest_of(
                &[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE,]
            ),
            HAND_AUTHORED_MID_POSTURE.strictest(HAND_AUTHORED_OTHER_POSTURE),
        );
        assert_eq!(
            ResourceLimits::strictest_of(&[DEFAULT_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS,]),
            DEFAULT_RESOURCE_LIMITS.strictest(UNBOUNDED_RESOURCE_LIMITS),
        );
    }

    #[test]
    fn resource_limits_most_permissive_of_two_elements_reduces_to_pairwise_most_permissive() {
        // N=2 reduction dual pin — the N-ary join on a 2-element slice
        // reduces to the pairwise combinator.
        assert_eq!(
            ResourceLimits::most_permissive_of(&[
                HAND_AUTHORED_MID_POSTURE,
                HAND_AUTHORED_OTHER_POSTURE,
            ]),
            HAND_AUTHORED_MID_POSTURE.most_permissive(HAND_AUTHORED_OTHER_POSTURE),
        );
        assert_eq!(
            ResourceLimits::most_permissive_of(&[DEFAULT_RESOURCE_LIMITS, EMPTY_RESOURCE_LIMITS,]),
            DEFAULT_RESOURCE_LIMITS.most_permissive(EMPTY_RESOURCE_LIMITS),
        );
    }

    #[test]
    fn resource_limits_strictest_of_agrees_with_direct_fold_over_slice() {
        // Method-agrees-with-fold pin — the sole behavioral claim the
        // N-ary aggregator makes is that it IS the inline
        // `.iter().copied().fold(UNBOUNDED, strictest)` cascade the
        // pre-lift caller composed at every consumption site. A drift
        // between the method's implementation and the inline fold
        // would break this equality on every non-empty slice.
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        assert_eq!(
            ResourceLimits::strictest_of(&postures),
            postures
                .iter()
                .copied()
                .fold(UNBOUNDED_RESOURCE_LIMITS, ResourceLimits::strictest),
        );
    }

    #[test]
    fn resource_limits_most_permissive_of_agrees_with_direct_fold_over_slice() {
        // Method-agrees-with-fold dual pin.
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        assert_eq!(
            ResourceLimits::most_permissive_of(&postures),
            postures
                .iter()
                .copied()
                .fold(EMPTY_RESOURCE_LIMITS, ResourceLimits::most_permissive),
        );
    }

    #[test]
    fn resource_limits_strictest_of_is_order_independent() {
        // Order-independence pin — the fold inherits commutativity AND
        // associativity of the pairwise `strictest`, so any permutation
        // of the input slice yields the same aggregate. Reversal is
        // the maximal permutation for a 3-element input (indices
        // 0,1,2 → 2,1,0); an aggregator that leaked fold order would
        // discriminate here.
        let forward = ResourceLimits::strictest_of(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ]);
        let reversed = ResourceLimits::strictest_of(&[
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_OTHER_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]);
        assert_eq!(forward, reversed);
    }

    #[test]
    fn resource_limits_most_permissive_of_is_order_independent() {
        let forward = ResourceLimits::most_permissive_of(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ]);
        let reversed = ResourceLimits::most_permissive_of(&[
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_OTHER_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]);
        assert_eq!(forward, reversed);
    }

    #[test]
    fn resource_limits_strictest_of_composes_at_compile_time_via_const_fn() {
        // Compile-time-composition pin — `strictest_of` is `const fn`,
        // so a caller binds an N-ary aggregate to a `pub const` and the
        // fold evaluates at compile time. Every `DEFAULT_MAX_*` is
        // strictly less than `usize::MAX`, so the meet of `[DEFAULT,
        // UNBOUNDED]` picks DEFAULT on every axis — a preset-pair
        // identity already pinned pairwise, verified here through the
        // N-ary method's const-context evaluation. The N-ary const-fn
        // peer of the pairwise const-fn pins on
        // [`ResourceLimits::strictest`]; a regression that turned
        // `strictest_of` into a runtime `fn` would break the `const`
        // binding below at compile time.
        const AGGREGATED: ResourceLimits =
            ResourceLimits::strictest_of(&[DEFAULT_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS]);
        assert_eq!(AGGREGATED, DEFAULT_RESOURCE_LIMITS);
    }

    #[test]
    fn resource_limits_most_permissive_of_composes_at_compile_time_via_const_fn() {
        // Compile-time-composition dual pin — every `DEFAULT_MAX_*` is
        // strictly greater than `0`, so the join of `[EMPTY, DEFAULT]`
        // picks DEFAULT on every axis.
        const AGGREGATED: ResourceLimits =
            ResourceLimits::most_permissive_of(&[EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS]);
        assert_eq!(AGGREGATED, DEFAULT_RESOURCE_LIMITS);
    }

    #[test]
    fn resource_limits_strictest_of_result_is_leq_every_operand() {
        // Lattice-relation pin — the N-ary meet sits `leq` every
        // operand. This is the N-ary extension of the pairwise
        // `strictest_is_leq_both_operands` pin; the meet aggregate
        // dominates from below (the greatest lower bound of the slice
        // sits at-or-below each input on every axis).
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        let met = ResourceLimits::strictest_of(&postures);
        for p in postures {
            assert!(met.leq(p));
        }
    }

    #[test]
    fn resource_limits_most_permissive_of_result_is_geq_every_operand() {
        // Lattice-relation dual pin — every operand sits `leq` the
        // N-ary join. The join aggregate is the least upper bound of
        // the slice.
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        let joined = ResourceLimits::most_permissive_of(&postures);
        for p in postures {
            assert!(p.leq(joined));
        }
    }

    #[test]
    fn expander_built_at_strictest_of_slice_gates_at_tightest_ceiling_across_the_slice() {
        // Behavioral pin — an expander constructed from the N-ary meet
        // of a slice of postures MUST gate at the tightest ceiling
        // across the slice on every axis. Peer of
        // `expander_built_at_strictest_of_two_presets_gates_at_the_tighter_ceiling`
        // one AGGREGATION-ARITY axis over: where the pairwise pin
        // composes exactly two postures, this pin composes THREE
        // through the N-ary aggregator, confirming the arity extension
        // preserves the "meet gates at tightest" behavioral contract.
        //
        // The slice tightens macro_arity to 1 (the tightest across the
        // three postures) via the middle operand; every other axis
        // stays at usize::MAX (the outer two operands supply
        // usize::MAX; the middle operand's struct-update literal
        // preserves usize::MAX everywhere except macro_arity).
        let tightened = ResourceLimits::strictest_of(&[
            UNBOUNDED_RESOURCE_LIMITS,
            ResourceLimits {
                max_macro_arity: 1,
                ..UNBOUNDED_RESOURCE_LIMITS
            },
            UNBOUNDED_RESOURCE_LIMITS,
        ]);
        assert_eq!(tightened.max_macro_arity, 1);
        assert_eq!(tightened.max_expansion_depth, usize::MAX);
        assert_eq!(tightened.max_cache_entries, usize::MAX);
        assert_eq!(tightened.max_expansion_size, usize::MAX);
        assert_eq!(tightened.max_macro_body_size, usize::MAX);
        assert_eq!(tightened.max_registered_macros, usize::MAX);
        let mut e = Expander::with_limits(tightened);
        let forms = read("(defmacro two (a b) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(
                err,
                LispError::MacroArityExceeded {
                    arity: 2,
                    limit: 1,
                    ..
                }
            ),
            "expected MacroArityExceeded from N-ary meet's tightened arity gate, got {err:?}",
        );
    }

    #[test]
    fn expander_built_at_strictest_of_two_presets_gates_at_the_tighter_ceiling() {
        // Behavioral pin — an expander constructed from the meet of
        // two postures MUST gate at the tighter of the two ceilings
        // on every axis. Build the meet of the ceiling-lifted preset
        // and a hand-authored posture whose `max_macro_arity` sits at
        // 1; the meet inherits the 1-slot arity ceiling (tighter than
        // [`usize::MAX`]) AND the [`usize::MAX`] ceiling on every
        // other axis (tighter than the hand-authored posture's small
        // values — no, wait: the OTHER posture's small values ARE
        // tighter. So the meet inherits 1 on arity and the OTHER
        // small values elsewhere.) Confirm the constructed expander
        // rejects a 2-arg macro registration with the arity gate.
        let tightened = UNBOUNDED_RESOURCE_LIMITS.strictest(ResourceLimits {
            max_macro_arity: 1,
            ..UNBOUNDED_RESOURCE_LIMITS
        });
        assert_eq!(tightened.max_macro_arity, 1);
        // Other five axes remain at `usize::MAX` (both operands carry
        // `usize::MAX` on those, so the pointwise `min` is `usize::MAX`).
        assert_eq!(tightened.max_expansion_depth, usize::MAX);
        assert_eq!(tightened.max_cache_entries, usize::MAX);
        assert_eq!(tightened.max_expansion_size, usize::MAX);
        assert_eq!(tightened.max_macro_body_size, usize::MAX);
        assert_eq!(tightened.max_registered_macros, usize::MAX);
        let mut e = Expander::with_limits(tightened);
        let forms = read("(defmacro two (a b) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(
                err,
                LispError::MacroArityExceeded {
                    arity: 2,
                    limit: 1,
                    ..
                }
            ),
            "the tighter arity ceiling from the meet MUST reach the register-time gate; got: {err:?}"
        );
    }

    // ── ResourceLimits::clamp — bounded-lattice bracket combinator ────

    /// A tighter-than-MID lower-bracket witness — every axis strictly
    /// smaller than `HAND_AUTHORED_MID_POSTURE`'s matching axis, so the
    /// pointwise `max(mid, floor) == mid` on every axis (`floor.leq(mid)`
    /// holds structurally). Peer of `HAND_AUTHORED_CLAMP_CEILING` one
    /// BRACKET-BOUND axis over on the (floor, ceiling) bracket-witness
    /// pair.
    const HAND_AUTHORED_CLAMP_FLOOR: ResourceLimits = ResourceLimits {
        max_expansion_depth: 2,
        max_cache_entries: 3,
        max_expansion_size: 5,
        max_macro_body_size: 7,
        max_registered_macros: 11,
        max_macro_arity: 13,
    };

    /// A looser-than-MID upper-bracket witness — every axis strictly larger
    /// than `HAND_AUTHORED_MID_POSTURE`'s matching axis, so the pointwise
    /// `min(mid, ceiling) == mid` on every axis (`mid.leq(ceiling)` holds
    /// structurally). Peer of `HAND_AUTHORED_CLAMP_FLOOR` one BRACKET-
    /// BOUND axis over. Together with `HAND_AUTHORED_CLAMP_FLOOR` the two
    /// bracket `HAND_AUTHORED_MID_POSTURE` strictly on every axis:
    /// `FLOOR.leq(MID) && MID.leq(CEILING) && FLOOR != MID && MID !=
    /// CEILING`.
    const HAND_AUTHORED_CLAMP_CEILING: ResourceLimits = ResourceLimits {
        max_expansion_depth: 47,
        max_cache_entries: 53,
        max_expansion_size: 59,
        max_macro_body_size: 61,
        max_registered_macros: 67,
        max_macro_arity: 71,
    };

    #[test]
    fn resource_limits_clamp_of_posture_already_in_range_returns_the_posture() {
        // In-range identity — when the input already sits within the
        // `[lower, upper]` bracket (`lower.leq(a) && a.leq(upper)` per-
        // axis), the clamp is the identity function: the pointwise
        // `max(a, lower) == a` (since `lower ≤ a` per-axis picks `a`),
        // then the pointwise `min(a, upper) == a` (since `a ≤ upper`
        // per-axis picks `a`). The primary invariant on the "input
        // already satisfies the bracket" arm of the three-arm bracket-
        // membership surface.
        //
        // Prerequisite pins — the two hand-authored bounds bracket
        // `MID` strictly on every axis (structural check that discharges
        // the "already in range" premise). A regression that inflated
        // `FLOOR` or deflated `CEILING` past `MID` would fail these
        // asserts before the clamp identity was tested, making the
        // premise's failure name itself rather than showing up as a
        // downstream misleading clamp mismatch.
        assert!(HAND_AUTHORED_CLAMP_FLOOR.leq(HAND_AUTHORED_MID_POSTURE));
        assert!(HAND_AUTHORED_MID_POSTURE.leq(HAND_AUTHORED_CLAMP_CEILING));
        let clamped =
            HAND_AUTHORED_MID_POSTURE.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
        assert_eq!(clamped, HAND_AUTHORED_MID_POSTURE);
    }

    #[test]
    fn resource_limits_clamp_of_posture_below_lower_returns_lower() {
        // Below-lower floor — when the input is tighter than the
        // bracket floor on every axis (`a.leq(lower)` per-axis), the
        // clamp lifts the input up to `lower`: the pointwise `max(a,
        // lower) == lower` (since `a ≤ lower` per-axis picks `lower`),
        // then the pointwise `min(lower, upper) == lower` (since
        // `lower ≤ upper` per-axis picks `lower`). Peer of
        // `resource_limits_clamp_of_posture_already_in_range_returns_the_posture`
        // one BRACKET-POSITION axis over on the (in-range, below-lower,
        // above-upper) three-arm bracket-membership surface.
        //
        // `EMPTY_RESOURCE_LIMITS` sits `leq` every posture (bounded-
        // lattice bottom), so `EMPTY.leq(FLOOR)` holds structurally
        // for any FLOOR; a clamp of `EMPTY` into `[FLOOR, CEILING]`
        // MUST return `FLOOR`.
        assert!(EMPTY_RESOURCE_LIMITS.leq(HAND_AUTHORED_CLAMP_FLOOR));
        assert!(HAND_AUTHORED_CLAMP_FLOOR.leq(HAND_AUTHORED_CLAMP_CEILING));
        let clamped =
            EMPTY_RESOURCE_LIMITS.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
        assert_eq!(clamped, HAND_AUTHORED_CLAMP_FLOOR);
    }

    #[test]
    fn resource_limits_clamp_of_posture_above_upper_returns_upper() {
        // Above-upper ceiling — when the input is looser than the
        // bracket ceiling on every axis (`upper.leq(a)` per-axis), the
        // clamp lowers the input down to `upper`: the pointwise
        // `max(a, lower) == a` (since `lower ≤ upper ≤ a` per-axis picks
        // `a`), then the pointwise `min(a, upper) == upper` (since
        // `upper ≤ a` per-axis picks `upper`). Peer of the
        // below-lower arm one BRACKET-POSITION axis over on the three-
        // arm bracket-membership surface.
        //
        // `UNBOUNDED_RESOURCE_LIMITS` sits `geq` every posture (bounded-
        // lattice top), so `CEILING.leq(UNBOUNDED)` holds structurally
        // for any CEILING; a clamp of `UNBOUNDED` into `[FLOOR, CEILING]`
        // MUST return `CEILING`.
        assert!(HAND_AUTHORED_CLAMP_CEILING.leq(UNBOUNDED_RESOURCE_LIMITS));
        assert!(HAND_AUTHORED_CLAMP_FLOOR.leq(HAND_AUTHORED_CLAMP_CEILING));
        let clamped =
            UNBOUNDED_RESOURCE_LIMITS.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
        assert_eq!(clamped, HAND_AUTHORED_CLAMP_CEILING);
    }

    #[test]
    fn resource_limits_clamp_result_sits_within_the_bracket() {
        // Bracket-membership contract — the DEFINING invariant on the
        // clamp primitive: for every well-formed bracket
        // (`lower.leq(upper)`) and every input `a`, the result sits
        // within the bracket `lower.leq(a.clamp(lower, upper)) &&
        // a.clamp(lower, upper).leq(upper)`. Exercised on ALL FOUR arm
        // positions of the bracket-membership surface via the four
        // known-preset inputs (below-lower → in-range → above-upper
        // → asymmetric-crossing) so a regression that inflated the
        // ceiling arm or deflated the floor arm exhausts all four
        // input positions and names the failing arm.
        assert!(HAND_AUTHORED_CLAMP_FLOOR.leq(HAND_AUTHORED_CLAMP_CEILING));
        let inputs = [
            EMPTY_RESOURCE_LIMITS,       // below-lower
            HAND_AUTHORED_MID_POSTURE,   // in-range
            UNBOUNDED_RESOURCE_LIMITS,   // above-upper
            HAND_AUTHORED_OTHER_POSTURE, // asymmetric (crosses the bracket)
        ];
        for a in inputs {
            let clamped = a.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
            assert!(
                HAND_AUTHORED_CLAMP_FLOOR.leq(clamped),
                "clamp result must sit at or above FLOOR; input={a:?} clamped={clamped:?}",
            );
            assert!(
                clamped.leq(HAND_AUTHORED_CLAMP_CEILING),
                "clamp result must sit at or below CEILING; input={a:?} clamped={clamped:?}",
            );
        }
    }

    #[test]
    fn resource_limits_clamp_with_lattice_extrema_returns_the_input() {
        // Extrema-bracket identity — clamping against the bounded-
        // lattice extrema (`EMPTY_RESOURCE_LIMITS` as the leq-minimum,
        // `UNBOUNDED_RESOURCE_LIMITS` as the leq-maximum) is the
        // identity function on every posture: every posture already
        // sits within the widest possible bracket. Cross-checks the
        // clamp primitive against the bounded-lattice identity elements
        // previously lifted; a regression that swapped the two extrema
        // in the impl would collapse every input to
        // `UNBOUNDED.strictest(EMPTY) == EMPTY` and fail this pin on
        // every non-EMPTY input.
        for a in [
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            EMPTY_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ] {
            assert_eq!(
                a.clamp(EMPTY_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS),
                a,
                "clamp against [EMPTY, UNBOUNDED] must be the identity on {a:?}",
            );
        }
    }

    #[test]
    fn resource_limits_clamp_with_equal_bounds_returns_the_bound() {
        // Degenerate-bracket collapse — a zero-width bracket
        // (`lower == upper`) collapses every input to the single point.
        // The pointwise `max(a, x)` lifts every axis to at least `x`,
        // then the pointwise `min(., x)` clamps every axis to exactly
        // `x` regardless of `a`'s per-axis position (since `x ≤ max(a,
        // x) ≤ max(x, x) == x` when `a.leq(x)` and `min(max(a, x), x)
        // == x` when `x.leq(a)`).
        for x in [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ] {
            for a in [
                EMPTY_RESOURCE_LIMITS,
                HAND_AUTHORED_MID_POSTURE,
                HAND_AUTHORED_OTHER_POSTURE,
                UNBOUNDED_RESOURCE_LIMITS,
            ] {
                assert_eq!(
                    a.clamp(x, x),
                    x,
                    "zero-width bracket [x, x] must collapse input {a:?} to x={x:?}",
                );
            }
        }
    }

    #[test]
    fn resource_limits_clamp_is_idempotent() {
        // Idempotence — re-applying the same bracket to an already-
        // clamped posture returns the same result. The clamp primitive
        // is idempotent because its output already sits within the
        // `[lower, upper]` bracket (pinned by
        // `resource_limits_clamp_result_sits_within_the_bracket`), so
        // the second application hits the in-range identity arm. Peer
        // of the idempotence pins on `strictest` and `most_permissive`
        // one ARITY axis over (2-input primitive → 3-input bracket) on
        // the lattice-algebra idempotence-law surface.
        assert!(HAND_AUTHORED_CLAMP_FLOOR.leq(HAND_AUTHORED_CLAMP_CEILING));
        for a in [
            EMPTY_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            UNBOUNDED_RESOURCE_LIMITS,
        ] {
            let once = a.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
            let twice = once.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
            assert_eq!(
                once, twice,
                "clamp must be idempotent; input={a:?} once={once:?} twice={twice:?}",
            );
        }
    }

    #[test]
    fn resource_limits_clamp_composes_at_compile_time_via_const_fn() {
        // Const-fn pin — the bracket combinator is evaluable in const
        // context, so a caller can pre-clamp a shipped preset against
        // an operator-supplied policy bracket at compile time. Sibling
        // of the const-fn composition pins on `strictest` /
        // `most_permissive` / `strictest_of` / `most_permissive_of`
        // one PRIMITIVE-KIND axis over: those four combinators compose
        // presets at const time, and this bracket combinator projects
        // a preset into a const-time bracket.
        //
        // A regression to a runtime `fn` here would fail the `pub
        // const` binding below at compile time — a stronger guarantee
        // than a runtime `assert!` because the const binding is
        // evaluated once at compile time, not per test invocation.
        const CLAMPED_DEFAULT: ResourceLimits =
            DEFAULT_RESOURCE_LIMITS.clamp(EMPTY_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS);
        assert_eq!(CLAMPED_DEFAULT, DEFAULT_RESOURCE_LIMITS);

        // Compile-time bracket-membership pin — const `assert!` on the
        // lattice-relation contract discharges the "clamp result sits
        // within the bracket" invariant at compile time on the
        // (DEFAULT, EMPTY, UNBOUNDED) preset triple.
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.leq(CLAMPED_DEFAULT));
        const _: () = assert!(CLAMPED_DEFAULT.leq(UNBOUNDED_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_clamp_agrees_with_direct_two_step_cascade() {
        // Structural-equivalence pin — the sole behavioral claim the
        // clamp primitive makes is that it IS the
        // `self.most_permissive(lower).strictest(upper)` two-step
        // cascade the pre-lift caller composed. A drift between the
        // method and the inline cascade would break this equality on
        // every input; the pin exhausts the four bracket-position arms
        // of the input surface.
        for a in [
            EMPTY_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            UNBOUNDED_RESOURCE_LIMITS,
        ] {
            let via_method = a.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
            let via_cascade = a
                .most_permissive(HAND_AUTHORED_CLAMP_FLOOR)
                .strictest(HAND_AUTHORED_CLAMP_CEILING);
            assert_eq!(via_method, via_cascade);
        }
    }

    #[test]
    fn expander_built_at_clamped_preset_gates_at_the_bracket_ceiling() {
        // Behavioral pin — an expander constructed from a preset
        // clamped into `[EMPTY, TIGHT_BRACKET]` MUST gate at the
        // bracket ceiling's arity axis. Confirms the clamp primitive
        // reaches through to the runtime gates that consume
        // `ResourceLimits`, so a future consumer that pre-clamps a
        // preset against a policy bracket inherits the bracket's
        // ceilings at every guard. Peer of
        // `expander_built_at_strictest_of_two_presets_gates_at_the_tighter_ceiling`
        // one COMBINATOR-ARITY axis over on the (pairwise-meet,
        // N-ary-meet, bracket) combinator-arity face.
        //
        // The bracket ceiling tightens `max_macro_arity` to 1; every
        // other axis stays at `usize::MAX` (the CEILING preset carries
        // `usize::MAX` on those, and the input UNBOUNDED preset also
        // carries `usize::MAX` on every axis — the clamp's `strictest`
        // arm picks `usize::MAX` from either side).
        let bracket_ceiling = ResourceLimits {
            max_macro_arity: 1,
            ..UNBOUNDED_RESOURCE_LIMITS
        };
        let clamped = UNBOUNDED_RESOURCE_LIMITS.clamp(EMPTY_RESOURCE_LIMITS, bracket_ceiling);
        assert_eq!(clamped.max_macro_arity, 1);
        assert_eq!(clamped.max_expansion_depth, usize::MAX);
        assert_eq!(clamped.max_cache_entries, usize::MAX);
        assert_eq!(clamped.max_expansion_size, usize::MAX);
        assert_eq!(clamped.max_macro_body_size, usize::MAX);
        assert_eq!(clamped.max_registered_macros, usize::MAX);
        let mut e = Expander::with_limits(clamped);
        let forms = read("(defmacro two (a b) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(
                err,
                LispError::MacroArityExceeded {
                    arity: 2,
                    limit: 1,
                    ..
                }
            ),
            "the bracket ceiling's arity gate MUST reach the register-time check; got: {err:?}",
        );
    }

    // ── ResourceLimits::within — bracket-membership predicate ─────────

    #[test]
    fn resource_limits_within_of_posture_in_range_is_true() {
        // In-range identity — when the input already sits within the
        // `[lower, upper]` bracket on every axis (`lower.leq(a) &&
        // a.leq(upper)`), the predicate returns `true`. Peer of
        // `resource_limits_clamp_of_posture_already_in_range_returns_the_posture`
        // one PRIMITIVE-KIND axis over on the (combinator, predicate)
        // face of the bracket-primitive surface.
        //
        // Prerequisite pins — the two hand-authored bounds bracket
        // `MID` strictly on every axis, structurally discharging the
        // "already in range" premise.
        assert!(HAND_AUTHORED_CLAMP_FLOOR.leq(HAND_AUTHORED_MID_POSTURE));
        assert!(HAND_AUTHORED_MID_POSTURE.leq(HAND_AUTHORED_CLAMP_CEILING));
        assert!(HAND_AUTHORED_MID_POSTURE
            .within(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING),);
    }

    #[test]
    fn resource_limits_within_of_posture_below_lower_is_false() {
        // Below-lower rejection — when the input is strictly tighter
        // than the bracket floor on some axis (`!lower.leq(a)`), the
        // predicate returns `false`. `EMPTY_RESOURCE_LIMITS` has every
        // axis at `0`, strictly below `HAND_AUTHORED_CLAMP_FLOOR`'s
        // per-axis ceilings; so `FLOOR.leq(EMPTY)` fails on every axis,
        // making the conjunction reject regardless of `EMPTY`'s relation
        // to `CEILING`. Peer of
        // `resource_limits_clamp_of_posture_below_lower_returns_lower`
        // one PRIMITIVE-KIND axis over.
        assert!(!HAND_AUTHORED_CLAMP_FLOOR.leq(EMPTY_RESOURCE_LIMITS));
        assert!(
            !EMPTY_RESOURCE_LIMITS.within(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING),
        );
    }

    #[test]
    fn resource_limits_within_of_posture_above_upper_is_false() {
        // Above-upper rejection — when the input is strictly looser
        // than the bracket ceiling on some axis (`!a.leq(upper)`), the
        // predicate returns `false`. `UNBOUNDED_RESOURCE_LIMITS` has
        // every axis at `usize::MAX`, strictly above
        // `HAND_AUTHORED_CLAMP_CEILING`'s per-axis ceilings; so
        // `UNBOUNDED.leq(CEILING)` fails on every axis. Peer of
        // `resource_limits_clamp_of_posture_above_upper_returns_upper`
        // one PRIMITIVE-KIND axis over.
        assert!(!UNBOUNDED_RESOURCE_LIMITS.leq(HAND_AUTHORED_CLAMP_CEILING));
        assert!(!UNBOUNDED_RESOURCE_LIMITS
            .within(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING),);
    }

    #[test]
    fn resource_limits_within_with_lattice_extrema_is_true() {
        // Extrema-bracket identity — every posture sits within the
        // widest possible bracket `[EMPTY_RESOURCE_LIMITS,
        // UNBOUNDED_RESOURCE_LIMITS]`. Cross-checks the predicate
        // against the bounded-lattice identity elements (`EMPTY` is
        // the leq-minimum, `UNBOUNDED` is the leq-maximum). Peer of
        // `resource_limits_clamp_with_lattice_extrema_returns_the_input`
        // one PRIMITIVE-KIND axis over — the predicate view of the
        // "clamp is the identity" property.
        for a in [
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            EMPTY_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ] {
            assert!(
                a.within(EMPTY_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS),
                "every posture must sit within the extrema bracket [EMPTY, UNBOUNDED]; got: {a:?}",
            );
        }
    }

    #[test]
    fn resource_limits_within_of_equal_bounds_iff_equal_to_bound() {
        // Degenerate-bracket collapse — a zero-width bracket admits
        // only the single point at the bounds. `a.within(x, x)` holds
        // iff `x.leq(a) && a.leq(x)` iff `a == x` by antisymmetry of
        // `leq`. Peer of `resource_limits_clamp_with_equal_bounds_returns_the_bound`
        // one PRIMITIVE-KIND axis over: the clamp collapses to `x`
        // unconditionally, and the predicate distinguishes the "was
        // already equal" case from the "would have been clamped" case.
        let bounds = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ];
        for x in bounds {
            for a in bounds {
                assert_eq!(
                    a.within(x, x),
                    a == x,
                    "a.within(x, x) must hold iff a == x; a={a:?} x={x:?}",
                );
            }
        }
    }

    #[test]
    fn resource_limits_within_of_self_is_reflexive() {
        // Reflexive-bracket identity — every posture sits within the
        // zero-width bracket at itself, since `a.leq(a)` holds by
        // reflexivity of `leq`. The reflexive-bracket peer of the
        // reflexive-leq pin (`resource_limits_leq_is_reflexive`) one
        // ARITY axis over (pairwise → three-input).
        for a in [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            UNBOUNDED_RESOURCE_LIMITS,
        ] {
            assert!(
                a.within(a, a),
                "a.within(a, a) must hold by reflexivity of leq; a={a:?}",
            );
        }
    }

    #[test]
    fn resource_limits_within_agrees_with_clamp_fixed_point() {
        // Clamp fixed-point theorem — `a.within(lower, upper) ⇔
        // a.clamp(lower, upper) == a`. The CANONICAL cross-check axiom
        // binding the `within` predicate to the `clamp` combinator,
        // analogous to the meet-agreement (`a.leq(b) ⇔ a.strictest(b)
        // == a`, pinned by `resource_limits_leq_agrees_with_meet`) and
        // join-agreement (`a.leq(b) ⇔ a.most_permissive(b) == b`,
        // pinned by `resource_limits_leq_agrees_with_join`) axioms
        // binding the `leq` relation to its combinator peers.
        //
        // Exercised on all four bracket-position arms of the input
        // surface (below-lower / in-range / above-upper / asymmetric-
        // crossing) so a regression that broke either direction of the
        // fixed-point equivalence exhausts every position and names the
        // failing arm.
        assert!(HAND_AUTHORED_CLAMP_FLOOR.leq(HAND_AUTHORED_CLAMP_CEILING));
        for a in [
            EMPTY_RESOURCE_LIMITS,       // below-lower — clamp != a, within false
            HAND_AUTHORED_MID_POSTURE,   // in-range   — clamp == a, within true
            UNBOUNDED_RESOURCE_LIMITS,   // above-upper — clamp != a, within false
            HAND_AUTHORED_OTHER_POSTURE, // asymmetric — clamp != a, within false
        ] {
            let clamped = a.clamp(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
            let within_holds = a.within(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
            let clamp_fixed = clamped == a;
            assert_eq!(
                within_holds, clamp_fixed,
                "within(lower, upper) must agree with clamp fixed-point; \
                 a={a:?} within={within_holds} clamp_fixed={clamp_fixed} clamped={clamped:?}",
            );
        }
    }

    #[test]
    fn resource_limits_within_agrees_with_direct_two_primitive_conjunction() {
        // Structural-equivalence pin — the sole behavioral claim the
        // predicate makes is that it IS the `lower.leq(a) && a.leq(upper)`
        // two-primitive conjunction the pre-lift caller composed. A drift
        // between the method and the inline conjunction would break this
        // equality on some input; the pin exhausts the four bracket-
        // position arms of the input surface. Peer of
        // `resource_limits_clamp_agrees_with_direct_two_step_cascade`
        // one PRIMITIVE-KIND axis over (combinator ↔ predicate).
        for a in [
            EMPTY_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            UNBOUNDED_RESOURCE_LIMITS,
        ] {
            let via_method = a.within(HAND_AUTHORED_CLAMP_FLOOR, HAND_AUTHORED_CLAMP_CEILING);
            let via_conjunction =
                HAND_AUTHORED_CLAMP_FLOOR.leq(a) && a.leq(HAND_AUTHORED_CLAMP_CEILING);
            assert_eq!(via_method, via_conjunction, "a={a:?}");
        }
    }

    #[test]
    fn resource_limits_within_composes_at_compile_time_via_const_fn() {
        // Const-fn pin — the bracket predicate is evaluable in const
        // context, so a caller can pin a preset-bracket-membership
        // identity at compile time. Sibling of the const-fn evaluability
        // pins on `leq` and `clamp` one PRIMITIVE-KIND axis over: the
        // relation and combinator both evaluate at const time, and the
        // predicate closing the (combinator, predicate) row does too.
        //
        // A regression to a runtime `fn` here would fail the `const _:
        // () = assert!(...)` bindings below at compile time.
        const _: () = assert!(
            DEFAULT_RESOURCE_LIMITS.within(EMPTY_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS)
        );
        const _: () = assert!(
            DEFAULT_RESOURCE_LIMITS.within(DEFAULT_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS)
        );
        const _: () = assert!(
            !UNBOUNDED_RESOURCE_LIMITS.within(EMPTY_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS,)
        );
    }

    #[test]
    fn expander_built_at_within_gated_preset_reaches_the_runtime_guards() {
        // Behavioral pin — a caller that CHECKS bracket-membership
        // before constructing an expander can safely reach through to
        // the runtime gates: if `within` reports true, `clamp` is a
        // no-op (by the fixed-point theorem), so the expander's
        // ceilings are the input posture's own. Peer of
        // `expander_built_at_clamped_preset_gates_at_the_bracket_ceiling`
        // one PRIMITIVE-KIND axis over — the predicate view of the
        // "clamp reaches through to the runtime gates" property.
        //
        // The candidate sits at the bracket ceiling (arity=1, other
        // axes at usize::MAX), so it MUST sit within the [EMPTY,
        // bracket_ceiling] bracket — the maximal within-membership arm
        // of the fixed-point theorem. Every other axis at usize::MAX
        // clears the register-time gates, so the arity gate at 1 is
        // the one that trips on a 2-parameter macro registration.
        let bracket_ceiling = ResourceLimits {
            max_macro_arity: 1,
            ..UNBOUNDED_RESOURCE_LIMITS
        };
        let candidate = ResourceLimits {
            max_macro_arity: 1,
            ..UNBOUNDED_RESOURCE_LIMITS
        };
        assert!(candidate.within(EMPTY_RESOURCE_LIMITS, bracket_ceiling));
        // Since candidate sits within the bracket, clamp is the
        // identity; the expander inherits candidate's ceilings verbatim.
        let clamped = candidate.clamp(EMPTY_RESOURCE_LIMITS, bracket_ceiling);
        assert_eq!(clamped, candidate);
        let mut e = Expander::with_limits(clamped);
        let forms = read("(defmacro two (a b) `,a)").unwrap();
        let err = e.expand_program(forms).unwrap_err();
        assert!(
            matches!(
                err,
                LispError::MacroArityExceeded {
                    arity: 2,
                    limit: 1,
                    ..
                }
            ),
            "the within-gated candidate's arity ceiling MUST reach the register-time check; got: {err:?}",
        );
    }

    // ── ResourceLimits::is_lower_bound_of / is_upper_bound_of ─────────
    //   N-ary boolean-conjunction peers of the pairwise `leq` relation,
    //   closing the (combinator, predicate) row on the N-ary-aggregation
    //   face of the lattice-algebra surface. See the docstring on
    //   `ResourceLimits::is_lower_bound_of` for the (pairwise, N-ary,
    //   bracket) × (combinator, predicate) placement.

    #[test]
    fn resource_limits_is_lower_bound_of_empty_slice_is_vacuously_true() {
        // Empty-conjunction identity — every posture is trivially a
        // lower bound of the empty set. Peer of `strictest_of(&[]) ==
        // UNBOUNDED_RESOURCE_LIMITS`'s empty-slice identity one
        // PRIMITIVE-KIND axis over: the empty slice aggregates to the
        // identity element of the underlying operation (`true` for
        // boolean conjunction, `UNBOUNDED` for pointwise `min`).
        assert!(HAND_AUTHORED_MID_POSTURE.is_lower_bound_of(&[]));
        assert!(EMPTY_RESOURCE_LIMITS.is_lower_bound_of(&[]));
        assert!(UNBOUNDED_RESOURCE_LIMITS.is_lower_bound_of(&[]));
        assert!(DEFAULT_RESOURCE_LIMITS.is_lower_bound_of(&[]));
    }

    #[test]
    fn resource_limits_is_upper_bound_of_empty_slice_is_vacuously_true() {
        // Empty-conjunction dual — every posture is trivially an upper
        // bound of the empty set. Peer of
        // `is_lower_bound_of_empty_slice_is_vacuously_true` one
        // COMBINATOR-DIRECTION axis over, AND peer of
        // `most_permissive_of(&[]) == EMPTY_RESOURCE_LIMITS`'s empty-
        // slice identity one PRIMITIVE-KIND axis over.
        assert!(HAND_AUTHORED_MID_POSTURE.is_upper_bound_of(&[]));
        assert!(EMPTY_RESOURCE_LIMITS.is_upper_bound_of(&[]));
        assert!(UNBOUNDED_RESOURCE_LIMITS.is_upper_bound_of(&[]));
        assert!(DEFAULT_RESOURCE_LIMITS.is_upper_bound_of(&[]));
    }

    #[test]
    fn resource_limits_is_lower_bound_of_single_element_reduces_to_leq() {
        // 1-input identity — the singleton predicate reduces to the
        // pairwise partial-order relation. The N-ary predicate on a
        // 1-element slice is the pairwise `leq` verbatim, mirroring
        // `strictest_of(&[a]) == a`'s reduction on the combinator side.
        let cases: [(ResourceLimits, ResourceLimits); 6] = [
            (EMPTY_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS),
            (UNBOUNDED_RESOURCE_LIMITS, EMPTY_RESOURCE_LIMITS),
            (DEFAULT_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS),
            (UNBOUNDED_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS),
            (HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE),
            (HAND_AUTHORED_OTHER_POSTURE, HAND_AUTHORED_MID_POSTURE),
        ];
        for (a, b) in cases {
            assert_eq!(
                a.is_lower_bound_of(&[b]),
                a.leq(b),
                "1-input is_lower_bound_of must agree with pairwise leq for ({a:?}, {b:?})",
            );
        }
    }

    #[test]
    fn resource_limits_is_upper_bound_of_single_element_reduces_to_leq() {
        // 1-input dual identity — the singleton upper-bound predicate
        // is the pairwise `leq` with the direction flipped
        // (`b.leq(a)`), since `self` sits ABOVE the operand rather than
        // BELOW it.
        let cases: [(ResourceLimits, ResourceLimits); 6] = [
            (EMPTY_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS),
            (UNBOUNDED_RESOURCE_LIMITS, EMPTY_RESOURCE_LIMITS),
            (DEFAULT_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS),
            (UNBOUNDED_RESOURCE_LIMITS, DEFAULT_RESOURCE_LIMITS),
            (HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE),
            (HAND_AUTHORED_OTHER_POSTURE, HAND_AUTHORED_MID_POSTURE),
        ];
        for (a, b) in cases {
            assert_eq!(
                a.is_upper_bound_of(&[b]),
                b.leq(a),
                "1-input is_upper_bound_of must agree with pairwise leq(other, self) for ({a:?}, {b:?})",
            );
        }
    }

    #[test]
    fn resource_limits_is_lower_bound_of_holds_for_the_meet_of_the_slice() {
        // Definitional bridge — the N-ary meet is always a lower bound
        // of the slice it aggregates. Pins the link between the N-ary
        // COMBINATOR (`strictest_of`) and the N-ary PREDICATE
        // (`is_lower_bound_of`): the meet is an ELEMENT of the lower-
        // bound set the predicate CHARACTERIZES.
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        let met = ResourceLimits::strictest_of(&postures);
        assert!(met.is_lower_bound_of(&postures));
    }

    #[test]
    fn resource_limits_is_upper_bound_of_holds_for_the_join_of_the_slice() {
        // Dual definitional bridge — the N-ary join is always an upper
        // bound of the slice it aggregates.
        let postures: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        let joined = ResourceLimits::most_permissive_of(&postures);
        assert!(joined.is_upper_bound_of(&postures));
    }

    #[test]
    fn resource_limits_empty_is_universal_lower_bound_of_every_slice() {
        // Universal-bottom witness — the lattice bottom is a common
        // lower bound of every slice, since `EMPTY.leq(a) == true` for
        // every posture by the lattice-bottom axiom (`0 ≤ x` per-axis).
        // The bounded-lattice specialization of the general "the meet-
        // identity is a lower bound of every set" theorem.
        let postures: [ResourceLimits; 4] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ];
        assert!(EMPTY_RESOURCE_LIMITS.is_lower_bound_of(&postures));
        // The three preset-carried postures each individually — the
        // universal-bottom witness holds on the singleton slice too.
        assert!(EMPTY_RESOURCE_LIMITS.is_lower_bound_of(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(EMPTY_RESOURCE_LIMITS.is_lower_bound_of(&[UNBOUNDED_RESOURCE_LIMITS]));
        assert!(EMPTY_RESOURCE_LIMITS.is_lower_bound_of(&[HAND_AUTHORED_MID_POSTURE]));
    }

    #[test]
    fn resource_limits_unbounded_is_universal_upper_bound_of_every_slice() {
        // Universal-top witness — the lattice top is a common upper
        // bound of every slice, since `a.leq(UNBOUNDED) == true` for
        // every posture by the lattice-top axiom (`x ≤ usize::MAX`
        // per-axis).
        let postures: [ResourceLimits; 4] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ];
        assert!(UNBOUNDED_RESOURCE_LIMITS.is_upper_bound_of(&postures));
        assert!(UNBOUNDED_RESOURCE_LIMITS.is_upper_bound_of(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(UNBOUNDED_RESOURCE_LIMITS.is_upper_bound_of(&[EMPTY_RESOURCE_LIMITS]));
        assert!(UNBOUNDED_RESOURCE_LIMITS.is_upper_bound_of(&[HAND_AUTHORED_MID_POSTURE]));
    }

    #[test]
    fn resource_limits_is_lower_bound_of_rejects_when_any_operand_is_below_self() {
        // Any-operand short-circuit — if `self` fails `leq` against ANY
        // operand in the slice, the N-ary conjunction rejects. The dual
        // of the "meet is a lower bound" witness on the false side:
        // moving `self` STRICTLY ABOVE an operand on any axis costs the
        // lower-bound property.
        //
        // MID sits above the join (element-wise) on some axes and below
        // on others, so MID is NEITHER a lower bound of {MID, OTHER}
        // (fails against OTHER's smaller-axis values) NOR is OTHER a
        // lower bound of {MID, OTHER} (fails against MID's smaller-axis
        // values).
        assert!(!HAND_AUTHORED_MID_POSTURE
            .is_lower_bound_of(&[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE,]));
        assert!(!HAND_AUTHORED_OTHER_POSTURE
            .is_lower_bound_of(&[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE,]));
        // A UNIVERSAL rejection — the lattice top is a lower bound
        // ONLY of the empty set OR of slices whose every element equals
        // UNBOUNDED. Given a strictly-smaller preset in the slice, the
        // top's per-axis usize::MAX loses `leq` on every axis whose
        // preset value is strictly smaller.
        assert!(!UNBOUNDED_RESOURCE_LIMITS.is_lower_bound_of(&[EMPTY_RESOURCE_LIMITS]));
        assert!(!UNBOUNDED_RESOURCE_LIMITS.is_lower_bound_of(&[DEFAULT_RESOURCE_LIMITS]));
    }

    #[test]
    fn resource_limits_is_upper_bound_of_rejects_when_any_operand_is_above_self() {
        // Dual any-operand short-circuit — if ANY operand fails `leq`
        // against `self`, the N-ary conjunction rejects.
        assert!(!HAND_AUTHORED_MID_POSTURE
            .is_upper_bound_of(&[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE,]));
        assert!(!HAND_AUTHORED_OTHER_POSTURE
            .is_upper_bound_of(&[HAND_AUTHORED_MID_POSTURE, HAND_AUTHORED_OTHER_POSTURE,]));
        // The bottom cannot bound anything from above except the empty
        // set OR a slice of EMPTY-only postures.
        assert!(!EMPTY_RESOURCE_LIMITS.is_upper_bound_of(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(!EMPTY_RESOURCE_LIMITS.is_upper_bound_of(&[UNBOUNDED_RESOURCE_LIMITS]));
    }

    #[test]
    fn resource_limits_is_lower_bound_of_agrees_with_direct_all_leq_conjunction() {
        // Method-vs-scaffold cross-check — the lifted N-ary predicate
        // agrees with the pre-lift two-primitive
        // `postures.iter().all(|p| self.leq(*p))` scaffolding on every
        // preset-carried posture across the shipped bounded-lattice
        // extrema AND the two hand-authored asymmetric witnesses. Pins
        // the lift is a semantic no-op — post-lift the consumer routes
        // through ONE name instead of composing the conjunction inline,
        // but the two paths compute the same boolean.
        let candidates: [ResourceLimits; 5] = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ];
        let slice: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        for c in candidates {
            let direct = slice.iter().all(|p| c.leq(*p));
            assert_eq!(
                c.is_lower_bound_of(&slice),
                direct,
                "is_lower_bound_of must agree with iter().all(|p| self.leq(*p)) on candidate {c:?}",
            );
        }
    }

    #[test]
    fn resource_limits_is_upper_bound_of_agrees_with_direct_all_leq_conjunction() {
        // Dual method-vs-scaffold cross-check.
        let candidates: [ResourceLimits; 5] = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ];
        let slice: [ResourceLimits; 3] = [
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
            DEFAULT_RESOURCE_LIMITS,
        ];
        for c in candidates {
            let direct = slice.iter().all(|p| p.leq(c));
            assert_eq!(
                c.is_upper_bound_of(&slice),
                direct,
                "is_upper_bound_of must agree with iter().all(|p| p.leq(self)) on candidate {c:?}",
            );
        }
    }

    #[test]
    fn resource_limits_is_lower_bound_of_composes_at_compile_time_via_const_fn() {
        // Const-fn pin — the N-ary lower-bound predicate is evaluable
        // in const context, so a caller can pin an N-ary-bound-
        // membership identity at compile time. Sibling of the const-fn
        // evaluability pins on `leq` and `within` one PRIMITIVE-KIND
        // axis over, AND sibling of `strictest_of`'s const-fn pin one
        // COMBINATOR-KIND axis over.
        //
        // A regression to a runtime `fn` here would fail the `const _:
        // () = assert!(...)` bindings below at compile time.
        const _: () = assert!(EMPTY_RESOURCE_LIMITS
            .is_lower_bound_of(&[DEFAULT_RESOURCE_LIMITS, UNBOUNDED_RESOURCE_LIMITS]));
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.is_lower_bound_of(&[]));
        const _: () =
            assert!(!UNBOUNDED_RESOURCE_LIMITS.is_lower_bound_of(&[EMPTY_RESOURCE_LIMITS]));
    }

    #[test]
    fn resource_limits_is_upper_bound_of_composes_at_compile_time_via_const_fn() {
        // Const-fn dual pin.
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS
            .is_upper_bound_of(&[DEFAULT_RESOURCE_LIMITS, EMPTY_RESOURCE_LIMITS]));
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.is_upper_bound_of(&[]));
        const _: () =
            assert!(!EMPTY_RESOURCE_LIMITS.is_upper_bound_of(&[UNBOUNDED_RESOURCE_LIMITS]));
    }

    /// The full canonical preset roster the strict-order pins sweep
    /// through — the (bottom, middle, top) bounded-lattice preset
    /// triple plus the two hand-authored incomparable asymmetric
    /// postures. Every strict-order law below quantifies over this
    /// slice, so a regression that breaks strict `<` on any preset
    /// pair discriminates at ONE named fixture rather than at a
    /// per-test ad-hoc literal.
    const STRICT_ORDER_ROSTER: &[ResourceLimits] = &[
        EMPTY_RESOURCE_LIMITS,
        DEFAULT_RESOURCE_LIMITS,
        UNBOUNDED_RESOURCE_LIMITS,
        HAND_AUTHORED_MID_POSTURE,
        HAND_AUTHORED_OTHER_POSTURE,
    ];

    #[test]
    fn resource_limits_lt_is_irreflexive() {
        // Strict partial-order law — `a < a == false` for every
        // posture. Irreflexivity is the strict-relation axiom peer of
        // reflexivity on `leq` one STRICTNESS axis over on the
        // partial-order axiom surface; a regression that dropped the
        // antisymmetric leg (`!other.leq(self)`) — leaving the body at
        // `self.leq(other)` — would fire here on every preset since
        // `leq` is reflexive.
        for &a in STRICT_ORDER_ROSTER {
            assert!(!a.lt(a), "irreflexivity failed on {a:?}");
        }
    }

    #[test]
    fn resource_limits_lt_is_asymmetric() {
        // Strict partial-order law — `a < b ⇒ ¬(b < a)` for every
        // pair. The two directions of the strict relation cannot both
        // hold, since `a.lt(b)` implies `!b.leq(a)` and `b.lt(a)`
        // requires `b.leq(a)`. Sweeps every ordered pair in the
        // canonical preset roster; discriminates a regression that
        // dropped the antisymmetric leg in either direction.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                if a.lt(b) {
                    assert!(!b.lt(a), "asymmetry failed on ({a:?}, {b:?})");
                }
            }
        }
    }

    #[test]
    fn resource_limits_lt_is_transitive() {
        // Strict partial-order law — `a < b ∧ b < c ⇒ a < c`. Sweeps
        // every ordered triple in the canonical preset roster; each
        // consequence is checked whenever both antecedents hold. On
        // the (bottom, middle, top) diagonal the canonical witness
        // `EMPTY < DEFAULT < UNBOUNDED` composes to
        // `EMPTY < UNBOUNDED`, exercising the transitivity chain on
        // the bounded-lattice diagonal explicitly; the sweep pins the
        // same law on every other transitively-related triple in the
        // roster.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                for &c in STRICT_ORDER_ROSTER {
                    if a.lt(b) && b.lt(c) {
                        assert!(a.lt(c), "transitivity failed on ({a:?}, {b:?}, {c:?})");
                    }
                }
            }
        }
    }

    #[test]
    fn resource_limits_lt_refines_leq() {
        // Refinement axiom — `a < b ⇒ a ≤ b`. The strict relation is
        // a refinement of the non-strict one; a witness of strict `<`
        // is also a witness of `≤`. Sweeps every ordered pair in the
        // canonical preset roster.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                if a.lt(b) {
                    assert!(a.leq(b), "refinement failed on ({a:?}, {b:?})");
                }
            }
        }
    }

    #[test]
    fn resource_limits_lt_agrees_with_leq_minus_equality() {
        // Antisymmetry consequence — on ANY antisymmetric partial
        // order (which the pointwise `≤` on `ResourceLimits` is),
        // `a < b ⇔ a ≤ b ∧ a ≠ b`. Cross-checks the shipped
        // antisymmetric-leq encoding against the leq-and-not-equal
        // encoding across the full 5×5 preset matrix; a regression to
        // a non-antisymmetric preorder encoding would fire here.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let shipped = a.lt(b);
                let alt = a.leq(b) && a != b;
                assert_eq!(
                    shipped, alt,
                    "encoding cross-check failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_lt_of_bottom_diagonal_pinned() {
        // Concrete-preset pin — the strict chain across the (bottom,
        // middle, top) preset triple on the bounded-lattice diagonal.
        // Every `DEFAULT_MAX_*` module constant is a concrete positive
        // value strictly less than [`usize::MAX`] and strictly greater
        // than `0`, so on every axis the three endpoints are strictly
        // ordered; the six-axis pointwise conjunction lifts the
        // per-axis strict chain to the posture-level strict chain.
        //
        // Peer of `resource_limits_leq_of_default_and_unbounded_is_a_
        // strict_order` one STRICTNESS axis over — where the non-
        // strict pin asserted "leq holds one way and not the other"
        // via two `leq` calls, this pin asserts the strict-chain
        // conclusion via one `lt` call per link and pinpoints the
        // three-preset chain on the bounded-lattice diagonal.
        assert!(EMPTY_RESOURCE_LIMITS.lt(DEFAULT_RESOURCE_LIMITS));
        assert!(DEFAULT_RESOURCE_LIMITS.lt(UNBOUNDED_RESOURCE_LIMITS));
        assert!(EMPTY_RESOURCE_LIMITS.lt(UNBOUNDED_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_lt_rejects_incomparable_postures() {
        // Partial-order non-total pin — the two hand-authored
        // asymmetric postures have MID smaller on three axes and OTHER
        // smaller on the other three, so neither `leq` direction
        // holds; strict `<` therefore fails in BOTH directions. The
        // pin discriminates a regression that promoted strict `<`
        // from partial to total (e.g. treating incomparable pairs as
        // strictly `<` in some canonical direction), and pairs with
        // `resource_limits_leq_is_not_total_on_asymmetric_postures`
        // one STRICTNESS axis over.
        assert!(!HAND_AUTHORED_MID_POSTURE.lt(HAND_AUTHORED_OTHER_POSTURE));
        assert!(!HAND_AUTHORED_OTHER_POSTURE.lt(HAND_AUTHORED_MID_POSTURE));
    }

    #[test]
    fn resource_limits_lt_agrees_with_direct_antisymmetric_encoding() {
        // Direct-encoding cross-check — `a.lt(b) == (a.leq(b) &&
        // !b.leq(a))` at every pair by definition. Sibling of the
        // `leq_minus_equality` pin one ENCODING axis over: that pin
        // routes through the equality-based encoding (an
        // antisymmetry consequence), this pin routes through the
        // definitional antisymmetric-leq encoding. A regression that
        // shipped a different (e.g. axis-wise strict) encoding of
        // `lt` diverges from this cross-check on the incomparable
        // asymmetric-preset pair.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let shipped = a.lt(b);
                let direct = a.leq(b) && !b.leq(a);
                assert_eq!(
                    shipped, direct,
                    "direct-encoding cross-check failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_gt_is_dual_of_lt() {
        // Direction-flip pin — `a.gt(b) == b.lt(a)` at every pair. The
        // shipped `gt` body delegates to `lt` verbatim so this
        // agreement holds definitionally, but the pin discriminates a
        // regression that re-implemented `gt` independently and
        // dropped the direction flip. Sweeps the full 5×5 preset
        // matrix so incomparable + strictly-ordered + equal pairs
        // are all exercised.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                assert_eq!(a.gt(b), b.lt(a), "gt/lt duality failed on ({a:?}, {b:?})");
            }
        }
    }

    #[test]
    fn resource_limits_gt_of_top_diagonal_pinned() {
        // Concrete-preset pin — the strict chain across the (top,
        // middle, bottom) preset triple on the bounded-lattice
        // diagonal, walked in the "above" direction. Peer of
        // `resource_limits_lt_of_bottom_diagonal_pinned` one
        // DIRECTION axis over.
        assert!(UNBOUNDED_RESOURCE_LIMITS.gt(DEFAULT_RESOURCE_LIMITS));
        assert!(DEFAULT_RESOURCE_LIMITS.gt(EMPTY_RESOURCE_LIMITS));
        assert!(UNBOUNDED_RESOURCE_LIMITS.gt(EMPTY_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_gt_is_irreflexive() {
        // Strict partial-order law dual — `a > a == false` for every
        // posture. Inherits from the irreflexivity of `lt` via the
        // shipped `gt` body's delegation, but pinned explicitly so a
        // future non-delegating re-implementation of `gt` still has
        // its irreflexivity gated at the type-level test cohort.
        for &a in STRICT_ORDER_ROSTER {
            assert!(!a.gt(a), "irreflexivity failed on {a:?}");
        }
    }

    #[test]
    fn resource_limits_lt_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the strict `<` relation is evaluable in
        // const context, so a caller can pin a preset-strict-order
        // identity at compile time. Sibling of the const-fn
        // evaluability pin on `leq` one STRICTNESS axis over.
        //
        // A regression to a runtime `fn` here would fail the `const
        // _: () = assert!(...)` bindings below at compile time.
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.lt(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(DEFAULT_RESOURCE_LIMITS.lt(UNBOUNDED_RESOURCE_LIMITS));
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.lt(UNBOUNDED_RESOURCE_LIMITS));
        const _: () = assert!(!DEFAULT_RESOURCE_LIMITS.lt(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(!UNBOUNDED_RESOURCE_LIMITS.lt(EMPTY_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_gt_evaluates_at_compile_time_via_const_fn() {
        // Const-fn dual pin — sibling of `lt`'s const-fn pin one
        // DIRECTION axis over.
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.gt(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(DEFAULT_RESOURCE_LIMITS.gt(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.gt(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(!DEFAULT_RESOURCE_LIMITS.gt(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(!EMPTY_RESOURCE_LIMITS.gt(UNBOUNDED_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_geq_is_dual_of_leq() {
        // Direction-flip pin — `a.geq(b) == b.leq(a)` at every pair.
        // The shipped `geq` body delegates to `leq` verbatim so this
        // agreement holds definitionally, but the pin discriminates a
        // regression that re-implemented `geq` independently and
        // dropped the direction flip. Sweeps the full 5×5 preset
        // matrix so incomparable + strictly-ordered + equal pairs are
        // all exercised. Peer of `resource_limits_gt_is_dual_of_lt`
        // one STRICTNESS axis over on the (below, above) × (non-strict,
        // strict) 2×2 pairwise partial-order face.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                assert_eq!(
                    a.geq(b),
                    b.leq(a),
                    "geq/leq duality failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_geq_is_reflexive() {
        // Non-strict partial-order law — `a ≥ a == true` for every
        // posture. Reflexivity is the non-strict-relation axiom peer of
        // irreflexivity on `gt` one STRICTNESS axis over on the
        // partial-order axiom surface; a regression that hardened the
        // delegation into a strict `!other.leq(self)` would fire here
        // on every preset since the reflexive pair collapses.
        for &a in STRICT_ORDER_ROSTER {
            assert!(a.geq(a), "reflexivity failed on {a:?}");
        }
    }

    #[test]
    fn resource_limits_geq_is_antisymmetric() {
        // Non-strict partial-order law — `a ≥ b ∧ b ≥ a ⇒ a == b`.
        // Antisymmetry is inherited from `leq` via the shipped `geq`
        // body's `other.leq(self)` delegation (which combined with
        // `b.geq(a)` — i.e. `a.leq(b)` — gives `leq` antisymmetry on
        // the pair). Sweeps the full 5×5 preset matrix; the pin fires
        // on any regression that let two DISTINCT postures satisfy
        // `geq` in both directions.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                if a.geq(b) && b.geq(a) {
                    assert_eq!(a, b, "antisymmetry failed on ({a:?}, {b:?})");
                }
            }
        }
    }

    #[test]
    fn resource_limits_geq_is_transitive() {
        // Non-strict partial-order law — `a ≥ b ∧ b ≥ c ⇒ a ≥ c`.
        // Inherits from the transitivity of `leq` via the shipped
        // delegation; sweeps every ordered triple in the canonical
        // preset roster. Peer of `resource_limits_lt_is_transitive`
        // one STRICTNESS axis over and `resource_limits_leq_is_
        // transitive` one DIRECTION axis over.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                for &c in STRICT_ORDER_ROSTER {
                    if a.geq(b) && b.geq(c) {
                        assert!(a.geq(c), "transitivity failed on ({a:?}, {b:?}, {c:?})");
                    }
                }
            }
        }
    }

    #[test]
    fn resource_limits_geq_refines_gt() {
        // Refinement axiom peer — `a > b ⇒ a ≥ b`. The strict
        // relation is a refinement of the non-strict one in the
        // "above" direction, exactly as `lt` refines `leq` in the
        // "below" direction (pinned by
        // `resource_limits_lt_refines_leq` one DIRECTION axis over).
        // A witness of strict `>` is also a witness of `≥`.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                if a.gt(b) {
                    assert!(a.geq(b), "refinement failed on ({a:?}, {b:?})");
                }
            }
        }
    }

    #[test]
    fn resource_limits_geq_agrees_with_gt_plus_equality() {
        // Antisymmetry consequence peer — on ANY antisymmetric partial
        // order, `a ≥ b ⇔ a > b ∨ a == b`. Cross-checks the shipped
        // delegation against the strict-or-equal encoding across the
        // full 5×5 preset matrix; a regression that shipped a non-
        // antisymmetric preorder encoding for `geq` fires here. Peer
        // of `resource_limits_lt_agrees_with_leq_minus_equality` one
        // DIRECTION-AND-STRICTNESS axis over.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let shipped = a.geq(b);
                let alt = a.gt(b) || a == b;
                assert_eq!(
                    shipped, alt,
                    "encoding cross-check failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_geq_of_top_diagonal_pinned() {
        // Concrete-preset pin — the non-strict chain across the (top,
        // middle, bottom) preset triple on the bounded-lattice
        // diagonal, walked in the "above" direction. Peer of
        // `resource_limits_gt_of_top_diagonal_pinned` one STRICTNESS
        // axis over: the non-strict pin also holds at the reflexive
        // diagonal, so every posture sits above ITSELF via `geq` in
        // addition to sitting above the strictly-tighter presets.
        assert!(UNBOUNDED_RESOURCE_LIMITS.geq(DEFAULT_RESOURCE_LIMITS));
        assert!(DEFAULT_RESOURCE_LIMITS.geq(EMPTY_RESOURCE_LIMITS));
        assert!(UNBOUNDED_RESOURCE_LIMITS.geq(EMPTY_RESOURCE_LIMITS));
        assert!(EMPTY_RESOURCE_LIMITS.geq(EMPTY_RESOURCE_LIMITS));
        assert!(DEFAULT_RESOURCE_LIMITS.geq(DEFAULT_RESOURCE_LIMITS));
        assert!(UNBOUNDED_RESOURCE_LIMITS.geq(UNBOUNDED_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_geq_rejects_incomparable_postures() {
        // Partial-order non-total pin — the two hand-authored
        // asymmetric postures have MID smaller on three axes and OTHER
        // smaller on the other three, so neither `leq` direction holds
        // and therefore neither `geq` direction holds. The pin
        // discriminates a regression that promoted `geq` from partial
        // to total, and pairs with
        // `resource_limits_lt_rejects_incomparable_postures` one
        // STRICTNESS-AND-DIRECTION axis over.
        assert!(!HAND_AUTHORED_MID_POSTURE.geq(HAND_AUTHORED_OTHER_POSTURE));
        assert!(!HAND_AUTHORED_OTHER_POSTURE.geq(HAND_AUTHORED_MID_POSTURE));
    }

    #[test]
    fn resource_limits_geq_agrees_with_is_upper_bound_of_singleton() {
        // Arity-reduction pin — `a.geq(b) == a.is_upper_bound_of(&[b])`
        // at every pair. The pairwise "above" relation is exactly the
        // 1-input specialization of the N-ary upper-bound predicate;
        // the pin cross-checks that the two named entries agree on
        // the single-element case, which discriminates a regression
        // that drifted one from the other. Peer of the single-element
        // identity docstring on `is_upper_bound_of` one ARITY axis
        // over.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                assert_eq!(
                    a.geq(b),
                    a.is_upper_bound_of(&[b]),
                    "arity-reduction failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_geq_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the non-strict `≥` relation is evaluable in
        // const context, so a caller can pin a preset-non-strict-order
        // identity at compile time. Sibling of the const-fn evaluability
        // pins on `leq` one DIRECTION axis over AND on `gt` one
        // STRICTNESS axis over.
        //
        // A regression to a runtime `fn` here would fail the `const _:
        // () = assert!(...)` bindings below at compile time.
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.geq(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(DEFAULT_RESOURCE_LIMITS.geq(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.geq(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(DEFAULT_RESOURCE_LIMITS.geq(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(!EMPTY_RESOURCE_LIMITS.geq(UNBOUNDED_RESOURCE_LIMITS));
    }

    #[test]
    fn resource_limits_is_incomparable_is_irreflexive() {
        // Antichain-corner reflexivity pin — `a.is_incomparable(a) ==
        // false` on every posture. Every posture is COMPARABLE to
        // itself via `leq`'s reflexivity (`a.leq(a) == true`), so the
        // conjunction's `!self.leq(other)` leg forces the verdict to
        // `false` at every diagonal input. Discriminates a regression
        // that dropped the `!` on `self.leq(other)` (leaving the body
        // at `self.leq(other) && !self.geq(other)`) — that would fold
        // the diagonal to `false` on the reflexive `leq` arm but
        // silently flip the antichain corner on non-diagonal cells.
        for &a in STRICT_ORDER_ROSTER {
            assert!(!a.is_incomparable(a), "irreflexivity failed on {a:?}");
        }
    }

    #[test]
    fn resource_limits_is_incomparable_is_symmetric() {
        // Antichain-corner symmetry pin — `a.is_incomparable(b) ==
        // b.is_incomparable(a)` on every pair. The composition
        // `!self.leq(other) && !self.geq(other)` folds through the
        // `self.leq(other) == other.geq(self)` dual identity on `geq`
        // and the conjunction's commutativity into an order-
        // independent projection on its two inputs. Sweeps every
        // ordered pair in the canonical preset roster;
        // discriminates a regression that broke either leg's dual
        // identity — one direction would fold to `false` on cells the
        // other still folded to `true`.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                assert_eq!(
                    a.is_incomparable(b),
                    b.is_incomparable(a),
                    "symmetry failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_incomparable_is_de_morgan_dual_of_comparable() {
        // De Morgan dual pin — `a.is_incomparable(b) == !(a.leq(b) ||
        // a.geq(b))` on every pair. The antichain corner is the SET-
        // COMPLEMENT of the union of the two pointwise-domination
        // directions on the (comparable, incomparable) two-cell
        // partition of the ordered pair × verdict surface. Sweeps
        // every ordered pair in the canonical preset roster;
        // discriminates a regression that drifted the antichain
        // characterization off the substrate's `!leq && !geq`
        // composition (e.g., a shortcut through `!self.leq(other) ||
        // !self.geq(other)` — the OR-form falsely reports
        // incomparability on non-equal comparable pairs).
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_named = a.is_incomparable(b);
                let via_composition = !(a.leq(b) || a.geq(b));
                assert_eq!(
                    via_named, via_composition,
                    "De Morgan dual failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_incomparable_partitions_ordered_pair_surface_with_comparable() {
        // Two-cell partition pin — on every ordered pair EITHER
        // (a.leq(b) || a.geq(b)) OR a.is_incomparable(b), and NEVER
        // both. The (comparable, incomparable) partition of the
        // ordered pair × verdict surface is exhaustive-and-disjoint —
        // a substrate-level EXCLUSIVITY THEOREM the projection pins
        // once. Sweeps every ordered pair in the canonical preset
        // roster; discriminates a regression that let the two cells
        // overlap (e.g., an implementation that reported the antichain
        // corner as `true` on the comparable diagonal).
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let comparable = a.leq(b) || a.geq(b);
                let incomparable = a.is_incomparable(b);
                assert!(
                    comparable != incomparable,
                    "partition failed on ({a:?}, {b:?}): comparable={comparable}, incomparable={incomparable}",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_incomparable_folds_false_at_the_bottom_pole() {
        // Bottom-pole absorption pin — `a.is_incomparable(
        // EMPTY_RESOURCE_LIMITS) == false` on every posture `a`.
        // `EMPTY_RESOURCE_LIMITS` is the bounded-lattice bottom, so
        // `EMPTY.leq(a)` holds on every axis (usize zero is the
        // minimum), which gives `a.geq(EMPTY)` through the `geq`
        // dual identity, which falsifies the `!self.geq(other)` leg.
        // Sweeps the canonical preset roster; pairs with the top-
        // pole absorption sibling one POLE axis over.
        for &a in STRICT_ORDER_ROSTER {
            assert!(
                !a.is_incomparable(EMPTY_RESOURCE_LIMITS),
                "bottom-pole absorption failed on {a:?}",
            );
            assert!(
                !EMPTY_RESOURCE_LIMITS.is_incomparable(a),
                "bottom-pole absorption failed on flipped ({a:?}, EMPTY)",
            );
        }
    }

    #[test]
    fn resource_limits_is_incomparable_folds_false_at_the_top_pole() {
        // Top-pole absorption pin — `a.is_incomparable(
        // UNBOUNDED_RESOURCE_LIMITS) == false` on every posture `a`.
        // `UNBOUNDED_RESOURCE_LIMITS` is the bounded-lattice top, so
        // `a.leq(UNBOUNDED)` holds on every axis (`a.max_* <=
        // usize::MAX` unconditionally), which falsifies the
        // `!self.leq(other)` leg. Sweeps the canonical preset
        // roster; pairs with the bottom-pole absorption sibling one
        // POLE axis over.
        for &a in STRICT_ORDER_ROSTER {
            assert!(
                !a.is_incomparable(UNBOUNDED_RESOURCE_LIMITS),
                "top-pole absorption failed on {a:?}",
            );
            assert!(
                !UNBOUNDED_RESOURCE_LIMITS.is_incomparable(a),
                "top-pole absorption failed on flipped ({a:?}, UNBOUNDED)",
            );
        }
    }

    #[test]
    fn resource_limits_is_incomparable_holds_on_the_hand_authored_antichain_pair() {
        // Antichain load-bearing arm — the two hand-authored
        // asymmetric postures sit on distinct branches (each is
        // smaller on three axes and larger on the other three), so
        // neither pointwise-domination direction closes and the
        // antichain verdict HOLDS in both orderings. Pairs with
        // `resource_limits_geq_rejects_incomparable_postures` +
        // `resource_limits_lt_rejects_incomparable_postures` one COVER
        // axis over: those pin the two comparable-direction predicates
        // FALSIFY on this pair; THIS pin confirms the antichain
        // verdict HOLDS on the SAME pair — the two are the negation-
        // paired sides of the (comparable, incomparable) two-cell
        // partition.
        assert!(
            HAND_AUTHORED_MID_POSTURE.is_incomparable(HAND_AUTHORED_OTHER_POSTURE),
            "antichain arm failed on (MID, OTHER)",
        );
        assert!(
            HAND_AUTHORED_OTHER_POSTURE.is_incomparable(HAND_AUTHORED_MID_POSTURE),
            "antichain arm failed on flipped (OTHER, MID)",
        );
    }

    #[test]
    fn resource_limits_is_incomparable_folds_false_on_the_shipped_preset_triangle() {
        // Shipped preset comparability pin — every ordered pair drawn
        // from the (EMPTY, DEFAULT, UNBOUNDED) shipped preset triangle
        // is COMPARABLE (in both directions the pairwise partial-order
        // relation gives a verdict). The three shipped presets form a
        // TOTALLY ORDERED chain on the pointwise partial-order (EMPTY
        // <= DEFAULT <= UNBOUNDED on every field), so the antichain
        // corner MUST fold to `false` on every ordered pair drawn from
        // them. Discriminates a regression that promoted a shipped
        // preset off the total-order chain by drifting ONE field
        // silently.
        const TRIANGLE: &[ResourceLimits] = &[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ];
        for &a in TRIANGLE {
            for &b in TRIANGLE {
                assert!(
                    !a.is_incomparable(b),
                    "shipped preset triangle comparability failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_incomparable_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the antichain characterization is evaluable
        // in const context, so a caller can pin an antichain-
        // disagreement identity at compile time. Sibling of the
        // const-fn evaluability pins on `leq` / `geq` / `lt` / `gt`
        // one COVER axis over on the pairwise-relation surface.
        //
        // A regression to a runtime `fn` here would fail the `const _:
        // () = assert!(...)` bindings below at compile time.
        const _: () = assert!(!EMPTY_RESOURCE_LIMITS.is_incomparable(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(!DEFAULT_RESOURCE_LIMITS.is_incomparable(DEFAULT_RESOURCE_LIMITS));
        const _: () =
            assert!(!UNBOUNDED_RESOURCE_LIMITS.is_incomparable(UNBOUNDED_RESOURCE_LIMITS));
        const _: () = assert!(!EMPTY_RESOURCE_LIMITS.is_incomparable(UNBOUNDED_RESOURCE_LIMITS));
        const _: () = assert!(!UNBOUNDED_RESOURCE_LIMITS.is_incomparable(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(!DEFAULT_RESOURCE_LIMITS.is_incomparable(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(!UNBOUNDED_RESOURCE_LIMITS.is_incomparable(DEFAULT_RESOURCE_LIMITS));
    }

    // ── ResourceLimits::is_comparable ─────────────────────────────────
    //
    // The COMPARABLE CORNER on the pairwise-relation surface — the
    // DIRECT POSITIVE DUAL of `is_incomparable` one COVER-COMPLEMENT
    // axis over on the (comparable, incomparable) two-cell partition
    // of the ordered pair × verdict surface. See `ResourceLimits::is_comparable`
    // for the algebra; the pins below fix each documented property
    // exactly once so a regression on any leg fires on a NAMED test
    // rather than an ad-hoc downstream break.

    #[test]
    fn resource_limits_is_comparable_is_reflexive() {
        // Comparable-corner reflexivity pin — `a.is_comparable(a) ==
        // true` on every posture. Every posture is COMPARABLE to
        // itself via `leq`'s reflexivity (`a.leq(a) == true`), so
        // the disjunction's `self.leq(other)` leg holds at every
        // diagonal input. Sibling of `is_incomparable`'s
        // irreflexivity one CELL axis over on the (comparable,
        // incomparable) partition — the diagonal MUST fold to `true`
        // here iff it folds to `false` there.
        for &a in STRICT_ORDER_ROSTER {
            assert!(a.is_comparable(a), "reflexivity failed on {a:?}");
        }
    }

    #[test]
    fn resource_limits_is_comparable_is_symmetric() {
        // Comparable-corner symmetry pin — `a.is_comparable(b) ==
        // b.is_comparable(a)` on every pair. The composition
        // `self.leq(other) || self.geq(other)` folds through the
        // `self.leq(other) == other.geq(self)` dual identity on
        // `geq` and the disjunction's commutativity into an order-
        // independent projection on its two inputs. Both cells of an
        // EXHAUSTIVE-AND-DISJOINT partition of a symmetric surface
        // must themselves be symmetric — the two verdicts flip in
        // lockstep on argument swap.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                assert_eq!(
                    a.is_comparable(b),
                    b.is_comparable(a),
                    "symmetry failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_comparable_is_de_morgan_dual_of_incomparable() {
        // De Morgan dual pin — `a.is_comparable(b) ==
        // !a.is_incomparable(b)` on every pair. The comparable corner
        // is the SET-COMPLEMENT of the antichain corner on the
        // (comparable, incomparable) two-cell partition of the
        // ordered pair × verdict surface. The DIRECT dual of
        // `resource_limits_is_incomparable_is_de_morgan_dual_of_comparable`
        // one CELL axis over: that test pins the antichain corner as
        // the negation of the `leq || geq` disjunction; THIS test
        // pins the comparability corner as the negation of the
        // antichain projection. Together the two pin BOTH SIDES of
        // the partition, closing it as a substrate-level
        // EXCLUSIVITY-AND-EXHAUSTIVENESS THEOREM.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_named = a.is_comparable(b);
                let via_negated_dual = !a.is_incomparable(b);
                assert_eq!(
                    via_named, via_negated_dual,
                    "De Morgan dual failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_comparable_agrees_with_leq_or_geq_composition() {
        // Direct composition pin — `a.is_comparable(b) == a.leq(b) ||
        // a.geq(b)` on every pair. Discriminates a regression that
        // drifted the comparability body off the substrate's `leq ||
        // geq` composition (e.g., a shortcut through `a.leq(b) &&
        // a.geq(b)` — the AND-form falsely reports comparability
        // only on the equality diagonal, dropping the strict-order
        // cells). Anchors the two-primitive delegation as a
        // substrate-level identity.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_named = a.is_comparable(b);
                let via_composition = a.leq(b) || a.geq(b);
                assert_eq!(
                    via_named, via_composition,
                    "leq||geq composition failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_comparable_folds_true_at_the_bottom_pole() {
        // Bottom-pole absorption pin — `a.is_comparable(
        // EMPTY_RESOURCE_LIMITS) == true` on every posture `a`.
        // `EMPTY_RESOURCE_LIMITS` is the bounded-lattice bottom, so
        // `EMPTY.leq(a)` holds on every axis (`usize` zero is the
        // minimum), which gives `a.geq(EMPTY)` through the `geq`
        // dual identity, which satisfies the `self.geq(other)` leg.
        // The DIRECT COMPLEMENT of
        // `resource_limits_is_incomparable_folds_false_at_the_bottom_pole`
        // one CELL axis over on the SAME preset roster — where the
        // antichain verdict FOLDS FALSE at the bottom pole, the
        // comparability verdict FOLDS TRUE.
        for &a in STRICT_ORDER_ROSTER {
            assert!(
                a.is_comparable(EMPTY_RESOURCE_LIMITS),
                "bottom-pole absorption failed on {a:?}",
            );
            assert!(
                EMPTY_RESOURCE_LIMITS.is_comparable(a),
                "bottom-pole absorption failed on flipped ({a:?}, EMPTY)",
            );
        }
    }

    #[test]
    fn resource_limits_is_comparable_folds_true_at_the_top_pole() {
        // Top-pole absorption pin — `a.is_comparable(
        // UNBOUNDED_RESOURCE_LIMITS) == true` on every posture `a`.
        // `UNBOUNDED_RESOURCE_LIMITS` is the bounded-lattice top, so
        // `a.leq(UNBOUNDED)` holds on every axis (`a.max_* <=
        // usize::MAX` unconditionally), which satisfies the
        // `self.leq(other)` leg. The DIRECT COMPLEMENT of
        // `resource_limits_is_incomparable_folds_false_at_the_top_pole`
        // one CELL axis over on the SAME preset roster.
        for &a in STRICT_ORDER_ROSTER {
            assert!(
                a.is_comparable(UNBOUNDED_RESOURCE_LIMITS),
                "top-pole absorption failed on {a:?}",
            );
            assert!(
                UNBOUNDED_RESOURCE_LIMITS.is_comparable(a),
                "top-pole absorption failed on flipped ({a:?}, UNBOUNDED)",
            );
        }
    }

    #[test]
    fn resource_limits_is_comparable_falsifies_on_the_hand_authored_antichain_pair() {
        // Antichain load-bearing arm — the two hand-authored
        // asymmetric postures sit on distinct branches (each is
        // smaller on three axes and larger on the other three), so
        // NEITHER pointwise-domination direction closes and the
        // comparability verdict FALSIFIES in both orderings. The
        // DIRECT NEGATION of
        // `resource_limits_is_incomparable_holds_on_the_hand_authored_antichain_pair`
        // one CELL axis over on the SAME hand-authored pair — the
        // two are the negation-paired sides of the (comparable,
        // incomparable) two-cell partition, and pinning BOTH cells'
        // verdicts on the SAME load-bearing antichain pair closes
        // the partition as a substrate-level EXCLUSIVITY THEOREM.
        assert!(
            !HAND_AUTHORED_MID_POSTURE.is_comparable(HAND_AUTHORED_OTHER_POSTURE),
            "antichain arm failed on (MID, OTHER)",
        );
        assert!(
            !HAND_AUTHORED_OTHER_POSTURE.is_comparable(HAND_AUTHORED_MID_POSTURE),
            "antichain arm failed on flipped (OTHER, MID)",
        );
    }

    #[test]
    fn resource_limits_is_comparable_holds_on_the_shipped_preset_triangle() {
        // Shipped preset comparability pin — every ordered pair
        // drawn from the (EMPTY, DEFAULT, UNBOUNDED) shipped preset
        // triangle is COMPARABLE (in at least one direction the
        // pairwise partial-order relation gives a verdict). The
        // three shipped presets form a TOTALLY ORDERED chain on the
        // pointwise partial-order (EMPTY <= DEFAULT <= UNBOUNDED on
        // every field), so the comparability corner MUST fold to
        // `true` on every ordered pair drawn from them. The DIRECT
        // COMPLEMENT of
        // `resource_limits_is_incomparable_folds_false_on_the_shipped_preset_triangle`
        // one CELL axis over on the SAME triangle. Discriminates a
        // regression that promoted a shipped preset off the total-
        // order chain by drifting ONE field silently.
        const TRIANGLE: &[ResourceLimits] = &[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ];
        for &a in TRIANGLE {
            for &b in TRIANGLE {
                assert!(
                    a.is_comparable(b),
                    "shipped preset triangle comparability failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_comparable_partitions_ordered_pair_surface_exhaustively() {
        // Exhaustive-and-disjoint partition pin — on every ordered
        // pair EXACTLY ONE of `a.is_comparable(b)` OR
        // `a.is_incomparable(b)` holds. The (comparable,
        // incomparable) partition of the ordered pair × verdict
        // surface is exhaustive-and-disjoint — a substrate-level
        // EXCLUSIVITY-AND-EXHAUSTIVENESS THEOREM the two projections
        // together pin. Complements
        // `resource_limits_is_incomparable_partitions_ordered_pair_surface_with_comparable`
        // one CELL axis over: that test pins the partition against
        // the raw `a.leq(b) || a.geq(b)` composition; THIS test pins
        // the partition against the NAMED comparability projection —
        // a regression that drifted `is_comparable` off the
        // composition without breaking the composition-based test
        // would still fire here.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let comparable = a.is_comparable(b);
                let incomparable = a.is_incomparable(b);
                assert!(
                    comparable != incomparable,
                    "partition failed on ({a:?}, {b:?}): comparable={comparable}, incomparable={incomparable}",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_comparable_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the comparability characterization is
        // evaluable in const context, so a caller can pin a
        // comparability-agreement identity at compile time. Sibling
        // of the const-fn evaluability pins on `leq` / `geq` / `lt`
        // / `gt` / `is_incomparable` one COVER axis over on the
        // pairwise-relation surface.
        //
        // A regression to a runtime `fn` here would fail the `const _:
        // () = assert!(...)` bindings below at compile time.
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.is_comparable(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(DEFAULT_RESOURCE_LIMITS.is_comparable(DEFAULT_RESOURCE_LIMITS));
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.is_comparable(UNBOUNDED_RESOURCE_LIMITS));
        const _: () = assert!(EMPTY_RESOURCE_LIMITS.is_comparable(UNBOUNDED_RESOURCE_LIMITS));
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.is_comparable(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(DEFAULT_RESOURCE_LIMITS.is_comparable(EMPTY_RESOURCE_LIMITS));
        const _: () = assert!(UNBOUNDED_RESOURCE_LIMITS.is_comparable(DEFAULT_RESOURCE_LIMITS));
    }

    // ── ResourceLimits::partial_cmp ───────────────────────────────────
    //
    // The `Option<Ordering>` FULL-VERDICT corner on the pairwise-
    // relation surface — the JOINT LIFT of the (comparable, incomparable)
    // two-cell partition together with the ordering-direction refinement
    // on the comparable arm. See `ResourceLimits::partial_cmp` for the
    // algebra; the pins below fix each documented property exactly once
    // so a regression on any leg fires on a NAMED test rather than an
    // ad-hoc downstream break.

    #[test]
    fn resource_limits_partial_cmp_is_equal_on_the_diagonal() {
        // Diagonal-equality pin — `a.partial_cmp(a) ==
        // Some(Ordering::Equal)` on every posture. The `leq`
        // reflexivity closes both arms of the equality-guarding
        // conjunction, so the diagonal cell of the (Less, Equal,
        // Greater, None) 4-tile partition pins to the Equal tile.
        // Sibling of `is_comparable_is_reflexive` one PROJECTION
        // axis over — where the projection folds TRUE at the
        // diagonal, THIS method refines the verdict to `Equal`.
        for &a in STRICT_ORDER_ROSTER {
            assert_eq!(
                a.partial_cmp(a),
                Some(Ordering::Equal),
                "diagonal-equality failed on {a:?}",
            );
        }
    }

    #[test]
    fn resource_limits_partial_cmp_reverses_under_argument_swap() {
        // Antisymmetric-swap pin — `a.partial_cmp(b) ==
        // b.partial_cmp(a).map(Ordering::reverse)` on every pair.
        // Swapping the argument pair FLIPS the ordering-direction
        // verdict (`Less <-> Greater`), fixes the diagonal-equality
        // arm, and fixes the antichain arm. Discriminates
        // `is_incomparable` / `is_comparable` (both SYMMETRIC on
        // argument swap) one POSTURE axis over — the FULL verdict
        // carries directional content that inverts under swap where
        // the projections do not.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let forward = a.partial_cmp(b);
                let swapped_reversed = b.partial_cmp(a).map(Ordering::reverse);
                assert_eq!(
                    forward, swapped_reversed,
                    "swap-reverse failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_partial_cmp_none_iff_incomparable() {
        // Antichain-arm identity pin — `a.partial_cmp(b).is_none()
        // == a.is_incomparable(b)` on every pair. The `None` arm of
        // the return coincides EXACTLY with the antichain-corner
        // projection. Anchors the joint-lift claim: THIS method
        // subsumes `is_incomparable` at its `is_none()` projection
        // without drifting the antichain characterization.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_partial_cmp = a.partial_cmp(b).is_none();
                let via_is_incomparable = a.is_incomparable(b);
                assert_eq!(
                    via_partial_cmp, via_is_incomparable,
                    "none-iff-incomparable failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_partial_cmp_some_iff_comparable() {
        // Comparability-arm identity pin — `a.partial_cmp(b).is_some()
        // == a.is_comparable(b)` on every pair. The `Some(_)` arm of
        // the return coincides EXACTLY with the comparability-corner
        // projection. The DUAL of the antichain-arm pin one CELL axis
        // over on the (comparable, incomparable) partition — together
        // the two pins close the JOINT LIFT of both cells at THIS
        // method.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_partial_cmp = a.partial_cmp(b).is_some();
                let via_is_comparable = a.is_comparable(b);
                assert_eq!(
                    via_partial_cmp, via_is_comparable,
                    "some-iff-comparable failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_partial_cmp_less_iff_lt() {
        // Strict-less agreement pin — `a.partial_cmp(b) ==
        // Some(Ordering::Less)` iff `a.lt(b)`. The strict-less arm of
        // the (Less, Equal, Greater, None) 4-tile partition binds to
        // the named `lt` companion primitive at exactly one dispatch
        // site. A regression that drifted the arm off `lt` (e.g., to
        // `leq` — including the equality diagonal) would fire here.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_partial_cmp = a.partial_cmp(b) == Some(Ordering::Less);
                let via_lt = a.lt(b);
                assert_eq!(
                    via_partial_cmp, via_lt,
                    "less-iff-lt failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_partial_cmp_greater_iff_gt() {
        // Strict-greater agreement pin — `a.partial_cmp(b) ==
        // Some(Ordering::Greater)` iff `a.gt(b)`. Dual of the strict-
        // less agreement pin one DIRECTION axis over on the (Less,
        // Greater) strict-order pair — a regression that dropped the
        // asymmetry between the two arms (e.g., collapsed both to
        // `Less`) would fire here.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_partial_cmp = a.partial_cmp(b) == Some(Ordering::Greater);
                let via_gt = a.gt(b);
                assert_eq!(
                    via_partial_cmp, via_gt,
                    "greater-iff-gt failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_partial_cmp_equal_iff_eq() {
        // Equality agreement pin — `a.partial_cmp(b) ==
        // Some(Ordering::Equal)` iff `a == b`. The equality arm of the
        // 4-tile partition binds through the pointwise antisymmetric-
        // equality characterization (`a.leq(b) && b.leq(a) → a == b`,
        // pinned by `resource_limits_leq_is_antisymmetric`) to the
        // `PartialEq::eq` companion. Discriminates a regression that
        // drifted the Equal arm off the antisymmetric conjunction.
        for &a in STRICT_ORDER_ROSTER {
            for &b in STRICT_ORDER_ROSTER {
                let via_partial_cmp = a.partial_cmp(b) == Some(Ordering::Equal);
                let via_eq = a == b;
                assert_eq!(
                    via_partial_cmp, via_eq,
                    "equal-iff-eq failed on ({a:?}, {b:?})",
                );
            }
        }
    }

    #[test]
    fn resource_limits_partial_cmp_folds_less_ascending_shipped_preset_chain() {
        // Bottom-to-top-pole ordering pin — every strictly-ascending
        // pair on the shipped preset chain (EMPTY <= DEFAULT <=
        // UNBOUNDED) folds to `Some(Ordering::Less)`. The three
        // shipped presets form a TOTALLY ORDERED chain on the
        // pointwise partial-order (every DEFAULT_MAX_* is a concrete
        // positive value strictly less than usize::MAX), so the
        // strict-less arm fires on every ordered pair drawn in
        // ascending direction.
        assert_eq!(
            EMPTY_RESOURCE_LIMITS.partial_cmp(DEFAULT_RESOURCE_LIMITS),
            Some(Ordering::Less),
        );
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.partial_cmp(UNBOUNDED_RESOURCE_LIMITS),
            Some(Ordering::Less),
        );
        assert_eq!(
            EMPTY_RESOURCE_LIMITS.partial_cmp(UNBOUNDED_RESOURCE_LIMITS),
            Some(Ordering::Less),
        );
    }

    #[test]
    fn resource_limits_partial_cmp_folds_greater_descending_shipped_preset_chain() {
        // Top-to-bottom-pole ordering pin — every strictly-descending
        // pair on the shipped preset chain folds to
        // `Some(Ordering::Greater)`. The DUAL of the ascending pin
        // one DIRECTION axis over — together the two pins close the
        // (ascending, descending) direction pair on the shipped
        // preset chain at the ordering-direction refinement.
        assert_eq!(
            DEFAULT_RESOURCE_LIMITS.partial_cmp(EMPTY_RESOURCE_LIMITS),
            Some(Ordering::Greater),
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.partial_cmp(DEFAULT_RESOURCE_LIMITS),
            Some(Ordering::Greater),
        );
        assert_eq!(
            UNBOUNDED_RESOURCE_LIMITS.partial_cmp(EMPTY_RESOURCE_LIMITS),
            Some(Ordering::Greater),
        );
    }

    #[test]
    fn resource_limits_partial_cmp_folds_none_on_the_hand_authored_antichain_pair() {
        // Antichain load-bearing arm — the two hand-authored
        // asymmetric postures sit on distinct branches (each is
        // smaller on three axes and larger on the other three), so
        // NEITHER pointwise-domination direction closes and the
        // fall-through `None` arm fires in both orderings. The DIRECT
        // LIFT of `is_incomparable_holds_on_the_hand_authored_antichain_pair`
        // one PROJECTION axis over on the SAME hand-authored pair —
        // where the projection folds TRUE, THIS method folds to
        // `None`. The two are the negation-paired sides of the
        // (Some(_), None) two-cell partition of `Option<Ordering>`.
        assert_eq!(
            HAND_AUTHORED_MID_POSTURE.partial_cmp(HAND_AUTHORED_OTHER_POSTURE),
            None,
        );
        assert_eq!(
            HAND_AUTHORED_OTHER_POSTURE.partial_cmp(HAND_AUTHORED_MID_POSTURE),
            None,
        );
    }

    #[test]
    fn resource_limits_partial_cmp_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the full-verdict projection is evaluable in
        // const context, so a caller can pin an ordering-direction
        // identity at compile time. Sibling of the const-fn
        // evaluability pins on `leq` / `geq` / `lt` / `gt` /
        // `is_incomparable` / `is_comparable` one COVER axis over on
        // the pairwise-relation surface.
        //
        // `matches!` in const context requires the pattern's variants
        // to be const-constructible — `Ordering::Less` / `Equal` /
        // `Greater` are plain enum constructors, so the assertions
        // below stay inside stable const-fn scope. A regression to a
        // runtime `fn` here would fail the `const _: () = assert!(
        // matches!(...))` bindings below at compile time.
        const _: () = assert!(matches!(
            EMPTY_RESOURCE_LIMITS.partial_cmp(EMPTY_RESOURCE_LIMITS),
            Some(Ordering::Equal),
        ));
        const _: () = assert!(matches!(
            EMPTY_RESOURCE_LIMITS.partial_cmp(UNBOUNDED_RESOURCE_LIMITS),
            Some(Ordering::Less),
        ));
        const _: () = assert!(matches!(
            UNBOUNDED_RESOURCE_LIMITS.partial_cmp(EMPTY_RESOURCE_LIMITS),
            Some(Ordering::Greater),
        ));
        const _: () = assert!(matches!(
            DEFAULT_RESOURCE_LIMITS.partial_cmp(UNBOUNDED_RESOURCE_LIMITS),
            Some(Ordering::Less),
        ));
        const _: () = assert!(matches!(
            EMPTY_RESOURCE_LIMITS.partial_cmp(DEFAULT_RESOURCE_LIMITS),
            Some(Ordering::Less),
        ));
    }

    #[test]
    fn resource_limits_is_chain_empty_slice_is_vacuously_true() {
        // Empty-slice vacuous truth — the empty conjunction is vacuously
        // true; the empty slice contains no distinct pairs to reject.
        // Peer of `is_lower_bound_of(&[]) == true`'s empty-slice identity
        // one PRIMITIVE-KIND axis over on the (leq, comparable) ×
        // (pairwise, N-ary) primitive surface.
        assert!(ResourceLimits::is_chain(&[]));
    }

    #[test]
    fn resource_limits_is_antichain_empty_slice_is_vacuously_true() {
        // Empty-slice vacuous truth — the empty conjunction is vacuously
        // true; the empty slice contains no distinct pairs to reject.
        // Peer of `is_chain(&[]) == true`'s empty-slice identity one
        // COVER-COMPLEMENT axis over: both cells of the (chain, antichain)
        // set-level pair AGREE at the empty slice on the vacuous-truth
        // verdict — the two cells coincide at the empty face of the
        // set-level verdict surface.
        assert!(ResourceLimits::is_antichain(&[]));
    }

    #[test]
    fn resource_limits_is_chain_singleton_is_vacuously_true() {
        // Singleton vacuous truth — a one-element slice contains no
        // distinct pairs, so the outer-and-inner-index conjunction never
        // enters the inner loop and returns `true` vacuously. Pinned on
        // every canonical preset AND on both hand-authored asymmetric
        // postures so the vacuous-truth verdict holds regardless of the
        // singleton element's lattice position.
        assert!(ResourceLimits::is_chain(&[EMPTY_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_chain(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_chain(&[UNBOUNDED_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_chain(&[HAND_AUTHORED_MID_POSTURE]));
        assert!(ResourceLimits::is_chain(&[HAND_AUTHORED_OTHER_POSTURE]));
    }

    #[test]
    fn resource_limits_is_antichain_singleton_is_vacuously_true() {
        // Singleton vacuous truth — a one-element slice contains no
        // distinct pairs, so the outer-and-inner-index conjunction never
        // enters the inner loop and returns `true` vacuously. Peer of
        // `is_chain`'s singleton-vacuous-truth identity: both cells AGREE
        // at singleton slices — the (chain, antichain) verdict surface
        // coincides at every slice with strictly fewer than two distinct
        // pairs.
        assert!(ResourceLimits::is_antichain(&[EMPTY_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_antichain(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_antichain(&[UNBOUNDED_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_antichain(&[HAND_AUTHORED_MID_POSTURE]));
        assert!(ResourceLimits::is_antichain(&[HAND_AUTHORED_OTHER_POSTURE]));
    }

    #[test]
    fn resource_limits_is_chain_of_diagonal_duplicate_is_true() {
        // Diagonal-duplicate identity — `is_comparable` is REFLEXIVE
        // (`a.is_comparable(a) == true`), so the single distinct index
        // pair `(0, 1)` binds `a.is_comparable(a) == true` and the
        // conjunction holds at every diagonal-duplicate slice.
        // Distinguishes it from `is_antichain` one COVER-COMPLEMENT axis
        // over, whose diagonal-duplicate verdict is `false` via
        // `is_incomparable`'s IRREFLEXIVITY.
        assert!(ResourceLimits::is_chain(&[
            DEFAULT_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_chain(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_antichain_of_diagonal_duplicate_is_false() {
        // Diagonal-duplicate rejection — `is_incomparable` is
        // IRREFLEXIVE (`a.is_incomparable(a) == false`), so the single
        // distinct index pair `(0, 1)` binds `a.is_incomparable(a) ==
        // false` and the conjunction rejects at every diagonal-duplicate
        // slice. The reflexivity/irreflexivity divergence between the
        // two pair-level projections PROPAGATES to the set-level
        // projections at any slice with a duplicated element — the two
        // set-level cells DIVERGE at every diagonal-duplicate slice, the
        // mirror of their AGREEMENT at every empty-or-singleton slice
        // one CARDINALITY axis over.
        assert!(!ResourceLimits::is_antichain(&[
            DEFAULT_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(!ResourceLimits::is_antichain(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_chain_holds_on_the_shipped_preset_triple() {
        // Ordered-chain closure — the shipped-preset triple on the
        // bounded-lattice diagonal is an ascending chain (`EMPTY <=
        // DEFAULT <= UNBOUNDED` pointwise), so every distinct pair among
        // the three is comparable. Pinned in every permutation of the
        // triple so the doubly-indexed all-pairs walk closes on every
        // enumeration of the same chain.
        assert!(ResourceLimits::is_chain(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_chain(&[
            UNBOUNDED_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_chain(&[
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_antichain_rejects_the_shipped_preset_pair() {
        // Chain rejection — the shipped-preset pair on the bounded-
        // lattice diagonal is a strict chain (`EMPTY.lt(DEFAULT)`), so
        // the single distinct pair is COMPARABLE and the antichain
        // conjunction rejects. The DIRECT FALSIFICATION of
        // `is_chain_holds_on_the_shipped_preset_triple` one CELL axis
        // over on the SAME lattice diagonal — the two set-level cells
        // carry the negation-paired verdict at every strictly-chained
        // slice, the mirror of their AGREEMENT at every empty-or-
        // singleton slice one CARDINALITY axis over.
        assert!(!ResourceLimits::is_antichain(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(!ResourceLimits::is_antichain(&[
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
        assert!(!ResourceLimits::is_antichain(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_chain_rejects_the_hand_authored_antichain_pair() {
        // Antichain rejection — the two hand-authored asymmetric
        // postures sit on distinct branches (each is smaller on three
        // axes and larger on the other three), so neither pointwise-
        // domination direction closes and the pair is INCOMPARABLE. The
        // chain conjunction rejects at the first incomparable pair.
        // Pinned in both orderings so the doubly-indexed pair walk
        // rejects regardless of index order (the diagonal-adjacent
        // pair-level rejection is symmetric on argument swap).
        assert!(!ResourceLimits::is_chain(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
        assert!(!ResourceLimits::is_chain(&[
            HAND_AUTHORED_OTHER_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_antichain_holds_on_the_hand_authored_antichain_pair() {
        // Hand-authored antichain closure — the two hand-authored
        // asymmetric postures sit on distinct branches (each is smaller
        // on three axes and larger on the other three), so neither
        // pointwise-domination direction closes and the pair is
        // INCOMPARABLE. The antichain conjunction accepts every distinct
        // pair of the slice. DIRECT LIFT of `is_chain`'s antichain
        // rejection one CELL axis over on the SAME hand-authored pair —
        // pinning BOTH cells' verdicts on the SAME load-bearing
        // antichain pair closes the (chain, antichain) two-cell face on
        // arity-2 slices as a substrate-level EXCLUSIVITY THEOREM.
        assert!(ResourceLimits::is_antichain(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
        assert!(ResourceLimits::is_antichain(&[
            HAND_AUTHORED_OTHER_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_chain_rejects_mixed_slice_with_one_antichain_pair() {
        // Mixed-set rejection — both `(DEFAULT, MID)` and `(DEFAULT,
        // OTHER)` are comparable pairs (DEFAULT's shipped `DEFAULT_MAX_*`
        // per-axis values are all much larger than either hand-authored
        // posture's, so DEFAULT dominates both pointwise), but the
        // `(MID, OTHER)` pair is the hand-authored INCOMPARABLE pair.
        // The set-level chain verdict is stricter than the union of its
        // pair-level verdicts — one antichain pair anywhere in the
        // slice falsifies the whole projection.
        assert!(!ResourceLimits::is_chain(&[
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_antichain_rejects_mixed_slice_with_one_comparable_pair() {
        // Mixed-set rejection — even though the second-and-third pair
        // is incomparable (the hand-authored antichain pair), the first
        // pair (`DEFAULT`-and-`MID`) is comparable, so the whole-set
        // conjunction rejects. Pins the three-cell (chain, antichain,
        // mixed) set-level face at the mixed-set cell: the same slice
        // both `is_chain` AND `is_antichain` reject at, and the third
        // cell of the three-cell face the two set-level projections
        // carry the ends of.
        assert!(!ResourceLimits::is_antichain(&[
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_antichain_and_is_chain_are_mutually_exclusive_on_distinct_pairs() {
        // De Morgan mirror at arity 2 — on any two-element slice `[a,
        // b]` with `a != b`, the set-level (chain, antichain) two-cell
        // face reduces to the pair-level (comparable, incomparable)
        // two-cell partition and the two cells become MUTUALLY
        // EXCLUSIVE (the mixed cell requires ≥3 elements to open). The
        // set-level De Morgan mirror of the pair-level identity
        // `a.is_comparable(b) == !a.is_incomparable(b)` `is_comparable`
        // pins one CARDINALITY axis over.
        let presets: [ResourceLimits; 5] = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ];
        for a in presets {
            for b in presets {
                if a == b {
                    continue;
                }
                let pair = [a, b];
                let chain = ResourceLimits::is_chain(&pair);
                let antichain = ResourceLimits::is_antichain(&pair);
                assert_ne!(
                    chain, antichain,
                    "distinct-pair mutual exclusivity failed on pair {a:?} / {b:?}",
                );
            }
        }
    }

    #[test]
    fn resource_limits_is_chain_and_is_antichain_agree_at_empty_and_singleton_slices() {
        // Empty-and-singleton agreement — the two set-level projections
        // carry the SAME vacuous-truth verdict at every slice with
        // strictly fewer than two distinct pairs (empty AND singleton).
        // Pinned as a substrate-level identity so a future rewrite of
        // either projection cannot silently drift from the shared
        // vacuous-truth verdict.
        assert_eq!(
            ResourceLimits::is_chain(&[]),
            ResourceLimits::is_antichain(&[]),
        );
        let presets: [ResourceLimits; 5] = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ];
        for a in presets {
            let single = [a];
            assert_eq!(
                ResourceLimits::is_chain(&single),
                ResourceLimits::is_antichain(&single),
                "singleton agreement failed on {a:?}",
            );
        }
    }

    #[test]
    fn resource_limits_is_chain_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the set-level chain projection is evaluable in
        // const context, so a caller can pin a chain-membership
        // identity at compile time. Sibling of the const-fn
        // evaluability pins on `is_comparable` one CARDINALITY axis
        // over and on `is_lower_bound_of` / `is_upper_bound_of` one
        // PRIMITIVE-KIND axis over on the N-ary aggregation surface.
        const _: () = assert!(ResourceLimits::is_chain(&[]));
        const _: () = assert!(ResourceLimits::is_chain(&[EMPTY_RESOURCE_LIMITS]));
        const _: () = assert!(ResourceLimits::is_chain(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_antichain_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the set-level antichain projection is
        // evaluable in const context, so a caller can pin an antichain-
        // membership identity at compile time. Sibling of the const-fn
        // evaluability pins on `is_incomparable` one CARDINALITY axis
        // over and on `is_chain` one COVER-COMPLEMENT axis over.
        const _: () = assert!(ResourceLimits::is_antichain(&[]));
        const _: () = assert!(ResourceLimits::is_antichain(&[EMPTY_RESOURCE_LIMITS]));
        const _: () = assert!(ResourceLimits::is_antichain(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_mixed_empty_slice_is_false() {
        // Empty-slice contract — is_chain and is_antichain BOTH return
        // `true` vacuously, so `!true && !true == false`. The empty
        // slice is NOT mixed. Sibling posture to the vacuous-truth
        // verdicts of is_chain + is_antichain one CELL axis over on the
        // (chain, antichain, mixed) three-cell face.
        assert!(!ResourceLimits::is_mixed(&[]));
    }

    #[test]
    fn resource_limits_is_mixed_singleton_is_false() {
        // Singleton contract — a one-element slice contains no distinct
        // pairs; is_chain + is_antichain BOTH return `true` vacuously.
        // Pinned on every canonical preset AND on both hand-authored
        // asymmetric postures so the false-at-singleton verdict holds
        // regardless of the singleton element's lattice position.
        assert!(!ResourceLimits::is_mixed(&[EMPTY_RESOURCE_LIMITS]));
        assert!(!ResourceLimits::is_mixed(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(!ResourceLimits::is_mixed(&[UNBOUNDED_RESOURCE_LIMITS]));
        assert!(!ResourceLimits::is_mixed(&[HAND_AUTHORED_MID_POSTURE]));
        assert!(!ResourceLimits::is_mixed(&[HAND_AUTHORED_OTHER_POSTURE]));
    }

    #[test]
    fn resource_limits_is_mixed_of_diagonal_duplicate_is_false() {
        // Diagonal-duplicate contract — is_chain returns `true` via
        // is_comparable's REFLEXIVITY; is_antichain returns `false` via
        // is_incomparable's IRREFLEXIVITY; the conjunction
        // `!true && !false == false`. The diagonal-duplicate slice is a
        // CHAIN (per the reflexivity arm), not mixed.
        assert!(!ResourceLimits::is_mixed(&[
            DEFAULT_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(!ResourceLimits::is_mixed(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_mixed_rejects_the_shipped_preset_triple() {
        // Chain rejection — the shipped-preset triple on the bounded-
        // lattice diagonal is an ascending chain, is_chain returns
        // `true`, and `!true && …` short-circuits to `false`. A PURE
        // chain is not mixed. Pinned in every permutation of the triple
        // so the projection factors through the ordering-agnostic
        // sibling is_chain verdict on the same chain.
        assert!(!ResourceLimits::is_mixed(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
        assert!(!ResourceLimits::is_mixed(&[
            UNBOUNDED_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_mixed_rejects_the_hand_authored_antichain_pair() {
        // Antichain rejection — the hand-authored antichain pair binds
        // is_antichain to `true`, and `!… && !true == false`. A PURE
        // antichain is not mixed. Pinned in both orderings so the
        // projection factors through the argument-swap-symmetric
        // sibling is_antichain verdict on the same antichain.
        assert!(!ResourceLimits::is_mixed(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
        assert!(!ResourceLimits::is_mixed(&[
            HAND_AUTHORED_OTHER_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_mixed_holds_on_the_mixed_slice_with_one_comparable_and_one_antichain_pair(
    ) {
        // Mixed-set closure — LOAD-BEARING `true`-arm catch. The
        // (DEFAULT, MID) pair is comparable (falsifying is_antichain)
        // while the (MID, OTHER) pair is incomparable (falsifying
        // is_chain); the conjunction `!false && !false == true`. This
        // is the SAME fixture the sibling is_chain + is_antichain BOTH
        // reject at — the DISCRIMINATING positive-arm catch for the
        // (mixed) cell of the three-cell face the two set-level
        // projections carry the ends of.
        assert!(ResourceLimits::is_mixed(&[
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_chain_is_antichain_and_is_mixed_partition_the_verdict_surface_on_distinct_slices(
    ) {
        // Trichotomy exhaustiveness at arity ≥2 with pairwise-distinct
        // elements — EXACTLY ONE of is_chain, is_antichain, is_mixed
        // returns `true` on every pair OR triple drawn from the shipped
        // presets whose elements are pairwise distinct. The three cells
        // partition the set-level verdict surface at every non-
        // degenerate slice. Substrate-level identity: pinning it here
        // catches a future rewrite of any of the three projections that
        // silently drifts from the partition contract.
        let presets: [ResourceLimits; 5] = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ];
        // Arity-2 sweep — the mixed cell CANNOT open at arity 2 (only
        // one distinct pair), so is_mixed is always false and the
        // partition reduces to the (chain, antichain) two-cell face
        // that is_chain + is_antichain already pinned MUTUALLY
        // EXCLUSIVE. Cross-check that the three-cell projection
        // AGREES with the two-cell projection at arity 2.
        for a in presets {
            for b in presets {
                if a == b {
                    continue;
                }
                let pair = [a, b];
                let chain = ResourceLimits::is_chain(&pair);
                let antichain = ResourceLimits::is_antichain(&pair);
                let mixed = ResourceLimits::is_mixed(&pair);
                let true_count = usize::from(chain) + usize::from(antichain) + usize::from(mixed);
                assert_eq!(
                    true_count, 1,
                    "trichotomy partition failed on distinct pair {a:?} / {b:?} — (chain, antichain, mixed) = ({chain}, {antichain}, {mixed})",
                );
                assert!(
                    !mixed,
                    "is_mixed unexpectedly true on distinct pair {a:?} / {b:?} — the mixed cell requires ≥3 elements to open",
                );
            }
        }
        // Arity-3 sweep on distinct triples — the mixed cell opens
        // whenever the triple carries both a comparable and an
        // incomparable pair (e.g. DEFAULT + MID + OTHER above).
        for a in presets {
            for b in presets {
                for c in presets {
                    if a == b || b == c || a == c {
                        continue;
                    }
                    let triple = [a, b, c];
                    let chain = ResourceLimits::is_chain(&triple);
                    let antichain = ResourceLimits::is_antichain(&triple);
                    let mixed = ResourceLimits::is_mixed(&triple);
                    let true_count =
                        usize::from(chain) + usize::from(antichain) + usize::from(mixed);
                    assert_eq!(
                        true_count, 1,
                        "trichotomy partition failed on distinct triple {a:?} / {b:?} / {c:?} — (chain, antichain, mixed) = ({chain}, {antichain}, {mixed})",
                    );
                }
            }
        }
    }

    #[test]
    fn resource_limits_is_mixed_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the set-level mixed projection is evaluable
        // in const context, so a caller can pin a mixed-set identity
        // at compile time. Sibling of the const-fn evaluability pins
        // on is_chain + is_antichain one CELL axis over.
        const _: () = assert!(!ResourceLimits::is_mixed(&[]));
        const _: () = assert!(!ResourceLimits::is_mixed(&[EMPTY_RESOURCE_LIMITS]));
        const _: () = assert!(ResourceLimits::is_mixed(&[
            DEFAULT_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
    }

    // ── ResourceLimits::is_ascending / ::is_descending — sequence-level ──

    #[test]
    fn resource_limits_is_ascending_empty_slice_is_vacuously_true() {
        // Empty-slice vacuous truth — the empty conjunction is vacuously
        // true; the empty slice contains no consecutive pairs to reject.
        // Peer of `is_chain(&[]) == true`'s empty-slice identity one
        // CONSECUTIVE-VS-ALL-PAIRS axis over: both cells of the (set-
        // level, sequence-level) projection pair AGREE at the empty slice
        // on the vacuous-truth verdict.
        assert!(ResourceLimits::is_ascending(&[]));
    }

    #[test]
    fn resource_limits_is_descending_empty_slice_is_vacuously_true() {
        // Peer of is_ascending's empty-slice identity one PAIR-LEVEL-
        // PRIMITIVE axis over: both cells of the (ascending, descending)
        // sequence-level pair AGREE at the empty slice.
        assert!(ResourceLimits::is_descending(&[]));
    }

    #[test]
    fn resource_limits_is_ascending_singleton_is_vacuously_true() {
        // Singleton vacuous truth — a one-element slice contains no
        // consecutive pairs, so the walk never enters the loop and
        // returns `true` vacuously. Pinned on every canonical preset AND
        // on both hand-authored asymmetric postures.
        assert!(ResourceLimits::is_ascending(&[EMPTY_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_ascending(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_ascending(&[UNBOUNDED_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_ascending(&[HAND_AUTHORED_MID_POSTURE]));
        assert!(ResourceLimits::is_ascending(&[HAND_AUTHORED_OTHER_POSTURE]));
    }

    #[test]
    fn resource_limits_is_descending_singleton_is_vacuously_true() {
        assert!(ResourceLimits::is_descending(&[EMPTY_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_descending(&[DEFAULT_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_descending(&[UNBOUNDED_RESOURCE_LIMITS]));
        assert!(ResourceLimits::is_descending(&[HAND_AUTHORED_MID_POSTURE]));
        assert!(ResourceLimits::is_descending(&[
            HAND_AUTHORED_OTHER_POSTURE
        ]));
    }

    #[test]
    fn resource_limits_is_ascending_of_diagonal_duplicate_is_true() {
        // Diagonal-duplicate identity — `leq` is REFLEXIVE
        // (`a.leq(a) == true` via each axis's `<=` reflexivity), so the
        // single consecutive pair `(0, 1)` binds `a.leq(a) == true` and
        // the conjunction holds at every diagonal-duplicate slice.
        // AGREES with is_chain's diagonal-duplicate verdict — the two
        // projections diverge only where the ORDER matters, and
        // duplicated elements carry no ordering information.
        assert!(ResourceLimits::is_ascending(&[
            DEFAULT_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_ascending(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_descending_of_diagonal_duplicate_is_true() {
        // Diagonal-duplicate identity — `geq` is REFLEXIVE, so the
        // single consecutive pair `(0, 1)` binds `a.geq(a) == true`.
        // AGREES with is_ascending's diagonal-duplicate verdict — both
        // leq and geq carry reflexivity, so the sequence-level (T, T)
        // corner opens at every diagonal-duplicate slice, distinct from
        // the set-level (T, F) verdict is_chain / is_antichain carry on
        // the same slice.
        assert!(ResourceLimits::is_descending(&[
            DEFAULT_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_descending(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_ascending_holds_on_the_ascending_shipped_preset_triple() {
        // Ordered ascending closure — the shipped-preset triple on the
        // bounded-lattice diagonal enumerated leq-ascending has
        // `EMPTY.leq(DEFAULT) == true` and `DEFAULT.leq(UNBOUNDED) ==
        // true`, so every consecutive pair passes the conjunction.
        // Pinned on the arity-2 prefix AND on the full arity-3 chain so
        // the walk closes at every non-degenerate ascending enumeration
        // length.
        assert!(ResourceLimits::is_ascending(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_ascending(&[
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_ascending(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_descending_holds_on_the_descending_shipped_preset_triple() {
        // Ordered descending closure — the reversed enumeration is a
        // geq-monotone descending sequence. The DIRECT MIRROR of
        // is_ascending's ascending closure one PERMUTATION axis over.
        assert!(ResourceLimits::is_descending(&[
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_descending(&[
            UNBOUNDED_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
        ]));
        assert!(ResourceLimits::is_descending(&[
            UNBOUNDED_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_ascending_rejects_the_descending_shipped_preset_triple() {
        // Order-sensitivity — the reversed enumeration of the same
        // shipped-preset chain has `UNBOUNDED.leq(DEFAULT) == false` at
        // the first consecutive pair. is_chain accepts BOTH orderings
        // (order-INSENSITIVE); this projection accepts only the leq-
        // sorted one — the DISCRIMINATING arm between the sequence-level
        // and set-level projections.
        assert!(!ResourceLimits::is_ascending(&[
            UNBOUNDED_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_descending_rejects_the_ascending_shipped_preset_triple() {
        // The direct falsification of is_ascending's ascending closure
        // one CELL axis over on the SAME slice.
        assert!(!ResourceLimits::is_descending(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_ascending_rejects_the_non_monotone_chain_permutation() {
        // Non-monotone chain permutation — [DEFAULT, EMPTY, UNBOUNDED]
        // is a permutation of the shipped-preset chain, so it IS a chain
        // (is_chain accepts it), but the first consecutive pair binds
        // `DEFAULT.leq(EMPTY) == false`, so the sequence-level ascending
        // walk rejects. Also is_descending rejects — the third
        // consecutive pair binds `EMPTY.geq(UNBOUNDED) == false`. Pins
        // the DISCRIMINATING arm between the sequence-level and set-
        // level projections at a slice that is a chain but neither
        // ascending nor descending.
        let slice = [
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ];
        assert!(ResourceLimits::is_chain(&slice));
        assert!(!ResourceLimits::is_ascending(&slice));
        assert!(!ResourceLimits::is_descending(&slice));
    }

    #[test]
    fn resource_limits_is_ascending_rejects_the_hand_authored_antichain_pair() {
        // The two hand-authored asymmetric postures are incomparable
        // (neither MID.leq(OTHER) nor OTHER.leq(MID)), so the single
        // consecutive pair rejects. Pinned in both orderings — the pair-
        // level leq verdict rejects on the antichain pair regardless of
        // which side is `self`.
        assert!(!ResourceLimits::is_ascending(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
        assert!(!ResourceLimits::is_ascending(&[
            HAND_AUTHORED_OTHER_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_descending_rejects_the_hand_authored_antichain_pair() {
        assert!(!ResourceLimits::is_descending(&[
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ]));
        assert!(!ResourceLimits::is_descending(&[
            HAND_AUTHORED_OTHER_POSTURE,
            HAND_AUTHORED_MID_POSTURE,
        ]));
    }

    #[test]
    fn resource_limits_is_ascending_implies_is_chain_on_every_shipped_slice() {
        // Transitivity theorem — for every slice `postures`,
        // `is_ascending(postures) == true` implies `is_chain(postures)
        // == true`. The pointwise partial order is TRANSITIVE, so a
        // consecutive-pair leq-chain closes under transitive composition
        // into the all-pairs leq-chain. Substrate-level THEOREM: the
        // sequence-level ascending verdict is strictly STRONGER than the
        // set-level chain verdict. Same identity for is_descending —
        // both sequence-level projections imply the set-level chain
        // projection.
        let presets: [ResourceLimits; 5] = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ];
        // Every arity-2 slice from the 5×5 preset matrix witnesses the
        // implication in both directions of the (ascending, descending)
        // pair.
        for a in presets {
            for b in presets {
                let slice = [a, b];
                if ResourceLimits::is_ascending(&slice) {
                    assert!(
                        ResourceLimits::is_chain(&slice),
                        "is_ascending ⇒ is_chain failed on pair {a:?} / {b:?}",
                    );
                }
                if ResourceLimits::is_descending(&slice) {
                    assert!(
                        ResourceLimits::is_chain(&slice),
                        "is_descending ⇒ is_chain failed on pair {a:?} / {b:?}",
                    );
                }
            }
        }
        // Load-bearing arity-3 witness — the shipped ascending chain
        // triple satisfies is_ascending AND is_chain; the descending
        // reversal satisfies is_descending AND is_chain.
        let asc = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ];
        assert!(ResourceLimits::is_ascending(&asc));
        assert!(ResourceLimits::is_chain(&asc));
        let desc = [
            UNBOUNDED_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ];
        assert!(ResourceLimits::is_descending(&desc));
        assert!(ResourceLimits::is_chain(&desc));
    }

    #[test]
    fn resource_limits_is_ascending_and_is_descending_agree_at_empty_and_singleton_slices() {
        // Empty-and-singleton agreement — the two sequence-level
        // projections carry the SAME vacuous-truth verdict at every
        // slice with fewer than two consecutive pairs. Pinned as a
        // substrate-level identity so a future rewrite of either
        // projection cannot silently drift from the shared vacuous-
        // truth verdict.
        assert_eq!(
            ResourceLimits::is_ascending(&[]),
            ResourceLimits::is_descending(&[]),
        );
        let presets: [ResourceLimits; 5] = [
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
            HAND_AUTHORED_MID_POSTURE,
            HAND_AUTHORED_OTHER_POSTURE,
        ];
        for a in presets {
            let single = [a];
            assert_eq!(
                ResourceLimits::is_ascending(&single),
                ResourceLimits::is_descending(&single),
                "empty-and-singleton agreement failed on singleton {a:?}",
            );
            let dup = [a, a];
            assert_eq!(
                ResourceLimits::is_ascending(&dup),
                ResourceLimits::is_descending(&dup),
                "diagonal-duplicate agreement failed on {a:?}",
            );
        }
    }

    #[test]
    fn resource_limits_is_ascending_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — the sequence-level ascending projection is
        // evaluable in const context, so a caller can pin an ascending-
        // sequence identity at compile time.
        const _: () = assert!(ResourceLimits::is_ascending(&[]));
        const _: () = assert!(ResourceLimits::is_ascending(&[EMPTY_RESOURCE_LIMITS]));
        const _: () = assert!(ResourceLimits::is_ascending(&[
            EMPTY_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
        const _: () = assert!(!ResourceLimits::is_ascending(&[
            UNBOUNDED_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ]));
    }

    #[test]
    fn resource_limits_is_descending_evaluates_at_compile_time_via_const_fn() {
        // Const-fn pin — sibling of is_ascending one PAIR-LEVEL-
        // PRIMITIVE axis over.
        const _: () = assert!(ResourceLimits::is_descending(&[]));
        const _: () = assert!(ResourceLimits::is_descending(&[EMPTY_RESOURCE_LIMITS]));
        const _: () = assert!(ResourceLimits::is_descending(&[
            UNBOUNDED_RESOURCE_LIMITS,
            DEFAULT_RESOURCE_LIMITS,
            EMPTY_RESOURCE_LIMITS,
        ]));
        const _: () = assert!(!ResourceLimits::is_descending(&[
            EMPTY_RESOURCE_LIMITS,
            UNBOUNDED_RESOURCE_LIMITS,
        ]));
    }
}