uor-foundation 0.3.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
// @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`).
pub const AFFINE_MAX_COEFFS: usize = 8;

/// Phase 17: maximum number of `LeafConstraintRef` conjuncts a
/// `Conjunction` can carry. Same reasoning as `AFFINE_MAX_COEFFS`.
pub const CONJUNCTION_MAX_TERMS: usize = 8;

/// 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 },
///     ];
/// }
/// 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];
}

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

/// 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.
pub const ROUTE_INPUT_BUFFER_BYTES: usize = 4096;

/// 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).
pub const ROUTE_OUTPUT_BUFFER_BYTES: usize = 4096;

/// 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.
pub const FOLD_UNROLL_THRESHOLD: usize = 8;

/// 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>: __sdk_seal::Sealed
where
    H: crate::HostTypes,
    B: crate::HostBounds,
    A: crate::enforcement::Hasher,
{
    /// 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>(
    input: M::Input,
) -> Result<crate::enforcement::Grounded<M::Output>, PipelineFailure>
where
    H: crate::HostTypes,
    B: crate::HostBounds,
    A: crate::enforcement::Hasher,
    M: PrismModel<H, B, 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>(arena_slice, &buf[..written])?;
    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/HasherProjection 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.
pub const TERM_VALUE_MAX_BYTES: usize = 4096;

/// 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-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`).
pub const UNFOLD_MAX_ITERATIONS: usize = 256;

/// 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::HasherProjection { input }` โ€” fold the input's bytes through the
///   application's `Hasher` substitution-axis impl and emit the digest.
/// # 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>(
    arena: &[crate::enforcement::Term],
    input_bytes: &[u8],
) -> Result<TermValue, PipelineFailure>
where
    A: crate::enforcement::Hasher,
{
    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>(arena, root_idx, input_bytes, None, None)
}

fn evaluate_term_at<A>(
    arena: &[crate::enforcement::Term],
    idx: usize,
    input_bytes: &[u8],
    recurse_value: Option<&[u8]>,
    unfold_value: Option<&[u8]>,
) -> Result<TermValue, PipelineFailure>
where
    A: crate::enforcement::Hasher,
{
    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(&[])));
            }
            if name_index == UNFOLD_PLACEHOLDER_NAME_INDEX {
                return Ok(TermValue::from_slice(unfold_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>(
                arena,
                operator,
                start,
                len,
                input_bytes,
                recurse_value,
                unfold_value,
            )
        }
        crate::enforcement::Term::Lift {
            operand_index,
            target,
        } => {
            let v = evaluate_term_at::<A>(
                arena,
                operand_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            )?;
            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>(
                arena,
                operand_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            )?;
            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>(
                arena,
                scrutinee_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            )?;
            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>(
                        arena,
                        body_idx,
                        input_bytes,
                        recurse_value,
                        unfold_value,
                    );
                }
                let pattern_val = evaluate_term_at::<A>(
                    arena,
                    pattern_idx,
                    input_bytes,
                    recurse_value,
                    unfold_value,
                )?;
                if pattern_val.bytes() == scrutinee.bytes() {
                    return evaluate_term_at::<A>(
                        arena,
                        body_idx,
                        input_bytes,
                        recurse_value,
                        unfold_value,
                    );
                }
                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>(
                arena,
                measure_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            )?;
            let n = bytes_to_u64_be(measure.bytes());
            let base_val = evaluate_term_at::<A>(
                arena,
                base_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            )?;
            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 {
                let next = evaluate_term_at::<A>(
                    arena,
                    step_index as usize,
                    input_bytes,
                    Some(&current_buf[..current_len]),
                    unfold_value,
                )?;
                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>(
                arena,
                seed_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            )?;
            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>(
                    arena,
                    step_index as usize,
                    input_bytes,
                    recurse_value,
                    Some(&state_buf[..state_len]),
                )?;
                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>(
                arena,
                body_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            ) {
                Ok(v) => Ok(v),
                Err(e) => {
                    if handler_index == u32::MAX {
                        Err(e)
                    } else {
                        evaluate_term_at::<A>(
                            arena,
                            handler_index as usize,
                            input_bytes,
                            recurse_value,
                            unfold_value,
                        )
                    }
                }
            }
        }
        crate::enforcement::Term::HasherProjection { input_index } => {
            let v = evaluate_term_at::<A>(
                arena,
                input_index as usize,
                input_bytes,
                recurse_value,
                unfold_value,
            )?;
            let mut hasher = <A as crate::enforcement::Hasher>::initial();
            hasher = hasher.fold_bytes(v.bytes());
            let digest = hasher.finalize();
            // Take the first `OUTPUT_BYTES` bytes of the digest as the canonical width.
            let width = if A::OUTPUT_BYTES > TERM_VALUE_MAX_BYTES {
                TERM_VALUE_MAX_BYTES
            } else {
                A::OUTPUT_BYTES
            };
            Ok(TermValue::from_slice(&digest[..width]))
        }
    }
}

fn apply_primitive_op<A>(
    arena: &[crate::enforcement::Term],
    operator: crate::PrimitiveOp,
    args_start: usize,
    args_len: usize,
    input_bytes: &[u8],
    recurse_value: Option<&[u8]>,
    unfold_value: Option<&[u8]>,
) -> Result<TermValue, PipelineFailure>
where
    A: crate::enforcement::Hasher,
{
    // 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>(arena, args_start, input_bytes, recurse_value, unfold_value)?;
        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>(arena, args_start, input_bytes, recurse_value, unfold_value)?;
        let rhs = evaluate_term_at::<A>(
            arena,
            args_start + 1,
            input_bytes,
            recurse_value,
            unfold_value,
        )?;
        // 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()
}

/// 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 },
///     ];
/// }
/// 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,
    ))
}