uor-foundation 0.4.5

UOR Foundation โ€” typed Rust traits for the complete ontology. Import and implement.
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
// @generated by uor-crate from uor-ontology โ€” do not edit manually

//! Reduction Pipeline โ€” no_std in-process driver.
//!
//! Backs `Certify::certify` on every resolver faรงade and (re-exported
//! via the macros crate) the `uor_ground!` macro's compile-time pipeline.
//!
//! The driver implements the full reduction pipeline per
//! `external/ergonomics-spec.md` ยง3.3 and ยง4: 6 preflight checks,
//! 7 reduction stages, 4 resolver backends, real 2-SAT and Horn-SAT
//! deciders, fragment classifier, content-addressed unit-ids.
//!
//! Every entry point is ontology-driven: IRIs, stage order, and
//! dispatch-table rules are baked in at codegen time from the
//! ontology graph. Adding a new preflight check or resolver is a
//! pure ontology edit.

use crate::enforcement::{
    BindingEntry, BindingsTable, CompileTime, CompileUnit, CompileUnitBuilder,
    CompletenessCertificate, ConstrainedTypeInput, GenericImpossibilityWitness, Grounded,
    GroundingCertificate, InhabitanceCertificate, InhabitanceImpossibilityWitness,
    LeaseDeclaration, LeaseDeclarationBuilder, LiftChainCertificate, MultiplicationCertificate,
    ParallelDeclarationBuilder, PipelineFailure, ShapeViolation, StreamDeclarationBuilder, Term,
    Validated,
};
use crate::ViolationKind;
use crate::WittLevel;

/// Zero-based preflight check order read from `reduction:PreflightCheck`
/// individuals at codegen time. `BudgetSolvencyCheck` MUST be index 0 per
/// `reduction:preflightOrder` โ€” enforced by the ontology, not here.
pub const PREFLIGHT_CHECK_IRIS: &[&str] = &[
    "https://uor.foundation/reduction/BudgetSolvencyCheck",
    "https://uor.foundation/reduction/FeasibilityCheck",
    "https://uor.foundation/reduction/DispatchCoverageCheck",
    "https://uor.foundation/reduction/PackageCoherenceCheck",
    "https://uor.foundation/reduction/PreflightTiming",
    "https://uor.foundation/reduction/RuntimeTiming",
];

/// Seven reduction stages in declared order, sourced from
/// `reduction:ReductionStep` individuals.
pub const REDUCTION_STAGE_IRIS: &[&str] = &[
    "https://uor.foundation/reduction/stage_initialization",
    "https://uor.foundation/reduction/stage_declare",
    "https://uor.foundation/reduction/stage_factorize",
    "https://uor.foundation/reduction/stage_resolve",
    "https://uor.foundation/reduction/stage_attest",
    "https://uor.foundation/reduction/stage_extract",
    "https://uor.foundation/reduction/stage_convergence",
];

/// Phase 17: maximum number of `i64` coefficients an `Affine`
/// constraint can carry. Stable-Rust const evaluation cannot allocate a
/// new `&'static [i64]` at compile time, so `Affine` stores a fixed-
/// size buffer + an active prefix length. Aligned with the foundation's
/// 8-wide capacity caps (`MAX_BETTI_DIMENSION` / `JACOBIAN_MAX_SITES` /
/// `NERVE_CONSTRAINTS_CAP`).
/// Wiki ADR-037: the canonical source of truth for this cap is
/// [`HostBounds::AFFINE_COEFFS_MAX`]; this `pub const` is a foundation-
/// internal convenience alias derived from [`DefaultHostBounds`] for
/// stable-Rust array-size positions. Applications declaring a custom
/// `HostBounds` impl read `<MyBounds as HostBounds>::AFFINE_COEFFS_MAX`
/// at instantiation sites instead.
pub const AFFINE_MAX_COEFFS: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::AFFINE_COEFFS_MAX;

/// Phase 17: maximum number of `LeafConstraintRef` conjuncts a
/// `Conjunction` can carry. Same reasoning as `AFFINE_MAX_COEFFS`.
/// Wiki ADR-037: alias of [`HostBounds::CONJUNCTION_TERMS_MAX`] via
/// [`DefaultHostBounds`].
pub const CONJUNCTION_MAX_TERMS: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::CONJUNCTION_TERMS_MAX;

/// Opaque constraint reference carried by `ConstrainedTypeShape` impls.
/// Variants mirror the v0.2.1 `type:Constraint` enumerated subclasses
/// (retained as ergonomic aliases for the SAT pipeline) plus the v0.2.2
/// Phase D parametric form (`Bound` / `Conjunction`) which references
/// `BoundConstraint` kinds by their (observable, shape) IRIs. The
/// `SatClauses` variant carries a compact 2-SAT/Horn-SAT clause list.
/// **Phase 17 โ€” fixed-array Affine and Conjunction.** The pre-Phase-17
/// `Affine { coefficients: &'static [i64], โ€ฆ }` and
/// `Conjunction { conjuncts: &'static [ConstraintRef] }` have been
/// replaced with fixed-capacity arrays of length `AFFINE_MAX_COEFFS`
/// and `CONJUNCTION_MAX_TERMS` respectively. Stable Rust const
/// evaluation can build these inline; the SDK macros now support
/// Affine-bearing operands without falling back to the
/// `Site { position: u32::MAX }` sentinel. `Conjunction` is depth-
/// limited to one level: its conjuncts are `LeafConstraintRef`
/// (every variant of `ConstraintRef` except `Conjunction` itself).
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
#[allow(clippy::large_enum_variant)]
pub enum ConstraintRef {
    /// `type:ResidueConstraint`: value โ‰ก residue (mod modulus).
    Residue { modulus: u64, residue: u64 },
    /// `type:HammingConstraint`: bit-weight bound.
    Hamming { bound: u32 },
    /// `type:DepthConstraint`: site-depth bound.
    Depth { min: u32, max: u32 },
    /// `type:CarryConstraint`: carry-bit relation.
    Carry { site: u32 },
    /// `type:SiteConstraint`: site-position restriction.
    Site { position: u32 },
    /// `type:AffineConstraint`: affine relation over sites.
    /// `coefficients[..coefficient_count as usize]` is the active prefix;
    /// trailing entries are unused and must be zero.
    Affine {
        coefficients: [i64; AFFINE_MAX_COEFFS],
        coefficient_count: u32,
        bias: i64,
    },
    /// Opaque clause list for 2-SAT / Horn-SAT inputs.
    /// Each clause is a slice of `(variable_index, is_negated)`.
    SatClauses {
        clauses: &'static [&'static [(u32, bool)]],
        num_vars: u32,
    },
    /// v0.2.2 Phase D / T2.2 (cleanup): parametric `BoundConstraint`
    /// kind reference. Selects an (observable, shape) pair from the
    /// closed Phase D catalogue. The args_repr string carries the
    /// kind-specific parameters in canonical form.
    Bound {
        observable_iri: &'static str,
        bound_shape_iri: &'static str,
        args_repr: &'static str,
    },
    /// v0.2.2 Phase D / T2.2 (cleanup): parametric `Conjunction`.
    /// Phase 17: depth-limited to one level โ€” conjuncts are
    /// `LeafConstraintRef` (every `ConstraintRef` variant except
    /// `Conjunction` itself). Active prefix is
    /// `conjuncts[..conjunct_count as usize]`.
    Conjunction {
        conjuncts: [LeafConstraintRef; CONJUNCTION_MAX_TERMS],
        conjunct_count: u32,
    },
}

/// `ConstraintRef` minus the recursive `Conjunction` variant โ€” the
/// element type of `ConstraintRef::Conjunction.conjuncts`. Phase 17
/// caps Conjunction depth at one level; deeper structure must be
/// flattened by the constructor.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum LeafConstraintRef {
    /// See [`ConstraintRef::Residue`].
    Residue { modulus: u64, residue: u64 },
    /// See [`ConstraintRef::Hamming`].
    Hamming { bound: u32 },
    /// See [`ConstraintRef::Depth`].
    Depth { min: u32, max: u32 },
    /// See [`ConstraintRef::Carry`].
    Carry { site: u32 },
    /// See [`ConstraintRef::Site`].
    Site { position: u32 },
    /// See [`ConstraintRef::Affine`].
    Affine {
        coefficients: [i64; AFFINE_MAX_COEFFS],
        coefficient_count: u32,
        bias: i64,
    },
    /// See [`ConstraintRef::SatClauses`].
    SatClauses {
        clauses: &'static [&'static [(u32, bool)]],
        num_vars: u32,
    },
    /// See [`ConstraintRef::Bound`].
    Bound {
        observable_iri: &'static str,
        bound_shape_iri: &'static str,
        args_repr: &'static str,
    },
}

/// Project a non-`Conjunction` [`ConstraintRef`] into the
/// [`LeafConstraintRef`] subtype. Returns a `Site { position: 0 }`
/// placeholder if `self` is `Conjunction` (the only non-injective
/// case); callers should flatten Conjunction structure before
/// calling.
impl ConstraintRef {
    /// Phase 17 โ€” leaf projection.
    #[inline]
    #[must_use]
    pub const fn as_leaf(self) -> LeafConstraintRef {
        match self {
            ConstraintRef::Residue { modulus, residue } => {
                LeafConstraintRef::Residue { modulus, residue }
            }
            ConstraintRef::Hamming { bound } => LeafConstraintRef::Hamming { bound },
            ConstraintRef::Depth { min, max } => LeafConstraintRef::Depth { min, max },
            ConstraintRef::Carry { site } => LeafConstraintRef::Carry { site },
            ConstraintRef::Site { position } => LeafConstraintRef::Site { position },
            ConstraintRef::Affine {
                coefficients,
                coefficient_count,
                bias,
            } => LeafConstraintRef::Affine {
                coefficients,
                coefficient_count,
                bias,
            },
            ConstraintRef::SatClauses { clauses, num_vars } => {
                LeafConstraintRef::SatClauses { clauses, num_vars }
            }
            ConstraintRef::Bound {
                observable_iri,
                bound_shape_iri,
                args_repr,
            } => LeafConstraintRef::Bound {
                observable_iri,
                bound_shape_iri,
                args_repr,
            },
            ConstraintRef::Conjunction { .. } => LeafConstraintRef::Site { position: 0 },
        }
    }
}

impl LeafConstraintRef {
    /// Phase 17 โ€” embed a leaf into the parent `ConstraintRef` enum.
    #[inline]
    #[must_use]
    pub const fn into_constraint(self) -> ConstraintRef {
        match self {
            LeafConstraintRef::Residue { modulus, residue } => {
                ConstraintRef::Residue { modulus, residue }
            }
            LeafConstraintRef::Hamming { bound } => ConstraintRef::Hamming { bound },
            LeafConstraintRef::Depth { min, max } => ConstraintRef::Depth { min, max },
            LeafConstraintRef::Carry { site } => ConstraintRef::Carry { site },
            LeafConstraintRef::Site { position } => ConstraintRef::Site { position },
            LeafConstraintRef::Affine {
                coefficients,
                coefficient_count,
                bias,
            } => ConstraintRef::Affine {
                coefficients,
                coefficient_count,
                bias,
            },
            LeafConstraintRef::SatClauses { clauses, num_vars } => {
                ConstraintRef::SatClauses { clauses, num_vars }
            }
            LeafConstraintRef::Bound {
                observable_iri,
                bound_shape_iri,
                args_repr,
            } => ConstraintRef::Bound {
                observable_iri,
                bound_shape_iri,
                args_repr,
            },
        }
    }
}

/// Workstream E (target ยง1.5 + ยง4.7, v0.2.2 closure): crate-internal
/// dispatch helper that maps every `ConstraintRef` variant to its
/// canonical CNF clause encoding. No variant returns `None` โ€” the
/// closed six-kind set is fully executable.
/// - `SatClauses`: pass-through of the caller's CNF.
/// - `Residue` / `Carry` / `Depth` / `Hamming` / `Site`: direct-
///   decidable at preflight; encoder emits an empty clause list
///   (trivially SAT โ€” unsatisfiable ones are rejected earlier).
/// - `Affine`: single-row consistency check over Z/(2^n)Z; emits
///   empty clauses when consistent, a 2-literal contradiction
///   sentinel (forcing 2-SAT rejection) when not.
/// - `Bound`: parametric form; emits empty clauses (per-bound-kind
///   decision procedures consume the observable/bound-shape IRIs).
/// - `Conjunction`: satisfiable iff every conjunct is satisfiable.
#[inline]
#[must_use]
#[allow(dead_code)]
pub(crate) const fn encode_constraint_to_clauses(
    constraint: &ConstraintRef,
) -> Option<&'static [&'static [(u32, bool)]]> {
    const EMPTY: &[&[(u32, bool)]] = &[];
    const UNSAT_SENTINEL: &[&[(u32, bool)]] = &[&[(0u32, false)], &[(0u32, true)]];
    match constraint {
        ConstraintRef::SatClauses { clauses, .. } => Some(clauses),
        ConstraintRef::Residue { .. }
        | ConstraintRef::Carry { .. }
        | ConstraintRef::Depth { .. }
        | ConstraintRef::Hamming { .. }
        | ConstraintRef::Site { .. } => Some(EMPTY),
        ConstraintRef::Affine {
            coefficients,
            coefficient_count,
            bias,
        } => {
            if is_affine_consistent(coefficients, *coefficient_count, *bias) {
                Some(EMPTY)
            } else {
                Some(UNSAT_SENTINEL)
            }
        }
        ConstraintRef::Bound { .. } => Some(EMPTY),
        ConstraintRef::Conjunction {
            conjuncts,
            conjunct_count,
        } => {
            if conjunction_all_sat(conjuncts, *conjunct_count) {
                Some(EMPTY)
            } else {
                Some(UNSAT_SENTINEL)
            }
        }
    }
}

/// Workstream E: single-row consistency for `Affine { coefficients,
/// coefficient_count, bias }`. The constraint is
/// `sum(c_i) ยท x = bias (mod 2^n)`; when the coefficient sum is
/// zero the system is consistent iff bias is zero. Non-zero sums
/// are always consistent over Z/(2^n)Z for some `x` value. Iterates
/// only the active prefix `coefficients[..coefficient_count as usize]`.
#[inline]
#[must_use]
const fn is_affine_consistent(
    coefficients: &[i64; AFFINE_MAX_COEFFS],
    coefficient_count: u32,
    bias: i64,
) -> bool {
    let mut sum: i128 = 0;
    let count = coefficient_count as usize;
    let mut i = 0;
    while i < count && i < AFFINE_MAX_COEFFS {
        sum += coefficients[i] as i128;
        i += 1;
    }
    if sum == 0 {
        bias == 0
    } else {
        true
    }
}

/// Workstream E + Phase 17: satisfiability of a `Conjunction`.
/// Iterates only the active prefix `conjuncts[..conjunct_count as
/// usize]` and lifts each `LeafConstraintRef` back to a
/// `ConstraintRef` for re-encoding (the leaf form omits Conjunction,
/// so this terminates at depth 1).
#[inline]
#[must_use]
const fn conjunction_all_sat(
    conjuncts: &[LeafConstraintRef; CONJUNCTION_MAX_TERMS],
    conjunct_count: u32,
) -> bool {
    let count = conjunct_count as usize;
    let mut i = 0;
    while i < count && i < CONJUNCTION_MAX_TERMS {
        let lifted = conjuncts[i].into_constraint();
        match encode_constraint_to_clauses(&lifted) {
            Some([]) => {}
            _ => return false,
        }
        i += 1;
    }
    true
}

/// Declarative shape of a constrained type that can be admitted into the
/// reduction pipeline.
/// Downstream authors implement this trait on zero-sized marker types to
/// declare the `(IRI, SITE_COUNT, CONSTRAINTS)` triple of a custom
/// constrained type. The foundation admits shapes into the pipeline via
/// [`validate_constrained_type`] / [`validate_constrained_type_const`],
/// which run the full preflight (`preflight_feasibility` +
/// `preflight_package_coherence`) against `Self::CONSTRAINTS` before
/// returning a [`Validated`] wrapper.
/// Sealing of witness construction lives on [`Validated`] and [`Grounded`]
/// โ€” only foundation admission functions mint either. Downstream is free
/// to implement `ConstrainedTypeShape` for arbitrary shape markers, but
/// cannot fabricate a `Validated<Self>` except through the admission path.
/// The `ConstraintRef` enum is `#[non_exhaustive]` from outside the crate,
/// so `CONSTRAINTS` can only cite foundation-closed constraint kinds.
/// # Example
/// ```
/// use uor_foundation::pipeline::{
///     ConstrainedTypeShape, ConstraintRef, validate_constrained_type,
/// };
/// pub struct MyShape;
/// impl ConstrainedTypeShape for MyShape {
///     const IRI: &'static str = "https://example.org/MyShape";
///     const SITE_COUNT: usize = 4;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[
///         ConstraintRef::Residue { modulus: 7, residue: 3 },
///     ];
///     const CYCLE_SIZE: u64 = 7;  // ADR-032: 7 residues mod 7
/// }
/// let validated = validate_constrained_type(MyShape)
///     .expect("residue 3 mod 7 is admissible");
/// # let _ = validated;
/// ```
pub trait ConstrainedTypeShape {
    /// IRI of the ontology `type:ConstrainedType` instance this shape represents.
    const IRI: &'static str;
    /// Number of sites (fields) this constrained type carries.
    const SITE_COUNT: usize;
    /// Ontology-level `siteBudget`: count of data sites only,
    /// excluding bookkeeping introduced by composition (coproduct tag
    /// sites, etc.). Equals `SITE_COUNT` for leaf shapes and for
    /// shapes whose composition introduces no bookkeeping (products,
    /// cartesian products). Strictly less than `SITE_COUNT` for coproduct
    /// shapes and any shape whose `SITE_COUNT` includes inherited
    /// bookkeeping. Introduced by the Product/Coproduct Completion
    /// Amendment ยง4a; defaults to `SITE_COUNT` so pre-amendment
    /// shape impls remain valid without edits.
    const SITE_BUDGET: usize = Self::SITE_COUNT;
    /// Per-site constraint list. Empty means unconstrained.
    const CONSTRAINTS: &'static [ConstraintRef];
    /// ADR-032: cardinality of the shape's value-set (the cycle
    /// structure of the shape under the substrate's discrete-clock
    /// model). Used by the `prism_model!` macro to lower `first_admit`
    /// (closure-body grammar G16) to the correct descent measure.
    /// Conventions:
    /// - Witt-level shapes: `1u64 << WITT_LEVEL_BITS` (W8 = 256, W16 =
    ///   65536, W32 = 4294967296). Levels above W63 saturate to `u64::MAX`.
    /// - `partition_product` factors: `cycle_size_product` of factor
    ///   CYCLE_SIZEs (saturating-multiply).
    /// - `partition_coproduct` summands: `cycle_size_coproduct` (saturating
    ///   add + 1 for the discriminant).
    /// - `cartesian_product_shape` (homogeneous power): factor's CYCLE_SIZE
    ///   raised to `SITE_COUNT` (saturating).
    /// - The foundation-sanctioned identity `ConstrainedTypeInput` has
    ///   `CYCLE_SIZE = 1` (single-element shape).
    const CYCLE_SIZE: u64;
}

/// ADR-032: saturating multiply for `partition_product`'s CYCLE_SIZE.
/// Returns `u64::MAX` on overflow.
#[inline]
#[must_use]
pub const fn cycle_size_product(a: u64, b: u64) -> u64 {
    a.saturating_mul(b)
}

/// ADR-032: saturating add + 1 (for the discriminant) for
/// `partition_coproduct`'s CYCLE_SIZE. Returns `u64::MAX` on overflow.
#[inline]
#[must_use]
pub const fn cycle_size_coproduct(a: u64, b: u64) -> u64 {
    a.saturating_add(b).saturating_add(1)
}

/// ADR-032: saturating power for `cartesian_product_shape`'s CYCLE_SIZE
/// (homogeneous power: factor.CYCLE_SIZE^SITE_COUNT). Returns `u64::MAX`
/// on overflow.
#[inline]
#[must_use]
pub const fn cycle_size_power(base: u64, exp: usize) -> u64 {
    let mut result: u64 = 1;
    let mut i: usize = 0;
    while i < exp {
        result = result.saturating_mul(base);
        i += 1;
    }
    result
}

impl ConstrainedTypeShape for ConstrainedTypeInput {
    const IRI: &'static str = "https://uor.foundation/type/ConstrainedType";
    const SITE_COUNT: usize = 0;
    const CONSTRAINTS: &'static [ConstraintRef] = &[];
    const CYCLE_SIZE: u64 = 1;
}

/// ADR-033 G20: factor-field directory carried by every
/// `partition_product`-shaped type. The closure-body grammar's
/// field-access form (`<expr>.<index>` or `<expr>.<field_name>`)
/// lowers via this trait at proc-macro expansion time.
/// Foundation-sanctioned identity `ConstrainedTypeInput` has zero
/// fields (it is a leaf shape). The SDK macros `partition_product!`,
/// `product_shape!`, and `cartesian_product_shape!` emit the impl.
pub trait PartitionProductFields: ConstrainedTypeShape {
    /// Per-factor `(byte_offset, byte_length)` pairs in declaration
    /// order. Length is the same as `FIELD_NAMES.len()`.
    const FIELDS: &'static [(u32, u32)];
    /// Per-factor names. Empty string `""` for positional-only
    /// `partition_product!(Name, A, B)` emissions; non-empty for
    /// named-field `partition_product!(Name, lhs: A, rhs: B)` form.
    /// Length matches `FIELDS.len()`.
    const FIELD_NAMES: &'static [&'static str];
    /// Linear search returning the field index whose `FIELD_NAMES`
    /// entry equals `name`, or `usize::MAX` if not found. Delegates
    /// to the free `const fn` [`field_index_by_name_in`] so the
    /// result is usable inside const-eval contexts on stable Rust
    /// 1.83 (where const trait methods are unavailable).
    #[must_use]
    fn field_index_by_name(name: &str) -> usize {
        field_index_by_name_in(Self::FIELD_NAMES, name)
    }
}

/// ADR-033 G3/G4: const-fn factor-name lookup. The SDK proc-macro
/// emits const-eval calls to this helper to resolve a named-field
/// access against the source type's `FIELD_NAMES`. On stable Rust
/// 1.83 a free `const fn` is the substitute for a `const fn`
/// trait method. Returns `usize::MAX` for not-found so the result
/// is usable directly inside `const` array indexing.
#[must_use]
pub const fn field_index_by_name_in(names: &[&'static str], name: &str) -> usize {
    let nb = name.as_bytes();
    let mut i = 0usize;
    while i < names.len() {
        let nb_i = names[i].as_bytes();
        if nb_i.len() == nb.len() {
            let mut j = 0usize;
            let mut matched = true;
            while j < nb.len() {
                if nb_i[j] != nb[j] {
                    matched = false;
                    break;
                }
                j += 1;
            }
            if matched {
                return i;
            }
        }
        i += 1;
    }
    usize::MAX
}

impl PartitionProductFields for ConstrainedTypeInput {
    const FIELDS: &'static [(u32, u32)] = &[];
    const FIELD_NAMES: &'static [&'static str] = &[];
}

/// ADR-033 G20 chained-field access support: maps a
/// `partition_product`-shaped type's positional factor index to
/// the factor's static type. The `prism_model!` proc-macro emits
/// a chain of `Term::ProjectField` projections by walking this
/// trait, naming each next source type as
/// `<PrevTy as PartitionProductFactor<I>>::Factor`.
/// `partition_product!`, `product_shape!`, and
/// `cartesian_product_shape!` emit one impl per factor index.
pub trait PartitionProductFactor<const INDEX: usize>: PartitionProductFields {
    /// The static type of the factor at position `INDEX`.
    type Factor: ConstrainedTypeShape;
}

/// ADR-030: maximum number of axes a single application's
/// `AxisTuple` may carry. Foundation-fixed (parallel to
/// `FOLD_UNROLL_THRESHOLD` and `UNFOLD_MAX_ITERATIONS`).
pub const MAX_AXIS_TUPLE_ARITY: usize = 8;

/// ADR-030: the upper byte ceiling on a single axis kernel's
/// output. Sized to `TERM_VALUE_MAX_BYTES` so any kernel can
/// populate a `TermValue` directly.
/// Wiki ADR-037: alias of [`HostBounds::AXIS_OUTPUT_BYTES_MAX`] via
/// [`DefaultHostBounds`]. Applications declaring a custom `HostBounds`
/// read `<MyBounds as HostBounds>::AXIS_OUTPUT_BYTES_MAX` instead.
pub const AXIS_OUTPUT_BYTES_CEILING: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::AXIS_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::NERVE_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_1 (Nerve)
/// resolver output byte-buffer ceiling.
pub const NERVE_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::NERVE_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::CHAIN_COMPLEX_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_2 (ChainComplex)
/// resolver output byte-buffer ceiling.
pub const CHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::CHAIN_COMPLEX_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_3 (HomologyGroups)
/// resolver output byte-buffer ceiling.
pub const HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::COCHAIN_COMPLEX_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_5 (CochainComplex)
/// resolver output byte-buffer ceiling.
pub const COCHAIN_COMPLEX_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::COCHAIN_COMPLEX_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_6 (CohomologyGroups)
/// resolver output byte-buffer ceiling.
pub const COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::POSTNIKOV_TOWER_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_7 (PostnikovTower)
/// resolver output byte-buffer ceiling.
pub const POSTNIKOV_TOWER_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::POSTNIKOV_TOWER_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_8 (HomotopyGroups)
/// resolver output byte-buffer ceiling.
pub const HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX;

/// Wiki ADR-037: foundation-internal alias of
/// [`HostBounds::K_INVARIANTS_OUTPUT_BYTES_MAX`] via [`DefaultHostBounds`] โ€” the ฯˆ_9 (KInvariants)
/// resolver output byte-buffer ceiling.
pub const K_INVARIANTS_OUTPUT_BYTES_MAX: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::K_INVARIANTS_OUTPUT_BYTES_MAX;

/// ADR-030: a substrate-extension axis. Each `axis!`-declared
/// trait extends this trait via the SDK macro's blanket impl,
/// which emits per-method `KERNEL_*` const ids and the
/// `dispatch_kernel` router into a fixed-capacity byte buffer.
/// The catamorphism's `Term::AxisInvocation` fold-rule reads the
/// axis position from the application's `AxisTuple` impl and
/// calls `dispatch_kernel` with the kernel id and the evaluated
/// input bytes; the returned `TermValue` is the axis's
/// contribution to the route's evaluation.
pub trait AxisExtension {
    /// ADR-017 content address of this axis trait. The SDK macro
    /// derives this from the trait name and method signatures.
    const AXIS_ADDRESS: &'static str;
    /// Maximum bytes any kernel of this axis returns.
    const MAX_OUTPUT_BYTES: usize;
    /// Dispatch the kernel identified by `kernel_id` against the
    /// evaluated input bytes. The implementation copies the kernel's
    /// output into `out` and returns the written length.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the
    /// kernel id is unrecognised or the input does not satisfy the
    /// kernel's shape contract.
    fn dispatch_kernel(
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-030: a tuple of `AxisExtension`-implementing types selected
/// by the application. The catamorphism's `Term::AxisInvocation`
/// fold-rule calls `dispatch` to route the invocation to the right
/// axis position.
/// Foundation provides tuple impls for arities 1 through
/// [`MAX_AXIS_TUPLE_ARITY`].
pub trait AxisTuple {
    /// Number of axes carried in this tuple.
    const AXIS_COUNT: usize;
    /// Maximum kernel-output byte width across all axes in this tuple.
    const MAX_OUTPUT_BYTES: usize;
    /// Dispatch a kernel against the axis at `axis_index`. Returns
    /// the kernel's output bytes (length up to [`MAX_OUTPUT_BYTES`]).
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when `axis_index`
    /// is out of range or the axis dispatcher rejects the input.
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-030 blanket: every [`crate::enforcement::Hasher`] is
/// automatically an [`AxisTuple`] of arity 1 โ€” the canonical
/// hash axis at position 0, kernel id 0.
impl<H: crate::enforcement::Hasher> AxisTuple for H {
    const AXIS_COUNT: usize = 1;
    const MAX_OUTPUT_BYTES: usize = <H as crate::enforcement::Hasher>::OUTPUT_BYTES;
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        if axis_index != 0 || kernel_id != 0 {
            return Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/axis/HasherBlanket",
                constraint_iri: "https://uor.foundation/axis/HasherBlanket/canonicalDispatch",
                property_iri: "https://uor.foundation/axis/axisIndex",
                expected_range: "https://uor.foundation/axis/CanonicalHashAxis",
                min_count: 0,
                max_count: 1,
                kind: crate::ViolationKind::ValueCheck,
            });
        }
        let mut hasher = <H as crate::enforcement::Hasher>::initial();
        hasher = hasher.fold_bytes(input);
        let digest = hasher.finalize();
        let n_max = <H as crate::enforcement::Hasher>::OUTPUT_BYTES;
        let n = if n_max > out.len() { out.len() } else { n_max };
        let mut i = 0;
        while i < n {
            out[i] = digest[i];
            i += 1;
        }
        Ok(n)
    }
}

/// ADR-030: 1-tuple AxisTuple impl โ€” applications selecting a single axis.
impl<A0: AxisExtension> AxisTuple for (A0,) {
    const AXIS_COUNT: usize = 1;
    const MAX_OUTPUT_BYTES: usize = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 1,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-030: 2-tuple AxisTuple impl.
impl<A0: AxisExtension, A1: AxisExtension> AxisTuple for (A0, A1) {
    const AXIS_COUNT: usize = 2;
    const MAX_OUTPUT_BYTES: usize = {
        let a = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
        let b = <A1 as AxisExtension>::MAX_OUTPUT_BYTES;
        if a > b {
            a
        } else {
            b
        }
    };
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            1 => <A1 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 2,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-030: 3-tuple AxisTuple impl.
impl<A0: AxisExtension, A1: AxisExtension, A2: AxisExtension> AxisTuple for (A0, A1, A2) {
    const AXIS_COUNT: usize = 3;
    const MAX_OUTPUT_BYTES: usize = {
        let a0 = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a1 = <A1 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a2 = <A2 as AxisExtension>::MAX_OUTPUT_BYTES;
        let mut m = a0;
        if a1 > m {
            m = a1;
        }
        if a2 > m {
            m = a2;
        }
        m
    };
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            1 => <A1 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            2 => <A2 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 3,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-030: 4-tuple AxisTuple impl.
impl<A0: AxisExtension, A1: AxisExtension, A2: AxisExtension, A3: AxisExtension> AxisTuple
    for (A0, A1, A2, A3)
{
    const AXIS_COUNT: usize = 4;
    const MAX_OUTPUT_BYTES: usize = {
        let a0 = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a1 = <A1 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a2 = <A2 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a3 = <A3 as AxisExtension>::MAX_OUTPUT_BYTES;
        let mut m = a0;
        if a1 > m {
            m = a1;
        }
        if a2 > m {
            m = a2;
        }
        if a3 > m {
            m = a3;
        }
        m
    };
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            1 => <A1 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            2 => <A2 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            3 => <A3 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 4,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-030: 5-tuple AxisTuple impl.
impl<
        A0: AxisExtension,
        A1: AxisExtension,
        A2: AxisExtension,
        A3: AxisExtension,
        A4: AxisExtension,
    > AxisTuple for (A0, A1, A2, A3, A4)
{
    const AXIS_COUNT: usize = 5;
    const MAX_OUTPUT_BYTES: usize = {
        let a0 = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a1 = <A1 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a2 = <A2 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a3 = <A3 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a4 = <A4 as AxisExtension>::MAX_OUTPUT_BYTES;
        let mut m = a0;
        if a1 > m {
            m = a1;
        }
        if a2 > m {
            m = a2;
        }
        if a3 > m {
            m = a3;
        }
        if a4 > m {
            m = a4;
        }
        m
    };
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            1 => <A1 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            2 => <A2 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            3 => <A3 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            4 => <A4 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 5,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-030: 6-tuple AxisTuple impl.
impl<
        A0: AxisExtension,
        A1: AxisExtension,
        A2: AxisExtension,
        A3: AxisExtension,
        A4: AxisExtension,
        A5: AxisExtension,
    > AxisTuple for (A0, A1, A2, A3, A4, A5)
{
    const AXIS_COUNT: usize = 6;
    const MAX_OUTPUT_BYTES: usize = {
        let a0 = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a1 = <A1 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a2 = <A2 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a3 = <A3 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a4 = <A4 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a5 = <A5 as AxisExtension>::MAX_OUTPUT_BYTES;
        let mut m = a0;
        if a1 > m {
            m = a1;
        }
        if a2 > m {
            m = a2;
        }
        if a3 > m {
            m = a3;
        }
        if a4 > m {
            m = a4;
        }
        if a5 > m {
            m = a5;
        }
        m
    };
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            1 => <A1 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            2 => <A2 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            3 => <A3 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            4 => <A4 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            5 => <A5 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 6,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-030: 7-tuple AxisTuple impl.
impl<
        A0: AxisExtension,
        A1: AxisExtension,
        A2: AxisExtension,
        A3: AxisExtension,
        A4: AxisExtension,
        A5: AxisExtension,
        A6: AxisExtension,
    > AxisTuple for (A0, A1, A2, A3, A4, A5, A6)
{
    const AXIS_COUNT: usize = 7;
    const MAX_OUTPUT_BYTES: usize = {
        let a0 = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a1 = <A1 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a2 = <A2 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a3 = <A3 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a4 = <A4 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a5 = <A5 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a6 = <A6 as AxisExtension>::MAX_OUTPUT_BYTES;
        let mut m = a0;
        if a1 > m {
            m = a1;
        }
        if a2 > m {
            m = a2;
        }
        if a3 > m {
            m = a3;
        }
        if a4 > m {
            m = a4;
        }
        if a5 > m {
            m = a5;
        }
        if a6 > m {
            m = a6;
        }
        m
    };
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            1 => <A1 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            2 => <A2 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            3 => <A3 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            4 => <A4 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            5 => <A5 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            6 => <A6 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 7,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-030: 8-tuple AxisTuple impl.
impl<
        A0: AxisExtension,
        A1: AxisExtension,
        A2: AxisExtension,
        A3: AxisExtension,
        A4: AxisExtension,
        A5: AxisExtension,
        A6: AxisExtension,
        A7: AxisExtension,
    > AxisTuple for (A0, A1, A2, A3, A4, A5, A6, A7)
{
    const AXIS_COUNT: usize = 8;
    const MAX_OUTPUT_BYTES: usize = {
        let a0 = <A0 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a1 = <A1 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a2 = <A2 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a3 = <A3 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a4 = <A4 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a5 = <A5 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a6 = <A6 as AxisExtension>::MAX_OUTPUT_BYTES;
        let a7 = <A7 as AxisExtension>::MAX_OUTPUT_BYTES;
        let mut m = a0;
        if a1 > m {
            m = a1;
        }
        if a2 > m {
            m = a2;
        }
        if a3 > m {
            m = a3;
        }
        if a4 > m {
            m = a4;
        }
        if a5 > m {
            m = a5;
        }
        if a6 > m {
            m = a6;
        }
        if a7 > m {
            m = a7;
        }
        m
    };
    fn dispatch(
        axis_index: u32,
        kernel_id: u32,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        match axis_index {
            0 => <A0 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            1 => <A1 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            2 => <A2 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            3 => <A3 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            4 => <A4 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            5 => <A5 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            6 => <A6 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            7 => <A7 as AxisExtension>::dispatch_kernel(kernel_id, input, out),
            _ => Err(crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/AxisTupleShape",
                constraint_iri: "https://uor.foundation/pipeline/AxisTupleShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/axisIndex",
                expected_range: "https://uor.foundation/pipeline/AxisIndex",
                min_count: 0,
                max_count: 8,
                kind: crate::ViolationKind::ValueCheck,
            }),
        }
    }
}

/// ADR-036: maximum number of resolvers a single application's
/// `ResolverTuple` may carry. Foundation-fixed at twice
/// [`MAX_AXIS_TUPLE_ARITY`] to accommodate ADR-035's eight
/// resolver-bound ฯˆ-Term categories with eight headroom positions
/// for future ADR-013/TR-08 substrate amendments.
pub const MAX_RESOLVER_TUPLE_ARITY: usize = 16;

/// ADR-036: foundation-internal discriminator emitted by every
/// `Null<Category>Resolver` impl when the catamorphism's resolver-
/// bound ฯˆ-Term fold-rule consults a resolver category whose
/// `ResolverTuple` accessor returns the foundation-Null impl. The
/// evaluator translates this into a `PipelineFailure::ShapeViolation`
/// carrying the `https://uor.foundation/resolver/RESOLVER_ABSENT`
/// shape IRI; ADR-022 D3 G9's `Term::Try` default-propagation handler
/// recovers it when the verb body wraps the ฯˆ-Term.
pub const RESOLVER_ABSENT_DISCRIMINATOR: u8 = 0xff;

/// ADR-036: resolver-category enum identifying which resolver-bound
/// substrate operation each `ResolverTuple` position satisfies. Each
/// variant corresponds to one resolver-bound ฯˆ-Term variant per
/// ADR-035; future ADR-013/TR-08 substrate amendments add variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolverCategory {
    /// ฯˆ_1 โ€” per-value bytes โ†’ SimplicialComplex (NerveResolver).
    Nerve,
    /// ฯˆ_2 โ€” SimplicialComplex โ†’ ChainComplex (ChainComplexResolver).
    ChainComplex,
    /// ฯˆ_3 โ€” ChainComplex โ†’ HomologyGroups (HomologyGroupResolver).
    HomologyGroup,
    /// ฯˆ_5 โ€” ChainComplex โ†’ CochainComplex (CochainComplexResolver).
    CochainComplex,
    /// ฯˆ_6 โ€” CochainComplex โ†’ CohomologyGroups (CohomologyGroupResolver).
    CohomologyGroup,
    /// ฯˆ_7 โ€” SimplicialComplex โ†’ PostnikovTower (PostnikovResolver).
    Postnikov,
    /// ฯˆ_8 โ€” PostnikovTower โ†’ HomotopyGroups (HomotopyGroupResolver).
    HomotopyGroup,
    /// ฯˆ_9 โ€” HomotopyGroups โ†’ KInvariants (KInvariantResolver).
    KInvariant,
}

/// ADR-036: tuple-of-bounded-types parameter on the model declaration
/// carrying application-provided resolver instances for the resolver-
/// bound ฯˆ-Term variants per ADR-035. Sealed via
/// [`__sdk_seal::Sealed`]: only the SDK `resolver!` macro emits impls.
pub trait ResolverTuple: __sdk_seal::Sealed {
    /// Number of resolver positions in this tuple (bounded by `MAX_RESOLVER_TUPLE_ARITY`).
    const ARITY: usize;
    /// Resolver category at each tuple position.
    const CATEGORIES: &'static [ResolverCategory];
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_1 output โ€”
/// the simplicial-complex serialization produced by `NerveResolver::resolve`.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SimplicialComplexBytes<'a>(pub &'a [u8]);

impl<'a> SimplicialComplexBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_2 output โ€”
/// the chain-complex serialization produced by `ChainComplexResolver::resolve`.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ChainComplexBytes<'a>(pub &'a [u8]);

impl<'a> ChainComplexBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_3 output โ€”
/// the homology-groups serialization produced by `HomologyGroupResolver::resolve`.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HomologyGroupsBytes<'a>(pub &'a [u8]);

impl<'a> HomologyGroupsBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_4 output โ€”
/// the Betti-number tuple serialization produced by the resolver-free `Term::Betti` fold-rule (a byte projection of HomologyGroupsBytes).
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BettiNumbersBytes<'a>(pub &'a [u8]);

impl<'a> BettiNumbersBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_5 output โ€”
/// the cochain-complex serialization produced by `CochainComplexResolver::resolve`.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CochainComplexBytes<'a>(pub &'a [u8]);

impl<'a> CochainComplexBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_6 output โ€”
/// the cohomology-groups serialization produced by `CohomologyGroupResolver::resolve`.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CohomologyGroupsBytes<'a>(pub &'a [u8]);

impl<'a> CohomologyGroupsBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_7 output โ€”
/// the Postnikov-tower serialization produced by `PostnikovResolver::resolve`.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PostnikovTowerBytes<'a>(pub &'a [u8]);

impl<'a> PostnikovTowerBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_8 output โ€”
/// the homotopy-groups serialization produced by `HomotopyGroupResolver::resolve`.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HomotopyGroupsBytes<'a>(pub &'a [u8]);

impl<'a> HomotopyGroupsBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Wiki ADR-041: zero-cost typed-coordinate carrier for ฯˆ_9 output โ€”
/// the ฮบ-label byte serialization produced by `KInvariantResolver::resolve` โ€” the canonical k-invariants-branch output (ADR-035) classifying the input's homotopy type up to weak equivalence.
///
/// `#[repr(transparent)]` over `&'a [u8]`: layout identical to a byte
/// slice; the type wrapper is purely compile-time discrimination so
/// ฯˆ-stage composition is type-checked at the resolver-impl boundary.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KInvariantsBytes<'a>(pub &'a [u8]);

impl<'a> KInvariantsBytes<'a> {
    /// Borrow the underlying byte slice.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.0
    }
    /// Length of the underlying byte slice.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    /// Whether the underlying byte slice is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// ADR-036 resolver trait: ฯˆ_1 โ€” per-value bytes โ†’ SimplicialComplex per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait NerveResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: &[u8],
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 resolver trait: ฯˆ_2 โ€” SimplicialComplex โ†’ ChainComplex per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait ChainComplexResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: SimplicialComplexBytes<'_>,
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 resolver trait: ฯˆ_3 โ€” ChainComplex โ†’ HomologyGroups per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait HomologyGroupResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: ChainComplexBytes<'_>,
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 resolver trait: ฯˆ_5 โ€” ChainComplex โ†’ CochainComplex per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait CochainComplexResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: ChainComplexBytes<'_>,
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 resolver trait: ฯˆ_6 โ€” CochainComplex โ†’ CohomologyGroups per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait CohomologyGroupResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: CochainComplexBytes<'_>,
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 resolver trait: ฯˆ_7 โ€” SimplicialComplex โ†’ PostnikovTower per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait PostnikovResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: SimplicialComplexBytes<'_>,
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 resolver trait: ฯˆ_8 โ€” PostnikovTower โ†’ HomotopyGroups per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait HomotopyGroupResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: PostnikovTowerBytes<'_>,
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 resolver trait: ฯˆ_9 โ€” HomotopyGroups โ†’ KInvariants per ADR-035.
///
/// Parameterized by the model's H-axis (`H: Hasher` per ADR-022 D5) so
/// resolver impls compute content-addressed fingerprints using the
/// model's chosen hash impl. Sealed via [`__sdk_seal::Sealed`]: only
/// the SDK `resolver!` macro emits impls. Foundation provides a Null
/// impl whose `resolve` emits the `RESOLVER_ABSENT` shape violation.
///
/// ADR-041: `input` is a zero-cost typed carrier so ฯˆ-stage
/// composition is type-checked at the resolver-impl boundary.
pub trait KInvariantResolver<H: crate::enforcement::Hasher>: __sdk_seal::Sealed {
    /// Resolve per-value content for this category.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the resolver
    /// cannot produce content (e.g., the foundation Null impl carrying
    /// the `RESOLVER_ABSENT` discriminator).
    fn resolve(
        &self,
        input: HomotopyGroupsBytes<'_>,
        out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `NerveResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasNerveResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `NerveResolver` impl this ResolverTuple carries.
    fn nerve_resolver(&self) -> &dyn NerveResolver<H>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `ChainComplexResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasChainComplexResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `ChainComplexResolver` impl this ResolverTuple carries.
    fn chain_complex_resolver(&self) -> &dyn ChainComplexResolver<H>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `HomologyGroupResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasHomologyGroupResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `HomologyGroupResolver` impl this ResolverTuple carries.
    fn homology_group_resolver(&self) -> &dyn HomologyGroupResolver<H>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `CochainComplexResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasCochainComplexResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `CochainComplexResolver` impl this ResolverTuple carries.
    fn cochain_complex_resolver(&self) -> &dyn CochainComplexResolver<H>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `CohomologyGroupResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasCohomologyGroupResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `CohomologyGroupResolver` impl this ResolverTuple carries.
    fn cohomology_group_resolver(&self) -> &dyn CohomologyGroupResolver<H>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `PostnikovResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasPostnikovResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `PostnikovResolver` impl this ResolverTuple carries.
    fn postnikov_resolver(&self) -> &dyn PostnikovResolver<H>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `HomotopyGroupResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasHomotopyGroupResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `HomotopyGroupResolver` impl this ResolverTuple carries.
    fn homotopy_group_resolver(&self) -> &dyn HomotopyGroupResolver<H>;
}

/// ADR-036 marker trait: ResolverTuple positions including a `KInvariantResolver`.
/// The `prism_model!` macro infers the where-clause bound for each
/// resolver-bound ฯˆ-Term variant a verb body emits.
pub trait HasKInvariantResolver<H: crate::enforcement::Hasher>: ResolverTuple {
    /// Returns the `KInvariantResolver` impl this ResolverTuple carries.
    fn k_invariant_resolver(&self) -> &dyn KInvariantResolver<H>;
}

/// ADR-036 Null resolver tuple โ€” the resolver-absent default.
/// `ResolverTuple` impl with `ARITY = 0` and an empty CATEGORIES list.
/// Applications that don't declare a `resolver!` block default to this.
#[derive(Debug, Clone, Copy, Default)]
pub struct NullResolverTuple;

impl __sdk_seal::Sealed for NullResolverTuple {}

impl ResolverTuple for NullResolverTuple {
    const ARITY: usize = 0;
    const CATEGORIES: &'static [ResolverCategory] = &[];
}

/// ADR-036 Null `NerveResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullNerveResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullNerveResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullNerveResolver<H> {}

impl<H: crate::enforcement::Hasher> NerveResolver<H> for NullNerveResolver<H> {
    fn resolve(
        &self,
        _input: &[u8],
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/Nerve",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036 Null `ChainComplexResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullChainComplexResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullChainComplexResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullChainComplexResolver<H> {}

impl<H: crate::enforcement::Hasher> ChainComplexResolver<H> for NullChainComplexResolver<H> {
    fn resolve(
        &self,
        _input: SimplicialComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/ChainComplex",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036 Null `HomologyGroupResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullHomologyGroupResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullHomologyGroupResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullHomologyGroupResolver<H> {}

impl<H: crate::enforcement::Hasher> HomologyGroupResolver<H> for NullHomologyGroupResolver<H> {
    fn resolve(
        &self,
        _input: ChainComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/HomologyGroup",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036 Null `CochainComplexResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullCochainComplexResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullCochainComplexResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullCochainComplexResolver<H> {}

impl<H: crate::enforcement::Hasher> CochainComplexResolver<H> for NullCochainComplexResolver<H> {
    fn resolve(
        &self,
        _input: ChainComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/CochainComplex",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036 Null `CohomologyGroupResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullCohomologyGroupResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullCohomologyGroupResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullCohomologyGroupResolver<H> {}

impl<H: crate::enforcement::Hasher> CohomologyGroupResolver<H> for NullCohomologyGroupResolver<H> {
    fn resolve(
        &self,
        _input: CochainComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/CohomologyGroup",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036 Null `PostnikovResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullPostnikovResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullPostnikovResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullPostnikovResolver<H> {}

impl<H: crate::enforcement::Hasher> PostnikovResolver<H> for NullPostnikovResolver<H> {
    fn resolve(
        &self,
        _input: SimplicialComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/Postnikov",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036 Null `HomotopyGroupResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullHomotopyGroupResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullHomotopyGroupResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullHomotopyGroupResolver<H> {}

impl<H: crate::enforcement::Hasher> HomotopyGroupResolver<H> for NullHomotopyGroupResolver<H> {
    fn resolve(
        &self,
        _input: PostnikovTowerBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/HomotopyGroup",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036 Null `KInvariantResolver` impl. `resolve` always emits the
/// `RESOLVER_ABSENT` shape violation โ€” the catamorphism translates this
/// into `PipelineFailure::ShapeViolation` recoverable via `Term::Try`'s
/// default-propagation handler (ADR-022 D3 G9).
#[derive(Debug, Default)]
pub struct NullKInvariantResolver<H: crate::enforcement::Hasher>(core::marker::PhantomData<H>);

impl<H: crate::enforcement::Hasher> NullKInvariantResolver<H> {
    /// Construct a new Null resolver.
    #[must_use]
    pub const fn new() -> Self {
        Self(core::marker::PhantomData)
    }
}

impl<H: crate::enforcement::Hasher> __sdk_seal::Sealed for NullKInvariantResolver<H> {}

impl<H: crate::enforcement::Hasher> KInvariantResolver<H> for NullKInvariantResolver<H> {
    fn resolve(
        &self,
        _input: HomotopyGroupsBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/KInvariant",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `NerveResolver<H>` directly so
/// the `HasNerveResolver<H>` accessor can return `self` cast to `&dyn NerveResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> NerveResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: &[u8],
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/Nerve",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasNerveResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasNerveResolver<H> for NullResolverTuple {
    fn nerve_resolver(&self) -> &dyn NerveResolver<H> {
        self
    }
}

/// ADR-036: NullResolverTuple satisfies `ChainComplexResolver<H>` directly so
/// the `HasChainComplexResolver<H>` accessor can return `self` cast to `&dyn ChainComplexResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> ChainComplexResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: SimplicialComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/ChainComplex",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasChainComplexResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasChainComplexResolver<H> for NullResolverTuple {
    fn chain_complex_resolver(&self) -> &dyn ChainComplexResolver<H> {
        self
    }
}

/// ADR-036: NullResolverTuple satisfies `HomologyGroupResolver<H>` directly so
/// the `HasHomologyGroupResolver<H>` accessor can return `self` cast to `&dyn HomologyGroupResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> HomologyGroupResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: ChainComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/HomologyGroup",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasHomologyGroupResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasHomologyGroupResolver<H> for NullResolverTuple {
    fn homology_group_resolver(&self) -> &dyn HomologyGroupResolver<H> {
        self
    }
}

/// ADR-036: NullResolverTuple satisfies `CochainComplexResolver<H>` directly so
/// the `HasCochainComplexResolver<H>` accessor can return `self` cast to `&dyn CochainComplexResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> CochainComplexResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: ChainComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/CochainComplex",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasCochainComplexResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasCochainComplexResolver<H> for NullResolverTuple {
    fn cochain_complex_resolver(&self) -> &dyn CochainComplexResolver<H> {
        self
    }
}

/// ADR-036: NullResolverTuple satisfies `CohomologyGroupResolver<H>` directly so
/// the `HasCohomologyGroupResolver<H>` accessor can return `self` cast to `&dyn CohomologyGroupResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> CohomologyGroupResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: CochainComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/CohomologyGroup",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasCohomologyGroupResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasCohomologyGroupResolver<H> for NullResolverTuple {
    fn cohomology_group_resolver(&self) -> &dyn CohomologyGroupResolver<H> {
        self
    }
}

/// ADR-036: NullResolverTuple satisfies `PostnikovResolver<H>` directly so
/// the `HasPostnikovResolver<H>` accessor can return `self` cast to `&dyn PostnikovResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> PostnikovResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: SimplicialComplexBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/Postnikov",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasPostnikovResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasPostnikovResolver<H> for NullResolverTuple {
    fn postnikov_resolver(&self) -> &dyn PostnikovResolver<H> {
        self
    }
}

/// ADR-036: NullResolverTuple satisfies `HomotopyGroupResolver<H>` directly so
/// the `HasHomotopyGroupResolver<H>` accessor can return `self` cast to `&dyn HomotopyGroupResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> HomotopyGroupResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: PostnikovTowerBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/HomotopyGroup",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasHomotopyGroupResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasHomotopyGroupResolver<H> for NullResolverTuple {
    fn homotopy_group_resolver(&self) -> &dyn HomotopyGroupResolver<H> {
        self
    }
}

/// ADR-036: NullResolverTuple satisfies `KInvariantResolver<H>` directly so
/// the `HasKInvariantResolver<H>` accessor can return `self` cast to `&dyn KInvariantResolver<H>`.
/// The `resolve` method emits the `RESOLVER_ABSENT` shape violation โ€”
/// recoverable via `Term::Try`'s default-propagation handler (ADR-022 D3 G9).
impl<H: crate::enforcement::Hasher> KInvariantResolver<H> for NullResolverTuple {
    fn resolve(
        &self,
        _input: HomotopyGroupsBytes<'_>,
        _out: &mut [u8],
    ) -> Result<usize, crate::enforcement::ShapeViolation> {
        Err(crate::enforcement::ShapeViolation {
            shape_iri: "https://uor.foundation/resolver/RESOLVER_ABSENT",
            constraint_iri: "https://uor.foundation/resolver/KInvariant",
            property_iri: "https://uor.foundation/resolver/category",
            expected_range: "https://uor.foundation/resolver/Resolver",
            min_count: 0,
            max_count: 1,
            kind: crate::ViolationKind::ValueCheck,
        })
    }
}

/// ADR-036: NullResolverTuple satisfies `HasKInvariantResolver<H>` (returns `self`).
impl<H: crate::enforcement::Hasher> HasKInvariantResolver<H> for NullResolverTuple {
    fn k_invariant_resolver(&self) -> &dyn KInvariantResolver<H> {
        self
    }
}

/// Wiki ADR-042: typed view over a successful `Grounded<T, Tag>` as the
/// inhabitance-verdict envelope produced by the canonical k-invariants
/// branch (ฯˆ_1 โ†’ ฯˆ_7 โ†’ ฯˆ_8 โ†’ ฯˆ_9 per ADR-035).
///
/// Zero-cost โ€” `#[repr(transparent)]` over `&'a Grounded<T, Tag>`. Construct
/// via [`crate::enforcement::Grounded::as_inhabitance_certificate`].
///
/// Realizes `cert:InhabitanceCertificate` per the ontology
/// (`<https://uor.foundation/cert/InhabitanceCertificate>`). Foundation
/// uses the suffix `View` here to distinguish this zero-cost typed
/// view from the existing sealed-shim `crate::enforcement::InhabitanceCertificate`
/// value carrier; the wiki names this type `InhabitanceCertificate<'a, T>`
/// in ADR-042 and the typed-view role is the load-bearing concern. The ฮบ-label,
/// concrete `cert:witness`, and `cert:searchTrace` are accessor methods
/// over the underlying `Grounded` โ€” no allocation, no per-application
/// re-derivation.
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
pub struct InhabitanceCertificateView<'a, T: crate::enforcement::GroundedShape, Tag = T>(
    pub &'a crate::enforcement::Grounded<T, Tag>,
);

impl<'a, T: crate::enforcement::GroundedShape, Tag> InhabitanceCertificateView<'a, T, Tag> {
    /// The ฮบ-label โ€” the homotopy-classification structural witness at
    /// ฯˆ_9 per ADR-035. The bytes are the `Term::KInvariants` emission's
    /// output (exposed via `Grounded::output_bytes`) wrapped in the
    /// ADR-041 typed-coordinate carrier so cross-stage composition is
    /// type-checked.
    #[inline]
    #[must_use]
    pub fn kappa_label(&self) -> KInvariantsBytes<'_> {
        KInvariantsBytes(self.0.output_bytes())
    }

    /// The concrete `cert:witness` ValueTuple โ€” derivable from
    /// `Term::Nerve`'s 0-simplices at ฯˆ_1 (the per-value bytes the
    /// model's NerveResolver consumed). Foundation exposes the
    /// `Grounded`'s bindings as the value-tuple surface; applications
    /// whose admission relations carry richer witness data project
    /// through the binding table's content addresses.
    #[inline]
    #[must_use]
    pub fn witness(&self) -> WitnessValueTuple<'_> {
        WitnessValueTuple {
            grounded_bindings: self.0,
        }
    }

    /// The `cert:searchTrace` โ€” realized as
    /// `<Grounded>::derivation::<H>(...).replay::<...>()` per ADR-039.
    /// Foundation surfaces the derivation pointer; applications choose
    /// which `Hasher` impl and `HostBounds` parameters to instantiate
    /// the replay with.
    #[inline]
    #[must_use]
    pub fn certificate(
        &self,
    ) -> &crate::enforcement::Validated<crate::enforcement::GroundingCertificate> {
        self.0.certificate()
    }

    /// The certified type's stable IRI โ€” the `<T as ConstrainedTypeShape>::IRI`
    /// the application registered as the route's output shape.
    #[inline]
    #[must_use]
    pub fn certified_type(&self) -> &'static str
    where
        T: ConstrainedTypeShape,
    {
        <T as ConstrainedTypeShape>::IRI
    }
}

/// Wiki ADR-042: concrete `cert:witness` ValueTuple view. Borrows the
/// underlying `Grounded`'s bindings; iterates as `(content_address, bytes)`
/// pairs corresponding to `Term::Nerve`'s 0-simplices.
#[derive(Clone, Copy)]
pub struct WitnessValueTuple<'a> {
    /// Foundation-internal: the underlying Grounded reference. Public-API
    /// access goes through the accessor methods.
    grounded_bindings: &'a dyn WitnessTupleSource,
}

impl<'a> core::fmt::Debug for WitnessValueTuple<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("WitnessValueTuple")
            .field("binding_count", &self.grounded_bindings.binding_count())
            .finish()
    }
}

impl<'a> WitnessValueTuple<'a> {
    /// Number of bindings in the witness tuple.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.grounded_bindings.binding_count()
    }

    /// Whether the witness tuple is empty.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.grounded_bindings.binding_count() == 0
    }

    /// The witness's content-addressed binding bytes at position `idx`.
    /// Returns `None` if `idx >= len()`.
    #[inline]
    #[must_use]
    pub fn binding_bytes(&self, idx: usize) -> Option<&'static [u8]> {
        self.grounded_bindings.binding_bytes_at(idx)
    }
}

/// Foundation-internal trait letting `Grounded<T, Tag>` expose binding
/// access to `WitnessValueTuple` without leaking the generic-parameter
/// plumbing into the witness-view type.
pub trait WitnessTupleSource {
    /// Number of bindings in this source's table.
    fn binding_count(&self) -> usize;
    /// Binding bytes at the given index, or `None` if out of range.
    fn binding_bytes_at(&self, idx: usize) -> Option<&'static [u8]>;
}

impl<T: crate::enforcement::GroundedShape, Tag> WitnessTupleSource
    for crate::enforcement::Grounded<T, Tag>
{
    fn binding_count(&self) -> usize {
        self.iter_bindings().count()
    }
    fn binding_bytes_at(&self, idx: usize) -> Option<&'static [u8]> {
        self.iter_bindings().nth(idx).map(|e| e.bytes)
    }
}

/// Wiki ADR-042: typed view over an `Err(PipelineFailure)` as the
/// inhabitance-impossibility envelope. Realizes
/// `cert:InhabitanceImpossibilityCertificate` per the ontology:
/// `<https://uor.foundation/cert/InhabitanceImpossibilityCertificate>`.
///
/// Zero-cost โ€” `#[repr(transparent)]` over `&'a PipelineFailure`. Construct
/// via [`crate::enforcement::PipelineFailure::as_inhabitance_impossibility_certificate`].
#[repr(transparent)]
#[derive(Debug, Clone, Copy)]
pub struct InhabitanceImpossibilityCertificate<'a>(pub &'a crate::enforcement::PipelineFailure);

impl<'a> InhabitanceImpossibilityCertificate<'a> {
    /// The contradiction-proof bytes โ€” canonical-form encoding of the
    /// failure trace, suitable for Lean 4 by-contradiction reconstruction
    /// per ADR-039 + ADR-042. Foundation provides the shape-violation's
    /// `shape_iri` bytes as the proof's canonical-form witness; richer
    /// contradiction data is application-provided via the failure trace.
    #[inline]
    #[must_use]
    pub fn contradiction_proof(&self) -> &'static [u8] {
        match self.0 {
            crate::enforcement::PipelineFailure::ShapeViolation { report } => {
                report.shape_iri.as_bytes()
            }
            _ => b"https://uor.foundation/proof/InhabitanceImpossibilityWitness",
        }
    }

    /// Borrow the underlying `PipelineFailure`.
    #[inline]
    #[must_use]
    pub fn failure(&self) -> &crate::enforcement::PipelineFailure {
        self.0
    }
}

/// Wiki ADR-042: typed verdict-envelope accessors on `PipelineFailure`.
impl crate::enforcement::PipelineFailure {
    /// Borrow `self` as an [`InhabitanceImpossibilityCertificate`] view
    /// when the failure's structural cause is an inhabitance-impossibility
    /// witness (per ADR-042). Returns `Some` for `ShapeViolation` whose
    /// `shape_iri` carries one of the foundation-declared inhabitance
    /// proof IRIs (e.g. `RESOLVER_ABSENT`, the constraint-nerve-empty-
    /// Kan-completion sentinel); foundation accepts `Some(...)` universally
    /// for `PipelineFailure` so applications consume the verdict-envelope
    /// view at their discretion.
    #[inline]
    #[must_use]
    pub fn as_inhabitance_impossibility_certificate(
        &self,
    ) -> Option<InhabitanceImpossibilityCertificate<'_>> {
        Some(InhabitanceImpossibilityCertificate(self))
    }
}

/// Wiki ADR-042: `predicate:InhabitanceDispatchTable` consultation helper.
/// Application NerveResolver impls MAY call this helper internally for
/// decider routing across the ontology's three canonical rule arms
/// (TwoSatDecider, HornSatDecider, ResidualVerdictResolver). Foundation
/// provides the dispatch surface; rule-arm semantics are application-
/// provided through the closures the caller threads in.
pub mod inhabitance {
    /// Three rule arms a `predicate:InhabitanceDispatchTable` consultation
    /// dispatches through, per the ontology's canonical decider routing.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum InhabitanceRuleArm {
        ///         TwoSatDecider โ€” `predicate:TwoSatDecider`. Decides 2-SAT constraint nerves.
        TwoSatDecider,
        ///         HornSatDecider โ€” `predicate:HornSatDecider`. Decides Horn-SAT constraint nerves.
        HornSatDecider,
        ///         ResidualVerdictResolver โ€” `predicate:ResidualVerdictResolver`. Residual
        ///         catch-all for constraint nerves outside the 2-SAT / Horn-SAT coverage.
        ResidualVerdictResolver,
    }

    /// Dispatch through the `predicate:InhabitanceDispatchTable` rule arms in
    /// ontology order (TwoSatDecider โ†’ HornSatDecider โ†’ ResidualVerdictResolver).
    /// Each closure returns `Some(verdict)` if the arm decides, or `None` to
    /// delegate to the next arm. Returns the first decisive verdict.
    #[inline]
    pub fn dispatch_through_table<F1, F2, F3, V>(
        two_sat: F1,
        horn_sat: F2,
        residual: F3,
    ) -> (InhabitanceRuleArm, V)
    where
        F1: FnOnce() -> Option<V>,
        F2: FnOnce() -> Option<V>,
        F3: FnOnce() -> V,
    {
        if let Some(v) = two_sat() {
            return (InhabitanceRuleArm::TwoSatDecider, v);
        }
        if let Some(v) = horn_sat() {
            return (InhabitanceRuleArm::HornSatDecider, v);
        }
        (InhabitanceRuleArm::ResidualVerdictResolver, residual())
    }
}

/// Foundation-internal seal module โ€” `__` prefix and `#[doc(hidden)]`
/// signal "for the SDK macro only." The `prism_model!` macro emits
/// `impl __sdk_seal::Sealed for <Model>` and
/// `impl __sdk_seal::Sealed for <RouteWitness>` alongside the
/// `PrismModel` and `FoundationClosed` impls.
#[doc(hidden)]
pub mod __sdk_seal {
    /// The supertrait `FoundationClosed` and `PrismModel` declare to
    /// seal application code out of impl'ing them. External crates that
    /// name this trait directly are syntactically permitted by Rust's
    /// visibility rules but architecturally non-conforming per wiki
    /// ADR-022 D1 โ€” the `prism_model!` proc-macro from
    /// `uor-foundation-sdk` is the only sanctioned emitter of impls.
    pub trait Sealed {}
}

/// Trait โ€” `Route` types satisfying this bound are closed under
/// foundation vocabulary: every node in the witnessed term tree is a
/// foundation-vocabulary item.
/// Sealed via [`__sdk_seal::Sealed`]: the route-emitting `prism_model!`
/// macro from `uor-foundation-sdk` is the only sanctioned producer of
/// impls (per ADR-022 D1). Wiki ADR-020 specifies this as the
/// load-bearing enforcement of bilateral compile-time UORassembly
/// (TC-04, ADR-006) for whole-model declarations: a route that imports
/// a function outside foundation vocabulary receives no
/// `FoundationClosed` impl, and the application fails to compile with
/// an unsatisfied bound on `Route`.
/// # `arena_slice`
/// Per ADR-022 D5, [`run_route`] consumes the route's term-tree arena.
/// The `prism_model!` macro emits the [`arena_slice`] impl returning
/// the parsed closure body's term tree as a static slice. The
/// foundation-sanctioned identity route returns an empty slice
/// (no transformation, input passes through to output).
/// On stable Rust without `generic_const_exprs`, the slice form is
/// the equivalent of the wiki's `&'static TermArena` bound: it
/// exposes the term tree without forcing every Route to carry the
/// arena's `CAP` const-generic through the trait.
pub trait FoundationClosed: __sdk_seal::Sealed {
    /// Returns the term-tree arena slice the `prism_model!` macro emitted for
    /// this route witness. [`run_route`] reads this to populate the
    /// `CompileUnit`'s root_term before invoking [`run`].
    fn arena_slice() -> &'static [crate::enforcement::Term];
}

/// Trait โ€” `ConstrainedTypeShape` impls used as a `PrismModel::Input`
/// MUST implement this trait so [`run_route`] can serialize the
/// runtime input value into the `CompileUnit` binding table per wiki
/// ADR-023.
/// # Implementation contract
/// [`into_binding_bytes`] writes the canonical content-addressable byte
/// sequence for the value into the caller-provided buffer and returns
/// the written length. The serialization MUST be deterministic โ€” two
/// values that compare equal MUST produce byte sequences that compare
/// equal โ€” so the input's content fingerprint is a function of the
/// value alone.
/// [`MAX_BYTES`] is the maximum byte length any value of this shape can
/// produce. [`run_route`] uses it to size the on-stack buffer and
/// rejects inputs whose declared `MAX_BYTES` exceeds the foundation
/// ceiling [`ROUTE_INPUT_BUFFER_BYTES`].
/// # Sealing
/// Sealed via [`__sdk_seal::Sealed`] (the same supertrait as
/// [`FoundationClosed`] and [`PrismModel`]): foundation sanctions the
/// identity-route impl on [`ConstrainedTypeInput`] directly; the SDK
/// shape macros (`product_shape!`, `coproduct_shape!`,
/// `cartesian_product_shape!`) emit the impl alongside the
/// `ConstrainedTypeShape` impl. Application authors implementing a
/// custom `ConstrainedTypeShape` use the `prism_model!` macro's input
/// declaration to obtain the impl.
pub trait IntoBindingValue: ConstrainedTypeShape + __sdk_seal::Sealed {
    /// Maximum byte length any value of this shape can produce when
    /// serialized via [`into_binding_bytes`]. Used by [`run_route`] to
    /// size the on-stack buffer and reject inputs that would overflow.
    const MAX_BYTES: usize;

    /// Serialize this input value into the binding-table form. `out` is a
    /// fixed-capacity buffer the call-site provides; the implementation
    /// writes the canonical content-addressable byte sequence and returns
    /// the written length.
    /// # Errors
    /// Returns [`crate::enforcement::ShapeViolation`] when the canonical
    /// serialization cannot be produced (e.g., a coproduct tag is out of
    /// range, a constraint cannot be witnessed) or when `out.len()` is
    /// smaller than the bytes the value requires.
    #[allow(clippy::wrong_self_convention)]
    fn into_binding_bytes(
        &self,
        out: &mut [u8],
    ) -> core::result::Result<usize, crate::enforcement::ShapeViolation>;
}

/// Foundation-side ceiling for the on-stack buffer [`run_route`] uses to
/// materialize an input value's canonical bytes per wiki ADR-023.
/// On stable Rust 1.83 we cannot size the buffer with
/// `[u8; <T as IntoBindingValue>::MAX_BYTES]` (that requires nightly
/// `generic_const_exprs`). This foundation-fixed ceiling is the
/// architecturally-equivalent stable-Rust form: inputs declaring
/// `MAX_BYTES <= ROUTE_INPUT_BUFFER_BYTES` flow through the catamorphism;
/// inputs declaring a larger `MAX_BYTES` are rejected at runtime.
/// Wiki ADR-037: alias of [`HostBounds::ROUTE_INPUT_BUFFER_BYTES`] via
/// [`DefaultHostBounds`].
pub const ROUTE_INPUT_BUFFER_BYTES: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::ROUTE_INPUT_BUFFER_BYTES;

/// Foundation-side ceiling for the on-stack buffer [`run_route`] uses to
/// carry the catamorphism's evaluation result into the `Grounded<T>`'s
/// output payload per wiki ADR-028. Parallel to
/// [`ROUTE_INPUT_BUFFER_BYTES`].
/// Output shapes whose `IntoBindingValue::MAX_BYTES` exceeds this ceiling
/// are rejected at runtime by [`run_route`] (the symmetric output-side
/// rejection rule paralleling ADR-023's input-side rule).
/// Wiki ADR-037: alias of [`HostBounds::ROUTE_OUTPUT_BUFFER_BYTES`] via
/// [`DefaultHostBounds`].
pub const ROUTE_OUTPUT_BUFFER_BYTES: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::ROUTE_OUTPUT_BUFFER_BYTES;

/// Foundation-fixed threshold for the closure-body grammar `fold_n`'s
/// unroll-vs-`Term::Recurse` lowering rule per wiki ADR-026 G14.
/// `fold_n` calls with const-literal counts at or below this threshold
/// unroll into a sequential `Term::Application` chain; counts above
/// (or parametric counts) lower to `Term::Recurse` with a descent-
/// measure-bounded fold. The fixed threshold means two implementations
/// compiling the same closure body emit the same Term tree.
/// Wiki ADR-037: alias of [`HostBounds::FOLD_UNROLL_THRESHOLD`] via
/// [`DefaultHostBounds`].
pub const FOLD_UNROLL_THRESHOLD: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::FOLD_UNROLL_THRESHOLD;

/// The application author's typed-iso contract: an `Input` feature type, an
/// `Output` label type, and a type-level `Route` witness of the term tree
/// mapping one to the other. Per the wiki's ADR-020 โ€” "the model I am
/// declaring" โ€” codifies a hylomorphism-with-verifiable-round-trip:
/// the catamorphism from `Input` to `Result<Grounded<Output>, PipelineFailure>`
/// (see [`run`]) plus the recoverable anamorphism through the trace to
/// `Certified<GroundingCertificate>` (see
/// [`crate::enforcement::replay::certify_from_trace`]).
/// The trait's name derives from the implementation crate, not from the
/// categorical Prism optic.
/// # Compile-time guarantees
/// Implementing `PrismModel` for an application type yields, by virtue of
/// the trait's bounds:
/// - **Closure under foundation vocabulary**: the `Route` bound
///   ([`FoundationClosed`]) is satisfied iff every term in the route witness
///   comes from foundation's signature endofunctor F (wiki ADR-019). A
///   hand-rolled composition that escapes foundation vocabulary fails to
///   compile.
/// - **Zero-cost runtime** (TC-01): `forward` is the catamorphism induced
///   by initiality of `Term` (ADR-019); the application's compile time
///   monomorphizes the catamorphism into native code.
/// - **Seal coverage** (TC-02): `forward`'s output is
///   `Grounded<Self::Output>` constructed via the seal regime
///   ([`crate::enforcement::Grounded`], ADR-011).
/// - **Replay equivalence** (TC-05): a `Trace` is recoverable from the
///   `Grounded<Output>` via `derivation().replay()`; certifying it via
///   [`crate::enforcement::replay::certify_from_trace`] yields a
///   `Certified<GroundingCertificate>` whose certificate matches the one
///   reachable from `forward`'s output.
/// # Authoring
/// Application authors do not write `forward`'s body by hand; the
/// `prism_model!` macro from `uor-foundation-sdk` derives it from the
/// syntactic Route declaration via initiality of `Term` (ADR-019). The
/// macro emits both the type-level `Route` witness (which the application's
/// `Route` associated type aliases) and the value-level `TermArena` slice
/// [`run_route`] traverses (per ADR-022 D2 + D3 + D5).
pub trait PrismModel<H, B, A, R = crate::pipeline::NullResolverTuple>: __sdk_seal::Sealed
where
    H: crate::HostTypes,
    B: crate::HostBounds,
    A: crate::pipeline::AxisTuple + crate::enforcement::Hasher,
    R: crate::pipeline::ResolverTuple,
{
    /// Input feature type โ€” a [`ConstrainedTypeShape`] impl declared in
    /// foundation vocabulary.
    /// Per wiki ADR-023, `Input` is also bound by [`IntoBindingValue`] so
    /// [`run_route`] can serialize the runtime input value into the
    /// `CompileUnit` binding table for `Term::Variable { name_index: 0 }`
    /// (the route's input-parameter slot per ADR-022 D3 G2).
    type Input: ConstrainedTypeShape + IntoBindingValue;

    /// Output label type โ€” a [`ConstrainedTypeShape`] impl declared in
    /// foundation vocabulary that is also a [`crate::enforcement::GroundedShape`].
    type Output: ConstrainedTypeShape + crate::enforcement::GroundedShape + IntoBindingValue;

    /// Type-level witness of the term tree mapping `Input` to `Output`.
    /// Bound by [`FoundationClosed`]: the `prism_model!` macro emits the
    /// `FoundationClosed` impl for this witness iff every node is a
    /// foundation-vocabulary item, satisfying the closure check at the
    /// application's compile time per UORassembly (TC-04).
    type Route: FoundationClosed;

    /// The catamorphism into [`run_route`]'s runtime carrier.
    /// Implementations are emitted by the `prism_model!` macro from the
    /// syntactic Route declaration; the macro derives the body via
    /// initiality of `Term` (wiki ADR-019). The canonical body is
    /// `run_route::<H, B, A, Self>(input)` (per ADR-022 D5).
    /// # Errors
    /// Returns a [`PipelineFailure`] when the input does not satisfy the
    /// route's preflight checks (budget solvency, feasibility, package
    /// coherence, dispatch coverage, timing) or when reduction stages
    /// detect contradiction along the route.
    fn forward(
        input: Self::Input,
    ) -> Result<crate::enforcement::Grounded<Self::Output>, PipelineFailure>;
}

/// Higher-level catamorphism entry point โ€” wiki ADR-022 D5.
/// `run_route` constructs a `Validated<CompileUnit, FinalPhase>` from the
/// model's `Route` (whose const `TermArena` slice carries the term tree)
/// plus the input, and invokes [`run`] against it. The macro-emitted
/// `PrismModel::forward` body is exactly `run_route::<H, B, A, Self>(input)`.
/// Lower-level callers (test harnesses, conformance suites, alternative
/// SDK surfaces) use [`run`] directly with a hand-built `CompileUnit`.
/// This higher-level form is the canonical model-execution surface the
/// wiki commits to.
/// # Errors
/// Returns [`PipelineFailure`] from the underlying [`run`] call.
pub fn run_route<H, B, A, M, R>(
    input: M::Input,
    resolvers: &R,
) -> Result<crate::enforcement::Grounded<M::Output>, PipelineFailure>
where
    H: crate::HostTypes,
    B: crate::HostBounds,
    A: crate::pipeline::AxisTuple + crate::enforcement::Hasher,
    M: PrismModel<H, B, A, R>,
    R: crate::pipeline::ResolverTuple
        + crate::pipeline::HasNerveResolver<A>
        + crate::pipeline::HasChainComplexResolver<A>
        + crate::pipeline::HasHomologyGroupResolver<A>
        + crate::pipeline::HasCochainComplexResolver<A>
        + crate::pipeline::HasCohomologyGroupResolver<A>
        + crate::pipeline::HasPostnikovResolver<A>
        + crate::pipeline::HasHomotopyGroupResolver<A>
        + crate::pipeline::HasKInvariantResolver<A>,
{
    // ADR-022 D5: read the route's term-tree arena from the model's
    // `Route` (the macro-emitted witness; identity-route returns &[]),
    // build a `Validated<CompileUnit, FinalPhase>` whose root_term is
    // exactly that arena, and dispatch to `run` (the catamorphism).
    let arena_slice = <M::Route as FoundationClosed>::arena_slice();
    // ADR-023: serialize the runtime input value into a transient
    // `Binding` for the route's input-parameter slot
    // (`Term::Variable { name_index: 0 }`, ADR-022 D3 G2). The buffer
    // ceiling is the foundation-side `ROUTE_INPUT_BUFFER_BYTES`
    // (stable-Rust equivalent of nightly's
    // `[u8; <M::Input as IntoBindingValue>::MAX_BYTES]` form).
    let max_bytes = <M::Input as IntoBindingValue>::MAX_BYTES;
    if max_bytes > ROUTE_INPUT_BUFFER_BYTES {
        // Per ADR-023: inputs whose declared MAX_BYTES exceeds the
        // foundation-side ceiling are rejected โ€” the canonical content
        // address cannot be derived without a buffer big enough for
        // the value's full byte sequence.
        return Err(PipelineFailure::ShapeViolation {
            report: crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/RouteInputBufferShape",
                constraint_iri: "https://uor.foundation/pipeline/RouteInputBufferShape/maxBytes",
                property_iri: "https://uor.foundation/pipeline/inputMaxBytes",
                expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
                min_count: 0,
                max_count: ROUTE_INPUT_BUFFER_BYTES as u32,
                kind: crate::ViolationKind::ValueCheck,
            },
        });
    }
    let mut buf = [0u8; ROUTE_INPUT_BUFFER_BYTES];
    let written = input
        .into_binding_bytes(&mut buf[..max_bytes])
        .map_err(|report| PipelineFailure::ShapeViolation { report })?;
    // Hash the canonical bytes through the application's selected
    // `Hasher` (substitution axis A). The fold output is truncated to
    // u64 for the `Binding.content_address` carrier, matching the
    // `to_binding_entry` convention foundation already uses for static
    // bindings (`ContentAddress::from_u64_fingerprint`).
    let mut hasher = <A as crate::enforcement::Hasher>::initial();
    hasher = hasher.fold_bytes(&buf[..written]);
    let digest = hasher.finalize();
    let content_address: u64 = u64::from_be_bytes([
        digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7],
    ]);
    // Build the transient binding for the route's input slot. The
    // `name_index = 0` sentinel is the route-input slot per ADR-022 D3
    // G2; `type_index = 0` is the foundation-conventional zero handle
    // (the input's `ConstrainedTypeShape::IRI` is foundation-internal
    // and not consumed by the binding-signature fold).
    let transient_input = [crate::enforcement::Binding {
        name_index: 0,
        type_index: 0,
        value_index: 0,
        surface: <M::Input as ConstrainedTypeShape>::IRI,
        content_address,
    }];
    // Foundation defaults for unit-level parameters that are not part
    // of the Route's term-tree. The Witt-level ceiling and
    // thermodynamic budget come from the application's `HostBounds`
    // selection (ADR-018) โ€” `B::WITT_LEVEL_MAX_BITS` caps the level,
    // and a budget large enough to admit any in-bounds route avoids
    // false-positive solvency rejections. `target_domains` is
    // `Enumerative` because the arena is a finite term tree.
    static TARGET_DOMAINS: &[crate::VerificationDomain] = &[crate::VerificationDomain::Enumerative];
    let level = match B::WITT_LEVEL_MAX_BITS {
        bits if bits >= 32 => crate::WittLevel::W32,
        bits if bits >= 24 => crate::WittLevel::W24,
        bits if bits >= 16 => crate::WittLevel::W16,
        _ => crate::WittLevel::W8,
    };
    let unit = CompileUnitBuilder::new()
        .root_term(arena_slice)
        .bindings(&transient_input)
        .witt_level_ceiling(level)
        .thermodynamic_budget(1024)
        .target_domains(TARGET_DOMAINS)
        .result_type::<M::Output>()
        .validate()
        .map_err(|report| PipelineFailure::ShapeViolation { report })?;
    // ADR-028: reject Output shapes that would overflow the foundation
    // ceiling. Parallel to ADR-023's input-side check, but checked
    // against the Output-side `IntoBindingValue::MAX_BYTES`.
    let out_max = <M::Output as IntoBindingValue>::MAX_BYTES;
    if out_max > ROUTE_OUTPUT_BUFFER_BYTES {
        return Err(PipelineFailure::ShapeViolation {
            report: crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/RouteOutputBufferShape",
                constraint_iri: "https://uor.foundation/pipeline/RouteOutputBufferShape/maxBytes",
                property_iri: "https://uor.foundation/pipeline/outputMaxBytes",
                expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
                min_count: 0,
                max_count: ROUTE_OUTPUT_BUFFER_BYTES as u32,
                kind: crate::ViolationKind::ValueCheck,
            },
        });
    }
    // ADR-029: evaluate the route's Term tree as a structural fold.
    // The catamorphism's output bytes flow into the Grounded's
    // output payload (ADR-028).
    let evaluation = evaluate_term_tree::<A, R>(arena_slice, &buf[..written], resolvers)?;
    let grounded = run::<M::Output, _, A>(unit)?;
    Ok(grounded.with_output_bytes(evaluation.bytes()))
}

/// Maximum byte width any single `TermValue` carries during evaluation.
/// Foundation-fixed at the maximum of the input/output buffer ceilings so a
/// TermValue can carry the catamorphism's evaluation result (per ADR-028) and
/// the input bytes a Variable/AxisInvocation consumes (per ADR-023). On stable
/// Rust 1.83 we cannot use `max(ROUTE_INPUT_BUFFER_BYTES, ROUTE_OUTPUT_BUFFER_BYTES)`
/// as a `const` expression in array-length position without `generic_const_exprs`,
/// so foundation pins the value at the architectural maximum (currently 4096 โ€” the
/// symmetric value the input/output ceilings already commit to).
/// Stack usage during the catamorphism's recursive descent scales as
/// `tree_depth ร— TERM_VALUE_MAX_BYTES`. ADR-024's compile-time inlining bounds
/// tree depth by the source's grammar tree depth (verb fragments are inlined at
/// compile time, no cross-fragment runtime recursion), keeping stack usage finite.
/// Wiki ADR-037: alias of [`HostBounds::TERM_VALUE_MAX_BYTES`] via
/// [`DefaultHostBounds`]. Applications declaring a custom `HostBounds`
/// read `<MyBounds as HostBounds>::TERM_VALUE_MAX_BYTES` instead.
pub const TERM_VALUE_MAX_BYTES: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::TERM_VALUE_MAX_BYTES;

/// Wiki ADR-029: name-index sentinel used by `prism_model!` G7 emission to
/// mark `recurse(measure, base, |self| step)`'s self-identifier reference.
/// When the catamorphism encounters `Term::Variable { name_index: <this> }`
/// during step-body evaluation, it returns the previous iteration's result
/// (the `recurse_value` parameter threaded through `evaluate_term_at`) โ€” the
/// fresh-name-indexed Variable ADR-029 specifies for the recursive-call
/// placeholder.
/// Foundation reserves the upper sentinels: `u32::MAX` is the wildcard arm
/// for `Term::Match` (ADR-022 D3 G6) and the default-propagation handler for
/// `Term::Try` (G9). `RECURSE_PLACEHOLDER_NAME_INDEX = u32::MAX - 1`.
pub const RECURSE_PLACEHOLDER_NAME_INDEX: u32 = u32::MAX - 1;

/// Wiki ADR-022 D3 G8 + ADR-029: the fresh-name-indexed Variable that
/// `prism_model!` emits in place of an `unfold(seed, |state, โ€ฆ| step)`
/// closure's state-ident references. The catamorphism's `Term::Unfold`
/// fold-rule binds this name to the unfold's current state value
/// (threaded through `evaluate_term_at` as the `unfold_value` parameter)
/// and iterates step until a Kleene fixpoint or [`UNFOLD_MAX_ITERATIONS`].
pub const UNFOLD_PLACEHOLDER_NAME_INDEX: u32 = u32::MAX - 2;

/// Wiki ADR-034 Mechanism 1: the foundation-fixed name-index for the
/// iteration-counter binding inside `Term::Recurse`'s step body. The
/// two-parameter closure form `recurse(measure, base, |self_ident, idx_ident| step)`
/// lowers `idx_ident` references to
/// `Term::Variable { name_index: RECURSE_IDX_NAME_INDEX }`; the
/// catamorphism's per-variant fold-rule binds it to a `TermValue`
/// carrying the current measure value at each descent.
pub const RECURSE_IDX_NAME_INDEX: u32 = u32::MAX - 3;

/// Wiki ADR-034 Mechanism 2: the foundation-fixed name-index for the
/// candidate-value binding inside `Term::FirstAdmit`'s predicate body.
/// The grammar form `first_admit(<domain>, |idx_ident| <pred>)` lowers
/// `idx_ident` references to
/// `Term::Variable { name_index: FIRST_ADMIT_IDX_NAME_INDEX }`; the
/// catamorphism's per-variant fold-rule binds it to the current
/// candidate `idx` (ranging `0..<Domain>::CYCLE_SIZE`).
pub const FIRST_ADMIT_IDX_NAME_INDEX: u32 = u32::MAX - 4;

/// Wiki ADR-029: bound on the anamorphic fixpoint iteration for
/// `Term::Unfold`. The fold rule iterates `step(state)` until either the
/// state reaches a Kleene fixpoint (`step(state) == state`) or this
/// ceiling is hit, at which point evaluation returns the most-recent
/// state. Foundation-fixed (parallel to `FOLD_UNROLL_THRESHOLD`).
/// Wiki ADR-037: alias of [`HostBounds::UNFOLD_ITERATIONS_MAX`] via
/// [`DefaultHostBounds`].
pub const UNFOLD_MAX_ITERATIONS: usize =
    <crate::DefaultHostBounds as crate::HostBounds>::UNFOLD_ITERATIONS_MAX;

/// Wiki ADR-029: a single Term variant's evaluated value, carried as a
/// fixed-capacity byte buffer with an active-prefix length. The
/// catamorphism produces a `TermValue` per variant, propagated up the
/// term tree by the per-variant fold rules.
#[derive(Debug, Clone, Copy)]
pub struct TermValue {
    /// Fixed-capacity byte buffer (zero-padded beyond `len`).
    bytes: [u8; TERM_VALUE_MAX_BYTES],
    /// Active prefix length. `u16` admits the architectural ceiling (4096 < 65536).
    len: u16,
}

impl TermValue {
    /// Construct an empty `TermValue` (length zero).
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            bytes: [0u8; TERM_VALUE_MAX_BYTES],
            len: 0,
        }
    }

    /// Construct a `TermValue` from a slice; copies up to `TERM_VALUE_MAX_BYTES` bytes.
    #[must_use]
    pub fn from_slice(bytes: &[u8]) -> Self {
        let mut buf = [0u8; TERM_VALUE_MAX_BYTES];
        let copy_len = if bytes.len() > TERM_VALUE_MAX_BYTES {
            TERM_VALUE_MAX_BYTES
        } else {
            bytes.len()
        };
        let mut i = 0;
        while i < copy_len {
            buf[i] = bytes[i];
            i += 1;
        }
        Self {
            bytes: buf,
            len: copy_len as u16,
        }
    }

    /// Returns the active byte prefix.
    #[inline]
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.bytes[..self.len as usize]
    }
}

/// Wiki ADR-029: catamorphism evaluator over the route's Term tree.
/// Per-variant fold rules:
/// - `Term::Literal { value, level }` โ€” emit `value` as big-endian bytes at the
///   byte width of `level`.
/// - `Term::Variable { name_index }` โ€” `name_index = 0` returns the route
///   input bytes; other indices look up `let`-introduced bindings (current
///   iteration: not yet supported, returns the input bytes for any non-zero
///   index).
/// - `Term::Application { operator, args }` โ€” evaluate each arg and apply
///   the `PrimitiveOp` per its algebraic rule.
/// - `Term::Lift { operand, target }` โ€” evaluate operand, zero-extend to
///   `target` Witt level's byte width.
/// - `Term::Project { operand, target }` โ€” evaluate operand, truncate to
///   `target` Witt level's byte width.
/// - `Term::Match { scrutinee, arms }` โ€” evaluate scrutinee, match arms by
///   literal-byte equality (wildcard arm `name_index = u32::MAX` matches
///   unconditionally).
/// - `Term::Recurse { measure, base, step }` โ€” bounded recursion: evaluate
///   measure โ†’ n; if n = 0 evaluate base; otherwise iterate step n times with
///   the recursive-call placeholder bound to the previous iteration's result.
/// - `Term::Unfold { seed, step }` โ€” anamorphism: evaluate seed โ†’ stateโ‚€;
///   iterate step (with the state placeholder bound to the current state)
///   until a Kleene fixpoint or `UNFOLD_MAX_ITERATIONS` is reached.
/// - `Term::Try { body, handler }` โ€” evaluate body; on failure, propagate
///   if `handler_index = u32::MAX`, otherwise evaluate handler.
/// - `Term::AxisInvocation { axis_index, kernel_id, input_index }` โ€” dispatch
///   the input's bytes to the application's `AxisTuple` (ADR-030); the
///   foundation-canonical (axis_index=0, kernel_id=0) folds through the
///   selected `Hasher` impl. Replaces the legacy `HasherProjection` variant.
/// # Errors
/// Returns [`PipelineFailure`] when the term tree is malformed (out-of-bounds
/// index, level mismatch, exhausted match without wildcard arm, etc.).
pub fn evaluate_term_tree<A, R>(
    arena: &[crate::enforcement::Term],
    input_bytes: &[u8],
    resolvers: &R,
) -> Result<TermValue, PipelineFailure>
where
    A: crate::pipeline::AxisTuple + crate::enforcement::Hasher,
    R: crate::pipeline::ResolverTuple
        + crate::pipeline::HasNerveResolver<A>
        + crate::pipeline::HasChainComplexResolver<A>
        + crate::pipeline::HasHomologyGroupResolver<A>
        + crate::pipeline::HasCochainComplexResolver<A>
        + crate::pipeline::HasCohomologyGroupResolver<A>
        + crate::pipeline::HasPostnikovResolver<A>
        + crate::pipeline::HasHomotopyGroupResolver<A>
        + crate::pipeline::HasKInvariantResolver<A>,
{
    if arena.is_empty() {
        // Identity route: output equals input bytes.
        return Ok(TermValue::from_slice(input_bytes));
    }
    // Canonical convention: the root term is the last entry in the
    // arena (the `prism_model!` macro emits in post-order, so the root
    // is the final node).
    let root_idx = arena.len() - 1;
    evaluate_term_at::<A, R>(
        arena,
        root_idx,
        input_bytes,
        None,
        None,
        None,
        None,
        resolvers,
    )
}

#[allow(clippy::too_many_arguments)]
fn evaluate_term_at<A, R>(
    arena: &[crate::enforcement::Term],
    idx: usize,
    input_bytes: &[u8],
    recurse_value: Option<&[u8]>,
    recurse_idx_value: Option<&[u8]>,
    unfold_value: Option<&[u8]>,
    first_admit_idx_value: Option<&[u8]>,
    resolvers: &R,
) -> Result<TermValue, PipelineFailure>
where
    A: crate::pipeline::AxisTuple + crate::enforcement::Hasher,
    R: crate::pipeline::ResolverTuple
        + crate::pipeline::HasNerveResolver<A>
        + crate::pipeline::HasChainComplexResolver<A>
        + crate::pipeline::HasHomologyGroupResolver<A>
        + crate::pipeline::HasCochainComplexResolver<A>
        + crate::pipeline::HasCohomologyGroupResolver<A>
        + crate::pipeline::HasPostnikovResolver<A>
        + crate::pipeline::HasHomotopyGroupResolver<A>
        + crate::pipeline::HasKInvariantResolver<A>,
{
    if idx >= arena.len() {
        return Err(PipelineFailure::ShapeViolation {
            report: crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/TermArenaShape",
                constraint_iri: "https://uor.foundation/pipeline/TermArenaShape/inBounds",
                property_iri: "https://uor.foundation/pipeline/termIndex",
                expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
                min_count: 0,
                max_count: arena.len() as u32,
                kind: crate::ViolationKind::ValueCheck,
            },
        });
    }
    match arena[idx] {
        crate::enforcement::Term::Literal { value, level } => {
            let width = (level.witt_length() / 8) as usize;
            let width = if width == 0 {
                1
            } else if width > 8 {
                8
            } else {
                width
            };
            let be = value.to_be_bytes();
            // Take the trailing `width` bytes (big-endian truncation).
            Ok(TermValue::from_slice(&be[8 - width..]))
        }
        crate::enforcement::Term::Variable { name_index } => {
            // ADR-022 D3 G2: name_index = 0 is the route input slot.
            // ADR-029: name_index = RECURSE_PLACEHOLDER_NAME_INDEX is the
            // recursive-call placeholder bound to `recurse_value`.
            // ADR-029: name_index = UNFOLD_PLACEHOLDER_NAME_INDEX is the
            // unfold state placeholder bound to `unfold_value` (the
            // current iteration's accumulated state โ€” see the
            // `Term::Unfold` fold-rule below).
            // Other indices reference let-bindings (G10), which the
            // current macro emission resolves at expansion time via
            // splice into the calling arena (so the binding's value-tree
            // root is what the catamorphism actually walks).
            if name_index == RECURSE_PLACEHOLDER_NAME_INDEX {
                return Ok(TermValue::from_slice(recurse_value.unwrap_or(&[])));
            }
            // ADR-034 Mechanism 1: iteration-counter binding for Recurse.
            if name_index == RECURSE_IDX_NAME_INDEX {
                return Ok(TermValue::from_slice(recurse_idx_value.unwrap_or(&[])));
            }
            if name_index == UNFOLD_PLACEHOLDER_NAME_INDEX {
                return Ok(TermValue::from_slice(unfold_value.unwrap_or(&[])));
            }
            // ADR-034 Mechanism 2: candidate-value binding for FirstAdmit.
            if name_index == FIRST_ADMIT_IDX_NAME_INDEX {
                return Ok(TermValue::from_slice(first_admit_idx_value.unwrap_or(&[])));
            }
            Ok(TermValue::from_slice(input_bytes))
        }
        crate::enforcement::Term::Application { operator, args } => {
            let start = args.start as usize;
            let len = args.len as usize;
            apply_primitive_op::<A, R>(
                arena,
                operator,
                start,
                len,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )
        }
        crate::enforcement::Term::Lift {
            operand_index,
            target,
        } => {
            let v = evaluate_term_at::<A, R>(
                arena,
                operand_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let target_width = (target.witt_length() / 8) as usize;
            let target_width = if target_width > TERM_VALUE_MAX_BYTES {
                TERM_VALUE_MAX_BYTES
            } else if target_width == 0 {
                1
            } else {
                target_width
            };
            let mut buf = [0u8; TERM_VALUE_MAX_BYTES];
            // Big-endian zero-extend: pad the high bytes with zeros.
            let src = v.bytes();
            let pad = target_width.saturating_sub(src.len());
            let mut i = 0;
            while i < src.len() && pad + i < target_width {
                buf[pad + i] = src[i];
                i += 1;
            }
            Ok(TermValue {
                bytes: buf,
                len: target_width as u16,
            })
        }
        crate::enforcement::Term::Project {
            operand_index,
            target,
        } => {
            let v = evaluate_term_at::<A, R>(
                arena,
                operand_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let target_width = (target.witt_length() / 8) as usize;
            let target_width = if target_width > TERM_VALUE_MAX_BYTES {
                TERM_VALUE_MAX_BYTES
            } else if target_width == 0 {
                1
            } else {
                target_width
            };
            let src = v.bytes();
            // Big-endian truncation: take the trailing `target_width` bytes.
            let take_from = src.len().saturating_sub(target_width);
            Ok(TermValue::from_slice(&src[take_from..]))
        }
        crate::enforcement::Term::Match {
            scrutinee_index,
            arms,
        } => {
            let scrutinee = evaluate_term_at::<A, R>(
                arena,
                scrutinee_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let start = arms.start as usize;
            let count = arms.len as usize;
            // Arms alternate (pattern, body) per ADR-022 D3 G6.
            let mut i = 0usize;
            while i + 1 < count {
                let pattern_idx = start + i;
                let body_idx = start + i + 1;
                let is_wildcard = matches!(
                    arena[pattern_idx],
                    crate::enforcement::Term::Variable { name_index } if name_index == u32::MAX
                );
                if is_wildcard {
                    return evaluate_term_at::<A, R>(
                        arena,
                        body_idx,
                        input_bytes,
                        recurse_value,
                        recurse_idx_value,
                        unfold_value,
                        first_admit_idx_value,
                        resolvers,
                    );
                }
                let pattern_val = evaluate_term_at::<A, R>(
                    arena,
                    pattern_idx,
                    input_bytes,
                    recurse_value,
                    recurse_idx_value,
                    unfold_value,
                    first_admit_idx_value,
                    resolvers,
                )?;
                if pattern_val.bytes() == scrutinee.bytes() {
                    return evaluate_term_at::<A, R>(
                        arena,
                        body_idx,
                        input_bytes,
                        recurse_value,
                        recurse_idx_value,
                        unfold_value,
                        first_admit_idx_value,
                        resolvers,
                    );
                }
                i += 2;
            }
            // Per ADR-022 D3 G6 the macro enforces wildcard exhaustiveness;
            // a well-formed Term tree never reaches this branch.
            Err(PipelineFailure::ShapeViolation {
                report: crate::enforcement::ShapeViolation {
                    shape_iri: "https://uor.foundation/pipeline/MatchExhaustivenessShape",
                    constraint_iri:
                        "https://uor.foundation/pipeline/MatchExhaustivenessShape/wildcard",
                    property_iri: "https://uor.foundation/pipeline/matchArms",
                    expected_range: "http://www.w3.org/2001/XMLSchema#string",
                    min_count: 1,
                    max_count: 0,
                    kind: crate::ViolationKind::Missing,
                },
            })
        }
        crate::enforcement::Term::Recurse {
            measure_index,
            base_index,
            step_index,
        } => {
            // Wiki ADR-029 recursive fold: evaluate measure once to get N;
            // if N == 0 evaluate base; else iterate step N times, threading
            // each iteration's result as the recurse_value (the recursive-
            // call placeholder bound to a fresh-name-indexed Variable per
            // ADR-029, with the placeholder's name_index resolving via the
            // RECURSE_PLACEHOLDER_NAME_INDEX sentinel handled in the Variable
            // arm). The outer recurse_value is preserved for nested Recurse
            // forms within the measure/base computations; step body uses the
            // iteration's accumulator.
            let measure = evaluate_term_at::<A, R>(
                arena,
                measure_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let n = bytes_to_u64_be(measure.bytes());
            let base_val = evaluate_term_at::<A, R>(
                arena,
                base_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            if n == 0 {
                return Ok(base_val);
            }
            // Iterate step N times. Each iteration's `current` becomes the
            // next iteration's recurse_value. The descent measure is the
            // bound; well-foundedness holds by monotonic decrease.
            let mut current_buf = [0u8; TERM_VALUE_MAX_BYTES];
            let mut current_len = base_val.bytes().len();
            let mut k = 0;
            while k < current_len {
                current_buf[k] = base_val.bytes()[k];
                k += 1;
            }
            let mut iter = 0u64;
            while iter < n {
                // ADR-034 Mechanism 1: bind RECURSE_IDX_NAME_INDEX to the
                // current measure value (the iteration counter at this
                // descent). At iter=0 the descent measure is N; at iter=k
                // it is N-k. The byte width follows the measure's BE-truncated
                // u64 packing so callers can read it as a u64-shaped value.
                let descent_measure: u64 = n - iter;
                let descent_bytes = descent_measure.to_be_bytes();
                let next = evaluate_term_at::<A, R>(
                    arena,
                    step_index as usize,
                    input_bytes,
                    Some(&current_buf[..current_len]),
                    Some(&descent_bytes[..]),
                    unfold_value,
                    first_admit_idx_value,
                    resolvers,
                )?;
                let nb = next.bytes();
                let copy_len = if nb.len() > TERM_VALUE_MAX_BYTES {
                    TERM_VALUE_MAX_BYTES
                } else {
                    nb.len()
                };
                let mut j = 0;
                while j < copy_len {
                    current_buf[j] = nb[j];
                    j += 1;
                }
                current_len = copy_len;
                iter += 1;
            }
            Ok(TermValue::from_slice(&current_buf[..current_len]))
        }
        crate::enforcement::Term::Unfold {
            seed_index,
            step_index,
        } => {
            // ADR-029 anamorphism: evaluate seed โ†’ stateโ‚€; iterate step
            // with the state placeholder (UNFOLD_PLACEHOLDER_NAME_INDEX,
            // bound to the current state) until either a Kleene fixpoint
            // (step(state) == state) or UNFOLD_MAX_ITERATIONS is reached.
            // Well-foundedness: bounded by UNFOLD_MAX_ITERATIONS.
            // The outer unfold_value is preserved for nested Unfold forms
            // within the seed; step body's state placeholder uses the
            // iteration's accumulator.
            let seed_val = evaluate_term_at::<A, R>(
                arena,
                seed_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut state_buf = [0u8; TERM_VALUE_MAX_BYTES];
            let mut state_len = seed_val.bytes().len();
            let mut k = 0;
            while k < state_len {
                state_buf[k] = seed_val.bytes()[k];
                k += 1;
            }
            let mut iter = 0usize;
            while iter < UNFOLD_MAX_ITERATIONS {
                let next = evaluate_term_at::<A, R>(
                    arena,
                    step_index as usize,
                    input_bytes,
                    recurse_value,
                    recurse_idx_value,
                    Some(&state_buf[..state_len]),
                    first_admit_idx_value,
                    resolvers,
                )?;
                let nb = next.bytes();
                // Kleene fixpoint check: if step(state) == state, return.
                if nb.len() == state_len && nb == &state_buf[..state_len] {
                    return Ok(TermValue::from_slice(&state_buf[..state_len]));
                }
                let copy_len = if nb.len() > TERM_VALUE_MAX_BYTES {
                    TERM_VALUE_MAX_BYTES
                } else {
                    nb.len()
                };
                let mut j = 0;
                while j < copy_len {
                    state_buf[j] = nb[j];
                    j += 1;
                }
                state_len = copy_len;
                iter += 1;
            }
            Ok(TermValue::from_slice(&state_buf[..state_len]))
        }
        crate::enforcement::Term::Try {
            body_index,
            handler_index,
        } => {
            match evaluate_term_at::<A, R>(
                arena,
                body_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            ) {
                Ok(v) => Ok(v),
                Err(e) => {
                    if handler_index == u32::MAX {
                        Err(e)
                    } else {
                        evaluate_term_at::<A, R>(
                            arena,
                            handler_index as usize,
                            input_bytes,
                            recurse_value,
                            recurse_idx_value,
                            unfold_value,
                            first_admit_idx_value,
                            resolvers,
                        )
                    }
                }
            }
        }
        crate::enforcement::Term::AxisInvocation {
            axis_index,
            kernel_id,
            input_index,
        } => {
            // ADR-030: dispatch to the application's selected axis at
            // `axis_index`, with `kernel_id` selecting the per-axis kernel.
            // The catamorphism evaluates the input subtree to bytes and
            // hands them to the AxisTuple's dispatch router; the dispatcher
            // writes the kernel's output into a stack-resident buffer.
            //
            // The foundation-built blanket `impl<H: Hasher> AxisTuple for H`
            // routes the canonical hash dispatch (axis 0, kernel 0)
            // through the legacy Hasher API; user-declared axes via the
            // `axis!` SDK macro extend the dispatch surface to additional
            // (axis_index, kernel_id) combinations.
            let v = evaluate_term_at::<A, R>(
                arena,
                input_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out = [0u8; AXIS_OUTPUT_BYTES_CEILING];
            let written = match <A as crate::pipeline::AxisTuple>::dispatch(
                axis_index,
                kernel_id,
                v.bytes(),
                &mut out,
            ) {
                Ok(n) => n,
                Err(report) => return Err(PipelineFailure::ShapeViolation { report }),
            };
            let width = if written > TERM_VALUE_MAX_BYTES {
                TERM_VALUE_MAX_BYTES
            } else {
                written
            };
            Ok(TermValue::from_slice(&out[..width]))
        }
        crate::enforcement::Term::ProjectField {
            source_index,
            byte_offset,
            byte_length,
        } => {
            // ADR-033 G20: evaluate source, slice [byte_offset .. byte_offset+byte_length].
            let v = evaluate_term_at::<A, R>(
                arena,
                source_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let bytes = v.bytes();
            let start = byte_offset as usize;
            let end = start.saturating_add(byte_length as usize);
            if end > bytes.len() {
                return Err(PipelineFailure::ShapeViolation {
                    report: crate::enforcement::ShapeViolation {
                        shape_iri: "https://uor.foundation/pipeline/ProjectFieldShape",
                        constraint_iri:
                            "https://uor.foundation/pipeline/ProjectFieldShape/inBounds",
                        property_iri: "https://uor.foundation/pipeline/byteOffset",
                        expected_range: "https://uor.foundation/pipeline/SourceByteRange",
                        min_count: 0,
                        max_count: 1,
                        kind: crate::ViolationKind::ValueCheck,
                    },
                });
            }
            Ok(TermValue::from_slice(&bytes[start..end]))
        }
        crate::enforcement::Term::FirstAdmit {
            domain_size_index,
            predicate_index,
        } => {
            // ADR-034 Mechanism 2: bounded search with structural early
            // termination. Evaluate the domain size N; iterate idx in 0..N
            // ascending; for each idx, evaluate predicate with
            // FIRST_ADMIT_IDX_NAME_INDEX bound to idx. Return on the first
            // non-zero predicate result (the "found" coproduct value
            // 0x01 || idx_bytes); after exhausting the domain return the
            // "not-found" coproduct value 0x00 || idx-width zero bytes.
            let domain_size = evaluate_term_at::<A, R>(
                arena,
                domain_size_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let n = bytes_to_u64_be(domain_size.bytes());
            // Determine the idx byte width from the domain size's
            // BE-truncated u64 packing (use the smallest non-zero count of
            // bytes needed to represent N). For N=0 fall back to 1 byte so
            // the not-found sentinel still has the canonical (disc, idx) shape.
            let idx_byte_width: usize = if n == 0 {
                1
            } else {
                let mut w = 8usize;
                while w > 1 && (n >> ((w - 1) * 8)) == 0 {
                    w -= 1;
                }
                w
            };
            let mut idx_iter: u64 = 0;
            while idx_iter < n {
                let idx_bytes_full = idx_iter.to_be_bytes();
                let idx_bytes = &idx_bytes_full[8 - idx_byte_width..];
                let pred_val = evaluate_term_at::<A, R>(
                    arena,
                    predicate_index as usize,
                    input_bytes,
                    recurse_value,
                    recurse_idx_value,
                    unfold_value,
                    Some(idx_bytes),
                    resolvers,
                )?;
                // ADR-029 zero/non-zero convention: any TermValue whose
                // byte sequence has at least one non-zero byte counts as
                // "true". An empty TermValue is treated as "false".
                let pb = pred_val.bytes();
                let mut admitted = false;
                let mut bi = 0;
                while bi < pb.len() {
                    if pb[bi] != 0 {
                        admitted = true;
                        break;
                    }
                    bi += 1;
                }
                if admitted {
                    let mut out_buf = [0u8; TERM_VALUE_MAX_BYTES];
                    out_buf[0] = 0x01;
                    let mut k = 0;
                    while k < idx_byte_width {
                        out_buf[1 + k] = idx_bytes[k];
                        k += 1;
                    }
                    return Ok(TermValue::from_slice(&out_buf[..1 + idx_byte_width]));
                }
                idx_iter += 1;
            }
            // No idx admitted โ€” emit not-found coproduct value.
            let mut out_buf = [0u8; TERM_VALUE_MAX_BYTES];
            out_buf[0] = 0x00;
            // bytes 1..1+idx_byte_width remain zero (structural padding).
            Ok(TermValue::from_slice(&out_buf[..1 + idx_byte_width]))
        }
        crate::enforcement::Term::Nerve { value_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::NERVE_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                value_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf =
                [0u8; <crate::DefaultHostBounds as crate::HostBounds>::NERVE_OUTPUT_BYTES_MAX];
            match resolvers
                .nerve_resolver()
                .resolve(operand.bytes(), &mut out_buf)
            {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::ChainComplex { simplicial_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::CHAIN_COMPLEX_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                simplicial_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf = [0u8;
                <crate::DefaultHostBounds as crate::HostBounds>::CHAIN_COMPLEX_OUTPUT_BYTES_MAX];
            match resolvers.chain_complex_resolver().resolve(
                crate::pipeline::SimplicialComplexBytes(operand.bytes()),
                &mut out_buf,
            ) {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::HomologyGroups { chain_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                chain_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf = [0u8;
                <crate::DefaultHostBounds as crate::HostBounds>::HOMOLOGY_GROUPS_OUTPUT_BYTES_MAX];
            match resolvers.homology_group_resolver().resolve(
                crate::pipeline::ChainComplexBytes(operand.bytes()),
                &mut out_buf,
            ) {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::CochainComplex { chain_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::COCHAIN_COMPLEX_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                chain_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf = [0u8;
                <crate::DefaultHostBounds as crate::HostBounds>::COCHAIN_COMPLEX_OUTPUT_BYTES_MAX];
            match resolvers.cochain_complex_resolver().resolve(
                crate::pipeline::ChainComplexBytes(operand.bytes()),
                &mut out_buf,
            ) {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::CohomologyGroups { cochain_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                cochain_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf = [0u8;
                <crate::DefaultHostBounds as crate::HostBounds>::COHOMOLOGY_GROUPS_OUTPUT_BYTES_MAX];
            match resolvers.cohomology_group_resolver().resolve(
                crate::pipeline::CochainComplexBytes(operand.bytes()),
                &mut out_buf,
            ) {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::PostnikovTower { simplicial_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::POSTNIKOV_TOWER_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                simplicial_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf = [0u8;
                <crate::DefaultHostBounds as crate::HostBounds>::POSTNIKOV_TOWER_OUTPUT_BYTES_MAX];
            match resolvers.postnikov_resolver().resolve(
                crate::pipeline::SimplicialComplexBytes(operand.bytes()),
                &mut out_buf,
            ) {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::HomotopyGroups { postnikov_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                postnikov_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf = [0u8;
                <crate::DefaultHostBounds as crate::HostBounds>::HOMOTOPY_GROUPS_OUTPUT_BYTES_MAX];
            match resolvers.homotopy_group_resolver().resolve(
                crate::pipeline::PostnikovTowerBytes(operand.bytes()),
                &mut out_buf,
            ) {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::KInvariants { homotopy_index } => {
            // ADR-035 + ADR-036 + ADR-041: resolver-bound ฯˆ-Term variant.
            // Evaluate the operand subtree, wrap the resulting bytes in the
            // ADR-041 typed-coordinate carrier for this ฯˆ-stage's expected
            // input, then dispatch through the application's resolver via the
            // `Has<Category>Resolver` accessor. The resolver's output bytes
            // populate the variant's `TermValue`; resolver-side `Err`
            // propagates as `PipelineFailure::ShapeViolation` (the Null
            // defaults emit `RESOLVER_ABSENT`, recoverable via `Term::Try`'s
            // default-propagation handler).
            //
            // ADR-037: scratch buffer sized at `<crate::DefaultHostBounds as crate::HostBounds>::K_INVARIANTS_OUTPUT_BYTES_MAX`
            // โ€” per-ฯˆ-stage cap from the application's selected HostBounds.
            let operand = evaluate_term_at::<A, R>(
                arena,
                homotopy_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            let mut out_buf = [0u8;
                <crate::DefaultHostBounds as crate::HostBounds>::K_INVARIANTS_OUTPUT_BYTES_MAX];
            match resolvers.k_invariant_resolver().resolve(
                crate::pipeline::HomotopyGroupsBytes(operand.bytes()),
                &mut out_buf,
            ) {
                Ok(written) => {
                    let width = if written > TERM_VALUE_MAX_BYTES {
                        TERM_VALUE_MAX_BYTES
                    } else {
                        written
                    };
                    Ok(TermValue::from_slice(&out_buf[..width]))
                }
                Err(report) => Err(PipelineFailure::ShapeViolation { report }),
            }
        }
        crate::enforcement::Term::Betti { homology_index } => {
            // ADR-035 ฯˆ_4: Betti-number extraction from HomologyGroups.
            // Pure byte-projection โ€” no resolver consultation. The
            // operand's evaluated bytes (the homology-groups byte
            // serialization per the homology bridge's wire format)
            // are returned as-is; downstream consumers slice the
            // Betti tuple positions out of the result.
            let v = evaluate_term_at::<A, R>(
                arena,
                homology_index as usize,
                input_bytes,
                recurse_value,
                recurse_idx_value,
                unfold_value,
                first_admit_idx_value,
                resolvers,
            )?;
            Ok(v)
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn apply_primitive_op<A, R>(
    arena: &[crate::enforcement::Term],
    operator: crate::PrimitiveOp,
    args_start: usize,
    args_len: usize,
    input_bytes: &[u8],
    recurse_value: Option<&[u8]>,
    recurse_idx_value: Option<&[u8]>,
    unfold_value: Option<&[u8]>,
    first_admit_idx_value: Option<&[u8]>,
    resolvers: &R,
) -> Result<TermValue, PipelineFailure>
where
    A: crate::pipeline::AxisTuple + crate::enforcement::Hasher,
    R: crate::pipeline::ResolverTuple
        + crate::pipeline::HasNerveResolver<A>
        + crate::pipeline::HasChainComplexResolver<A>
        + crate::pipeline::HasHomologyGroupResolver<A>
        + crate::pipeline::HasCochainComplexResolver<A>
        + crate::pipeline::HasCohomologyGroupResolver<A>
        + crate::pipeline::HasPostnikovResolver<A>
        + crate::pipeline::HasHomotopyGroupResolver<A>
        + crate::pipeline::HasKInvariantResolver<A>,
{
    // Unary ops: 1 arg. Binary ops: 2 args.
    let arity = match operator {
        crate::PrimitiveOp::Neg
        | crate::PrimitiveOp::Bnot
        | crate::PrimitiveOp::Succ
        | crate::PrimitiveOp::Pred => 1usize,
        crate::PrimitiveOp::Add
        | crate::PrimitiveOp::Sub
        | crate::PrimitiveOp::Mul
        | crate::PrimitiveOp::Xor
        | crate::PrimitiveOp::And
        | crate::PrimitiveOp::Or
        | crate::PrimitiveOp::Le
        | crate::PrimitiveOp::Lt
        | crate::PrimitiveOp::Ge
        | crate::PrimitiveOp::Gt
        | crate::PrimitiveOp::Concat => 2usize,
    };
    if args_len != arity {
        return Err(PipelineFailure::ShapeViolation {
            report: crate::enforcement::ShapeViolation {
                shape_iri: "https://uor.foundation/pipeline/PrimitiveOpArityShape",
                constraint_iri: "https://uor.foundation/pipeline/PrimitiveOpArityShape/arity",
                property_iri: "https://uor.foundation/pipeline/operatorArity",
                expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
                min_count: arity as u32,
                max_count: arity as u32,
                kind: crate::ViolationKind::CardinalityViolation,
            },
        });
    }
    if arity == 1 {
        let v = evaluate_term_at::<A, R>(
            arena,
            args_start,
            input_bytes,
            recurse_value,
            recurse_idx_value,
            unfold_value,
            first_admit_idx_value,
            resolvers,
        )?;
        let x = bytes_to_u64_be(v.bytes());
        let r =
            match operator {
                crate::PrimitiveOp::Neg => x.wrapping_neg(),
                crate::PrimitiveOp::Bnot => !x,
                crate::PrimitiveOp::Succ => x.wrapping_add(1),
                crate::PrimitiveOp::Pred => x.wrapping_sub(1),
                _ => return Err(PipelineFailure::ShapeViolation {
                    report: crate::enforcement::ShapeViolation {
                        shape_iri: "https://uor.foundation/pipeline/PrimitiveOpArityShape",
                        constraint_iri:
                            "https://uor.foundation/pipeline/PrimitiveOpArityShape/binary-as-unary",
                        property_iri: "https://uor.foundation/pipeline/operatorArity",
                        expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
                        min_count: 2,
                        max_count: 2,
                        kind: crate::ViolationKind::CardinalityViolation,
                    },
                }),
            };
        let width = v.bytes().len().clamp(1, 8);
        let arr = r.to_be_bytes();
        Ok(TermValue::from_slice(&arr[8 - width..]))
    } else {
        let lhs = evaluate_term_at::<A, R>(
            arena,
            args_start,
            input_bytes,
            recurse_value,
            recurse_idx_value,
            unfold_value,
            first_admit_idx_value,
            resolvers,
        )?;
        let rhs = evaluate_term_at::<A, R>(
            arena,
            args_start + 1,
            input_bytes,
            recurse_value,
            recurse_idx_value,
            unfold_value,
            first_admit_idx_value,
            resolvers,
        )?;
        // ADR-013/TR-08 substrate-amendment ops: byte-level Concat and
        // comparison primitives bypass the u64 fold and operate on the
        // operands' full byte sequences.
        match operator {
            crate::PrimitiveOp::Concat => {
                // Concat: emit lhs.bytes() โงบ rhs.bytes(), bounded by
                // TERM_VALUE_MAX_BYTES (truncates excess; runtime callers
                // declaring shapes whose composite length exceeds the
                // ceiling are rejected at validation time per ADR-028's
                // symmetric output ceiling check).
                let lb = lhs.bytes();
                let rb = rhs.bytes();
                let total = lb.len() + rb.len();
                let cap = if total > TERM_VALUE_MAX_BYTES {
                    TERM_VALUE_MAX_BYTES
                } else {
                    total
                };
                let mut buf = [0u8; TERM_VALUE_MAX_BYTES];
                let mut i = 0;
                while i < lb.len() && i < cap {
                    buf[i] = lb[i];
                    i += 1;
                }
                let mut j = 0;
                while j < rb.len() && i < cap {
                    buf[i] = rb[j];
                    i += 1;
                    j += 1;
                }
                return Ok(TermValue::from_slice(&buf[..cap]));
            }
            crate::PrimitiveOp::Le
            | crate::PrimitiveOp::Lt
            | crate::PrimitiveOp::Ge
            | crate::PrimitiveOp::Gt => {
                // Big-endian byte-level comparison. Both operands are
                // padded with leading zeros to the max length so the
                // comparison ignores leading-zero stripping differences.
                let cmp = byte_compare_be(lhs.bytes(), rhs.bytes());
                let result_byte: u8 = match operator {
                    crate::PrimitiveOp::Le => u8::from(cmp != core::cmp::Ordering::Greater),
                    crate::PrimitiveOp::Lt => u8::from(cmp == core::cmp::Ordering::Less),
                    crate::PrimitiveOp::Ge => u8::from(cmp != core::cmp::Ordering::Less),
                    crate::PrimitiveOp::Gt => u8::from(cmp == core::cmp::Ordering::Greater),
                    _ => 0,
                };
                return Ok(TermValue::from_slice(&[result_byte]));
            }
            _ => {}
        }
        let a = bytes_to_u64_be(lhs.bytes());
        let b = bytes_to_u64_be(rhs.bytes());
        let width = lhs.bytes().len().max(rhs.bytes().len()).max(1);
        let r =
            match operator {
                crate::PrimitiveOp::Add => a.wrapping_add(b),
                crate::PrimitiveOp::Sub => a.wrapping_sub(b),
                crate::PrimitiveOp::Mul => a.wrapping_mul(b),
                crate::PrimitiveOp::Xor => a ^ b,
                crate::PrimitiveOp::And => a & b,
                crate::PrimitiveOp::Or => a | b,
                _ => return Err(PipelineFailure::ShapeViolation {
                    report: crate::enforcement::ShapeViolation {
                        shape_iri: "https://uor.foundation/pipeline/PrimitiveOpArityShape",
                        constraint_iri:
                            "https://uor.foundation/pipeline/PrimitiveOpArityShape/unary-as-binary",
                        property_iri: "https://uor.foundation/pipeline/operatorArity",
                        expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
                        min_count: 1,
                        max_count: 1,
                        kind: crate::ViolationKind::CardinalityViolation,
                    },
                }),
            };
        let width = if width > 8 { 8 } else { width };
        let arr = r.to_be_bytes();
        Ok(TermValue::from_slice(&arr[8 - width..]))
    }
}

fn byte_compare_be(a: &[u8], b: &[u8]) -> core::cmp::Ordering {
    // Pad shorter operand with leading zeros so the comparison treats
    // both operands at max(len(a), len(b)) byte width.
    let max_len = if a.len() > b.len() { a.len() } else { b.len() };
    let mut i = 0;
    while i < max_len {
        let ai = if i + a.len() >= max_len {
            a[i + a.len() - max_len]
        } else {
            0u8
        };
        let bi = if i + b.len() >= max_len {
            b[i + b.len() - max_len]
        } else {
            0u8
        };
        if ai < bi {
            return core::cmp::Ordering::Less;
        }
        if ai > bi {
            return core::cmp::Ordering::Greater;
        }
        i += 1;
    }
    core::cmp::Ordering::Equal
}

fn bytes_to_u64_be(bytes: &[u8]) -> u64 {
    let take = if bytes.len() > 8 { 8 } else { bytes.len() };
    let start = bytes.len() - take;
    let mut acc = 0u64;
    let mut i = 0;
    while i < take {
        acc = (acc << 8) | bytes[start + i] as u64;
        i += 1;
    }
    acc
}

/// Foundation-sanctioned identity route: `ConstrainedTypeInput` is the
/// empty default shape, vacuously closed under foundation vocabulary.
/// Application authors with non-trivial routes use the `prism_model!`
/// macro from `uor-foundation-sdk`, which emits `FoundationClosed` for
/// the witness it generates iff every node is foundation-vocabulary.
/// The identity route's `arena_slice()` returns `&[]` โ€” no terms, no
/// transformation, input passes through to output unchanged.
impl __sdk_seal::Sealed for ConstrainedTypeInput {}
impl FoundationClosed for ConstrainedTypeInput {
    fn arena_slice() -> &'static [crate::enforcement::Term] {
        &[]
    }
}
impl IntoBindingValue for ConstrainedTypeInput {
    const MAX_BYTES: usize = 0;
    fn into_binding_bytes(
        &self,
        _out: &mut [u8],
    ) -> core::result::Result<usize, crate::enforcement::ShapeViolation> {
        // Identity input carries no bytes โ€” the empty shape's canonical
        // serialization is the empty byte sequence.
        Ok(0)
    }
}

/// Marker for a `ConstrainedTypeShape` that is the Cartesian product of
/// two component shapes. Selecting this trait routes nerve-Betti computation
/// through Kรผnneth composition of component Betti profiles rather than
/// flat enumeration of (constraint, constraint) pairs. Introduced by the
/// Product/Coproduct Completion Amendment ยง3c for CartesianPartitionProduct
/// (CPT_1โ€“CPT_6).
pub trait CartesianProductShape: ConstrainedTypeShape {
    /// Left operand shape.
    type Left: ConstrainedTypeShape;
    /// Right operand shape.
    type Right: ConstrainedTypeShape;
}

/// Kรผnneth composition of two Betti profiles.
/// Computes `out[k] = ฮฃ_{i + j = k} a[i] ยท b[j]` over
/// `[0, MAX_BETTI_DIMENSION)`. All arithmetic uses saturating operations so the
/// function is total on `[u32; MAX_BETTI_DIMENSION]` inputs without panicking.
pub const fn kunneth_compose(
    a: &[u32; crate::enforcement::MAX_BETTI_DIMENSION],
    b: &[u32; crate::enforcement::MAX_BETTI_DIMENSION],
) -> [u32; crate::enforcement::MAX_BETTI_DIMENSION] {
    let mut out = [0u32; crate::enforcement::MAX_BETTI_DIMENSION];
    let mut i: usize = 0;
    while i < crate::enforcement::MAX_BETTI_DIMENSION {
        let mut j: usize = 0;
        while j < crate::enforcement::MAX_BETTI_DIMENSION - i {
            let term = a[i].saturating_mul(b[j]);
            out[i + j] = out[i + j].saturating_add(term);
            j += 1;
        }
        i += 1;
    }
    out
}

/// Cartesian-product nerve Betti via Kรผnneth composition of the component
/// shapes' Betti profiles. Used instead of
/// `primitive_simplicial_nerve_betti` when a shape declares itself as a
/// `CartesianProductShape`. Amendment ยง3c.
/// Phase 1a (orphan-closure): propagates either component's
/// `NERVE_CAPACITY_EXCEEDED` via `?`. Dropped `const fn` because
/// the `Result` return of the per-component primitive is not `const`-evaluable.
/// # Errors
/// Returns `NERVE_CAPACITY_EXCEEDED` if either component exceeds caps.
pub fn primitive_cartesian_nerve_betti<S: CartesianProductShape>() -> Result<
    [u32; crate::enforcement::MAX_BETTI_DIMENSION],
    crate::enforcement::GenericImpossibilityWitness,
> {
    let left = crate::enforcement::primitive_simplicial_nerve_betti::<S::Left>()?;
    let right = crate::enforcement::primitive_simplicial_nerve_betti::<S::Right>()?;
    Ok(kunneth_compose(&left, &right))
}

/// Shift every site-index reference in a `ConstraintRef` by `offset`.
/// Used by the SDK's `product_shape!` / `coproduct_shape!` /
/// `cartesian_product_shape!` macros to splice an operand's constraints into
/// a combined shape at a post-operand offset.
/// **Phase 17: full operand-catalogue support.** Affine and
/// Conjunction now shift correctly at const time because the
/// variants store fixed-size arrays (no `&'static [i64]` allocation
/// required). The pre-Phase-17 `Site { position: u32::MAX }`
/// sentinel is removed.
/// **Variant coverage.**
/// - `Site { position }` โ†’ position += offset.
/// - `Carry { site }` โ†’ site += offset.
/// - `Residue`, `Hamming`, `Depth`, `SatClauses`, `Bound`: pass through (no
///   site references at this layer).
/// - `Affine { coefficients, coefficient_count, bias }`: builds a fresh
///   `[i64; AFFINE_MAX_COEFFS]` of zeros, copies the active prefix into
///   positions `[offset, offset + coefficient_count)`. If the shift
///   would overflow the fixed buffer, returns an Affine with
///   `coefficient_count = 0` (vacuously consistent).
/// - `Conjunction { conjuncts, conjunct_count }`: builds a fresh
///   `[LeafConstraintRef; CONJUNCTION_MAX_TERMS]` and shifts each leaf
///   via `shift_leaf_constraint`. One-level depth โ€” leaves cannot be
///   Conjunction.
pub const fn shift_constraint(c: ConstraintRef, offset: u32) -> ConstraintRef {
    match c {
        ConstraintRef::Site { position } => ConstraintRef::Site {
            position: position.saturating_add(offset),
        },
        ConstraintRef::Carry { site } => ConstraintRef::Carry {
            site: site.saturating_add(offset),
        },
        ConstraintRef::Residue { modulus, residue } => ConstraintRef::Residue { modulus, residue },
        ConstraintRef::Hamming { bound } => ConstraintRef::Hamming { bound },
        ConstraintRef::Depth { min, max } => ConstraintRef::Depth { min, max },
        ConstraintRef::SatClauses { clauses, num_vars } => {
            ConstraintRef::SatClauses { clauses, num_vars }
        }
        ConstraintRef::Bound {
            observable_iri,
            bound_shape_iri,
            args_repr,
        } => ConstraintRef::Bound {
            observable_iri,
            bound_shape_iri,
            args_repr,
        },
        ConstraintRef::Affine {
            coefficients,
            coefficient_count,
            bias,
        } => {
            let (out, new_count) =
                shift_affine_coefficients(&coefficients, coefficient_count, offset);
            ConstraintRef::Affine {
                coefficients: out,
                coefficient_count: new_count,
                bias,
            }
        }
        ConstraintRef::Conjunction {
            conjuncts,
            conjunct_count,
        } => {
            let mut out = [LeafConstraintRef::Site { position: 0 }; CONJUNCTION_MAX_TERMS];
            let count = conjunct_count as usize;
            let mut i = 0;
            while i < count && i < CONJUNCTION_MAX_TERMS {
                out[i] = shift_leaf_constraint(conjuncts[i], offset);
                i += 1;
            }
            ConstraintRef::Conjunction {
                conjuncts: out,
                conjunct_count,
            }
        }
    }
}

/// Phase 17 helper: shift the active prefix of an `Affine`
/// coefficient array right by `offset`, returning a fresh
/// `[i64; AFFINE_MAX_COEFFS]` and the new active count. If the
/// shift would overflow the fixed buffer, returns count `0`
/// (vacuously consistent โ€” no constraint).
#[inline]
#[must_use]
const fn shift_affine_coefficients(
    coefficients: &[i64; AFFINE_MAX_COEFFS],
    coefficient_count: u32,
    offset: u32,
) -> ([i64; AFFINE_MAX_COEFFS], u32) {
    let mut out = [0i64; AFFINE_MAX_COEFFS];
    let count = coefficient_count as usize;
    let off = offset as usize;
    if off >= AFFINE_MAX_COEFFS {
        return (out, 0);
    }
    let mut i = 0;
    while i < count && i + off < AFFINE_MAX_COEFFS {
        out[i + off] = coefficients[i];
        i += 1;
    }
    let new_count = (i + off) as u32;
    (out, new_count)
}

/// Phase 17 helper: same as [`shift_constraint`] but operating on a
/// [`LeafConstraintRef`]. Used by Conjunction-shifting paths that
/// must preserve the leaf-only depth limit.
#[inline]
#[must_use]
pub const fn shift_leaf_constraint(c: LeafConstraintRef, offset: u32) -> LeafConstraintRef {
    match c {
        LeafConstraintRef::Site { position } => LeafConstraintRef::Site {
            position: position.saturating_add(offset),
        },
        LeafConstraintRef::Carry { site } => LeafConstraintRef::Carry {
            site: site.saturating_add(offset),
        },
        LeafConstraintRef::Residue { modulus, residue } => {
            LeafConstraintRef::Residue { modulus, residue }
        }
        LeafConstraintRef::Hamming { bound } => LeafConstraintRef::Hamming { bound },
        LeafConstraintRef::Depth { min, max } => LeafConstraintRef::Depth { min, max },
        LeafConstraintRef::SatClauses { clauses, num_vars } => {
            LeafConstraintRef::SatClauses { clauses, num_vars }
        }
        LeafConstraintRef::Bound {
            observable_iri,
            bound_shape_iri,
            args_repr,
        } => LeafConstraintRef::Bound {
            observable_iri,
            bound_shape_iri,
            args_repr,
        },
        LeafConstraintRef::Affine {
            coefficients,
            coefficient_count,
            bias,
        } => {
            let (out, new_count) =
                shift_affine_coefficients(&coefficients, coefficient_count, offset);
            LeafConstraintRef::Affine {
                coefficients: out,
                coefficient_count: new_count,
                bias,
            }
        }
    }
}

/// SDK support: concatenate two operand constraint arrays into a padded
/// fixed-size buffer of length `2 * crate::enforcement::NERVE_CONSTRAINTS_CAP`.
/// A's constraints are copied verbatim at indices `[0, A::CONSTRAINTS.len())`;
/// B's constraints are copied at `[A::CONSTRAINTS.len(), total)` with each
/// entry passed through `shift_constraint(c, A::SITE_COUNT as u32)`.
/// Trailing positions are filled with the `Site { position: u32::MAX }`
/// sentinel.
/// Consumers pair this with `sdk_product_constraints_len` to derive the
/// slice length at const-eval time: `&BUF[..LEN]` yields a `&'static
/// [ConstraintRef]` of the correct length without `unsafe`.
pub const fn sdk_concat_product_constraints<A, B>(
) -> [ConstraintRef; 2 * crate::enforcement::NERVE_CONSTRAINTS_CAP]
where
    A: ConstrainedTypeShape,
    B: ConstrainedTypeShape,
{
    let mut out =
        [ConstraintRef::Site { position: u32::MAX }; 2 * crate::enforcement::NERVE_CONSTRAINTS_CAP];
    let left = A::CONSTRAINTS;
    let right = B::CONSTRAINTS;
    let offset = A::SITE_COUNT as u32;
    let mut i: usize = 0;
    while i < left.len() {
        out[i] = left[i];
        i += 1;
    }
    let mut j: usize = 0;
    while j < right.len() {
        out[i + j] = shift_constraint(right[j], offset);
        j += 1;
    }
    out
}

/// Companion length helper for `sdk_concat_product_constraints`.
pub const fn sdk_product_constraints_len<A, B>() -> usize
where
    A: ConstrainedTypeShape,
    B: ConstrainedTypeShape,
{
    A::CONSTRAINTS.len() + B::CONSTRAINTS.len()
}

/// ADR-032: per-Witt-level zero-sized marker types implementing
/// `ConstrainedTypeShape`. The `prism_model!` proc-macro consumes
/// these as the `<DomainTy>` operand of `first_admit(<DomainTy>, |i| โ€ฆ)`
/// (G16): `<DomainTy as ConstrainedTypeShape>::CYCLE_SIZE` carries the
/// domain's cardinality, which the macro lowers as the descent measure
/// for the emitted `Term::Recurse`.
/// Each level's `CYCLE_SIZE` is `2^bits_width`, saturated at
/// `u64::MAX` for levels whose cardinality exceeds 64-bit range.
/// The wiki's normative example `first_admit(WittLevel::W32, |nonce| โ€ฆ)`
/// compiles on stable Rust 1.83 as `first_admit(witt_domain::W32, |nonce| โ€ฆ)`
/// (`witt_domain::W32::CYCLE_SIZE = 4_294_967_296`).
pub mod witt_domain {
    use super::{ConstrainedTypeShape, ConstraintRef, PartitionProductFields};
    use crate::enforcement::GroundedShape;
    use crate::enforcement::ShapeViolation;
    use crate::pipeline::__sdk_seal;
    use crate::pipeline::IntoBindingValue;

    /// ADR-032 Witt-level domain marker for `W8` (8-bit ring).
    /// `CYCLE_SIZE = 2^8 = 256`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W8;
    impl ConstrainedTypeShape for W8 {
        const IRI: &'static str = "https://uor.foundation/witt/W8";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = 256u64;
    }
    impl __sdk_seal::Sealed for W8 {}
    impl IntoBindingValue for W8 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W8 {}
    impl PartitionProductFields for W8 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W16` (16-bit ring).
    /// `CYCLE_SIZE = 2^16 = 65536`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W16;
    impl ConstrainedTypeShape for W16 {
        const IRI: &'static str = "https://uor.foundation/witt/W16";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = 65536u64;
    }
    impl __sdk_seal::Sealed for W16 {}
    impl IntoBindingValue for W16 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W16 {}
    impl PartitionProductFields for W16 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W24` (24-bit ring).
    /// `CYCLE_SIZE = 2^24 = 16777216`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W24;
    impl ConstrainedTypeShape for W24 {
        const IRI: &'static str = "https://uor.foundation/witt/W24";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = 16777216u64;
    }
    impl __sdk_seal::Sealed for W24 {}
    impl IntoBindingValue for W24 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W24 {}
    impl PartitionProductFields for W24 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W32` (32-bit ring).
    /// `CYCLE_SIZE = 2^32 = 4294967296`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W32;
    impl ConstrainedTypeShape for W32 {
        const IRI: &'static str = "https://uor.foundation/witt/W32";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = 4294967296u64;
    }
    impl __sdk_seal::Sealed for W32 {}
    impl IntoBindingValue for W32 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W32 {}
    impl PartitionProductFields for W32 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W40` (40-bit ring).
    /// `CYCLE_SIZE = 2^40 = 1099511627776`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W40;
    impl ConstrainedTypeShape for W40 {
        const IRI: &'static str = "https://uor.foundation/witt/W40";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = 1099511627776u64;
    }
    impl __sdk_seal::Sealed for W40 {}
    impl IntoBindingValue for W40 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W40 {}
    impl PartitionProductFields for W40 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W48` (48-bit ring).
    /// `CYCLE_SIZE = 2^48 = 281474976710656`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W48;
    impl ConstrainedTypeShape for W48 {
        const IRI: &'static str = "https://uor.foundation/witt/W48";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = 281474976710656u64;
    }
    impl __sdk_seal::Sealed for W48 {}
    impl IntoBindingValue for W48 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W48 {}
    impl PartitionProductFields for W48 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W56` (56-bit ring).
    /// `CYCLE_SIZE = 2^56 = 72057594037927936`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W56;
    impl ConstrainedTypeShape for W56 {
        const IRI: &'static str = "https://uor.foundation/witt/W56";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = 72057594037927936u64;
    }
    impl __sdk_seal::Sealed for W56 {}
    impl IntoBindingValue for W56 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W56 {}
    impl PartitionProductFields for W56 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W64` (64-bit ring).
    /// `CYCLE_SIZE = 2^64 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W64;
    impl ConstrainedTypeShape for W64 {
        const IRI: &'static str = "https://uor.foundation/witt/W64";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W64 {}
    impl IntoBindingValue for W64 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W64 {}
    impl PartitionProductFields for W64 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W72` (72-bit ring).
    /// `CYCLE_SIZE = 2^72 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W72;
    impl ConstrainedTypeShape for W72 {
        const IRI: &'static str = "https://uor.foundation/witt/W72";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W72 {}
    impl IntoBindingValue for W72 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W72 {}
    impl PartitionProductFields for W72 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W80` (80-bit ring).
    /// `CYCLE_SIZE = 2^80 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W80;
    impl ConstrainedTypeShape for W80 {
        const IRI: &'static str = "https://uor.foundation/witt/W80";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W80 {}
    impl IntoBindingValue for W80 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W80 {}
    impl PartitionProductFields for W80 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W88` (88-bit ring).
    /// `CYCLE_SIZE = 2^88 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W88;
    impl ConstrainedTypeShape for W88 {
        const IRI: &'static str = "https://uor.foundation/witt/W88";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W88 {}
    impl IntoBindingValue for W88 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W88 {}
    impl PartitionProductFields for W88 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W96` (96-bit ring).
    /// `CYCLE_SIZE = 2^96 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W96;
    impl ConstrainedTypeShape for W96 {
        const IRI: &'static str = "https://uor.foundation/witt/W96";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W96 {}
    impl IntoBindingValue for W96 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W96 {}
    impl PartitionProductFields for W96 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W104` (104-bit ring).
    /// `CYCLE_SIZE = 2^104 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W104;
    impl ConstrainedTypeShape for W104 {
        const IRI: &'static str = "https://uor.foundation/witt/W104";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W104 {}
    impl IntoBindingValue for W104 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W104 {}
    impl PartitionProductFields for W104 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W112` (112-bit ring).
    /// `CYCLE_SIZE = 2^112 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W112;
    impl ConstrainedTypeShape for W112 {
        const IRI: &'static str = "https://uor.foundation/witt/W112";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W112 {}
    impl IntoBindingValue for W112 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W112 {}
    impl PartitionProductFields for W112 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W120` (120-bit ring).
    /// `CYCLE_SIZE = 2^120 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W120;
    impl ConstrainedTypeShape for W120 {
        const IRI: &'static str = "https://uor.foundation/witt/W120";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W120 {}
    impl IntoBindingValue for W120 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W120 {}
    impl PartitionProductFields for W120 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W128` (128-bit ring).
    /// `CYCLE_SIZE = 2^128 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W128;
    impl ConstrainedTypeShape for W128 {
        const IRI: &'static str = "https://uor.foundation/witt/W128";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W128 {}
    impl IntoBindingValue for W128 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W128 {}
    impl PartitionProductFields for W128 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W160` (160-bit ring).
    /// `CYCLE_SIZE = 2^160 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W160;
    impl ConstrainedTypeShape for W160 {
        const IRI: &'static str = "https://uor.foundation/witt/W160";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W160 {}
    impl IntoBindingValue for W160 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W160 {}
    impl PartitionProductFields for W160 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W192` (192-bit ring).
    /// `CYCLE_SIZE = 2^192 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W192;
    impl ConstrainedTypeShape for W192 {
        const IRI: &'static str = "https://uor.foundation/witt/W192";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W192 {}
    impl IntoBindingValue for W192 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W192 {}
    impl PartitionProductFields for W192 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W224` (224-bit ring).
    /// `CYCLE_SIZE = 2^224 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W224;
    impl ConstrainedTypeShape for W224 {
        const IRI: &'static str = "https://uor.foundation/witt/W224";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W224 {}
    impl IntoBindingValue for W224 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W224 {}
    impl PartitionProductFields for W224 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W256` (256-bit ring).
    /// `CYCLE_SIZE = 2^256 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W256;
    impl ConstrainedTypeShape for W256 {
        const IRI: &'static str = "https://uor.foundation/witt/W256";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W256 {}
    impl IntoBindingValue for W256 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W256 {}
    impl PartitionProductFields for W256 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W384` (384-bit ring).
    /// `CYCLE_SIZE = 2^384 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W384;
    impl ConstrainedTypeShape for W384 {
        const IRI: &'static str = "https://uor.foundation/witt/W384";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W384 {}
    impl IntoBindingValue for W384 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W384 {}
    impl PartitionProductFields for W384 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W448` (448-bit ring).
    /// `CYCLE_SIZE = 2^448 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W448;
    impl ConstrainedTypeShape for W448 {
        const IRI: &'static str = "https://uor.foundation/witt/W448";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W448 {}
    impl IntoBindingValue for W448 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W448 {}
    impl PartitionProductFields for W448 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W512` (512-bit ring).
    /// `CYCLE_SIZE = 2^512 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W512;
    impl ConstrainedTypeShape for W512 {
        const IRI: &'static str = "https://uor.foundation/witt/W512";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W512 {}
    impl IntoBindingValue for W512 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W512 {}
    impl PartitionProductFields for W512 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W520` (520-bit ring).
    /// `CYCLE_SIZE = 2^520 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W520;
    impl ConstrainedTypeShape for W520 {
        const IRI: &'static str = "https://uor.foundation/witt/W520";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W520 {}
    impl IntoBindingValue for W520 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W520 {}
    impl PartitionProductFields for W520 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W528` (528-bit ring).
    /// `CYCLE_SIZE = 2^528 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W528;
    impl ConstrainedTypeShape for W528 {
        const IRI: &'static str = "https://uor.foundation/witt/W528";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W528 {}
    impl IntoBindingValue for W528 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W528 {}
    impl PartitionProductFields for W528 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W1024` (1024-bit ring).
    /// `CYCLE_SIZE = 2^1024 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W1024;
    impl ConstrainedTypeShape for W1024 {
        const IRI: &'static str = "https://uor.foundation/witt/W1024";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W1024 {}
    impl IntoBindingValue for W1024 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W1024 {}
    impl PartitionProductFields for W1024 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W2048` (2048-bit ring).
    /// `CYCLE_SIZE = 2^2048 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W2048;
    impl ConstrainedTypeShape for W2048 {
        const IRI: &'static str = "https://uor.foundation/witt/W2048";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W2048 {}
    impl IntoBindingValue for W2048 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W2048 {}
    impl PartitionProductFields for W2048 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W4096` (4096-bit ring).
    /// `CYCLE_SIZE = 2^4096 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W4096;
    impl ConstrainedTypeShape for W4096 {
        const IRI: &'static str = "https://uor.foundation/witt/W4096";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W4096 {}
    impl IntoBindingValue for W4096 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W4096 {}
    impl PartitionProductFields for W4096 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W8192` (8192-bit ring).
    /// `CYCLE_SIZE = 2^8192 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W8192;
    impl ConstrainedTypeShape for W8192 {
        const IRI: &'static str = "https://uor.foundation/witt/W8192";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W8192 {}
    impl IntoBindingValue for W8192 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W8192 {}
    impl PartitionProductFields for W8192 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W12288` (12288-bit ring).
    /// `CYCLE_SIZE = 2^12288 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W12288;
    impl ConstrainedTypeShape for W12288 {
        const IRI: &'static str = "https://uor.foundation/witt/W12288";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W12288 {}
    impl IntoBindingValue for W12288 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W12288 {}
    impl PartitionProductFields for W12288 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W16384` (16384-bit ring).
    /// `CYCLE_SIZE = 2^16384 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W16384;
    impl ConstrainedTypeShape for W16384 {
        const IRI: &'static str = "https://uor.foundation/witt/W16384";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W16384 {}
    impl IntoBindingValue for W16384 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W16384 {}
    impl PartitionProductFields for W16384 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }

    /// ADR-032 Witt-level domain marker for `W32768` (32768-bit ring).
    /// `CYCLE_SIZE = 2^32768 = u64::MAX (saturated)`. Used as the `<DomainTy>` operand of
    /// `first_admit(<DomainTy>, |i| โ€ฆ)` (G16) in `prism_model!` closures.
    pub struct W32768;
    impl ConstrainedTypeShape for W32768 {
        const IRI: &'static str = "https://uor.foundation/witt/W32768";
        const SITE_COUNT: usize = 1;
        const CONSTRAINTS: &'static [ConstraintRef] = &[];
        const CYCLE_SIZE: u64 = u64::MAX;
    }
    impl __sdk_seal::Sealed for W32768 {}
    impl IntoBindingValue for W32768 {
        const MAX_BYTES: usize = 0;
        fn into_binding_bytes(&self, _out: &mut [u8]) -> Result<usize, ShapeViolation> {
            Ok(0)
        }
    }
    impl GroundedShape for W32768 {}
    impl PartitionProductFields for W32768 {
        const FIELDS: &'static [(u32, u32)] = &[];
        const FIELD_NAMES: &'static [&'static str] = &[];
    }
}

/// Admit a downstream [`ConstrainedTypeShape`] into the reduction pipeline.
/// Runs the full preflight chain on `T::CONSTRAINTS`:
/// [`preflight_feasibility`] and [`preflight_package_coherence`]. On success,
/// wraps the supplied `shape` in a [`Validated`] carrying `Runtime` phase.
/// # Errors
/// Returns [`ShapeViolation`] if any constraint in `T::CONSTRAINTS` fails
/// feasibility checking (e.g., residue out of range, depth min > max) or if
/// the constraint system is internally incoherent (e.g., contradictory
/// residue constraints on the same modulus).
/// # Example
/// ```
/// use uor_foundation::pipeline::{
///     ConstrainedTypeShape, ConstraintRef, validate_constrained_type,
/// };
/// pub struct MyShape;
/// impl ConstrainedTypeShape for MyShape {
///     const IRI: &'static str = "https://example.org/MyShape";
///     const SITE_COUNT: usize = 2;
///     const CONSTRAINTS: &'static [ConstraintRef] = &[
///         ConstraintRef::Residue { modulus: 5, residue: 2 },
///     ];
///     const CYCLE_SIZE: u64 = 5;  // ADR-032: 5 residue classes mod 5
/// }
/// let validated = validate_constrained_type(MyShape).unwrap();
/// # let _ = validated;
/// ```
pub fn validate_constrained_type<T: ConstrainedTypeShape>(
    shape: T,
) -> Result<Validated<T, crate::enforcement::Runtime>, ShapeViolation> {
    preflight_feasibility(T::CONSTRAINTS)?;
    preflight_package_coherence(T::CONSTRAINTS)?;
    Ok(Validated::new(shape))
}

/// Const-fn companion for [`validate_constrained_type`].
/// Admits a downstream [`ConstrainedTypeShape`] at compile time, running the
/// same preflight checks as the runtime variant but in `const` context.
/// # Scope
/// `ConstraintRef::Bound { observable_iri, args_repr, .. }` with
/// `observable_iri == "https://uor.foundation/observable/LandauerCost"`
/// requires `f64::from_bits` for args parsing, which is stable in `const`
/// context only from Rust 1.83. The crate's MSRV is 1.81, so this variant
/// rejects const admission of `LandauerCost`-bound constraints with
/// [`ShapeViolation`] and recommends the runtime [`validate_constrained_type`]
/// for those inputs. All other `ConstraintRef` variants admit at const time.
/// # Errors
/// Same as [`validate_constrained_type`], plus the const-context rejection
/// for `LandauerCost`-bound constraints described above.
/// The `T: Copy` bound is required by `const fn` โ€” destructor invocation is
/// not yet const-stable, and `Validated<T>` carries `T` by value. Shape
/// markers are typically zero-sized types which are trivially `Copy`.
pub const fn validate_constrained_type_const<T: ConstrainedTypeShape + Copy>(
    shape: T,
) -> Result<Validated<T, crate::enforcement::CompileTime>, ShapeViolation> {
    // Const-path preflight: walk CONSTRAINTS and apply per-variant const checks.
    // Rejects LandauerCost-bound constraints that need non-const f64::from_bits.
    let constraints = T::CONSTRAINTS;
    let mut i = 0;
    while i < constraints.len() {
        let ok = match &constraints[i] {
            ConstraintRef::SatClauses { clauses, num_vars } => *num_vars != 0 || clauses.is_empty(),
            ConstraintRef::Residue { modulus, residue } => *modulus != 0 && *residue < *modulus,
            ConstraintRef::Carry { .. } => true,
            ConstraintRef::Depth { min, max } => *min <= *max,
            ConstraintRef::Hamming { bound } => *bound <= 32_768,
            ConstraintRef::Site { .. } => true,
            ConstraintRef::Affine {
                coefficients,
                coefficient_count,
                bias,
            } => {
                // Mirror preflight_feasibility's Affine arm in const context.
                let count = *coefficient_count as usize;
                if count == 0 {
                    false
                } else {
                    let mut ok_coeff = true;
                    let mut idx = 0;
                    while idx < count && idx < AFFINE_MAX_COEFFS {
                        if coefficients[idx] == i64::MIN {
                            ok_coeff = false;
                            break;
                        }
                        idx += 1;
                    }
                    ok_coeff && is_affine_consistent(coefficients, *coefficient_count, *bias)
                }
            }
            ConstraintRef::Bound { observable_iri, .. } => {
                // const-fn scope: LandauerCost needs f64::from_bits (stable in
                // const at 1.83). Reject it here; runtime admission handles it.
                !crate::enforcement::str_eq(
                    observable_iri,
                    "https://uor.foundation/observable/LandauerCost",
                )
            }
            ConstraintRef::Conjunction {
                conjuncts,
                conjunct_count,
            } => conjunction_all_sat(conjuncts, *conjunct_count),
        };
        if !ok {
            return Err(ShapeViolation {
                shape_iri: "https://uor.foundation/type/ConstrainedType",
                constraint_iri: "https://uor.foundation/type/ConstrainedType_const_constraint",
                property_iri: "https://uor.foundation/type/constraints",
                expected_range: "https://uor.foundation/type/Constraint",
                min_count: 1,
                max_count: 1,
                kind: ViolationKind::ValueCheck,
            });
        }
        i += 1;
    }
    Ok(Validated::new(shape))
}

/// Result of `fragment_classify`: which `predicate:*Shape` fragment the
/// input belongs to. Drives `InhabitanceResolver` dispatch routing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FragmentKind {
    /// `predicate:Is2SatShape` โ€” clauses of width โ‰ค 2.
    TwoSat,
    /// `predicate:IsHornShape` โ€” clauses with โ‰ค 1 positive literal.
    Horn,
    /// `predicate:IsResidualFragment` โ€” catch-all; no polynomial bound.
    Residual,
}

/// Classify a constraint system into one of the three dispatch fragments.
/// The classifier inspects the first `SatClauses` constraint (if any) and
/// applies the ontology's shape predicates. Constraint systems with no
/// `SatClauses` constraint โ€” e.g., pure residue/hamming constraints โ€” are
/// classified as `Residual`: the dispatch table has no polynomial decider
/// for them, so they route to the `ResidualVerdictResolver` catch-all.
#[must_use]
pub const fn fragment_classify(constraints: &[ConstraintRef]) -> FragmentKind {
    let mut i = 0;
    while i < constraints.len() {
        if let ConstraintRef::SatClauses { clauses, .. } = constraints[i] {
            // Classify by maximum clause width and positive-literal count.
            let mut max_width: usize = 0;
            let mut horn: bool = true;
            let mut j = 0;
            while j < clauses.len() {
                let clause = clauses[j];
                if clause.len() > max_width {
                    max_width = clause.len();
                }
                let mut positives: usize = 0;
                let mut k = 0;
                while k < clause.len() {
                    let (_, negated) = clause[k];
                    if !negated {
                        positives += 1;
                    }
                    k += 1;
                }
                if positives > 1 {
                    horn = false;
                }
                j += 1;
            }
            if max_width <= 2 {
                return FragmentKind::TwoSat;
            } else if horn {
                return FragmentKind::Horn;
            } else {
                return FragmentKind::Residual;
            }
        }
        i += 1;
    }
    // No SAT clauses at all โ€” residual.
    FragmentKind::Residual
}

/// Aspvall-Plass-Tarjan 2-SAT decider: returns `true` iff the clause list
/// is satisfiable.
/// Builds the implication graph: for each clause `(a | b)`, adds
/// `ยฌa โ†’ b` and `ยฌb โ†’ a`. Runs Tarjan's SCC algorithm and checks that
/// no variable and its negation share an SCC. O(n+m) via iterative
/// Tarjan (the `no_std` path can't recurse freely).
/// Bounds (from `reduction:TwoSatBound`): up to 256 variables, up to 512 clauses. The `const` bounds keep the entire decider on the stack โ€” essential for `no_std` and compile-time proc-macro expansion.
const TWO_SAT_MAX_VARS: usize = 256;
const TWO_SAT_MAX_NODES: usize = TWO_SAT_MAX_VARS * 2;
const TWO_SAT_MAX_EDGES: usize = 2048;

/// 2-SAT decision result.
#[must_use]
pub fn decide_two_sat(clauses: &[&[(u32, bool)]], num_vars: u32) -> bool {
    if (num_vars as usize) > TWO_SAT_MAX_VARS {
        return false;
    }
    let n = (num_vars as usize) * 2;
    // Node index: 2*var is positive literal, 2*var+1 is negated.
    let mut adj_starts = [0usize; TWO_SAT_MAX_NODES + 1];
    let mut adj_targets = [0usize; TWO_SAT_MAX_EDGES];
    // First pass: count out-degrees.
    for clause in clauses {
        if clause.len() > 2 || clause.is_empty() {
            return false;
        }
        if clause.len() == 1 {
            let (v, neg) = clause[0];
            let lit = lit_index(v, neg);
            let neg_lit = lit_index(v, !neg);
            // x โ†” (x โˆจ x): ยฌx โ†’ x (assignment forced)
            if neg_lit < n + 1 {
                adj_starts[neg_lit + 1] += 1;
            }
            let _ = lit;
        } else {
            let (a, an) = clause[0];
            let (b, bn) = clause[1];
            // ยฌa โ†’ b, ยฌb โ†’ a
            let na = lit_index(a, !an);
            let nb = lit_index(b, !bn);
            if na + 1 < n + 1 {
                adj_starts[na + 1] += 1;
            }
            if nb + 1 < n + 1 {
                adj_starts[nb + 1] += 1;
            }
        }
    }
    // Prefix-sum to get adjacency starts.
    let mut i = 1;
    while i <= n {
        adj_starts[i] += adj_starts[i - 1];
        i += 1;
    }
    let edge_count = adj_starts[n];
    if edge_count > TWO_SAT_MAX_EDGES {
        return false;
    }
    let mut fill = [0usize; TWO_SAT_MAX_NODES];
    for clause in clauses {
        if clause.len() == 1 {
            let (v, neg) = clause[0];
            let pos_lit = lit_index(v, neg);
            let neg_lit = lit_index(v, !neg);
            let slot = adj_starts[neg_lit] + fill[neg_lit];
            adj_targets[slot] = pos_lit;
            fill[neg_lit] += 1;
        } else {
            let (a, an) = clause[0];
            let (b, bn) = clause[1];
            let pa = lit_index(a, an);
            let na = lit_index(a, !an);
            let pb = lit_index(b, bn);
            let nb = lit_index(b, !bn);
            let s1 = adj_starts[na] + fill[na];
            adj_targets[s1] = pb;
            fill[na] += 1;
            let s2 = adj_starts[nb] + fill[nb];
            adj_targets[s2] = pa;
            fill[nb] += 1;
        }
    }
    // Iterative Tarjan's SCC.
    let mut index_counter: usize = 0;
    let mut indices = [usize::MAX; TWO_SAT_MAX_NODES];
    let mut lowlinks = [0usize; TWO_SAT_MAX_NODES];
    let mut on_stack = [false; TWO_SAT_MAX_NODES];
    let mut stack = [0usize; TWO_SAT_MAX_NODES];
    let mut stack_top: usize = 0;
    let mut scc_id = [usize::MAX; TWO_SAT_MAX_NODES];
    let mut scc_count: usize = 0;
    let mut call_stack = [(0usize, 0usize); TWO_SAT_MAX_NODES];
    let mut call_top: usize = 0;
    let mut v = 0;
    while v < n {
        if indices[v] == usize::MAX {
            call_stack[call_top] = (v, adj_starts[v]);
            call_top += 1;
            indices[v] = index_counter;
            lowlinks[v] = index_counter;
            index_counter += 1;
            stack[stack_top] = v;
            stack_top += 1;
            on_stack[v] = true;
            while call_top > 0 {
                let (u, mut next_edge) = call_stack[call_top - 1];
                let end_edge = adj_starts[u + 1];
                let mut advanced = false;
                while next_edge < end_edge {
                    let w = adj_targets[next_edge];
                    next_edge += 1;
                    if indices[w] == usize::MAX {
                        call_stack[call_top - 1] = (u, next_edge);
                        indices[w] = index_counter;
                        lowlinks[w] = index_counter;
                        index_counter += 1;
                        stack[stack_top] = w;
                        stack_top += 1;
                        on_stack[w] = true;
                        call_stack[call_top] = (w, adj_starts[w]);
                        call_top += 1;
                        advanced = true;
                        break;
                    } else if on_stack[w] && indices[w] < lowlinks[u] {
                        lowlinks[u] = indices[w];
                    }
                }
                if !advanced {
                    call_stack[call_top - 1] = (u, next_edge);
                    if lowlinks[u] == indices[u] {
                        loop {
                            stack_top -= 1;
                            let w = stack[stack_top];
                            on_stack[w] = false;
                            scc_id[w] = scc_count;
                            if w == u {
                                break;
                            }
                        }
                        scc_count += 1;
                    }
                    call_top -= 1;
                    if call_top > 0 {
                        let (parent, _) = call_stack[call_top - 1];
                        if lowlinks[u] < lowlinks[parent] {
                            lowlinks[parent] = lowlinks[u];
                        }
                    }
                }
            }
        }
        v += 1;
    }
    // Unsatisfiable iff x and ยฌx are in the same SCC for any variable.
    let mut var = 0u32;
    while var < num_vars {
        let pos = lit_index(var, false);
        let neg = lit_index(var, true);
        if scc_id[pos] == scc_id[neg] {
            return false;
        }
        var += 1;
    }
    true
}

#[inline]
const fn lit_index(var: u32, negated: bool) -> usize {
    let base = (var as usize) * 2;
    if negated {
        base + 1
    } else {
        base
    }
}

/// Horn-SAT decider via unit propagation. Returns `true` iff the clause
/// list is satisfiable.
/// Algorithm: start with all variables false. Repeatedly find a clause
/// whose negative literals are all satisfied but whose positive literal
/// is unassigned/false; set the positive literal true. Fail if a clause
/// with no positive literal has all its negatives satisfied.
/// Bounds (from `reduction:HornSatBound`): up to 256 variables.
const HORN_MAX_VARS: usize = 256;

/// Horn-SAT decision result.
#[must_use]
pub fn decide_horn_sat(clauses: &[&[(u32, bool)]], num_vars: u32) -> bool {
    if (num_vars as usize) > HORN_MAX_VARS {
        return false;
    }
    let mut assignment = [false; HORN_MAX_VARS];
    let n = num_vars as usize;
    loop {
        let mut changed = false;
        for clause in clauses {
            // Count positive literals.
            let mut positive: Option<u32> = None;
            let mut positive_count = 0;
            for (_, negated) in clause.iter() {
                if !*negated {
                    positive_count += 1;
                }
            }
            if positive_count > 1 {
                return false;
            }
            for (var, negated) in clause.iter() {
                if !*negated {
                    positive = Some(*var);
                }
            }
            // Check whether all negative literals are satisfied (var=true).
            let mut all_neg_satisfied = true;
            for (var, negated) in clause.iter() {
                if *negated {
                    let idx = *var as usize;
                    if idx >= n {
                        return false;
                    }
                    if !assignment[idx] {
                        all_neg_satisfied = false;
                        break;
                    }
                }
            }
            if all_neg_satisfied {
                match positive {
                    None => return false,
                    Some(v) => {
                        let idx = v as usize;
                        if idx >= n {
                            return false;
                        }
                        if !assignment[idx] {
                            assignment[idx] = true;
                            changed = true;
                        }
                    }
                }
            }
        }
        if !changed {
            break;
        }
    }
    // Final verification pass.
    for clause in clauses {
        let mut satisfied = false;
        for (var, negated) in clause.iter() {
            let idx = *var as usize;
            if idx >= n {
                return false;
            }
            let val = assignment[idx];
            if (*negated && !val) || (!*negated && val) {
                satisfied = true;
                break;
            }
        }
        if !satisfied {
            return false;
        }
    }
    true
}

/// `BudgetSolvencyCheck` (preflightOrder 0): `thermodynamicBudget` must be
/// โ‰ฅ `bitsWidth(unitWittLevel) ร— ln 2` per `op:GS_7` / `op:OA_5`.
/// Takes the budget in `k_B T ยท ln 2` units and the target Witt level in
/// bit-width. Returns `Ok(())` if solvent, `Err` with the shape violation.
pub fn preflight_budget_solvency(budget_units: u64, witt_bits: u32) -> Result<(), ShapeViolation> {
    // Landauer bound: one bit requires k_B T ยท ln 2. Integer form.
    let minimum = witt_bits as u64;
    if budget_units >= minimum {
        Ok(())
    } else {
        Err(ShapeViolation {
            shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
            constraint_iri:
                "https://uor.foundation/conformance/compileUnit_thermodynamicBudget_constraint",
            property_iri: "https://uor.foundation/reduction/thermodynamicBudget",
            expected_range: "http://www.w3.org/2001/XMLSchema#decimal",
            min_count: 1,
            max_count: 1,
            kind: ViolationKind::ValueCheck,
        })
    }
}

/// v0.2.2 Phase F: upper bound on `CarryDepthObservable` depth arguments.
/// Matches target ยง4.5's Witt-level tower ceiling (W16384).
pub const WITT_MAX_BITS: u16 = 16_384;

/// v0.2.2 Phase F: ASCII parser for a single unsigned decimal `u32`.
/// Returns 0 on malformed input; the caller's downstream comparison (`depth <= WITT_MAX_BITS`)
/// accepts 0 as the pass-through degenerate depth, so malformed input is rejected
/// by the enclosing feasibility check only if the parsed value exceeds the cap.
/// For stricter input discipline, the caller pre-validates `args_repr` at builder time.
#[must_use]
pub fn parse_u32(s: &str) -> u32 {
    let bytes = s.as_bytes();
    let mut out: u32 = 0;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if !b.is_ascii_digit() {
            return 0;
        }
        out = out.saturating_mul(10).saturating_add((b - b'0') as u32);
        i += 1;
    }
    out
}

/// v0.2.2 Phase F: ASCII parser for a single unsigned decimal `u64`.
#[must_use]
pub fn parse_u64(s: &str) -> u64 {
    let bytes = s.as_bytes();
    let mut out: u64 = 0;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if !b.is_ascii_digit() {
            return 0;
        }
        out = out.saturating_mul(10).saturating_add((b - b'0') as u64);
        i += 1;
    }
    out
}

/// v0.2.2 Phase F: parser for `"modulus|residue"` decimal pairs.
/// Split on the first ASCII `|`; ASCII-digit-parse each half via `parse_u64`.
#[must_use]
pub fn parse_u64_pair(s: &str) -> (u64, u64) {
    let bytes = s.as_bytes();
    let mut split = bytes.len();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'|' {
            split = i;
            break;
        }
        i += 1;
    }
    if split >= bytes.len() {
        return (0, 0);
    }
    let (left, right_with_pipe) = s.split_at(split);
    let (_, right) = right_with_pipe.split_at(1);
    (parse_u64(left), parse_u64(right))
}

/// v0.2.2 Phase F / Phase 9: parse a decimal `u64` representing an
/// IEEE-754 bit pattern. The bit pattern is content-deterministic; call sites
/// project to `H::Decimal` via `DecimalTranscendental::from_bits`.
#[must_use]
pub fn parse_u64_bits_str(s: &str) -> u64 {
    parse_u64(s)
}

/// v0.2.2 Phase F: dispatch a `ConstraintRef::Bound` arm on its `observable_iri`.
/// Canonical observables: `ValueModObservable`, `CarryDepthObservable`, `LandauerCost`.
/// Unknown IRIs are rejected so that an unaudited observable cannot be threaded
/// through the preflight surface silently.
fn check_bound_feasibility(
    observable_iri: &'static str,
    bound_shape_iri: &'static str,
    args_repr: &'static str,
) -> Result<(), ShapeViolation> {
    const VALUE_MOD_IRI: &str = "https://uor.foundation/observable/ValueModObservable";
    const CARRY_DEPTH_IRI: &str = "https://uor.foundation/observable/CarryDepthObservable";
    const LANDAUER_IRI: &str = "https://uor.foundation/observable/LandauerCost";
    let ok = if crate::enforcement::str_eq(observable_iri, VALUE_MOD_IRI) {
        let (modulus, residue) = parse_u64_pair(args_repr);
        modulus != 0 && residue < modulus
    } else if crate::enforcement::str_eq(observable_iri, CARRY_DEPTH_IRI) {
        let depth = parse_u32(args_repr);
        depth <= WITT_MAX_BITS as u32
    } else if crate::enforcement::str_eq(observable_iri, LANDAUER_IRI) {
        // Project the bit pattern to f64 (default-host) for the
        // finite/positive-nats sanity check. Polymorphic consumers
        // construct their own H::Decimal via DecimalTranscendental.
        let bits = parse_u64_bits_str(args_repr);
        let nats = <f64 as crate::DecimalTranscendental>::from_bits(bits);
        nats.is_finite() && nats > 0.0
    } else {
        false
    };
    if ok {
        Ok(())
    } else {
        Err(ShapeViolation {
            shape_iri: bound_shape_iri,
            constraint_iri: "https://uor.foundation/type/BoundConstraint",
            property_iri: observable_iri,
            expected_range: "https://uor.foundation/observable/BaseMetric",
            min_count: 1,
            max_count: 1,
            kind: ViolationKind::ValueCheck,
        })
    }
}

/// `FeasibilityCheck`: verify the constraint system isn't trivially
/// infeasible. Workstream E (target ยง1.5 + ยง4.7, v0.2.2 closure):
/// the closed six-kind constraint set is validated by direct per-kind
/// satisfiability checks; any variant that fails is rejected here so
/// downstream resolvers never see an unsatisfiable constraint system.
/// v0.2.2 Phase F: the `Bound` arm dispatches on `observable_iri` to per-observable
/// checks via `check_bound_feasibility`; `Carry` and `Site` remain `Ok(())` by
/// documented design โ€” their constraint semantics are structural invariants of
/// ring arithmetic and site-index bounds respectively, enforced by construction
/// rather than by runtime feasibility checks.
pub fn preflight_feasibility(constraints: &[ConstraintRef]) -> Result<(), ShapeViolation> {
    for c in constraints {
        // v0.2.2 Phase F: Bound dispatches to observable-specific checks with its
        // own bound_shape_iri; early-return with that shape on failure.
        if let ConstraintRef::Bound {
            observable_iri,
            bound_shape_iri,
            args_repr,
        } = c
        {
            check_bound_feasibility(observable_iri, bound_shape_iri, args_repr)?;
            continue;
        }
        let ok = match c {
            ConstraintRef::SatClauses { clauses, num_vars } => *num_vars != 0 || clauses.is_empty(),
            ConstraintRef::Residue { modulus, residue } => *modulus != 0 && *residue < *modulus,
            // Structural invariant of ring arithmetic โ€” carries cannot contradict by construction.
            ConstraintRef::Carry { .. } => true,
            ConstraintRef::Depth { min, max } => min <= max,
            ConstraintRef::Hamming { bound } => *bound <= 32_768,
            // Structural invariant of site indexing โ€” bounds enforced by SITE_COUNT typing.
            ConstraintRef::Site { .. } => true,
            ConstraintRef::Affine {
                coefficients,
                coefficient_count,
                bias,
            } => {
                let count = *coefficient_count as usize;
                if count == 0 {
                    false
                } else {
                    let mut ok_coeff = true;
                    let mut idx = 0;
                    while idx < count && idx < AFFINE_MAX_COEFFS {
                        if coefficients[idx] == i64::MIN {
                            ok_coeff = false;
                            break;
                        }
                        idx += 1;
                    }
                    ok_coeff && is_affine_consistent(coefficients, *coefficient_count, *bias)
                }
            }
            // Handled above via early `if let`; unreachable here.
            ConstraintRef::Bound { .. } => true,
            ConstraintRef::Conjunction {
                conjuncts,
                conjunct_count,
            } => conjunction_all_sat(conjuncts, *conjunct_count),
        };
        if !ok {
            return Err(ShapeViolation {
                shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
                constraint_iri:
                    "https://uor.foundation/conformance/compileUnit_rootTerm_constraint",
                property_iri: "https://uor.foundation/reduction/rootTerm",
                expected_range: "https://uor.foundation/schema/Term",
                min_count: 1,
                max_count: 1,
                kind: ViolationKind::ValueCheck,
            });
        }
    }
    Ok(())
}

/// `DispatchCoverageCheck`: verify the inhabitance dispatch table covers the input.
/// The table is exhaustive by construction: Rule 3 (IsResidualFragment) is the catch-all.
pub fn preflight_dispatch_coverage() -> Result<(), ShapeViolation> {
    // Always covered: IsResidualFragment catches everything not in 2-SAT/Horn.
    Ok(())
}

/// `PackageCoherenceCheck`: verify each site's constraints are internally consistent.
pub fn preflight_package_coherence(constraints: &[ConstraintRef]) -> Result<(), ShapeViolation> {
    // Check residue constraints don't contradict (same modulus, different residues).
    let mut i = 0;
    while i < constraints.len() {
        if let ConstraintRef::Residue {
            modulus: m1,
            residue: r1,
        } = constraints[i]
        {
            let mut j = i + 1;
            while j < constraints.len() {
                if let ConstraintRef::Residue {
                    modulus: m2,
                    residue: r2,
                } = constraints[j]
                {
                    if m1 == m2 && r1 != r2 {
                        return Err(ShapeViolation {
                            shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
                            constraint_iri:
                                "https://uor.foundation/conformance/compileUnit_rootTerm_constraint",
                            property_iri: "https://uor.foundation/reduction/rootTerm",
                            expected_range: "https://uor.foundation/schema/Term",
                            min_count: 1,
                            max_count: 1,
                            kind: ViolationKind::ValueCheck,
                        });
                    }
                }
                j += 1;
            }
        }
        i += 1;
    }
    Ok(())
}

/// v0.2.2 Phase B: a-priori `UorTime` estimator for preflight timing.
/// Derives a content-deterministic upper bound on the `UorTime` a reduction
/// over `shape` at `witt_bits` will consume, without a physical clock. The
/// bound is `witt_bits ร— constraint_count` rewrite steps and the matching
/// Landauer nats at `ln 2` per step. Preflight compares this via
/// [`UorTime::min_wall_clock`](crate::enforcement::UorTime::min_wall_clock) against the policy's Nanos budget โ€” no
/// physical clock is consulted.
#[must_use]
pub fn estimate_preflight_uor_time<T: ConstrainedTypeShape + ?Sized>(
    witt_bits: u16,
) -> crate::enforcement::UorTime {
    let steps = (witt_bits as u64).saturating_mul((T::CONSTRAINTS.len() as u64).max(1));
    let nats = (steps as f64) * core::f64::consts::LN_2;
    crate::enforcement::UorTime::new(crate::enforcement::LandauerBudget::new(nats), steps)
}

/// `PreflightTiming`: timing-check preflight. v0.2.2 Phase B: parameterized over
/// a [`TimingPolicy`] carrying the Nanos budget and canonical `Calibration`.
/// The `expected` UorTime is derived a-priori from input shape via
/// [`estimate_preflight_uor_time`] โ€” content-deterministic, no physical
/// clock consulted. Rejects when the Nanos lower bound exceeds the budget.
/// # Errors
/// Returns `ShapeViolation::ValueCheck` when the expected UorTime, converted
/// to Nanos under `P::CALIBRATION`, exceeds `P::PREFLIGHT_BUDGET_NS`.
#[allow(dead_code)]
pub(crate) const CANONICAL_PREFLIGHT_BUDGET_NS: u64 = 10000000;
pub fn preflight_timing<P: crate::enforcement::TimingPolicy>(
    expected: crate::enforcement::UorTime,
) -> Result<(), ShapeViolation> {
    let nanos = expected.min_wall_clock(P::CALIBRATION).as_u64();
    if nanos <= P::PREFLIGHT_BUDGET_NS {
        Ok(())
    } else {
        Err(ShapeViolation {
            shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
            constraint_iri: "https://uor.foundation/reduction/PreflightTimingBound",
            property_iri: "https://uor.foundation/reduction/preflightBudgetNs",
            expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
            min_count: 1,
            max_count: 1,
            kind: ViolationKind::ValueCheck,
        })
    }
}

/// `RuntimeTiming`: runtime timing-check preflight. v0.2.2 Phase B: parameterized
/// over a [`TimingPolicy`] carrying the Nanos budget and canonical `Calibration`.
/// Identical comparison shape as [`preflight_timing`], against the runtime budget.
/// # Errors
/// Returns `ShapeViolation::ValueCheck` when the expected UorTime, converted
/// to Nanos under `P::CALIBRATION`, exceeds `P::RUNTIME_BUDGET_NS`.
#[allow(dead_code)]
pub(crate) const CANONICAL_RUNTIME_BUDGET_NS: u64 = 10000000;
pub fn runtime_timing<P: crate::enforcement::TimingPolicy>(
    expected: crate::enforcement::UorTime,
) -> Result<(), ShapeViolation> {
    let nanos = expected.min_wall_clock(P::CALIBRATION).as_u64();
    if nanos <= P::RUNTIME_BUDGET_NS {
        Ok(())
    } else {
        Err(ShapeViolation {
            shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
            constraint_iri: "https://uor.foundation/reduction/RuntimeTimingBound",
            property_iri: "https://uor.foundation/reduction/runtimeBudgetNs",
            expected_range: "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
            min_count: 1,
            max_count: 1,
            kind: ViolationKind::ValueCheck,
        })
    }
}

/// Reduction stage executor. Takes a classified input and runs the 7 stages
/// in order, producing a `StageOutcome` on success.
#[derive(Debug, Clone, Copy)]
pub struct StageOutcome {
    /// Witt level the compile unit was resolved at.
    pub witt_bits: u16,
    /// Fragment classification decided at `stage_resolve`.
    pub fragment: FragmentKind,
    /// Whether the input is satisfiable (carrier non-empty).
    pub satisfiable: bool,
}

/// Run the 7 reduction stages on a constrained-type input.
///
/// v0.2.2 T6.14: the `unit_address` field was removed. The substrate-
/// computed `ContentAddress` lives on `Grounded` and is derived at the
/// caller from the `H: Hasher` output buffer, not inside this stage
/// executor.
///
/// # Errors
///
/// Returns `PipelineFailure` with the `reduction:PipelineFailureReason` IRI
/// of whichever stage rejected the input.
pub fn run_reduction_stages<T: ConstrainedTypeShape + ?Sized>(
    witt_bits: u16,
) -> Result<StageOutcome, PipelineFailure> {
    // Stage 0 (initialization): content-addressed unit-id is computed by
    // the caller via the consumer-supplied substrate Hasher; nothing to
    // do here.
    // Stage 1 (declare): no-op; declarations already captured by the derive macro.
    // Stage 2 (factorize): no-op; ring factorization is not required for Boolean fragments.
    // Stage 3 (resolve): fragment classification.
    let fragment = fragment_classify(T::CONSTRAINTS);
    // Stage 4 (attest): run the decider associated with the fragment.
    let satisfiable = match fragment {
        FragmentKind::TwoSat => {
            let mut sat = true;
            for c in T::CONSTRAINTS {
                if let ConstraintRef::SatClauses { clauses, num_vars } = c {
                    sat = decide_two_sat(clauses, *num_vars);
                    break;
                }
            }
            sat
        }
        FragmentKind::Horn => {
            let mut sat = true;
            for c in T::CONSTRAINTS {
                if let ConstraintRef::SatClauses { clauses, num_vars } = c {
                    sat = decide_horn_sat(clauses, *num_vars);
                    break;
                }
            }
            sat
        }
        FragmentKind::Residual => {
            // No polynomial decider available. Residual constraint systems are
            // treated as vacuously satisfiable when they carry no SatClauses โ€”
            // pure residue/hamming/etc. inputs always have some value satisfying
            // at least the trivial case. Non-trivial residuals yield
            // ConvergenceStall at stage_convergence below.
            let mut has_sat_clauses = false;
            for c in T::CONSTRAINTS {
                if matches!(c, ConstraintRef::SatClauses { .. }) {
                    has_sat_clauses = true;
                    break;
                }
            }
            !has_sat_clauses
        }
    };
    if matches!(fragment, FragmentKind::Residual) && !satisfiable {
        return Err(PipelineFailure::ConvergenceStall {
            stage_iri: "https://uor.foundation/reduction/stage_convergence",
            angle_milliradians: 0,
        });
    }
    // Stage 5 (extract): ConstrainedTypeShape inputs carry no term AST, so no
    // bindings flow through this path. CompileUnit-bearing callers retrieve the
    // declared bindings directly via `unit.bindings()` (Phase H1); runtime
    // `BindingsTable` materialization is not possible because `BindingsTable::entries`
    // is `&'static [BindingEntry]` by contract (compile-time-constructed catalogs
    // are the sole source of sorted-address binary-search tables).
    // Stage 6 (convergence): verify fixpoint reached. Trivially true for
    // classified fragments.
    Ok(StageOutcome {
        witt_bits,
        fragment,
        satisfiable,
    })
}

/// Run the `TowerCompletenessResolver` pipeline on a `ConstrainedTypeShape`
/// input at the requested Witt level. Emits a `LiftChainCertificate` on
/// success or a generic `ImpossibilityWitness` on failure.
/// # Errors
/// Returns `GenericImpossibilityWitness` when the input is unsatisfiable or
/// when any preflight / reduction stage rejects it.
pub fn run_tower_completeness<T: ConstrainedTypeShape + ?Sized, H: crate::enforcement::Hasher>(
    _input: &T,
    level: WittLevel,
) -> Result<Validated<LiftChainCertificate>, GenericImpossibilityWitness> {
    let witt_bits = level.witt_length() as u16;
    preflight_budget_solvency(witt_bits as u64, witt_bits as u32)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    preflight_feasibility(T::CONSTRAINTS).map_err(|_| GenericImpossibilityWitness::default())?;
    preflight_package_coherence(T::CONSTRAINTS)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    preflight_dispatch_coverage().map_err(|_| GenericImpossibilityWitness::default())?;
    let expected = estimate_preflight_uor_time::<T>(witt_bits);
    preflight_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    runtime_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    let outcome =
        run_reduction_stages::<T>(witt_bits).map_err(|_| GenericImpossibilityWitness::default())?;
    if outcome.satisfiable {
        // v0.2.2 T6.7: thread H: Hasher through fold_unit_digest to compute
        // a real substrate fingerprint. Witt level + budget=0 (no CompileUnit).
        let mut hasher = H::initial();
        hasher = crate::enforcement::fold_unit_digest(
            hasher,
            outcome.witt_bits,
            0,
            T::IRI,
            T::SITE_COUNT,
            T::CONSTRAINTS,
            crate::enforcement::CertificateKind::TowerCompleteness,
        );
        let buffer = hasher.finalize();
        let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
        let cert = LiftChainCertificate::with_level_and_fingerprint_const(outcome.witt_bits, fp);
        Ok(Validated::new(cert))
    } else {
        Err(GenericImpossibilityWitness::default())
    }
}

/// Workstream F (target ontology: `resolver:IncrementalCompletenessResolver`):
/// sealed `SpectralSequencePage` kernel type recording one step of the
/// `Q_n โ†’ Q_{n+1}` spectral-sequence walk. Each page carries its index,
/// the from/to Witt bit widths, and the differential-vanished flag
/// (true โ‡’ page is trivial; false โ‡’ obstruction present with class IRI).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SpectralSequencePage {
    page_index: u32,
    source_bits: u16,
    target_bits: u16,
    differential_vanished: bool,
    obstruction_class_iri: &'static str,
    _sealed: (),
}

impl SpectralSequencePage {
    /// Crate-internal constructor. Minted only by the incremental walker.
    #[inline]
    #[must_use]
    pub(crate) const fn from_parts(
        page_index: u32,
        source_bits: u16,
        target_bits: u16,
        differential_vanished: bool,
        obstruction_class_iri: &'static str,
    ) -> Self {
        Self {
            page_index,
            source_bits,
            target_bits,
            differential_vanished,
            obstruction_class_iri,
            _sealed: (),
        }
    }

    /// Page index (0, 1, 2, โ€ฆ) along the spectral-sequence walk.
    #[inline]
    #[must_use]
    pub const fn page_index(&self) -> u32 {
        self.page_index
    }

    /// Witt bit width at the page's source level.
    #[inline]
    #[must_use]
    pub const fn source_bits(&self) -> u16 {
        self.source_bits
    }

    /// Witt bit width at the page's target level.
    #[inline]
    #[must_use]
    pub const fn target_bits(&self) -> u16 {
        self.target_bits
    }

    /// True iff the page's differential vanishes (no obstruction).
    #[inline]
    #[must_use]
    pub const fn differential_vanished(&self) -> bool {
        self.differential_vanished
    }

    /// Obstruction class IRI when the differential is non-trivial;
    /// empty string when the page is trivial.
    #[inline]
    #[must_use]
    pub const fn obstruction_class_iri(&self) -> &'static str {
        self.obstruction_class_iri
    }
}

/// Run the `IncrementalCompletenessResolver` (spectral-sequence walk)
/// at `target_level`.
///
/// Per `spec/src/namespaces/resolver.rs` (`IncrementalCompletenessResolver`),
/// the walk proceeds without re-running the full ฯˆ-pipeline from
/// scratch. Workstream F (v0.2.2 closure) implements the canonical page
/// structure: iterate each `Q_n โ†’ Q_{n+1}` step from `W8` up to
/// `target_level`, compute each page's differential via
/// `run_reduction_stages` at the higher level, and record the
/// `SpectralSequencePage`. A non-vanishing differential halts with a
/// `GenericImpossibilityWitness` whose obstruction-class IRI is
/// `https://uor.foundation/type/LiftObstruction`. All trivial pages
/// produce a `LiftChainCertificate` stamped with
/// `CertificateKind::IncrementalCompleteness`, discriminable from
/// `run_tower_completeness`'s certificate by the kind byte.
///
/// # Errors
///
/// Returns `GenericImpossibilityWitness` when any page's differential
/// does not vanish, or when preflight checks reject the input.
pub fn run_incremental_completeness<
    T: ConstrainedTypeShape + ?Sized,
    H: crate::enforcement::Hasher,
>(
    _input: &T,
    target_level: WittLevel,
) -> Result<Validated<LiftChainCertificate>, GenericImpossibilityWitness> {
    let target_bits = target_level.witt_length() as u16;
    preflight_budget_solvency(target_bits as u64, target_bits as u32)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    preflight_feasibility(T::CONSTRAINTS).map_err(|_| GenericImpossibilityWitness::default())?;
    preflight_package_coherence(T::CONSTRAINTS)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    preflight_dispatch_coverage().map_err(|_| GenericImpossibilityWitness::default())?;
    let expected = estimate_preflight_uor_time::<T>(target_bits);
    preflight_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    runtime_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|_| GenericImpossibilityWitness::default())?;

    // v0.2.2 Phase H4: Betti-driven spectral-sequence walk. At each page, compute
    // the constraint-nerve Betti tuple (via primitive_simplicial_nerve_betti)
    // and run reduction at both source and target levels. The differential at
    // page r with bidegree (p, q) vanishes iff the bidegree-q projection
    // `betti[q]` is unchanged between source and target AND both reductions
    // are satisfiable at their levels. A mismatch in any bidegree or a
    // non-satisfiable reduction produces a non-trivial differential โ†’
    // `LiftObstruction` halt with `GenericImpossibilityWitness`.
    //
    // Betti-threading also produces content-distinct fingerprints for distinct
    // constraint topologies: two input shapes with different Betti profiles will
    // produce different certs even if both satisfy at every level.
    let betti = crate::enforcement::primitive_simplicial_nerve_betti::<T>()?;
    let mut page_index: u32 = 0;
    let mut from_bits: u16 = 8;
    let mut pages_hasher = H::initial();
    while from_bits < target_bits {
        let to_bits = if from_bits + 8 > target_bits {
            target_bits
        } else {
            from_bits + 8
        };
        // Reduce at source and target; both must be satisfiable for the
        // differential to have a chance of vanishing.
        let outcome_source = run_reduction_stages::<T>(from_bits)
            .map_err(|_| GenericImpossibilityWitness::default())?;
        let outcome_target = run_reduction_stages::<T>(to_bits)
            .map_err(|_| GenericImpossibilityWitness::default())?;
        // bidegree q = page_index + 1 (first non-trivial homological degree per page).
        let q: usize = ((page_index as usize) + 1).min(crate::enforcement::MAX_BETTI_DIMENSION - 1);
        let betti_q = betti[q];
        // Differential vanishes iff source โ‰ก target in Betti bidegree q
        // AND both reduction levels are satisfiable. Betti is shape-invariant
        // (level-independent); the bidegree check is trivially equal, but the
        // satisfiability conjunction captures the level-specific obstruction.
        let differential_vanishes = outcome_source.satisfiable && outcome_target.satisfiable;
        let page = SpectralSequencePage::from_parts(
            page_index,
            from_bits,
            to_bits,
            differential_vanishes,
            if differential_vanishes {
                ""
            } else {
                "https://uor.foundation/type/LiftObstruction"
            },
        );
        if !page.differential_vanished() {
            return Err(GenericImpossibilityWitness::default());
        }
        // Fold the per-page Betti/satisfiability contribution so distinct
        // constraint shapes yield distinct incremental-completeness certs.
        pages_hasher = pages_hasher.fold_bytes(&page_index.to_be_bytes());
        pages_hasher = pages_hasher.fold_bytes(&from_bits.to_be_bytes());
        pages_hasher = pages_hasher.fold_bytes(&to_bits.to_be_bytes());
        pages_hasher = pages_hasher.fold_bytes(&betti_q.to_be_bytes());
        page_index += 1;
        from_bits = to_bits;
    }
    // The accumulated pages_hasher is currently unused in the final fold;
    // the Betti primitive's full tuple is folded below via fold_betti_tuple
    // to keep the cert content-addressed over the whole spectral walk.
    let _ = pages_hasher;

    // Final reduction at the target level โ€” the walk converges when
    // every page's differential has vanished; this guarantees the
    // target-level outcome is satisfiable.
    let outcome = run_reduction_stages::<T>(target_bits)
        .map_err(|_| GenericImpossibilityWitness::default())?;
    if !outcome.satisfiable {
        return Err(GenericImpossibilityWitness::default());
    }
    // v0.2.2 Phase H4: fold the Betti tuple into the cert alongside the
    // canonical unit digest so distinct constraint topologies produce distinct
    // incremental-completeness fingerprints.
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_betti_tuple(hasher, &betti);
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        outcome.witt_bits,
        page_index as u64,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::IncrementalCompleteness,
    );
    let buffer = hasher.finalize();
    let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    let cert = LiftChainCertificate::with_level_and_fingerprint_const(outcome.witt_bits, fp);
    Ok(Validated::new(cert))
}

/// Run the `GroundingAwareResolver` on a `CompileUnit` input at `level`,
/// exploiting `state:GroundedContext` bindings for O(1) resolution per
/// `op:GS_5`.
///
/// v0.2.2 Phase H2: walks `unit.root_term()` enumerating every
/// `Term::Variable { name_index }` and resolves each via linear search
/// over `unit.bindings()`. Unresolved variables (declared in the term AST
/// but absent from the bindings slice) trigger a `GenericImpossibilityWitness`
/// corresponding to `SC5_UNBOUND_VARIABLE`. Resolved bindings are folded
/// into the fingerprint via `primitive_session_binding_signature` so the
/// cert content-addresses the full grounding context, not just the unit
/// shape โ€” distinct binding sets yield distinct fingerprints.
///
/// # Errors
///
/// Returns `GenericImpossibilityWitness` on grounding failure: unresolved
/// variables, or any variable reference whose name index is absent from
/// `unit.bindings()`.
pub fn run_grounding_aware<H: crate::enforcement::Hasher>(
    unit: &CompileUnit,
    level: WittLevel,
) -> Result<Validated<GroundingCertificate>, GenericImpossibilityWitness> {
    let witt_bits = level.witt_length() as u16;
    // v0.2.2 Phase H2: walk root_term enumerating Term::Variable name_indices,
    // linear-search unit.bindings() for each, reject unresolved variables.
    let root_term = unit.root_term();
    let bindings = unit.bindings();
    let mut ti = 0;
    while ti < root_term.len() {
        if let crate::enforcement::Term::Variable { name_index } = root_term[ti] {
            let mut found = false;
            let mut bi = 0;
            while bi < bindings.len() {
                if bindings[bi].name_index == name_index {
                    found = true;
                    break;
                }
                bi += 1;
            }
            if !found {
                // SC_5 violation: variable referenced but no matching binding.
                return Err(GenericImpossibilityWitness::default());
            }
        }
        ti += 1;
    }
    // Fold: witt_bits / thermodynamic_budget / result_type_iri / session_signature / Grounding kind.
    let mut hasher = H::initial();
    hasher = hasher.fold_bytes(&witt_bits.to_be_bytes());
    hasher = hasher.fold_bytes(&unit.thermodynamic_budget().to_be_bytes());
    hasher = hasher.fold_bytes(unit.result_type_iri().as_bytes());
    hasher = hasher.fold_byte(0);
    let (binding_count, fold_addr) =
        crate::enforcement::primitive_session_binding_signature(bindings);
    hasher = crate::enforcement::fold_session_signature(hasher, binding_count, fold_addr);
    hasher = hasher.fold_byte(crate::enforcement::certificate_kind_discriminant(
        crate::enforcement::CertificateKind::Grounding,
    ));
    let buffer = hasher.finalize();
    let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    let cert = GroundingCertificate::with_level_and_fingerprint_const(witt_bits, fp);
    Ok(Validated::new(cert))
}

/// Run the `InhabitanceResolver` dispatch on a `ConstrainedTypeShape`
/// input at `level`.
///
/// Routes to the 2-SAT / Horn-SAT / residual decider via
/// `predicate:InhabitanceDispatchTable` rules (ordered by priority).
///
/// # Errors
///
/// Returns `InhabitanceImpossibilityWitness` when the input is unsatisfiable.
pub fn run_inhabitance<T: ConstrainedTypeShape + ?Sized, H: crate::enforcement::Hasher>(
    _input: &T,
    level: WittLevel,
) -> Result<Validated<InhabitanceCertificate>, InhabitanceImpossibilityWitness> {
    let witt_bits = level.witt_length() as u16;
    preflight_budget_solvency(witt_bits as u64, witt_bits as u32)
        .map_err(|_| InhabitanceImpossibilityWitness::default())?;
    preflight_feasibility(T::CONSTRAINTS)
        .map_err(|_| InhabitanceImpossibilityWitness::default())?;
    preflight_package_coherence(T::CONSTRAINTS)
        .map_err(|_| InhabitanceImpossibilityWitness::default())?;
    preflight_dispatch_coverage().map_err(|_| InhabitanceImpossibilityWitness::default())?;
    let expected = estimate_preflight_uor_time::<T>(witt_bits);
    preflight_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|_| InhabitanceImpossibilityWitness::default())?;
    runtime_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|_| InhabitanceImpossibilityWitness::default())?;
    let outcome = run_reduction_stages::<T>(witt_bits)
        .map_err(|_| InhabitanceImpossibilityWitness::default())?;
    if outcome.satisfiable {
        // v0.2.2 T6.7: thread H: Hasher through fold_unit_digest.
        let mut hasher = H::initial();
        hasher = crate::enforcement::fold_unit_digest(
            hasher,
            outcome.witt_bits,
            0,
            T::IRI,
            T::SITE_COUNT,
            T::CONSTRAINTS,
            crate::enforcement::CertificateKind::Inhabitance,
        );
        let buffer = hasher.finalize();
        let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
        let cert = InhabitanceCertificate::with_level_and_fingerprint_const(outcome.witt_bits, fp);
        Ok(Validated::new(cert))
    } else {
        Err(InhabitanceImpossibilityWitness::default())
    }
}

/// v0.2.2 W14: the single typed pipeline entry point producing `Grounded<T>`
/// from a validated `CompileUnit`. The caller declares the expected shape `T`;
/// the pipeline verifies the unit's root term produces a value of that shape
/// and returns `Grounded<T>` on success or a typed `PipelineFailure`.
/// Replaces the v0.2.1 `run_pipeline(&datum, level: u8)` form whose bare
/// integer level argument was never type-safe.
/// # Errors
/// Returns `PipelineFailure` on preflight, reduction, or shape-mismatch failure.
/// # Example
/// ```no_run
/// use uor_foundation::enforcement::{
///     CompileUnitBuilder, ConstrainedTypeInput, Term,
/// };
/// use uor_foundation::pipeline::run;
/// use uor_foundation::{VerificationDomain, WittLevel};
/// # struct Fnv1aHasher16; // downstream substrate; see foundation/examples/custom_hasher_substrate.rs
/// # impl uor_foundation::enforcement::Hasher for Fnv1aHasher16 {
/// #     const OUTPUT_BYTES: usize = 16;
/// #     fn initial() -> Self { Self }
/// #     fn fold_byte(self, _: u8) -> Self { self }
/// #     fn finalize(self) -> [u8; 32] { [0; 32] }
/// # }
/// static TERMS: &[Term] = &[Term::Literal { value: 1, level: WittLevel::W8 }];
/// static DOMAINS: &[VerificationDomain] = &[VerificationDomain::Enumerative];
/// let unit = CompileUnitBuilder::new()
///     .root_term(TERMS)
///     .witt_level_ceiling(WittLevel::W32)
///     .thermodynamic_budget(1024)
///     .target_domains(DOMAINS)
///     .result_type::<ConstrainedTypeInput>()
///     .validate()
///     .expect("unit well-formed");
/// let grounded = run::<ConstrainedTypeInput, _, Fnv1aHasher16>(unit)
///     .expect("pipeline admits");
/// # let _ = grounded;
/// ```
pub fn run<T, P, H>(unit: Validated<CompileUnit, P>) -> Result<Grounded<T>, PipelineFailure>
where
    T: ConstrainedTypeShape + crate::enforcement::GroundedShape,
    P: crate::enforcement::ValidationPhase,
    H: crate::enforcement::Hasher,
{
    let witt_bits = unit.inner().witt_level().witt_length() as u16;
    let budget = unit.inner().thermodynamic_budget();
    // v0.2.2 T6.11: ShapeMismatch detection. The unit declares its
    // result_type_iri at validation time; the caller's `T::IRI` must match.
    let unit_iri = unit.inner().result_type_iri();
    if !crate::enforcement::str_eq(unit_iri, T::IRI) {
        return Err(PipelineFailure::ShapeMismatch {
            expected: T::IRI,
            got: unit_iri,
        });
    }
    // Preflights. Each maps its ShapeViolation into a PipelineFailure.
    preflight_budget_solvency(witt_bits as u64, witt_bits as u32)
        .map_err(|report| PipelineFailure::ShapeViolation { report })?;
    preflight_feasibility(T::CONSTRAINTS)
        .map_err(|report| PipelineFailure::ShapeViolation { report })?;
    preflight_package_coherence(T::CONSTRAINTS)
        .map_err(|report| PipelineFailure::ShapeViolation { report })?;
    preflight_dispatch_coverage().map_err(|report| PipelineFailure::ShapeViolation { report })?;
    let expected = estimate_preflight_uor_time::<T>(witt_bits);
    preflight_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|report| PipelineFailure::ShapeViolation { report })?;
    runtime_timing::<crate::enforcement::CanonicalTimingPolicy>(expected)
        .map_err(|report| PipelineFailure::ShapeViolation { report })?;
    // v0.2.2 T5 C1: actually call run_reduction_stages and propagate its
    // failure. The previous v0.2.2 path skipped this call entirely,
    // returning a degenerate Grounded with ContentAddress::zero(). The
    // typed `run` entry point now mirrors `run_pipeline`'s reduction-stage
    // sequence.
    let outcome = run_reduction_stages::<T>(witt_bits)?;
    if !outcome.satisfiable {
        return Err(PipelineFailure::ContradictionDetected {
            at_step: 0,
            trace_iri: "https://uor.foundation/trace/InhabitanceSearchTrace",
        });
    }
    // v0.2.2 T5 C3.f: thread the consumer-supplied substrate Hasher through
    // the canonical CompileUnit byte layout to compute the parametric
    // content fingerprint.
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        witt_bits,
        budget,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::Grounding,
    );
    let buffer = hasher.finalize();
    let content_fingerprint =
        crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    let unit_address = crate::enforcement::unit_address_from_buffer(&buffer);
    let grounding = Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
        witt_bits,
        content_fingerprint,
    ));
    let bindings = empty_bindings_table();
    Ok(Grounded::<T>::new_internal(
        grounding,
        bindings,
        outcome.witt_bits,
        unit_address,
        content_fingerprint,
    ))
}

/// Construct an empty `BindingsTable`.
/// v0.2.2 T6.9: the empty slice is vacuously sorted, so direct struct
/// construction is sound. Public callers with non-empty entries go
/// through `BindingsTable::try_new` (validating).
/// # Driver contract
/// Every pipeline driver (`run`, `run_const`, `run_parallel`, `run_stream`,
/// `run_interactive`, `run_inhabitance`) mints `Grounded<T>` with this
/// empty table today: runtime-dynamic binding materialization in
/// `Grounded<T>` requires widening `BindingsTable.entries: &'static [...]`
/// to a non-`'static` carrier (a separate architectural change).
/// Downstream that needs a compile-time binding catalog uses the pattern
/// shown in `foundation/examples/static_bindings_catalog.rs`:
/// `Binding::to_binding_entry()` (const-fn) + `BindingsTable::try_new(&[...])`.
#[must_use]
pub const fn empty_bindings_table() -> BindingsTable {
    BindingsTable { entries: &[] }
}

// Suppress warning: BindingEntry is re-exported via use but not used in
// this module directly; it's part of the public pipeline surface.
#[allow(dead_code)]
const _BINDING_ENTRY_REF: Option<BindingEntry> = None;
// Same for CompletenessCertificate โ€” the pipeline does not mint this subclass
// directly; Phase D resolvers emit the canonical `GroundingCertificate` carrier
// and cert-subclass lifts happen in substrate-specific consumers.
#[allow(dead_code)]
const _COMPLETENESS_CERT_REF: Option<CompletenessCertificate> = None;

/// v0.2.2 Phase F / T2.7: parallel-declaration compile unit. Carries the
/// declared site partition cardinality plus (Phase A widening) the raw
/// partition slice and disjointness-witness IRI from the builder โ€”
/// previously these were discarded at validate-time by a shadowed
/// enforcement-local `ParallelDeclaration` that nothing consumed.
/// v0.2.2 T6.11: also carries `result_type_iri` for ShapeMismatch detection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ParallelDeclaration<'a> {
    payload: u64,
    result_type_iri: &'static str,
    /// v0.2.2 Phase A: raw site-partition slice retained from the builder.
    /// Empty slice for declarations built via the site-count-only constructor.
    site_partition: &'a [u32],
    /// v0.2.2 Phase A: disjointness-witness IRI retained from the builder.
    /// Empty string for declarations built via the site-count-only constructor.
    disjointness_witness: &'a str,
    _sealed: (),
}

impl<'a> ParallelDeclaration<'a> {
    /// v0.2.2 Phase H3: construct a parallel declaration carrying the full
    /// partition slice and disjointness-witness IRI from the builder.
    /// This is the sole public constructor; the v0.2.2 Phase A site-count-only
    /// `new::<T>(site_count)` form was deleted in Phase H3 under the "no
    /// compatibility" discipline โ€” every caller supplies a real partition.
    #[inline]
    #[must_use]
    pub const fn new_with_partition<T: ConstrainedTypeShape>(
        site_partition: &'a [u32],
        disjointness_witness: &'a str,
    ) -> Self {
        Self {
            payload: site_partition.len() as u64,
            result_type_iri: T::IRI,
            site_partition,
            disjointness_witness,
            _sealed: (),
        }
    }

    /// Returns the declared site partition cardinality.
    #[inline]
    #[must_use]
    pub const fn site_count(&self) -> u64 {
        self.payload
    }

    /// v0.2.2 T6.11: returns the result-type IRI.
    #[inline]
    #[must_use]
    pub const fn result_type_iri(&self) -> &'static str {
        self.result_type_iri
    }

    /// v0.2.2 Phase A: returns the raw site-partition slice.
    #[inline]
    #[must_use]
    pub const fn site_partition(&self) -> &'a [u32] {
        self.site_partition
    }

    /// v0.2.2 Phase A: returns the disjointness-witness IRI.
    #[inline]
    #[must_use]
    pub const fn disjointness_witness(&self) -> &'a str {
        self.disjointness_witness
    }
}

/// v0.2.2 Phase F / T2.7: stream-declaration compile unit. Carries a
/// payload field encoding the productivity-witness countdown.
/// v0.2.2 T6.11: also carries `result_type_iri` for ShapeMismatch detection.
/// v0.2.2 Phase A: also retains the builder's seed/step term slices and
/// the productivity-witness IRI so stream resolvers can walk declared
/// structure. Distinct from the enforcement-local `StreamDeclaration`
/// which records only the `StreamShape` validation surface.
/// Note: `Hash` is not derived because `Term` does not implement `Hash`;
/// downstream code that needs deterministic hashing should fold through
/// the substrate `Hasher` via the pipeline's `fold_stream_digest`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StreamDeclaration<'a> {
    payload: u64,
    result_type_iri: &'static str,
    /// v0.2.2 Phase A: stream seed term slice retained from the builder.
    seed: &'a [Term],
    /// v0.2.2 Phase A: stream step term slice retained from the builder.
    step: &'a [Term],
    /// v0.2.2 Phase A: productivity-witness IRI retained from the builder.
    productivity_witness: &'a str,
    _sealed: (),
}

impl<'a> StreamDeclaration<'a> {
    /// v0.2.2 T6.11: construct a stream declaration with the given productivity
    /// bound and result type. Phase A: leaves seed/step/witness empty; use
    /// `new_full` to retain the full structure.
    #[inline]
    #[must_use]
    pub const fn new<T: ConstrainedTypeShape>(
        productivity_bound: u64,
    ) -> StreamDeclaration<'static> {
        StreamDeclaration {
            payload: productivity_bound,
            result_type_iri: T::IRI,
            seed: &[],
            step: &[],
            productivity_witness: "",
            _sealed: (),
        }
    }

    /// v0.2.2 Phase A: construct a stream declaration carrying the full
    /// seed/step/witness structure from the builder.
    #[inline]
    #[must_use]
    pub const fn new_full<T: ConstrainedTypeShape>(
        productivity_bound: u64,
        seed: &'a [Term],
        step: &'a [Term],
        productivity_witness: &'a str,
    ) -> Self {
        Self {
            payload: productivity_bound,
            result_type_iri: T::IRI,
            seed,
            step,
            productivity_witness,
            _sealed: (),
        }
    }

    /// Returns the declared productivity bound.
    #[inline]
    #[must_use]
    pub const fn productivity_bound(&self) -> u64 {
        self.payload
    }

    /// v0.2.2 T6.11: returns the result-type IRI.
    #[inline]
    #[must_use]
    pub const fn result_type_iri(&self) -> &'static str {
        self.result_type_iri
    }

    /// v0.2.2 Phase A: returns the seed term slice.
    #[inline]
    #[must_use]
    pub const fn seed(&self) -> &'a [Term] {
        self.seed
    }

    /// v0.2.2 Phase A: returns the step term slice.
    #[inline]
    #[must_use]
    pub const fn step(&self) -> &'a [Term] {
        self.step
    }

    /// v0.2.2 Phase A: returns the productivity-witness IRI.
    #[inline]
    #[must_use]
    pub const fn productivity_witness(&self) -> &'a str {
        self.productivity_witness
    }
}

/// v0.2.2 Phase F / T2.7: interaction-declaration compile unit. Carries a
/// payload field encoding the convergence-predicate seed.
/// v0.2.2 T6.11: also carries `result_type_iri` for ShapeMismatch detection.
/// v0.2.2 Phase A: lifetime-parameterized for consistency with the other
/// widened runtime carriers. The interaction builder stores scalar fields
/// only, so there is no additional borrowed structure to retain; the `'a`
/// is vestigial but keeps the carrier signature uniform with
/// `ParallelDeclaration<'a>` and `StreamDeclaration<'a>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InteractionDeclaration<'a> {
    payload: u64,
    result_type_iri: &'static str,
    _sealed: (),
    _lifetime: core::marker::PhantomData<&'a ()>,
}

impl<'a> InteractionDeclaration<'a> {
    /// v0.2.2 T6.11: construct an interaction declaration with the given
    /// convergence-predicate seed and result type.
    #[inline]
    #[must_use]
    pub const fn new<T: ConstrainedTypeShape>(
        convergence_seed: u64,
    ) -> InteractionDeclaration<'static> {
        InteractionDeclaration {
            payload: convergence_seed,
            result_type_iri: T::IRI,
            _sealed: (),
            _lifetime: core::marker::PhantomData,
        }
    }

    /// Returns the declared convergence seed.
    #[inline]
    #[must_use]
    pub const fn convergence_seed(&self) -> u64 {
        self.payload
    }

    /// v0.2.2 T6.11: returns the result-type IRI.
    #[inline]
    #[must_use]
    pub const fn result_type_iri(&self) -> &'static str {
        self.result_type_iri
    }
}

/// v0.2.2 Phase F: fixed-size inline payload buffer carried by `PeerInput`.
/// Sized for the largest `Datum<L>` the foundation supports at this release
/// (up to 32 u64 limbs = 2048 bits); smaller levels use the leading bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PeerPayload {
    words: [u64; 32],
    bit_width: u16,
    _sealed: (),
}

impl PeerPayload {
    /// Construct a zeroed payload of the given bit width.
    #[inline]
    #[must_use]
    pub const fn zero(bit_width: u16) -> Self {
        Self {
            words: [0u64; 32],
            bit_width,
            _sealed: (),
        }
    }

    /// Access the underlying limbs.
    #[inline]
    #[must_use]
    pub const fn words(&self) -> &[u64; 32] {
        &self.words
    }

    /// Bit width of the payload's logical Datum.
    #[inline]
    #[must_use]
    pub const fn bit_width(&self) -> u16 {
        self.bit_width
    }
}

/// v0.2.2 Phase F: a peer-supplied input to an interaction driver step.
/// Fixed-size โ€” holds a `PeerPayload` inline plus the peer's content
/// address. No heap, no dynamic dispatch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PeerInput {
    peer_id: u128,
    payload: PeerPayload,
    _sealed: (),
}

impl PeerInput {
    /// Construct a new peer input with the given peer id and payload.
    #[inline]
    #[must_use]
    pub const fn new(peer_id: u128, payload: PeerPayload) -> Self {
        Self {
            peer_id,
            payload,
            _sealed: (),
        }
    }

    /// Access the peer id.
    #[inline]
    #[must_use]
    pub const fn peer_id(&self) -> u128 {
        self.peer_id
    }

    /// Access the payload.
    #[inline]
    #[must_use]
    pub const fn payload(&self) -> &PeerPayload {
        &self.payload
    }
}

/// v0.2.2 Phase F: outcome of a single `InteractionDriver::step` call.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum StepResult<T: crate::enforcement::GroundedShape> {
    /// The step was absorbed; the driver is ready for another peer input.
    Continue,
    /// The step produced an intermediate grounded output.
    Output(Grounded<T>),
    /// The convergence predicate is satisfied; interaction is complete.
    Converged(Grounded<T>),
    /// v0.2.2 Phase T.1: the commutator norm failed to decrease for
    /// `INTERACTION_DIVERGENCE_BUDGET` consecutive steps โ€” the interaction is
    /// non-convergent and the driver is no longer advanceable.
    Diverged,
    /// The step failed; the driver is no longer advanceable.
    Failure(PipelineFailure),
}

/// v0.2.2 Phase F: sealed commutator-algebra state carried by an
/// interaction driver across peer steps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CommutatorState<L> {
    accumulator: [u64; 4],
    _level: core::marker::PhantomData<L>,
    _sealed: (),
}

impl<L> CommutatorState<L> {
    /// Construct a zero commutator state.
    #[inline]
    #[must_use]
    pub const fn zero() -> Self {
        Self {
            accumulator: [0u64; 4],
            _level: core::marker::PhantomData,
            _sealed: (),
        }
    }

    /// Access the commutator accumulator words.
    #[inline]
    #[must_use]
    pub const fn accumulator(&self) -> &[u64; 4] {
        &self.accumulator
    }
}

/// v0.2.2 Phase F / T2.7: sealed iterator driver returned by `run_stream`.
/// Carries the productivity countdown initialized from the unit's
/// `StreamDeclaration::productivity_bound()`, plus a unit-derived address
/// seed for generating distinct `Grounded` outputs per step. Each call to
/// `next()` decrements the countdown and yields a `Grounded` whose
/// `unit_address` differs from the previous step's.
#[derive(Debug, Clone)]
pub struct StreamDriver<
    T: crate::enforcement::GroundedShape,
    P: crate::enforcement::ValidationPhase,
    H: crate::enforcement::Hasher,
> {
    rewrite_steps: u64,
    landauer_nats: u64,
    productivity_countdown: u64,
    seed: u64,
    result_type_iri: &'static str,
    terminated: bool,
    _shape: core::marker::PhantomData<T>,
    _phase: core::marker::PhantomData<P>,
    _hasher: core::marker::PhantomData<H>,
    _sealed: (),
}

impl<
        T: crate::enforcement::GroundedShape,
        P: crate::enforcement::ValidationPhase,
        H: crate::enforcement::Hasher,
    > StreamDriver<T, P, H>
{
    /// Crate-internal constructor. Callable only from `pipeline::run_stream`.
    #[inline]
    #[must_use]
    #[allow(dead_code)]
    pub(crate) const fn new_internal(
        productivity_bound: u64,
        seed: u64,
        result_type_iri: &'static str,
    ) -> Self {
        Self {
            rewrite_steps: 0,
            landauer_nats: 0,
            productivity_countdown: productivity_bound,
            seed,
            result_type_iri,
            terminated: false,
            _shape: core::marker::PhantomData,
            _phase: core::marker::PhantomData,
            _hasher: core::marker::PhantomData,
            _sealed: (),
        }
    }

    /// Total rewrite steps taken so far.
    #[inline]
    #[must_use]
    pub const fn rewrite_steps(&self) -> u64 {
        self.rewrite_steps
    }

    /// Total Landauer cost accumulated so far.
    #[inline]
    #[must_use]
    pub const fn landauer_nats(&self) -> u64 {
        self.landauer_nats
    }

    /// v0.2.2 T5.10: returns `true` once the driver has stopped producing
    /// rewrite steps. A terminated driver is observationally equivalent to
    /// one whose next `next()` call returns `None`. Use this when the driver
    /// is held inside a larger state machine that needs to decide whether
    /// to advance without consuming a step.
    /// Parallel to `InteractionDriver::is_converged()`.
    #[inline]
    #[must_use]
    pub const fn is_terminated(&self) -> bool {
        self.terminated
    }
}

impl<
        T: crate::enforcement::GroundedShape + ConstrainedTypeShape,
        P: crate::enforcement::ValidationPhase,
        H: crate::enforcement::Hasher,
    > Iterator for StreamDriver<T, P, H>
{
    type Item = Result<Grounded<T>, PipelineFailure>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.terminated || self.productivity_countdown == 0 {
            self.terminated = true;
            return None;
        }
        // v0.2.2 T6.11: ShapeMismatch detection โ€” first step only
        // (subsequent steps inherit the same result_type_iri).
        if self.rewrite_steps == 0 && !crate::enforcement::str_eq(self.result_type_iri, T::IRI) {
            self.terminated = true;
            return Some(Err(PipelineFailure::ShapeMismatch {
                expected: T::IRI,
                got: self.result_type_iri,
            }));
        }
        self.productivity_countdown -= 1;
        self.rewrite_steps += 1;
        self.landauer_nats += 1;
        // v0.2.2 T6.1: thread H: Hasher through fold_stream_step_digest
        // to compute a real per-step substrate fingerprint.
        let mut hasher = H::initial();
        hasher = crate::enforcement::fold_stream_step_digest(
            hasher,
            self.productivity_countdown,
            self.rewrite_steps,
            self.seed,
            self.result_type_iri,
            crate::enforcement::CertificateKind::Grounding,
        );
        let buffer = hasher.finalize();
        let content_fingerprint =
            crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
        let unit_address = crate::enforcement::unit_address_from_buffer(&buffer);
        let grounding = Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
            32,
            content_fingerprint,
        ));
        let bindings = empty_bindings_table();
        Some(Ok(Grounded::<T>::new_internal(
            grounding,
            bindings,
            32, // default witt level for stream output
            unit_address,
            content_fingerprint,
        )))
    }
}

/// v0.2.2 Phase F / T2.7: sealed state-machine driver returned by
/// `run_interactive`. Exposes `step(PeerInput)`, `is_converged()`, and
/// `finalize()`. The driver folds each peer input into its
/// `commutator_acc` accumulator via XOR; convergence is signalled when
/// a peer input arrives with `peer_id == 0` (the closing handshake).
#[derive(Debug, Clone)]
pub struct InteractionDriver<
    T: crate::enforcement::GroundedShape,
    P: crate::enforcement::ValidationPhase,
    H: crate::enforcement::Hasher,
> {
    commutator_acc: [u64; 4],
    peer_step_count: u64,
    converged: bool,
    /// Convergence seed read from the source InteractionDeclaration.
    /// Available via `seed()` for downstream inspection.
    seed: u64,
    /// v0.2.2 Phase T.1: previous step's commutator norm (Euclidean-squared
    /// over the 4 u64 limbs, saturating). Used to detect divergence.
    prev_commutator_norm: u64,
    /// v0.2.2 Phase T.1: count of consecutive non-decreasing norm steps.
    /// Reset to 0 on any decrease; divergence triggers at `DIVERGENCE_BUDGET`.
    consecutive_non_decreasing: u32,
    /// v0.2.2 T6.11: result-type IRI from the source InteractionDeclaration.
    result_type_iri: &'static str,
    _shape: core::marker::PhantomData<T>,
    _phase: core::marker::PhantomData<P>,
    _hasher: core::marker::PhantomData<H>,
    _sealed: (),
}

/// v0.2.2 Phase T.1: divergence budget โ€” max consecutive non-decreasing commutator-norm
/// steps before the interaction driver fails. Foundation-canonical; override at the
/// `InteractionDeclaration` level not supported in this release.
pub const INTERACTION_DIVERGENCE_BUDGET: u32 = 16;

impl<
        T: crate::enforcement::GroundedShape,
        P: crate::enforcement::ValidationPhase,
        H: crate::enforcement::Hasher,
    > InteractionDriver<T, P, H>
{
    /// Crate-internal constructor. Callable only from `pipeline::run_interactive`.
    #[inline]
    #[must_use]
    #[allow(dead_code)]
    pub(crate) const fn new_internal(seed: u64, result_type_iri: &'static str) -> Self {
        // Initial commutator seeded from the unit's convergence seed.
        Self {
            commutator_acc: [seed, 0, 0, 0],
            peer_step_count: 0,
            converged: false,
            seed,
            // Initial norm = seedยฒ (saturating) so the first step can only
            // decrease the norm via peer input (which is the convergence path).
            prev_commutator_norm: seed.saturating_mul(seed),
            consecutive_non_decreasing: 0,
            result_type_iri,
            _shape: core::marker::PhantomData,
            _phase: core::marker::PhantomData,
            _hasher: core::marker::PhantomData,
            _sealed: (),
        }
    }

    /// v0.2.2 Phase T.1: convergence threshold derived from the seed. Termination
    /// triggers when the commutator norm falls below this value. Foundation-canonical:
    /// `seed.rotate_right(32) ^ 0xDEADBEEF_CAFEBABE`.
    #[inline]
    #[must_use]
    pub const fn convergence_threshold(&self) -> u64 {
        self.seed.rotate_right(32) ^ 0xDEAD_BEEF_CAFE_BABE
    }

    /// Advance the driver by folding in a single peer input (v0.2.2 Phase T.1).
    /// Each step XOR-folds the peer payload's first 4 limbs into the
    /// commutator accumulator, then recomputes the Euclidean-squared
    /// norm over the 4 limbs (saturating `u64`). Termination rules:
    /// * **Converged** if the norm falls below `convergence_threshold()`,
    ///   OR if `peer_id == 0` (explicit closing handshake).
    /// * **Diverged** (via `PipelineFailure::ConvergenceStall`) if the norm is
    ///   non-decreasing for `INTERACTION_DIVERGENCE_BUDGET` consecutive steps.
    /// * **Continue** otherwise.
    #[must_use]
    pub fn step(&mut self, input: PeerInput) -> StepResult<T>
    where
        T: ConstrainedTypeShape,
    {
        self.peer_step_count += 1;
        // Fold the first 4 payload words into the accumulator.
        let words = input.payload().words();
        let mut i = 0usize;
        while i < 4 {
            self.commutator_acc[i] ^= words[i];
            i += 1;
        }
        // v0.2.2 Phase T.1: compute the Euclidean-squared norm over the 4 limbs.
        let mut norm: u64 = 0;
        let mut j = 0usize;
        while j < 4 {
            let limb = self.commutator_acc[j];
            norm = norm.saturating_add(limb.saturating_mul(limb));
            j += 1;
        }
        let threshold = self.convergence_threshold();
        // v0.2.2 Phase T.1: convergence on norm-below-threshold OR explicit
        // handshake (peer_id == 0). Divergence on consecutive non-decreasing norm.
        let norm_converged = norm < threshold;
        let handshake_close = input.peer_id() == 0;
        if norm_converged || handshake_close {
            self.converged = true;
            // v0.2.2 T6.1: thread H: Hasher through fold_interaction_step_digest
            // to compute a real convergence-time substrate fingerprint.
            let mut hasher = H::initial();
            hasher = crate::enforcement::fold_interaction_step_digest(
                hasher,
                &self.commutator_acc,
                self.peer_step_count,
                self.seed,
                self.result_type_iri,
                crate::enforcement::CertificateKind::Grounding,
            );
            let buffer = hasher.finalize();
            let content_fingerprint =
                crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
            let unit_address = crate::enforcement::unit_address_from_buffer(&buffer);
            let grounding = Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
                32,
                content_fingerprint,
            ));
            let bindings = empty_bindings_table();
            return StepResult::Converged(Grounded::<T>::new_internal(
                grounding,
                bindings,
                32,
                unit_address,
                content_fingerprint,
            ));
        }
        // v0.2.2 Phase T.1: divergence detection โ€” count consecutive
        // non-decreasing norm steps. Reset on any decrease.
        if norm >= self.prev_commutator_norm {
            self.consecutive_non_decreasing = self.consecutive_non_decreasing.saturating_add(1);
        } else {
            self.consecutive_non_decreasing = 0;
        }
        self.prev_commutator_norm = norm;
        if self.consecutive_non_decreasing >= INTERACTION_DIVERGENCE_BUDGET {
            return StepResult::Diverged;
        }
        StepResult::Continue
    }

    /// Whether the driver has reached the convergence predicate.
    #[inline]
    #[must_use]
    pub const fn is_converged(&self) -> bool {
        self.converged
    }

    /// Number of peer steps applied so far.
    #[inline]
    #[must_use]
    pub const fn peer_step_count(&self) -> u64 {
        self.peer_step_count
    }

    /// Convergence seed inherited from the source InteractionDeclaration.
    #[inline]
    #[must_use]
    pub const fn seed(&self) -> u64 {
        self.seed
    }

    /// Finalize the interaction, producing a grounded result.
    /// Returns a `Grounded<T>` whose `unit_address` is a hash of the
    /// accumulated commutator state, so two interaction drivers that
    /// processed different peer inputs return distinct grounded values.
    /// # Errors
    /// Returns a `PipelineFailure::ShapeViolation` if the driver has
    /// not converged, or `PipelineFailure::ShapeMismatch` if the source
    /// declaration's result_type_iri does not match `T::IRI`.
    pub fn finalize(self) -> Result<Grounded<T>, PipelineFailure>
    where
        T: ConstrainedTypeShape,
    {
        // v0.2.2 T6.11: ShapeMismatch detection.
        if !crate::enforcement::str_eq(self.result_type_iri, T::IRI) {
            return Err(PipelineFailure::ShapeMismatch {
                expected: T::IRI,
                got: self.result_type_iri,
            });
        }
        if !self.converged {
            return Err(PipelineFailure::ShapeViolation {
                report: ShapeViolation {
                    shape_iri: "https://uor.foundation/conformance/InteractionShape",
                    constraint_iri:
                        "https://uor.foundation/conformance/InteractionShape#convergence",
                    property_iri: "https://uor.foundation/conformance/convergencePredicate",
                    expected_range: "http://www.w3.org/2002/07/owl#Thing",
                    min_count: 1,
                    max_count: 1,
                    kind: ViolationKind::Missing,
                },
            });
        }
        // v0.2.2 T6.1: thread H: Hasher through fold_interaction_step_digest.
        let mut hasher = H::initial();
        hasher = crate::enforcement::fold_interaction_step_digest(
            hasher,
            &self.commutator_acc,
            self.peer_step_count,
            self.seed,
            self.result_type_iri,
            crate::enforcement::CertificateKind::Grounding,
        );
        let buffer = hasher.finalize();
        let content_fingerprint =
            crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
        let unit_address = crate::enforcement::unit_address_from_buffer(&buffer);
        let grounding = Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
            32,
            content_fingerprint,
        ));
        let bindings = empty_bindings_table();
        Ok(Grounded::<T>::new_internal(
            grounding,
            bindings,
            32,
            unit_address,
            content_fingerprint,
        ))
    }
}

/// v0.2.2 Phase F / T2.7: parallel driver entry point.
/// Consumes a `Validated<ParallelDeclaration, P>` and produces a unified
/// `Grounded<T>` whose `unit_address` is derived from the declaration's
/// site count via FNV-1a. Two units with different site counts produce
/// `Grounded` values with different addresses.
/// # Errors
/// Returns `PipelineFailure::ShapeMismatch` when the declaration's
/// `result_type_iri` does not match `T::IRI` โ€” the caller asked for
/// `Grounded<T>` but the declaration was built over a different shape.
/// Returns `PipelineFailure::ContradictionDetected` when the declared
/// partition cardinality is zero โ€” a parallel composition with no
/// sites is inadmissible by construction.
/// Success: `run_parallel` folds the declaration's site count through
/// `fold_parallel_digest` to produce a content fingerprint; distinct
/// partitions produce distinct fingerprints by construction.
/// # Example
/// ```no_run
/// use uor_foundation::enforcement::{ConstrainedTypeInput, Validated};
/// use uor_foundation::pipeline::{run_parallel, ParallelDeclaration};
/// # use uor_foundation::enforcement::Hasher;
/// # struct Fnv1aHasher16;
/// # impl Hasher for Fnv1aHasher16 {
/// #     const OUTPUT_BYTES: usize = 16;
/// #     fn initial() -> Self { Self }
/// #     fn fold_byte(self, _: u8) -> Self { self }
/// #     fn finalize(self) -> [u8; 32] { [0; 32] }
/// # }
/// # fn wrap<T>(t: T) -> Validated<T> { unimplemented!() /* see uor_foundation_test_helpers */ }
/// // 3-component partition over 9 sites.
/// static PARTITION: &[u32] = &[0, 0, 0, 1, 1, 1, 2, 2, 2];
/// let decl: Validated<ParallelDeclaration> = wrap(
///     ParallelDeclaration::new_with_partition::<ConstrainedTypeInput>(
///         PARTITION,
///         "https://uor.foundation/parallel/ParallelDisjointnessWitness",
///     ),
/// );
/// let grounded = run_parallel::<ConstrainedTypeInput, _, Fnv1aHasher16>(decl)
///     .expect("partition admits");
/// # let _ = grounded;
/// ```
pub fn run_parallel<T, P, H>(
    unit: Validated<ParallelDeclaration, P>,
) -> Result<Grounded<T>, PipelineFailure>
where
    T: ConstrainedTypeShape + crate::enforcement::GroundedShape,
    P: crate::enforcement::ValidationPhase,
    H: crate::enforcement::Hasher,
{
    let decl = unit.inner();
    let site_count = decl.site_count();
    let partition = decl.site_partition();
    let witness_iri = decl.disjointness_witness();
    // Runtime invariants declared in the ParallelDeclaration rustdoc:
    // (1) result_type_iri must match T::IRI (target ยง5 + T6.11);
    // (2) site_count > 0 (zero-site parallel composition is vacuous);
    // (3) v0.2.2 Phase H3: partition length must equal site_count;
    // (4) v0.2.2 Phase H3: partition must be non-empty (only constructor is
    //     `new_with_partition`, which takes a real partition slice).
    if !crate::enforcement::str_eq(decl.result_type_iri(), T::IRI) {
        return Err(PipelineFailure::ShapeMismatch {
            expected: T::IRI,
            got: decl.result_type_iri(),
        });
    }
    if site_count == 0 || partition.is_empty() {
        return Err(PipelineFailure::ContradictionDetected {
            at_step: 0,
            trace_iri: "https://uor.foundation/parallel/ParallelProduct",
        });
    }
    if partition.len() as u64 != site_count {
        return Err(PipelineFailure::ShapeMismatch {
            expected: T::IRI,
            got: decl.result_type_iri(),
        });
    }
    // v0.2.2 Phase H3: walk partition, count sites per component, fold
    // per-component into the content fingerprint. Enumerates unique component
    // IDs into a fixed stack buffer sized by WITT_MAX_BITS.
    let mut hasher = H::initial();
    // component_ids: seen component IDs in first-appearance order.
    // component_counts: parallel site-count per component.
    let mut component_ids = [0u32; WITT_MAX_BITS as usize];
    let mut component_counts = [0u32; WITT_MAX_BITS as usize];
    let mut n_components: usize = 0;
    let mut si = 0;
    while si < partition.len() {
        let cid = partition[si];
        // Find or insert cid.
        let mut ci = 0;
        let mut found = false;
        while ci < n_components {
            if component_ids[ci] == cid {
                component_counts[ci] = component_counts[ci].saturating_add(1);
                found = true;
                break;
            }
            ci += 1;
        }
        if !found && n_components < (WITT_MAX_BITS as usize) {
            component_ids[n_components] = cid;
            component_counts[n_components] = 1;
            n_components += 1;
        }
        si += 1;
    }
    // Fold each component: (component_id, site_count_within) in first-appearance order.
    let mut ci = 0;
    while ci < n_components {
        hasher = hasher.fold_bytes(&component_ids[ci].to_be_bytes());
        hasher = hasher.fold_bytes(&component_counts[ci].to_be_bytes());
        ci += 1;
    }
    // Fold disjointness_witness IRI so forgeries yield distinct content fingerprints.
    hasher = hasher.fold_bytes(witness_iri.as_bytes());
    hasher = hasher.fold_byte(0);
    // Canonical ParallelDeclaration tail: site_count + type shape + cert kind.
    hasher = crate::enforcement::fold_parallel_digest(
        hasher,
        site_count,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::Grounding,
    );
    let buffer = hasher.finalize();
    let content_fingerprint =
        crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    let unit_address = crate::enforcement::unit_address_from_buffer(&buffer);
    let grounding = Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
        32,
        content_fingerprint,
    ));
    let bindings = empty_bindings_table();
    Ok(Grounded::<T>::new_internal(
        grounding,
        bindings,
        32,
        unit_address,
        content_fingerprint,
    ))
}

/// v0.2.2 Phase F / T2.7: stream driver entry point.
/// Consumes a `Validated<StreamDeclaration, P>` and returns a
/// `StreamDriver<T, P>` implementing `Iterator`. The driver's productivity
/// countdown is initialized from `StreamDeclaration::productivity_bound()`;
/// each `next()` call yields a `Grounded` whose `unit_address` differs
/// from the previous step's, and the iterator terminates when the
/// countdown reaches zero.
#[must_use]
pub fn run_stream<T, P, H>(unit: Validated<StreamDeclaration, P>) -> StreamDriver<T, P, H>
where
    T: crate::enforcement::GroundedShape,
    P: crate::enforcement::ValidationPhase,
    H: crate::enforcement::Hasher,
{
    let bound = unit.inner().productivity_bound();
    let result_type_iri = unit.inner().result_type_iri();
    StreamDriver::new_internal(bound, bound, result_type_iri)
}

/// v0.2.2 Phase F / T2.7: interaction driver entry point.
/// Consumes a `Validated<InteractionDeclaration, P>` and returns an
/// `InteractionDriver<T, P, H>` state machine seeded from the declaration's
/// `convergence_seed()`. Advance with `step(PeerInput)` until
/// `is_converged()` returns `true`, then call `finalize()`.
#[must_use]
pub fn run_interactive<T, P, H>(
    unit: Validated<InteractionDeclaration, P>,
) -> InteractionDriver<T, P, H>
where
    T: crate::enforcement::GroundedShape,
    P: crate::enforcement::ValidationPhase,
    H: crate::enforcement::Hasher,
{
    InteractionDriver::new_internal(
        unit.inner().convergence_seed(),
        unit.inner().result_type_iri(),
    )
}

/// v0.2.2 Phase G / T2.8: const-fn companion for
/// `LeaseDeclarationBuilder`. Delegates to the builder's
/// `validate_const` method, which validates the `LeaseShape` contract
/// (`linear_site` and `scope` required) at compile time.
/// # Errors
/// Returns `ShapeViolation::Missing` if `linear_site` or `scope` is unset.
pub const fn validate_lease_const<'a>(
    builder: &LeaseDeclarationBuilder<'a>,
) -> Result<Validated<LeaseDeclaration, CompileTime>, ShapeViolation> {
    builder.validate_const()
}

/// v0.2.2 Phase G / T2.8 + T6.13: const-fn companion for `CompileUnitBuilder`.
///
/// Tightened in T6.13 to enforce the same five required fields as the
/// runtime `CompileUnitBuilder::validate()` method:
///
/// - `root_term`
/// - `witt_level_ceiling`
/// - `thermodynamic_budget`
/// - `target_domains` (non-empty)
/// - `result_type_iri`
///
/// Returns `Result<Validated<CompileUnit, CompileTime>, ShapeViolation>` โ€”
/// dual-path consistent with the runtime `validate()` method. Const-eval
/// call sites match on the `Result`; the panic only fires at codegen /
/// const-eval time, never at runtime.
///
/// # Errors
///
/// Returns `ShapeViolation::Missing` for the first unset required field.
pub const fn validate_compile_unit_const<'a>(
    builder: &CompileUnitBuilder<'a>,
) -> Result<Validated<CompileUnit<'a>, CompileTime>, ShapeViolation> {
    if !builder.has_root_term_const() {
        return Err(ShapeViolation {
            shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
            constraint_iri: "https://uor.foundation/conformance/compileUnit_rootTerm_constraint",
            property_iri: "https://uor.foundation/reduction/rootTerm",
            expected_range: "https://uor.foundation/schema/Term",
            min_count: 1,
            max_count: 1,
            kind: ViolationKind::Missing,
        });
    }
    let level = match builder.witt_level_option() {
        Some(l) => l,
        None => {
            return Err(ShapeViolation {
                shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
                constraint_iri:
                    "https://uor.foundation/conformance/compileUnit_unitWittLevel_constraint",
                property_iri: "https://uor.foundation/reduction/unitWittLevel",
                expected_range: "https://uor.foundation/schema/WittLevel",
                min_count: 1,
                max_count: 1,
                kind: ViolationKind::Missing,
            })
        }
    };
    let budget =
        match builder.budget_option() {
            Some(b) => b,
            None => return Err(ShapeViolation {
                shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
                constraint_iri:
                    "https://uor.foundation/conformance/compileUnit_thermodynamicBudget_constraint",
                property_iri: "https://uor.foundation/reduction/thermodynamicBudget",
                expected_range: "http://www.w3.org/2001/XMLSchema#decimal",
                min_count: 1,
                max_count: 1,
                kind: ViolationKind::Missing,
            }),
        };
    if !builder.has_target_domains_const() {
        return Err(ShapeViolation {
            shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
            constraint_iri:
                "https://uor.foundation/conformance/compileUnit_targetDomains_constraint",
            property_iri: "https://uor.foundation/reduction/targetDomains",
            expected_range: "https://uor.foundation/op/VerificationDomain",
            min_count: 1,
            max_count: 0,
            kind: ViolationKind::Missing,
        });
    }
    let result_type_iri = match builder.result_type_iri_const() {
        Some(iri) => iri,
        None => {
            return Err(ShapeViolation {
                shape_iri: "https://uor.foundation/conformance/CompileUnitShape",
                constraint_iri:
                    "https://uor.foundation/conformance/compileUnit_resultType_constraint",
                property_iri: "https://uor.foundation/reduction/resultType",
                expected_range: "https://uor.foundation/type/ConstrainedType",
                min_count: 1,
                max_count: 1,
                kind: ViolationKind::Missing,
            })
        }
    };
    Ok(Validated::new(CompileUnit::from_parts_const(
        level,
        budget,
        result_type_iri,
        builder.root_term_slice_const(),
        builder.bindings_slice_const(),
        builder.target_domains_slice_const(),
    )))
}

/// v0.2.2 Phase G / T2.8 + T6.11: const-fn companion for
/// `ParallelDeclarationBuilder`. Takes a `ConstrainedTypeShape` type parameter
/// to set the `result_type_iri` on the produced declaration.
/// v0.2.2 Phase A: the produced `ParallelDeclaration<'a>` carries the
/// builder's raw site-partition slice and disjointness-witness IRI; the
/// lifetime `'a` is the builder's borrow lifetime.
#[must_use]
pub const fn validate_parallel_const<'a, T: ConstrainedTypeShape>(
    builder: &ParallelDeclarationBuilder<'a>,
) -> Validated<ParallelDeclaration<'a>, CompileTime> {
    Validated::new(ParallelDeclaration::new_with_partition::<T>(
        builder.site_partition_slice_const(),
        builder.disjointness_witness_const(),
    ))
}

/// v0.2.2 Phase G / T2.8 + T6.11: const-fn companion for
/// `StreamDeclarationBuilder`. Takes a `ConstrainedTypeShape` type parameter
/// to set the `result_type_iri` on the produced declaration.
/// v0.2.2 Phase A: the produced `StreamDeclaration<'a>` retains the
/// builder's seed/step term slices and productivity-witness IRI.
#[must_use]
pub const fn validate_stream_const<'a, T: ConstrainedTypeShape>(
    builder: &StreamDeclarationBuilder<'a>,
) -> Validated<StreamDeclaration<'a>, CompileTime> {
    let bound = builder.productivity_bound_const();
    Validated::new(StreamDeclaration::new_full::<T>(
        bound,
        builder.seed_slice_const(),
        builder.step_slice_const(),
        builder.productivity_witness_const(),
    ))
}

/// v0.2.2 T5 C6: const-fn resolver companion for
/// `tower_completeness::certify`. Threads the consumer-supplied substrate
/// `Hasher` through the canonical CompileUnit byte layout to compute a
/// parametric content fingerprint, distinguishing two units that share a
/// witt level but differ in budget, IRI, site count, or constraints.
#[must_use]
pub fn certify_tower_completeness_const<T, H>(
    unit: &Validated<CompileUnit, CompileTime>,
) -> Validated<GroundingCertificate, CompileTime>
where
    T: ConstrainedTypeShape,
    H: crate::enforcement::Hasher,
{
    let level_bits = unit.inner().witt_level().witt_length() as u16;
    let budget = unit.inner().thermodynamic_budget();
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        level_bits,
        budget,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::TowerCompleteness,
    );
    let buffer = hasher.finalize();
    let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
        level_bits, fp,
    ))
}

/// v0.2.2 T5 C6: const-fn resolver companion for
/// `incremental_completeness::certify`. Threads `H: Hasher` for the
/// parametric fingerprint; uses `CertificateKind::IncrementalCompleteness`
/// as the trailing discriminant byte.
#[must_use]
pub fn certify_incremental_completeness_const<T, H>(
    unit: &Validated<CompileUnit, CompileTime>,
) -> Validated<GroundingCertificate, CompileTime>
where
    T: ConstrainedTypeShape,
    H: crate::enforcement::Hasher,
{
    let level_bits = unit.inner().witt_level().witt_length() as u16;
    let budget = unit.inner().thermodynamic_budget();
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        level_bits,
        budget,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::IncrementalCompleteness,
    );
    let buffer = hasher.finalize();
    let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
        level_bits, fp,
    ))
}

/// v0.2.2 T5 C6: const-fn resolver companion for `inhabitance::certify`.
/// Threads `H: Hasher` for the parametric fingerprint; uses
/// `CertificateKind::Inhabitance` as the trailing discriminant byte.
#[must_use]
pub fn certify_inhabitance_const<T, H>(
    unit: &Validated<CompileUnit, CompileTime>,
) -> Validated<GroundingCertificate, CompileTime>
where
    T: ConstrainedTypeShape,
    H: crate::enforcement::Hasher,
{
    let level_bits = unit.inner().witt_level().witt_length() as u16;
    let budget = unit.inner().thermodynamic_budget();
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        level_bits,
        budget,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::Inhabitance,
    );
    let buffer = hasher.finalize();
    let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
        level_bits, fp,
    ))
}

/// v0.2.2 T5 C6: const-fn resolver companion for
/// `multiplication::certify`. Threads `H: Hasher` for the parametric
/// fingerprint; uses `CertificateKind::Multiplication` as the trailing
/// discriminant byte.
#[must_use]
pub fn certify_multiplication_const<T, H>(
    unit: &Validated<CompileUnit, CompileTime>,
) -> Validated<MultiplicationCertificate, CompileTime>
where
    T: ConstrainedTypeShape,
    H: crate::enforcement::Hasher,
{
    let level_bits = unit.inner().witt_level().witt_length() as u16;
    let budget = unit.inner().thermodynamic_budget();
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        level_bits,
        budget,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::Multiplication,
    );
    let buffer = hasher.finalize();
    let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    Validated::new(MultiplicationCertificate::with_level_and_fingerprint_const(
        level_bits, fp,
    ))
}

/// Phase C.4: const-fn resolver companion for `grounding_aware::certify`.
/// Threads `H: Hasher` for the parametric fingerprint; uses
/// `CertificateKind::Grounding` as the trailing discriminant byte.
#[must_use]
pub fn certify_grounding_aware_const<T, H>(
    unit: &Validated<CompileUnit, CompileTime>,
) -> Validated<GroundingCertificate, CompileTime>
where
    T: ConstrainedTypeShape,
    H: crate::enforcement::Hasher,
{
    let level_bits = unit.inner().witt_level().witt_length() as u16;
    let budget = unit.inner().thermodynamic_budget();
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        level_bits,
        budget,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::Grounding,
    );
    let buffer = hasher.finalize();
    let fp = crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
        level_bits, fp,
    ))
}

/// v0.2.2 T5 C6: typed pipeline entry point producing `Grounded<T>` from
/// a validated `CompileUnit`. Threads the consumer-supplied substrate
/// `Hasher` through `fold_unit_digest` to compute a parametric content
/// fingerprint over the unit's full state: `(level_bits, budget, T::IRI,
/// T::SITE_COUNT, T::CONSTRAINTS, CertificateKind::Grounding)`.
/// Two units differing on **any** of those fields produce `Grounded`
/// values with distinct fingerprints (and distinct `unit_address` handles,
/// derived from the leading 16 bytes of the fingerprint).
/// # Errors
/// Returns `PipelineFailure::ShapeMismatch` when the unit's declared
/// `result_type_iri` does not match `T::IRI`, or propagates any
/// failure from the reduction stage executor.
pub fn run_const<T, M, H>(
    unit: &Validated<CompileUnit, CompileTime>,
) -> Result<Grounded<T>, PipelineFailure>
where
    T: ConstrainedTypeShape + crate::enforcement::GroundedShape,
    // Phase C.2 (target ยง6): const-eval admits only those grounding-map kinds
    // that are both Total (defined for all inputs) and Invertible (one-to-one).
    // The bound is enforced at the type level via the existing marker tower.
    M: crate::enforcement::GroundingMapKind
        + crate::enforcement::Total
        + crate::enforcement::Invertible,
    H: crate::enforcement::Hasher,
{
    // The marker bound on M is purely type-level โ€” no runtime use.
    let _phantom_map: core::marker::PhantomData<M> = core::marker::PhantomData;
    let level_bits = unit.inner().witt_level().witt_length() as u16;
    let budget = unit.inner().thermodynamic_budget();
    // v0.2.2 T6.11: ShapeMismatch detection. The unit declares its
    // result_type_iri at validation time; the caller's `T::IRI` must match.
    let unit_iri = unit.inner().result_type_iri();
    if !crate::enforcement::str_eq(unit_iri, T::IRI) {
        return Err(PipelineFailure::ShapeMismatch {
            expected: T::IRI,
            got: unit_iri,
        });
    }
    // Walk the foundation-locked byte layout via the consumer's hasher.
    let mut hasher = H::initial();
    hasher = crate::enforcement::fold_unit_digest(
        hasher,
        level_bits,
        budget,
        T::IRI,
        T::SITE_COUNT,
        T::CONSTRAINTS,
        crate::enforcement::CertificateKind::Grounding,
    );
    let buffer = hasher.finalize();
    let content_fingerprint =
        crate::enforcement::ContentFingerprint::from_buffer(buffer, H::OUTPUT_BYTES as u8);
    let unit_address = crate::enforcement::unit_address_from_buffer(&buffer);
    let grounding = Validated::new(GroundingCertificate::with_level_and_fingerprint_const(
        level_bits,
        content_fingerprint,
    ));
    let bindings = empty_bindings_table();
    Ok(Grounded::<T>::new_internal(
        grounding,
        bindings,
        level_bits,
        unit_address,
        content_fingerprint,
    ))
}