keleusma 0.2.2

Total Functional Stream Processor with definitive WCET and WCMU verification, targeting no_std + alloc embedded scripting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
extern crate alloc;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::String;
// The `vec!` macro is used only by the test module; lib code uses the
// fully-qualified `alloc::vec!`.
#[cfg(test)]
use alloc::vec;
use alloc::vec::Vec;

use allocator_api2::vec::Vec as ArenaVec;
use keleusma_arena::BottomHandle;

use crate::bytecode::*;
#[cfg(feature = "verify")]
use crate::verify;
#[allow(unused_imports)]
use crate::word::{WideWord, Word};

/// Operand stack and call-frame stack type. Borrows the host-owned
/// arena's bottom region. The `Vm` drops and recreates these at every
/// arena reset because their storage pointer would otherwise alias
/// memory that the bump allocator returns for subsequent allocations.
type StackVec<'arena, T> = ArenaVec<T, BottomHandle<'arena>>;

/// Push a value onto the operand stack, returning early with
/// `VmError::OutOfArena` on allocation failure rather than aborting
/// the host process via `handle_alloc_error`.
///
/// V0.2.0 routes every operand-stack push through this macro so that
/// arena exhaustion during execution surfaces as a typed error to
/// the host. The minimum pre-reservation at `Vm::new` covers the
/// first few pushes; growth beyond the reservation attempts to
/// extend the arena and may fail.
macro_rules! sp {
    ($self:expr, $val:expr) => {
        match $self.stack.try_reserve(1) {
            Ok(()) => $self.stack.push($val),
            Err(_) => {
                return Err(out_of_arena_push("operand stack", $self.arena.capacity()));
            }
        }
    };
}

/// Push a call frame, returning early with `VmError::OutOfArena` on
/// allocation failure. Counterpart to `sp!` for the call-frame stack.
macro_rules! fp {
    ($self:expr, $val:expr) => {
        match $self.frames.try_reserve(1) {
            Ok(()) => $self.frames.push($val),
            Err(_) => {
                return Err(out_of_arena_push("call frame", $self.arena.capacity()));
            }
        }
    };
}

/// A runtime error from the Keleusma VM.
#[derive(Debug, Clone)]
pub enum VmError {
    /// The value stack was empty when a pop was attempted.
    StackUnderflow,
    /// A type mismatch occurred during an operation.
    TypeError(String),
    /// Division or modulo by zero.
    DivisionByZero,
    /// Array or tuple index out of bounds.
    IndexOutOfBounds(i64, usize),
    /// Struct field not found.
    FieldNotFound(String, String),
    /// A native function returned an error.
    NativeError(String),
    /// A fallible native function failed and reported a `Word` error
    /// code alongside a message (B35 P7). The code is the value the
    /// native-error `error(code)` arm binds; the message aids host
    /// diagnostics. Produced through the `keleusma-macros`
    /// `KeleusmaError` derive (`From<E> for VmError`) or constructed
    /// directly. Categorized as a soft host error like
    /// [`VmError::NativeError`].
    NativeErrorCode {
        /// The `Word`-valued error code, often a discriminant-only
        /// enum's discriminant.
        code: i64,
        /// A human-readable message for host diagnostics.
        message: String,
    },
    /// Invalid or unexpected bytecode.
    InvalidBytecode(String),
    /// A newtype refinement predicate returned false at a
    /// construction site. One of the partial-operation traps; see
    /// [`crate::bytecode::TrapKind`].
    RefinementFailed,
    /// No head of a multiheaded function matched the arguments.
    NoMatchingHead,
    /// No arm of a `match` expression matched the scrutinee.
    /// Reachable only when every arm carries a `when` guard.
    NoMatchingArm,
    /// No arm of a checked-arithmetic construct matched the outcome.
    CheckedArithNoArm,
    /// An enum-to-`Word` cast met a `Value::Enum` whose variant is
    /// outside the declared set, reachable only through a host-
    /// constructed enum value.
    EnumVariantUnmapped,
    /// A debug `assert` condition evaluated to false at runtime.
    /// Reachable only in debug builds, which compile the assert check
    /// in; release builds compile it out (B29). The failing
    /// assertion's source location and message, when present, live in
    /// the chunk's strippable `AssertionContext` debug record.
    AssertionFailed,
    /// Structural verification failed at load time.
    VerifyError(String),
    /// Bytecode load failure encountered before verification could run,
    /// such as a header mismatch or postcard decode error.
    LoadError(String),
    /// The host-owned arena ran out of space and the runtime cannot
    /// allocate the storage the script requires. Returned by
    /// [`Vm::new`] and related entry points when the arena is too
    /// small for the operand stack and call-frame preamble that the
    /// program needs. Replaces the previous behavior of aborting the
    /// host process through `handle_alloc_error`.
    OutOfArena(String),
    /// [`Vm::resume`] or [`Vm::resume_err`] was called on a VM that is
    /// not in the suspended state. The host must call [`Vm::call`]
    /// first to enter a coroutine and reach the first `yield` before
    /// resuming. Distinguished from [`VmError::InvalidBytecode`] to
    /// keep API misuse separate from corrupt or malformed bytecode.
    NotSuspended,
}

impl From<crate::bytecode::LoadError> for VmError {
    fn from(e: crate::bytecode::LoadError) -> Self {
        VmError::LoadError(format!("{}", e))
    }
}

impl From<crate::bytecode::ScalarError> for VmError {
    fn from(e: crate::bytecode::ScalarError) -> Self {
        // A bad flat scalar read or write -- an out-of-range offset, a
        // reference kind on the fixed-scalar path, or an unsupported width --
        // is malformed bytecode reaching the runtime (V0.2.1 audit, the
        // read_scalar_le totality cluster).
        VmError::InvalidBytecode(format!("flat scalar codec: {:?}", e))
    }
}

/// Coarse policy category for a [`VmError`]. Used by hosts that want
/// to make a single retry-or-halt decision without matching the
/// full variant set.
///
/// The category is a derivation from the variant, not a stored
/// field, so adding a new `VmError` variant requires updating
/// [`VmError::category`] but does not change the wire format or any
/// per-error allocation. Hosts that need finer policy than the
/// three-way split continue to match on the variant directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VmErrorCategory {
    /// Unrecoverable. The VM is in an undefined intermediate state
    /// and must not be resumed. Hosts that wish to continue running
    /// programs must call [`Vm::reset_after_error`] before any
    /// further [`Vm::call`] or [`Vm::resume`]. Examples:
    /// `StackUnderflow`, `InvalidBytecode`, `VerifyError`,
    /// `LoadError`, `OutOfArena`, `NotSuspended`.
    Halt,
    /// Recoverable script-side error. The script asked for something
    /// that the VM rejected; the host may surface the error to the
    /// script through [`Vm::resume_err`] or restart the iteration.
    /// Examples: `TypeError`, `DivisionByZero`, `IndexOutOfBounds`,
    /// `FieldNotFound`, `NoMatch`, `Trap`.
    SoftScript,
    /// Recoverable host-side error. A native function the host
    /// registered returned an error. The host owns the recovery
    /// policy (retry, fallback, surface to the script through
    /// [`Vm::resume_err`]). Example: `NativeError`.
    SoftHost,
}

impl VmError {
    /// Coarse retry-or-halt category for this error.
    ///
    /// See [`VmErrorCategory`] for the three-way split and per-variant
    /// rationale. Hosts that need finer policy match on `self`
    /// directly.
    pub fn category(&self) -> VmErrorCategory {
        match self {
            // Halt: the VM state is undefined or unrecoverable.
            VmError::StackUnderflow
            | VmError::InvalidBytecode(_)
            | VmError::VerifyError(_)
            | VmError::LoadError(_)
            | VmError::OutOfArena(_)
            | VmError::NotSuspended => VmErrorCategory::Halt,
            // Soft script: the script's request was invalid at the
            // VM level, but the VM's invariants hold and the host
            // can ask the script to retry through `resume_err`.
            VmError::TypeError(_)
            | VmError::DivisionByZero
            | VmError::IndexOutOfBounds(_, _)
            | VmError::FieldNotFound(_, _)
            | VmError::RefinementFailed
            | VmError::NoMatchingHead
            | VmError::NoMatchingArm
            | VmError::CheckedArithNoArm
            | VmError::EnumVariantUnmapped
            | VmError::AssertionFailed => VmErrorCategory::SoftScript,
            // Soft host: a native returned an error. The host owns
            // the policy.
            VmError::NativeError(_) | VmError::NativeErrorCode { .. } => VmErrorCategory::SoftHost,
        }
    }
}

/// The source location a runtime fault maps back to, resolved from a
/// chunk's strippable debug records (B29). Owned (rather than borrowing
/// the chunk's debug pool, like [`crate::debug_meta::SourceLocation`])
/// because [`GenericVm::fault_source_location`] decodes the pool on
/// demand and the borrow could not outlive that call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FaultSource {
    /// The source file name recorded for the span, when present. The
    /// compiler emits an empty placeholder it does not know the source
    /// path, so this is commonly `Some("")` until a host rewrites it.
    pub file: Option<String>,
    /// Byte offset of the span's start in the file.
    pub byte_offset: u32,
    /// Byte length of the span.
    pub byte_length: u32,
    /// `true` when the span is keyed to the faulting op itself (an
    /// exact match, e.g. a `CallSite` or `AssertionContext` at that op);
    /// `false` when it is the nearest enclosing statement's `SourceSpan`
    /// resolved as a fallback. A host that needs precision should not
    /// treat a non-exact location as the precise fault site.
    pub exact: bool,
}

/// Type alias for the bundled 64-bit `VmState` shape.
pub type VmState = GenericVmState<i64, f64>;

/// The execution state of the VM, parametric over the runtime's
/// word and float widths.
///
/// **Composite-value lifetime (read-before-resume, B28 P3 item 5 C3).** A
/// `Yielded` or `Finished` value whose body is a flat composite (a struct,
/// enum, tuple, or array) stays resident in the VM's arena rather than being
/// copied to the global heap. The host must read it before it is
/// invalidated: decode it through [`GenericVm::decode`] (which resolves the
/// arena body) before the next [`GenericVm::resume`] for a `Yielded` value,
/// since `resume` RESETs the arena, and before dropping the VM for a
/// `Finished` value. A read after that point resolves to a clean
/// [`VmError`] (the arena body is stale), never undefined behaviour. Scalar
/// values (`Int`, `Float`, `Bool`, and the like) are self-contained and
/// carry no such restriction. This trades the previous "value survives the
/// arena" guarantee for the no-global-heap property the embedded target
/// requires.
#[derive(Debug, Clone)]
pub enum GenericVmState<W: crate::word::Word, F: crate::float::Float> {
    /// The coroutine yielded a value and is suspended. A composite value is
    /// arena-resident; decode it before the next `resume` (see the type-level
    /// read-before-resume note).
    Yielded(crate::bytecode::GenericValue<W, F>),
    /// The function completed with a return value. A composite value is
    /// arena-resident; decode it before dropping the VM (see the type-level
    /// read-before-resume note).
    Finished(crate::bytecode::GenericValue<W, F>),
    /// The stream hit a Reset boundary.
    Reset,
    /// Execution paused at an armed breakpoint, before executing the op
    /// at `(chunk, op)`. The operand and call-frame stacks are intact;
    /// the host inspects state and continues with
    /// [`GenericVm::resume_from_breakpoint`]. Breakpoints are a
    /// host-driven debugging mechanism (B29); a debugger maps a
    /// `BreakpointCandidate` debug record's op index to a position and
    /// arms it through [`GenericVm::set_breakpoint`].
    BreakpointHit {
        /// Chunk index of the paused position.
        chunk: usize,
        /// Op index within the chunk of the paused position.
        op: usize,
    },
}

/// Policy for handling WCET and WCMU bound overflow at verification.
///
/// The compiler saturates the declared WCET and WCMU header fields to
/// `u32::MAX` when the static analysis cannot bound the value. Under
/// the default [`OverflowPolicy::Reject`] policy, `Vm::new_with_options`
/// rejects such modules as a `VmError::VerifyError`. Hosts that wish to
/// accept the module despite the overflow may downgrade the policy to
/// [`OverflowPolicy::Warn`] (returns the module with a `VerifyWarning`
/// describing the overflow) or [`OverflowPolicy::Allow`] (admits the
/// module silently).
///
/// The policy applies to the declared header fields only. Resource
/// bounds against the arena capacity continue to be enforced because
/// they are a load-time admissibility check rather than a static
/// analysis overflow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OverflowPolicy {
    /// Overflow is a verification error. Default.
    #[default]
    Reject,
    /// Overflow produces a [`VerifyWarning`] entry and admits the module.
    Warn,
    /// Overflow admits the module silently.
    Allow,
}

/// Construction-time options for [`Vm::new_with_options`].
///
/// The default options apply the strict overflow policy
/// ([`OverflowPolicy::Reject`]) and otherwise match the behaviour of
/// the bare [`Vm::new`] constructor.
#[derive(Debug, Clone, Copy, Default)]
pub struct VmOptions {
    /// Policy for handling WCET and WCMU bound overflow at the
    /// declared header level. See [`OverflowPolicy`].
    pub overflow_policy: OverflowPolicy,
}

/// Non-fatal finding produced by [`Vm::new_with_options`] when an
/// overflow condition is downgraded under the chosen
/// [`OverflowPolicy`].
#[derive(Debug, Clone)]
pub struct VerifyWarning {
    /// Human-readable description of the warning.
    pub message: String,
    /// The category of warning. Hosts may switch on this to route
    /// warnings to telemetry or to apply per-kind handling.
    pub kind: WarningKind,
}

/// Category of [`VerifyWarning`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WarningKind {
    /// The declared WCET cycles field saturated to `u32::MAX`.
    WcetOverflow,
    /// The declared WCMU bytes field saturated to `u32::MAX`.
    WcmuOverflow,
}

/// A call frame on the VM call stack.
#[derive(Debug, Clone, Copy)]
struct CallFrame {
    /// Index of the chunk being executed.
    chunk_idx: usize,
    /// Instruction pointer (next instruction to execute).
    ip: usize,
    /// Stack base for this frame's local variables.
    base: usize,
}

/// Context passed to native functions that opt into arena access.
///
/// Created freshly at each [`crate::bytecode::Op::CallVerifiedNative`] or [`crate::bytecode::Op::CallExternalNative`] dispatch with a borrow
/// of the host-owned arena. Native functions allocate dynamic strings
/// through `KString::alloc(ctx.arena, s)` and return them as
/// [`crate::bytecode::GenericValue::KStr`] for the bounded-memory path. Natives that do not
/// need arena access can be registered through [`Vm::register_native`]
/// or [`Vm::register_fn`], whose function types omit the context.
pub struct NativeCtx<'a> {
    /// Borrow of the host-owned arena for string and scratch
    /// allocations.
    pub arena: &'a keleusma_arena::Arena,
    /// The VM's ephemeral opaque registry, so a composite argument with an
    /// opaque field can resolve it during marshalling (B28 P3).
    pub opaques: &'a [alloc::sync::Arc<dyn crate::opaque::HostOpaque>],
    /// The module's packed word byte width, used to read a flat composite
    /// argument's fields at the width the body was packed with.
    pub word_bytes: usize,
    /// The module's packed float byte width, paired with `word_bytes`.
    pub float_bytes: usize,
}

impl<'a> NativeCtx<'a> {
    /// The resolution context for marshalling a composite argument that may
    /// hold `Text` or opaque fields (B28 P3).
    pub fn ref_context(&self) -> crate::marshall::RefContext<'a> {
        crate::marshall::RefContext {
            arena: self.arena,
            opaques: self.opaques,
            word_bytes: self.word_bytes,
            float_bytes: self.float_bytes,
            // A native argument is materialised at the current epoch and read
            // synchronously within the call, before any RESET, so the current
            // arena epoch is the argument body's originating epoch (B28 P3
            // item 1).
            ref_epoch: self.arena.epoch(),
        }
    }
}

/// Type alias for a native function callable from Keleusma.
///
/// All native functions internally accept a [`NativeCtx`] to support
/// arena-aware natives. Natives registered through the no-context API
/// ignore the context.
type NativeFn<W, F> = Box<
    dyn for<'a> Fn(
        &NativeCtx<'a>,
        &[crate::bytecode::GenericValue<W, F>],
    ) -> Result<crate::bytecode::GenericValue<W, F>, VmError>,
>;

/// A registered native function.
struct NativeEntry<W: crate::word::Word, F: crate::float::Float> {
    name: String,
    func: NativeFn<W, F>,
    /// Host-attested worst-case execution time, in the same unitless cost
    /// space as `Op::cost()`. Default `DEFAULT_NATIVE_WCET`.
    #[allow(dead_code)]
    wcet: u32,
    /// Host-attested worst-case memory usage in bytes. Native functions
    /// that allocate from the arena must override this for the analysis
    /// to remain sound. Default `DEFAULT_NATIVE_WCMU_BYTES`.
    #[allow(dead_code)]
    wcmu_bytes: u32,
    /// Classification recorded at registration. Cross-checked at
    /// the call-site dispatch against the bytecode's opcode
    /// (`CallVerifiedNative` versus `CallExternalNative`). A
    /// mismatch is rejected as a `VmError::VerifyError`.
    classification: NativeClassification,
    /// External-native upper bound on the per-iteration invocation
    /// count. Recorded for external natives at registration and
    /// consumed by future verifier passes that bound external-call
    /// cost contribution against this attestation. `None` for
    /// verified natives. Current verifier passes use `wcmu_bytes`
    /// for the per-call attestation; the invocation-count
    /// attestation is forward-looking V0.2.x work.
    #[allow(dead_code)]
    max_invocations_per_iteration: Option<u32>,
}

/// Per-native classification recorded at host registration and
/// cross-checked against the call-site opcode at `Vm::new`.
///
/// `Verified` natives are registered through
/// [`GenericVm::register_native`], [`GenericVm::register_fn`], or
/// [`GenericVm::register_verified_native`]. The host attests the
/// per-call WCET and WCMU bound; the verifier folds these into the
/// iteration's static budget.
///
/// `External` natives are registered through
/// [`GenericVm::register_external_native`]. The host attests the
/// maximum invocation count per iteration rather than the per-call
/// cost; the verifier observes the structural marker without
/// charging the iteration budget for individual call cost.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NativeClassification {
    /// `use module::name` import. Per-call WCET / WCMU attested.
    Verified,
    /// `use external module::name` import. Per-iteration invocation
    /// count attested.
    External,
}

/// Default WCET attestation for a native function. Equal to the cost of a
/// single native-call opcode.
pub const DEFAULT_NATIVE_WCET: u32 = 10;

/// Default WCMU attestation for a native function. Native functions that
/// allocate from the arena must override this through
/// `Vm::set_native_bounds`.
pub const DEFAULT_NATIVE_WCMU_BYTES: u32 = 0;

/// Default arena capacity in bytes when constructed via `Vm::new`. The host
/// can override this by calling `Vm::new_with_arena_capacity`.
pub const DEFAULT_ARENA_CAPACITY: usize = 64 * 1024;

/// Minimum operand-stack capacity pre-reserved at `Vm::new`, in slots.
/// The reservation lets `Vm::new` fail fast with `VmError::OutOfArena`
/// when the arena is too small to hold even a trivial program's working
/// set, rather than aborting the host process on a later push.
///
/// The value is a conservative floor that covers small `fn main`
/// programs without overcommitting tiny arenas beyond what they can
/// hold. Stream programs whose WCMU exceeds this floor still rely on
/// in-execution growth.
const MIN_STACK_RESERVE_SLOTS: usize = 4;

/// Minimum call-frame capacity pre-reserved at `Vm::new`.
const MIN_FRAMES_RESERVE: usize = 1;

/// Build a `VmError::OutOfArena` for an in-execution push that exceeded
/// the arena's capacity.
/// Error for reading a flat composite body whose arena allocation has
/// been released by a `RESET` (its epoch no longer matches) (B28 P2 arena
/// residence). A well-formed program never reads a value across the
/// `RESET` that issued it, since `RESET` also clears the operand stack, so
/// this surfaces a corrupted or mis-compiled artefact rather than a script
/// error.
fn stale_arena_body() -> VmError {
    VmError::InvalidBytecode(alloc::string::String::from(
        "flat composite body read after arena reset (stale)",
    ))
}

/// Fault when an `==`/`!=` reaches the runtime `CmpEq`/`CmpNe` with a flat
/// composite operand (B28 P3 item 5).
///
/// The compiler emits every nameable composite comparison field-wise, so a
/// flat composite body only reaches the runtime comparison when the compiler
/// could not determine the operand's type, which happens for the result of a
/// native called without a declared signature. A raw-byte comparison of a flat
/// body would silently diverge from IEEE float equality (`+0.0`/`-0.0`,
/// `NaN`), so this faults with a clear, actionable message rather than
/// returning a wrong answer. Scalars and boxed composites pass through.
fn reject_untyped_flat_composite_cmp<W: crate::word::Word, F: crate::float::Float>(
    a: &crate::bytecode::GenericValue<W, F>,
    b: &crate::bytecode::GenericValue<W, F>,
) -> Result<(), VmError> {
    // Fault only when BOTH operands are flat composites, the case where the
    // derived `PartialEq` would perform an IEEE-unsafe raw-byte compare. A
    // flat composite compared against a scalar, `Value::None`, or a boxed
    // body short-circuits to `false` on the variant mismatch with no byte
    // compare, so it is safe (and necessary: a flat `Option::Some` matched
    // against `Value::None` in an `Option::None` arm reaches here, B28 P3
    // item 5 C4).
    // A variant check, not a byte read, so it is valid on an arena-resident
    // body without first copying it out (B28 P3 item 5 zero-copy); the byte
    // body is never read here.
    if crate::bytecode::flat_composite_ref(a).is_some()
        && crate::bytecode::flat_composite_ref(b).is_some()
    {
        return Err(VmError::TypeError(alloc::string::String::from(
            "cannot compare a flat composite whose type the compiler could not \
             determine (an unsignatured native's composite result); add a \
             `use name() -> T` signature or a type annotation so the comparison \
             is emitted field-wise",
        )));
    }
    Ok(())
}

/// Replace a flat composite value's body with `fc`, preserving its kind
/// (B28 P3 item 5, item 3a). Used to rewrap a value whose body was copied into
/// the arena persistent region. A non-flat-composite value is returned
/// unchanged, which a correct caller never passes.
fn rewrap_flat_body<W: crate::word::Word, F: crate::float::Float>(
    val: crate::bytecode::GenericValue<W, F>,
    fc: crate::flat_value::FlatComposite,
) -> crate::bytecode::GenericValue<W, F> {
    use crate::bytecode::{ArrayBody, EnumBody, GenericValue, StructBody, TupleBody};
    match val {
        GenericValue::Tuple(TupleBody::Flat(_)) => GenericValue::Tuple(TupleBody::Flat(fc)),
        GenericValue::Array(ArrayBody::Flat(_)) => GenericValue::Array(ArrayBody::Flat(fc)),
        GenericValue::Struct(StructBody::Flat(_)) => GenericValue::Struct(StructBody::Flat(fc)),
        GenericValue::Enum(EnumBody::Flat(_)) => GenericValue::Enum(EnumBody::Flat(fc)),
        other => other,
    }
}

fn out_of_arena_push(region: &str, capacity: usize) -> VmError {
    use alloc::format;
    VmError::OutOfArena(format!(
        "arena exhausted while growing the {} (capacity {} bytes). \
         Increase the arena, or compute a sufficient size with \
         `auto_arena_capacity_for` plus a host-side margin.",
        region, capacity
    ))
}

/// Build a `VmError::OutOfArena` with the minimum reservation message.
fn out_of_arena_min(capacity: usize) -> VmError {
    use alloc::format;
    VmError::OutOfArena(format!(
        "arena capacity of {} bytes is too small to pre-reserve the \
         operand-stack and call-frame minimums ({} slots and {} frames). \
         Increase the arena capacity, or compute a sufficient size with \
         `auto_arena_capacity_for` plus a host-side margin.",
        capacity, MIN_STACK_RESERVE_SLOTS, MIN_FRAMES_RESERVE
    ))
}

/// Element capacity of the opaque registry given the compiler's
/// `aux_arena_bytes` bound (B28 P3 item 5, Phase C).
///
/// `aux_arena_bytes` is the compiler's sound upper bound on the registry's
/// per-iteration peak in bytes; dividing by the `Arc` width gives the
/// element capacity. Shared by `module_bottom_reservations` and the
/// construction path so the reservation, the autosize, and a later
/// `full_reset` all agree on the figure. `checked_div` guards the
/// (never-zero in practice) `Arc` width without a manual zero check; a
/// zero width or zero bound yields no reservation.
fn opaque_registry_capacity(aux_arena_bytes: u32) -> usize {
    let arc_bytes = core::mem::size_of::<alloc::sync::Arc<dyn crate::opaque::HostOpaque>>();
    (aux_arena_bytes as usize)
        .checked_div(arc_bytes)
        .unwrap_or(0)
}

/// Pre-size a fresh bottom-region arena vector to exactly `capacity`
/// elements (B28 P3 item 5, priority 1).
///
/// Uses `try_reserve_exact` so the backing allocation is exactly
/// `capacity * size_of::<T>()` bytes, with no amortised-growth slack. This
/// keeps the runtime footprint equal to the figure
/// [`auto_arena_capacity_for`] reports, so a host that sizes its arena from
/// that figure can construct with zero margin. Reserving up front means the
/// vector never reallocates during execution — deterministic allocation, as
/// the worst-case-memory guarantee requires (no allocation after
/// initialisation). An arena too small to hold the reservation fails here,
/// at construction, rather than aborting on a later push.
fn pre_sized_bottom_vec<'arena, T>(
    arena: &'arena keleusma_arena::Arena,
    capacity: usize,
) -> Result<StackVec<'arena, T>, VmError> {
    let mut v = ArenaVec::new_in(arena.bottom_handle());
    if capacity > 0 {
        v.try_reserve_exact(capacity)
            .map_err(|_| out_of_arena_min(arena.capacity()))?;
    }
    Ok(v)
}

/// Bottom-region reservation counts for `module`: operand-stack slots,
/// call-frame depth, and opaque-registry capacity, each floored at the
/// conservative minimum so a trivial module still reserves a usable
/// working set (B28 P3 item 5, priority 1).
///
/// Gated on the `verify` feature because the operand-slot and frame-depth
/// figures come from the verifier's static analysis. With the feature off
/// (the host attests bounds through a build-time step) the minimums are
/// used and the operand stack and frames grow on demand as before.
#[cfg(feature = "verify")]
fn module_bottom_reservations(module: &crate::bytecode::Module) -> (usize, usize, usize) {
    let (slots, frames) = match verify::module_runtime_footprint(module, &[]) {
        Ok(fp) => (
            (fp.max_operand_slots as usize).max(MIN_STACK_RESERVE_SLOTS),
            (fp.max_frame_depth as usize).max(MIN_FRAMES_RESERVE),
        ),
        // A module whose footprint cannot be computed (for example a
        // recursive call graph) is rejected by `verify` before
        // construction is reached on the checked path; fall back to the
        // minimums defensively for the trust-skip path.
        Err(_) => (MIN_STACK_RESERVE_SLOTS, MIN_FRAMES_RESERVE),
    };
    (
        slots,
        frames,
        opaque_registry_capacity(module.aux_arena_bytes),
    )
}

#[cfg(not(feature = "verify"))]
fn module_bottom_reservations(module: &crate::bytecode::Module) -> (usize, usize, usize) {
    (
        MIN_STACK_RESERVE_SLOTS,
        MIN_FRAMES_RESERVE,
        opaque_registry_capacity(module.aux_arena_bytes),
    )
}

/// Decode every op in every chunk of a bytecode buffer and return
/// the resulting per-chunk owned op vectors.
///
/// The returned vector is indexed by chunk index. Each inner vector
/// contains the chunk's ops in instruction order. The hot dispatch
/// loop reads from these vectors directly through `chunk_op` to
/// avoid the per-fetch discriminant match against the archived form.
///
/// The buffer's framing is validated through `Module::access_bytes`.
/// The op decoding uses `op_from_archived` for each op slot. This is
/// the same conversion that the previous hot-path fetch performed;
/// pre-decoding amortizes its cost across the VM lifetime instead of
/// paying it per fetch.
///
/// Both the owned (`AlignedVec`) and the borrowed (`&[u8]`) paths
/// route through this helper. The single source of truth for op
/// pre-decoding lives here.
/// Compute the `(low, high, flag)` outputs that the
/// `CheckedAdd` / `CheckedSub` / `CheckedMul` / `CheckedNeg`
/// dispatch pushes, given the true result `r` in `W::Wide` and
/// the bytecode's declared word width.
///
/// Semantics. The flag is `0` ok, `1` overflow, `2` underflow
/// against the declared width. The low half is sign-extended
/// truncated to the declared width through
/// [`crate::bytecode::truncate_int_to_declared_width`]; the
/// high half carries the bits above the declared low half, so
/// `r == (high << declared_bits) + low_signed_at_declared_width`
/// reproduces the true result. Both halves are interpreted as
/// signed values at the declared width.
///
/// When the bytecode-declared word width matches or exceeds the
/// runtime word width (`word_bits_log2 >= W::BITS_LOG2`), the
/// helper reduces to the runtime-width semantics: `high` becomes
/// the wide high half, `low` becomes the wide-to-narrow wrap of
/// `r`, and `flag` fires at `W::MIN` / `W::MAX`. When the
/// bytecode declares a narrower width than the runtime supports,
/// the flag fires at the declared range and the high half
/// carries the bits beyond the declared low.
fn checked_arith_outputs<W: crate::word::Word>(r: W::Wide, word_bits_log2: u8) -> (W, W, W) {
    let runtime_bits_log2 = <W as crate::word::Word>::BITS_LOG2;
    let (declared_min, declared_max, narrow) = if word_bits_log2 >= runtime_bits_log2 {
        (
            <W as crate::word::Word>::MIN.widen(),
            <W as crate::word::Word>::MAX.widen(),
            false,
        )
    } else {
        let declared_bits = 1u32 << word_bits_log2;
        let one_widened = <W as crate::word::Word>::from_i64_wrap(1).widen();
        let max = (one_widened << (declared_bits - 1)) - one_widened;
        let min = -(one_widened << (declared_bits - 1));
        (min, max, true)
    };
    let low_raw = <W as crate::word::Word>::from_wide_wrap(r);
    let low_at_declared_i64 =
        crate::bytecode::truncate_int_to_declared_width(low_raw.to_i64(), word_bits_log2);
    let low = <W as crate::word::Word>::from_i64_wrap(low_at_declared_i64);
    let high = if narrow {
        let declared_bits = 1u32 << word_bits_log2;
        let low_widened = low.widen();
        let high_wide = (r - low_widened) >> declared_bits;
        <W as crate::word::Word>::from_wide_wrap(high_wide)
    } else {
        <W as crate::word::Word>::from_wide_wrap(r.high_half())
    };
    let flag: i64 = if r >= declared_min && r <= declared_max {
        0
    } else if r > declared_max {
        1
    } else {
        2
    };
    (low, high, <W as crate::word::Word>::from_i64_wrap(flag))
}

/// Classify a checked `Fixed` result already computed in the wide
/// `i128` domain into the construct's `(low, flag)` pair: the
/// two's-complement-wrapped `Word`-width result and the outcome flag
/// `0` (ok, in range), `1` (overflow, above `i64::MAX`), or `2`
/// (underflow, below `i64::MIN`). `Fixed` always occupies the full
/// runtime word width, so the range is the runtime `Word` range with
/// no narrow-declared-width handling. Unlike `Op::FixedMul` and
/// `Op::FixedDiv`, which saturate, the checked form wraps so the
/// `overflow`/`underflow` arms observe the two's-complement result,
/// matching the wrapping default of the other checked families.
fn fixed_checked_outputs<W: crate::word::Word>(r: W::Wide) -> (W, i64) {
    let min = <W as crate::word::Word>::MIN.widen();
    let max = <W as crate::word::Word>::MAX.widen();
    let flag: i64 = if r >= min && r <= max {
        0
    } else if r > max {
        1
    } else {
        2
    };
    (<W as crate::word::Word>::from_wide_wrap(r), flag)
}

/// Classify a checked floating-point result into the construct's
/// flag: `0` ok (finite), `1` overflow (positive infinity), `2`
/// underflow (negative infinity), `4` not-a-number. The Institute of
/// Electrical and Electronics Engineers 754 operations are total, so
/// there is no zero-divisor flag (flag `3`) for floats; a division by
/// zero produces an infinity or a NaN classified here.
#[cfg(feature = "floats")]
fn float_checked_flag(rf: f64) -> i64 {
    if rf.is_nan() {
        4
    } else if rf.is_infinite() {
        if rf > 0.0 { 1 } else { 2 }
    } else {
        0
    }
}

fn decode_all_ops(bytes: &[u8]) -> Result<Vec<Vec<Op>>, VmError> {
    // V0.2.0 Phase 7c routes the per-chunk op decode through
    // the wire-format opcode stream. Each chunk's slice in the
    // stream is bounded by the WireChunk's `op_byte_offset` and
    // `op_record_count`; the records decode through the shared
    // operand pool.
    let sections = crate::wire_format::parse_wire_sections(bytes)?;
    let archived = rkyv::access::<crate::wire_format::ArchivedWireAuxBody, rkyv::rancor::Error>(
        sections.aux_body,
    )
    .map_err(|e| crate::bytecode::LoadError::Codec(alloc::format!("rkyv access failed: {}", e)))?;
    let mut all_ops: Vec<Vec<Op>> = Vec::with_capacity(archived.chunks.len());
    for chunk in archived.chunks.iter() {
        let start = chunk.op_byte_offset.to_native() as usize;
        let record_count = chunk.op_record_count.to_native() as usize;
        let byte_span = record_count
            .checked_mul(crate::wire_format::OPCODE_RECORD_BYTES)
            .ok_or_else(|| {
                crate::bytecode::LoadError::Codec(alloc::string::String::from(
                    "opcode span overflow",
                ))
            })?;
        let end = start.checked_add(byte_span).ok_or_else(|| {
            crate::bytecode::LoadError::Codec(alloc::string::String::from("opcode span overflow"))
        })?;
        if end > sections.opcode_stream.len() {
            return Err(crate::bytecode::LoadError::Codec(alloc::format!(
                "chunk opcode span [{}..{}) exceeds opcode stream length {}",
                start,
                end,
                sections.opcode_stream.len(),
            ))
            .into());
        }
        let ops = crate::wire_format::decode_op_stream(
            &sections.opcode_stream[start..end],
            sections.operand_pool,
        )?;
        all_ops.push(ops);
    }
    Ok(all_ops)
}

/// Compute the exact arena capacity (excluding the persistent `data`
/// region) that the bundled `i64`/`f64` runtime needs to construct and
/// run the given module under the supplied native attestations.
///
/// Because the runtime now pre-allocates its entire bottom-region working
/// set at construction (B28 P3 item 5, priority 1), the figure is the sum
/// of every component, each sized to the real bundled-runtime footprint:
///
/// - the operand stack, `max_operand_slots * size_of::<Value>()`;
/// - the call frames, `max_frame_depth * size_of::<CallFrame>()`;
/// - the opaque registry, `aux_arena_bytes`;
/// - the per-iteration arena heap, `max_heap_bytes`.
///
/// The operand-slot and frame-depth components are floored at the same
/// minimums the constructor applies (`MIN_STACK_RESERVE_SLOTS`,
/// `MIN_FRAMES_RESERVE`) so the reported figure exactly matches the
/// reservation the constructor makes, letting a host size its arena with
/// zero margin. A host that needs headroom (for example to call a `Func`
/// chunk whose stack exceeds the Stream worst case) is already covered:
/// the footprint is the module-wide maximum over every chunk.
///
/// **Slot width.** This entry point uses the bundled runtime's
/// `size_of::<GenericValue<i64, f64>>()`, the common case. A narrow
/// `GenericVm<W, A, F>` has a different slot width; such hosts size their
/// arena from [`verify::module_runtime_footprint`] multiplied by their own
/// `size_of::<GenericValue<W, F>>()`. Note this is *not*
/// `bytecode::VALUE_SLOT_SIZE_BYTES` (32), which under-states the real
/// 64-bit-runtime slot; the binding admission check in [`GenericVm::new`]
/// already uses the real `size_of`, so that constant governs only the
/// compile-time advisory header.
///
/// Available only when the `verify` feature is enabled because the
/// computation routes through [`verify::module_runtime_footprint`]. Hosts
/// that build without the verifier must size arenas through a build-time
/// analysis instead.
#[cfg(feature = "verify")]
pub fn auto_arena_capacity_for(
    module: &crate::bytecode::Module,
    native_wcmu: &[u32],
) -> Result<usize, VmError> {
    let footprint = verify::module_runtime_footprint(module, native_wcmu)
        .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
    let slots = (footprint.max_operand_slots as usize).max(MIN_STACK_RESERVE_SLOTS);
    let frames = (footprint.max_frame_depth as usize).max(MIN_FRAMES_RESERVE);
    let stack_bytes =
        slots.saturating_mul(core::mem::size_of::<crate::bytecode::GenericValue<i64, f64>>());
    let frame_bytes = frames.saturating_mul(core::mem::size_of::<CallFrame>());
    Ok(stack_bytes
        .saturating_add(frame_bytes)
        .saturating_add(module.aux_arena_bytes as usize)
        .saturating_add(footprint.max_heap_bytes as usize))
}

/// Bytecode storage for the VM.
///
/// `Owned` carries an `AlignedVec` produced by serializing a `Module`
/// at construction time. `Borrowed` carries a slice supplied by the
/// host through `Vm::view_bytes_unchecked` for true zero-copy
/// execution from `.rodata` or any addressable buffer.
enum BytecodeStore<'a> {
    Owned(rkyv::util::AlignedVec<8>),
    Borrowed(&'a [u8]),
}

impl<'a> BytecodeStore<'a> {
    fn as_slice(&self) -> &[u8] {
        match self {
            BytecodeStore::Owned(v) => v.as_slice(),
            BytecodeStore::Borrowed(b) => b,
        }
    }
}

/// The Keleusma virtual machine.
///
/// Two lifetime parameters. `'a` reflects the bytecode source. VMs
/// constructed from an owned `Module` or from arbitrary byte slices
/// carry `Vm<'static, 'arena>`. VMs constructed via
/// [`Vm::view_bytes_unchecked`] from a borrowed slice carry
/// `Vm<'a, 'arena>` for the slice's lifetime.
///
/// `'arena` ties the VM to a host-owned [`keleusma_arena::Arena`].
/// The host constructs the arena and passes it as a shared reference at
/// VM construction time. Dynamic strings produced during execution
/// allocate into this arena and survive until the next reset.
///
/// Reset of the arena is initiated by the VM through
/// [`keleusma_arena::Arena::reset_unchecked`] because the VM holds the
/// arena through a shared reference. The VM's internal discipline
/// guarantees no allocator-bound collection retains storage in the
/// arena at the moment of reset. Hosts that want to reset the arena
/// from outside the VM must do so when the VM is not borrowing the
/// arena, which means the VM must be dropped first or the host must
/// invoke [`Vm::reset_after_error`] which routes through the unsafe
/// path with the same safety justification.
/// Type alias for the bundled 64-bit `Vm` shape. Existing call
/// sites continue to write `Vm<'a, 'arena>`; the alias expands
/// to `GenericVm<'a, 'arena, i64, u64, f64>`. Sub-64-bit
/// runtimes use a different specialization; hosts introduce a
/// local alias for ergonomic call sites.
pub type Vm<'a, 'arena> = GenericVm<'a, 'arena, i64, u64, f64>;

/// Parametric stack-based virtual machine. The type parameters
/// model the runtime's word, address, and float widths so a host
/// can construct a narrow-width runtime (`GenericVm<i16, u16, f32>`)
/// for embedded targets. The default specialization
/// (`GenericVm<i64, u64, f64>`) is the bundled [`Vm`] alias.
pub struct GenericVm<
    'a,
    'arena,
    W: crate::word::Word = i64,
    A: crate::address::Address = u64,
    F: crate::float::Float = f64,
> {
    bytecode: BytecodeStore<'a>,
    /// Phantom marker for the script-visible address-width type
    /// parameter. No `GenericValue` variant carries an address
    /// payload, so `A` does not appear in any field directly.
    _phantom_a: core::marker::PhantomData<A>,
    /// Per-op decode cache, populated at VM construction and at every
    /// `replace_module`. Indexed as `decoded_ops[chunk_idx][ip]`.
    decoded_ops: Vec<Vec<Op>>,
    /// Operand stack. Bump-allocated from the arena's bottom region.
    stack: StackVec<'arena, crate::bytecode::GenericValue<W, F>>,
    /// Call-frame stack. Same arena-backed discipline as `stack`.
    frames: StackVec<'arena, CallFrame>,
    natives: Vec<NativeEntry<W, F>>,
    /// Number of shared slots. Cached at construction from the
    /// module's data layout. Shared slots live in the host-owned buffer
    /// borrowed for each call (B28 item 2), not in the VM. The unified slot
    /// index space partitions into `[0, shared_slot_count)` (shared) and
    /// `[shared_slot_count, shared_slot_count + private_slot_count)`
    /// (private, in the arena's persistent region).
    shared_slot_count: u16,
    /// Number of private slots. Cached at construction. Private
    /// slots live in the arena's persistent region starting at
    /// `arena.persistent_ptr()` and occupy
    /// `private_slot_count * size_of::<crate::bytecode::GenericValue<W, F>>()` bytes there.
    private_slot_count: u16,
    /// Host-owned dual-end bump-allocated arena. Borrowed for the
    /// lifetime of the VM. Native functions that allocate dynamic
    /// strings pass `vm.arena()` to [`crate::kstring::KString::alloc`].
    /// The arena's persistent region holds this module's private
    /// data slots.
    arena: &'arena keleusma_arena::Arena,
    started: bool,
    /// Host-armed breakpoint positions as `(chunk_idx, op_index)`. The
    /// run loop suspends with [`GenericVmState::BreakpointHit`] before
    /// executing an op whose position is listed. Empty by default; the
    /// per-op check is gated on `is_empty` so a program with no
    /// breakpoints pays nothing. Breakpoints are runtime debugging
    /// state, not part of the verified bytecode, so they do not affect
    /// the declared WCET or WCMU bounds.
    breakpoints: alloc::vec::Vec<(usize, usize)>,
    /// One-shot suppression of the breakpoint at this position, set by
    /// [`GenericVm::resume_from_breakpoint`] so resuming executes the
    /// op at a breakpoint rather than re-triggering it immediately.
    skip_breakpoint_at: Option<(usize, usize)>,
    /// Position `(chunk_idx, op_index)` of the op the run loop was
    /// executing when it last returned an error, or `None` after a
    /// successful run or before any run. The run loop records the
    /// current op here before dispatching it and the [`GenericVm::run`]
    /// wrapper clears it on success, so after a failed `call`/`resume`
    /// it names the faulting op. A host maps it back to source through
    /// [`GenericVm::fault_source_location`] (B29). Tracking it is a
    /// single `Option` write per op; it is runtime debugging state, not
    /// part of the verified bytecode, so it does not affect the
    /// declared WCET or WCMU bounds.
    fault_location: Option<(usize, usize)>,
    /// Cached load-time native classification check. Populated on
    /// the first `call` after natives are registered (or after
    /// `replace_module`). `None` means the check has not been run
    /// yet; `Some(Ok(()))` means the check succeeded; the error
    /// arm is surfaced at the call boundary the first time it is
    /// detected and is not re-cached, so the host can recover by
    /// re-registering natives with the correct classification.
    /// Any `register_*` method or `replace_module` resets this
    /// field to `None`.
    native_classifications_verified: bool,
    /// Registry of opaque host references reachable from ephemeral
    /// (arena-resident) flat composite bodies (B28 P3). A flat
    /// composite stores a `word_bytes` index into this Vec rather
    /// than the `Arc` itself, because `Arc<dyn HostOpaque>` is a
    /// `Drop`-bearing fat pointer that cannot be packed into the
    /// reset-without-Drop arena bytes. `RESET` clears this Vec,
    /// running each `Arc`'s `Drop` and decrementing the host
    /// refcount, which is correct because the arena bodies that hold
    /// the indices are themselves reclaimed at `RESET`. Opaques that
    /// must survive `RESET` (those reachable from `private data`) will
    /// use a separate persistent registry in a later slice.
    /// Relocated into the arena's bottom region (B28 P3 item 5, Phase C2):
    /// like the operand stack and frames, the backing survives a normal
    /// `RESET` (which reclaims only the top region) and is `clear()`ed each
    /// iteration — running each `Arc`'s `Drop` while retaining capacity, so it
    /// grows on demand to its steady-state per-iteration maximum and then no
    /// longer reallocates. No global-heap allocation; the worst-case bytes are
    /// reported through `Module::aux_arena_bytes`.
    ephemeral_opaques: StackVec<'arena, alloc::sync::Arc<dyn crate::opaque::HostOpaque>>,
    /// Pre-sized bottom-region reservations, in elements, captured at
    /// construction (B28 P3 item 5, priority 1). The operand stack and
    /// call frames are reserved to these counts up front so the runtime
    /// performs no allocation after initialisation (JPL Power-of-10
    /// rule 3); `full_reset_arena_internal` re-applies them after a
    /// rewind so the recovered VM keeps the same deterministic footprint.
    /// On the trust-skip view path the figures default to the
    /// conservative minimums because that path receives raw bytes with no
    /// `Module` to analyse.
    reserved_operand_slots: usize,
    /// Pre-sized call-frame reservation, in frames. See
    /// [`Self::reserved_operand_slots`].
    reserved_frame_depth: usize,
    /// Pre-sized opaque-registry reservation, in `Arc` elements. See
    /// [`Self::reserved_operand_slots`].
    reserved_opaque_capacity: usize,
    /// VM-owned, read-only pool of materialised scalar const-composite
    /// bodies (B28 P3 item 2, Increment 2). A transitively-scalar const
    /// composite (no string or opaque leaf) is packed once at construction
    /// into a boxed byte body here, outside the arena, and lives for the
    /// VM's lifetime. This is the const-as-rodata model: const bodies sit
    /// alongside the bytecode image, not in the arena, so they consume no
    /// arena capacity and do not enter the arena WCMU bound (the same model
    /// as a rodata `KStr` pointing into the immortal image). A boxed body's
    /// heap buffer is stable across `Vec` growth, so a handle minted into it
    /// stays valid. The `Box<[u8]>` holds plain bytes with no inner `Drop`,
    /// so the pool frees cleanly when the VM drops.
    const_pool: alloc::vec::Vec<alloc::boxed::Box<[u8]>>,
    /// Per-`(chunk, const)` cached const-composite template, indexed
    /// `const_templates[chunk_idx][const_idx]` (B28 P3 item 2, Increment 2).
    /// `Some` for a pooled scalar const composite, whose `Flat(Arena)` body
    /// points into [`Self::const_pool`]; `None` for a constant that is not a
    /// pooled composite (a scalar, a string, or a string/opaque-bearing boxed
    /// composite). `chunk_const` returns a clone of the template, which copies
    /// only the two-word arena handle, so a composite const load is
    /// allocation-free and WCET-flat.
    const_templates: alloc::vec::Vec<alloc::vec::Vec<Option<crate::bytecode::GenericValue<W, F>>>>,
    /// The host-owned shared-data buffer borrowed for the current
    /// `call`/`resume`, or inactive (B28 item 2 shared-data
    /// re-architecture). Set at the top of `call_with_shared`/
    /// `resume_with_shared` from the `&mut [u8]` argument and cleared before
    /// the entry point returns; a shared-slot access reads or writes the host
    /// buffer through it when active, and falls back to the slot `data` vector
    /// when inactive (the coexistence path for `set_data`-based hosts). All
    /// raw-pointer unsafety is confined to [`crate::shared_buf::SharedBuf`].
    shared_buf: crate::shared_buf::SharedBuf,
    /// Host-supplied trust matrix for cryptographic module
    /// signatures. Populated through
    /// [`Self::register_verifying_key`] before the host hot-swaps
    /// a signed module via
    /// [`Self::replace_module_from_bytes`]. Empty by default; an
    /// empty matrix rejects every signed module with
    /// [`crate::bytecode::LoadError::InvalidSignature`]. Gated on
    /// the `signatures` cargo feature; builds without it carry no
    /// trust matrix at all.
    #[cfg(feature = "signatures")]
    verifying_keys: Vec<ed25519_dalek::VerifyingKey>,
}

/// Compute the arena persistent-capacity needed to back a
/// module's private data segment.
///
/// Hosts call this to size a pool arena before constructing the
/// VM:
///
/// ```text
/// let needed = required_persistent_capacity_for(&module);
/// arena.resize_persistent(needed)?;
/// let vm = Vm::new(module, &arena)?;
/// ```
///
/// The returned value is `private_slot_count * size_of::<crate::bytecode::GenericValue<W, F>>()`,
/// which is the actual runtime storage requirement. It differs
/// from `module.private_data_bytes` because that field is in
/// `VALUE_SLOT_SIZE_BYTES`-sized logical units for WCMU
/// accounting; the actual `Value` enum is larger than the WCMU
/// slot size by an implementation-defined factor.
pub fn required_persistent_capacity_for(module: &crate::bytecode::Module) -> usize {
    required_persistent_capacity_for_generic::<i64, f64>(module)
}

/// Generic counterpart sized against the host's specific
/// `GenericValue<W, F>` storage requirement.
pub fn required_persistent_capacity_for_generic<W: crate::word::Word, F: crate::float::Float>(
    module: &crate::bytecode::Module,
) -> usize {
    let private_count = module.data_layout.as_ref().map_or(0, |dl| {
        dl.slots
            .iter()
            .filter(|s| matches!(s.visibility, crate::bytecode::SlotVisibility::Private))
            .count()
    });
    // The private-slot `Value` array, plus the persistent flat-composite body
    // pool those slots need (B28 P3 item 5, item 3a). A private slot holding a
    // flat composite stores its body in the pool, which follows the slot array
    // in the persistent region and survives RESET in place. `0` for a module
    // with no private composite slots, so this is unchanged for such modules.
    private_count * core::mem::size_of::<crate::bytecode::GenericValue<W, F>>()
        + module.persistent_composite_bytes as usize
}

/// Flat byte length of the borrowed shared-data buffer `module` expects
/// (B28 item 2), without constructing the VM first.
///
/// An embedder uses this to pre-size the host-owned `&mut [u8]` it lends to
/// [`GenericVm::call_with_shared`], for example to allocate the buffer before
/// the arena and VM exist. Matches [`GenericVm::shared_data_bytes`] for a VM
/// built from the same module.
pub fn shared_data_bytes_for(module: &crate::bytecode::Module) -> usize {
    module.shared_data_bytes as usize
}

impl<'a, 'arena, W: crate::word::Word, A: crate::address::Address, F: crate::float::Float> Drop
    for GenericVm<'a, 'arena, W, A, F>
{
    /// Drop the `Value` instances stored in the arena's
    /// persistent region. The arena itself is host-owned and
    /// outlives the VM; without this drop, every private slot's
    /// owned contents (heap-allocated strings, vectors,
    /// reference counts) would leak when the VM is dropped.
    ///
    /// The arena's persistent capacity is left unchanged because
    /// the host may want to reassign the same arena to another
    /// VM; calling `Arena::resize_persistent` is the host's
    /// choice.
    fn drop(&mut self) {
        if self.private_slot_count == 0 {
            return;
        }
        let base = self.arena.persistent_ptr().as_ptr() as *mut crate::bytecode::GenericValue<W, F>;
        for i in 0..self.private_slot_count as usize {
            // SAFETY: each private slot was initialised to
            // `crate::bytecode::GenericValue::Unit` at construction and updated through
            // `write_data_slot` (which drops the old occupant
            // and writes a new value). At drop time every slot
            // therefore holds a valid `Value` that needs its
            // destructor run.
            unsafe {
                core::ptr::drop_in_place(base.add(i));
            }
        }
    }
}

impl<'a, 'arena, W: crate::word::Word, A: crate::address::Address, F: crate::float::Float>
    GenericVm<'a, 'arena, W, A, F>
{
    /// Borrow the archived auxiliary body from internal bytecode storage.
    ///
    /// V0.2.0 Phase 7c routes the lookup through the section-
    /// partitioned wire format. The opcode stream and operand
    /// pool sections are not consulted here; consumers of
    /// per-chunk ops use `self.decoded_ops` which was populated
    /// once at construction time. The aux body section starts
    /// at an 8-byte aligned offset declared in the framing
    /// header. The bytes were validated at construction time,
    /// so `access_unchecked` is sound here.
    fn archived(&self) -> &crate::wire_format::ArchivedWireAuxBody {
        let bytes = self.bytecode.as_slice();
        let aux_body_offset =
            u32::from_le_bytes([bytes[48], bytes[49], bytes[50], bytes[51]]) as usize;
        let aux_body_length =
            u32::from_le_bytes([bytes[52], bytes[53], bytes[54], bytes[55]]) as usize;
        let aux = &bytes[aux_body_offset..aux_body_offset + aux_body_length];
        unsafe { rkyv::access_unchecked::<crate::wire_format::ArchivedWireAuxBody>(aux) }
    }

    /// Deserialize the current bytecode to an owned `Module`.
    ///
    /// Used by cold-path methods such as resource-bounds re-verification
    /// and auto-arena-capacity computation that operate on owned
    /// `Module` values. The hot execution path uses `archived` directly.
    /// Available only when the `verify` feature is enabled because all
    /// current callers are themselves gated behind that feature.
    #[cfg(feature = "verify")]
    fn module_owned(&self) -> Result<Module, VmError> {
        Ok(Module::from_bytes(self.bytecode.as_slice())?)
    }

    /// Read the op at `(chunk_idx, ip)` from the per-op decode cache
    /// populated at VM construction. The hot dispatch loop calls this
    /// per fetch, so the implementation is a direct slice index. The
    /// archived form is no longer consulted on the hot path.
    fn chunk_op(&self, chunk_idx: usize, ip: usize) -> Op {
        self.decoded_ops[chunk_idx][ip]
    }

    /// Materialize the constant at `(chunk_idx, idx)` from archived storage.
    fn chunk_const(&self, chunk_idx: usize, idx: usize) -> crate::bytecode::GenericValue<W, F> {
        let chunk = &self.archived().chunks[chunk_idx];
        // A non-empty top-level string constant loads as a rodata-backed `KStr`
        // pointing directly at the immortal bytecode image, not an owned
        // `StaticStr` heap copy (B28 P3 item 4). This is zero-copy (no per-load
        // allocation) and WCET-flat (no construction-time scan), the 6502/NES
        // "bake the ROM address" model. An empty string returns an owned empty
        // `StaticStr`, both to avoid resting on the non-null guarantee of the
        // archived empty-string pointer and because an empty body needs no
        // handle. A composite constant that contains strings still materialises
        // through `value_from_archived` below; its string leaves become owned
        // `StaticStr` there, which the flat packer copies into the arena as a
        // genuinely-owned (host-like) string.
        if let crate::bytecode::ArchivedConstValue::StaticStr(s) = &chunk.constants[idx] {
            let bytes = s.as_str().as_bytes();
            if bytes.is_empty() {
                return crate::bytecode::GenericValue::StaticStr(alloc::string::String::new());
            }
            let addr = bytes.as_ptr() as usize;
            let len = bytes.len();
            // SAFETY: `addr` addresses `len` valid UTF-8 bytes inside
            // `self.bytecode`, the immortal bytecode image the VM owns for its
            // whole lifetime and which only a hot swap replaces. The bytes are
            // read-only and the handle is never written through. The address
            // lies outside the arena's ephemeral region, so `addr_is_live`
            // short-circuits to true regardless of epoch and the handle never
            // goes stale; a sentinel zero epoch documents that this is
            // epoch-independent rodata. A hot swap reallocates the image, but
            // `replace_module_inner` clears the operand stack and frames and
            // zeroes the persistent composite pool before the new image is
            // read, so no `KStr` minted against the old image survives a swap.
            let ks = unsafe { crate::kstring::KString::from_raw_parts(addr, len, 0) };
            return crate::bytecode::GenericValue::KStr(ks);
        }
        // A pooled scalar const composite returns a clone of its cached
        // template, whose flat body points into the VM-owned const pool (B28
        // P3 item 2, Increment 2). The clone copies only the two-word arena
        // handle, so the load is allocation-free and WCET-flat; the body bytes
        // live once in the pool for the VM's lifetime. A constant that was not
        // pooled (a scalar, a string, or a string/opaque-bearing boxed
        // composite) falls through to direct materialisation below.
        if let Some(Some(template)) = self
            .const_templates
            .get(chunk_idx)
            .and_then(|row| row.get(idx))
        {
            return template.clone();
        }
        // Materialise constants at the module-declared scalar widths so a
        // constant tuple's flat body matches the offsets the compiler
        // baked into its access instructions (B28 P2).
        crate::bytecode::value_from_archived(
            &chunk.constants[idx],
            self.module_word_bytes(),
            self.module_float_bytes(),
        )
    }

    /// Number of ops in the chunk. V0.2.0 Phase 7c reads the
    /// count from the WireChunk's `op_record_count` rather than
    /// the no-longer-present `ops` vector; the ops themselves
    /// live in the opcode stream section.
    fn chunk_op_count(&self, chunk_idx: usize) -> usize {
        self.archived().chunks[chunk_idx]
            .op_record_count
            .to_native() as usize
    }

    /// Local-variable slot count for the chunk (includes parameters).
    fn chunk_local_count(&self, chunk_idx: usize) -> u16 {
        self.archived().chunks[chunk_idx].local_count.to_native()
    }

    /// Module-wide word-width exponent. Used by the checked-
    /// arithmetic dispatch to apply narrow-width truncation to the
    /// `low` result when the bytecode declares a word size smaller
    /// than the runtime supports (cross-architecture portability).
    fn word_bits_log2(&self) -> u8 {
        self.archived().word_bits_log2
    }

    /// Module-declared word width in bytes. Used by the B28 flat
    /// composite handlers to pack and read scalar fields at the same
    /// width the compiler baked offsets against, so the runtime and
    /// the artefact agree regardless of the runtime `Word` width.
    fn module_word_bytes(&self) -> usize {
        (1usize << self.archived().word_bits_log2) / 8
    }

    /// Module-declared float width in bytes. The companion of
    /// [`Self::module_word_bytes`] for floating-point fields.
    fn module_float_bytes(&self) -> usize {
        (1usize << self.archived().float_bits_log2) / 8
    }

    /// The discriminant and padded-body payload size for `variant` of enum
    /// `type_name`, from the module's [`crate::bytecode::EnumLayout`] table
    /// (B37 / audit finding 25 follow-up), or `None` when the module declares no
    /// such enum (a built-in like `Option`, or a host type absent from the
    /// program's enums).
    fn enum_variant_layout(&self, type_name: &str, variant: &str) -> Option<(i64, usize)> {
        for el in self.archived().enum_layouts.iter() {
            if el.type_name.as_str() == type_name {
                let min_payload = el.min_payload.to_native() as usize;
                let disc = el
                    .variants
                    .iter()
                    .find(|v| v.name.as_str() == variant)
                    .map(|v| v.disc.to_native())
                    .unwrap_or(0);
                return Some((disc, min_payload));
            }
        }
        None
    }

    /// Make a host-supplied value's boxed enums type-driven before flattening
    /// (B37 / audit finding 25 follow-up).
    ///
    /// An unsignatured native builds a boxed enum with the arena-less
    /// [`crate::bytecode::EnumBody::boxed`], which defaults the discriminant to
    /// `0` and records no padding, so flattening it against the compiler's baked
    /// flat access silently misreads a non-first, non-largest variant. Here each
    /// boxed enum's discriminant and padding are corrected from the module's
    /// `enum_layouts`, the way a script-built or signatured-native value already
    /// carries them, so the discriminant is derived from the type rather than
    /// asserted by the caller. Recurses through boxed composite bodies; a flat
    /// body is already correct bytes and is returned unchanged, as is a scalar.
    ///
    /// An enum absent from the table (a built-in `Option`, whose boxed hints the
    /// marshalling layer already sets) keeps its existing hints rather than
    /// having them reset, so this pass never degrades a correctly-built value.
    fn correct_native_enum_hints(
        &self,
        v: crate::bytecode::GenericValue<W, F>,
    ) -> crate::bytecode::GenericValue<W, F> {
        use crate::bytecode::{
            ArrayBody, BoxedEnum, BoxedStruct, EnumBody, GenericValue as G, StructBody, TupleBody,
        };
        match v {
            G::Tuple(TupleBody::Boxed(items)) => G::Tuple(TupleBody::boxed(
                items
                    .into_iter()
                    .map(|e| self.correct_native_enum_hints(e))
                    .collect(),
            )),
            G::Array(ArrayBody::Boxed(items)) => G::Array(ArrayBody::boxed(
                items
                    .into_iter()
                    .map(|e| self.correct_native_enum_hints(e))
                    .collect(),
            )),
            G::Struct(StructBody::Boxed(b)) => {
                let BoxedStruct { type_name, fields } = *b;
                G::Struct(StructBody::boxed(
                    type_name,
                    fields
                        .into_iter()
                        .map(|(k, val)| (k, self.correct_native_enum_hints(val)))
                        .collect(),
                ))
            }
            G::Enum(EnumBody::Boxed(b)) => {
                let BoxedEnum {
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields,
                } = *b;
                let fields: alloc::vec::Vec<_> = fields
                    .into_iter()
                    .map(|f| self.correct_native_enum_hints(f))
                    .collect();
                // Correct from the type table when the enum is known; otherwise
                // preserve the value's own hints (do not reset to `boxed`, which
                // would clobber a correctly-set discriminant such as
                // `Option::Some == 1`).
                let (disc, min_payload) = self
                    .enum_variant_layout(&type_name, &variant)
                    .unwrap_or((disc, min_payload));
                G::Enum(EnumBody::boxed_with_layout(
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields,
                ))
            }
            other => other,
        }
    }

    /// Test whether a chunk index is in range.
    fn chunk_count(&self) -> usize {
        self.archived().chunks.len()
    }

    /// Look up a native function name by index. Returns `None` if out of bounds.
    fn native_name(&self, idx: usize) -> Option<alloc::string::String> {
        use alloc::string::ToString;
        self.archived()
            .native_names
            .get(idx)
            .map(|s| s.as_str().to_string())
    }

    /// Read a string-typed constant. Returns `None` if not a string.
    fn chunk_const_str(&self, chunk_idx: usize, idx: usize) -> Option<alloc::string::String> {
        use alloc::string::ToString;
        let chunk = &self.archived().chunks[chunk_idx];
        match &chunk.constants[idx] {
            crate::bytecode::ArchivedConstValue::StaticStr(s) => Some(s.as_str().to_string()),
            _ => None,
        }
    }

    /// Look up a struct template's type name and field names.
    fn struct_template(
        &self,
        chunk_idx: usize,
        idx: usize,
    ) -> (
        alloc::string::String,
        alloc::vec::Vec<alloc::string::String>,
    ) {
        use alloc::string::ToString;
        let template = &self.archived().chunks[chunk_idx].struct_templates[idx];
        let type_name = template.type_name.as_str().to_string();
        let field_names: alloc::vec::Vec<_> = template
            .field_names
            .iter()
            .map(|s| s.as_str().to_string())
            .collect();
        (type_name, field_names)
    }
}

impl<'a, 'arena, W: crate::word::Word, A: crate::address::Address, F: crate::float::Float>
    GenericVm<'a, 'arena, W, A, F>
{
    /// Create a new VM with the given compiled module and a host-owned
    /// arena.
    ///
    /// The arena's capacity must accommodate the module's worst-case
    /// memory usage. The host typically sizes the arena via
    /// [`auto_arena_capacity_for`] before constructing the VM. Runs
    /// structural verification on the module and resource bounds
    /// verification against the arena's capacity. Returns an error if
    /// either check fails.
    ///
    /// Gated behind the `verify` feature (audit finding 22): without it there
    /// is no verifier to run, so a no-verify host must construct through the
    /// explicitly `unsafe` [`Vm::new_unchecked`] rather than receive an
    /// unverified VM through a safe constructor.
    #[cfg(feature = "verify")]
    pub fn new(module: Module, arena: &'arena keleusma_arena::Arena) -> Result<Self, VmError> {
        let (vm, _warnings) = Self::new_with_options(module, arena, VmOptions::default())?;
        Ok(vm)
    }

    /// Create a new VM with explicit construction-time options.
    ///
    /// Same admissibility checks as [`Vm::new`] (structural
    /// verification followed by the resource-bounds check against the
    /// arena capacity), plus a configurable overflow policy that
    /// decides what to do when the module's declared WCET or WCMU
    /// header fields saturated to `u32::MAX` during compilation. The
    /// default policy ([`OverflowPolicy::Reject`]) treats overflow as
    /// a `VerifyError`, matching the historic behaviour of `Vm::new`.
    /// Hosts that wish to admit overflow-saturated modules can supply
    /// [`OverflowPolicy::Warn`] to receive a [`VerifyWarning`] for
    /// each overflowing field, or [`OverflowPolicy::Allow`] to admit
    /// the module silently.
    ///
    /// Returns the constructed VM together with a vector of warnings.
    /// Under the default policy the vector is always empty because
    /// the function returns `Err` before reaching the construction
    /// step on overflow.
    #[cfg(feature = "verify")]
    pub fn new_with_options(
        module: Module,
        arena: &'arena keleusma_arena::Arena,
        options: VmOptions,
    ) -> Result<(Self, Vec<VerifyWarning>), VmError> {
        let mut module = module;
        let mut warnings: Vec<VerifyWarning> = Vec::new();
        // R1. The module must declare an entry point. The compiler sets
        // `entry_point` from the `main` function. Detecting absence
        // here gives a clear `VerifyError` at the API boundary instead
        // of deferring the failure to the first `Vm::call`, which
        // would otherwise surface as `InvalidBytecode("no entry
        // point")` at the first use site.
        if module.entry_point.is_none() {
            return Err(VmError::VerifyError(String::from(
                "module has no entry point: declare a `fn main`, `yield main`, or `loop main`",
            )));
        }
        // Signed modules cannot be loaded through `Vm::new` because
        // the Module representation has already lost the signature
        // payload. Hosts use [`Vm::load_signed_bytes`] for an
        // initial signed load, or hot-swap signed bytes onto an
        // existing VM through
        // [`Vm::replace_module_from_bytes`]. The `Vm::new_unchecked`
        // path bypasses this check (and every other verification).
        if (module.flags & crate::wire_format::FLAG_REQUIRES_SIGNATURE) != 0 {
            return Err(VmError::VerifyError(String::from(
                "module declares FLAG_REQUIRES_SIGNATURE; load through Vm::load_signed_bytes or hot-swap via Vm::replace_module_from_bytes",
            )));
        }
        if module.wcet_cycles == u32::MAX {
            let message = String::from(
                "module declared WCET (cycles) overflowed to u32::MAX during compilation; the static analysis could not bound the cost",
            );
            match options.overflow_policy {
                OverflowPolicy::Reject => return Err(VmError::VerifyError(message)),
                OverflowPolicy::Warn => {
                    warnings.push(VerifyWarning {
                        message,
                        kind: WarningKind::WcetOverflow,
                    });
                    // Rewrite the declared field to the auto-compute
                    // sentinel so the downstream serializer and the
                    // load-time overflow check in `Module::access_bytes`
                    // do not re-reject the module. The warning preserves
                    // the original overflow signal for the host.
                    module.wcet_cycles = 0;
                }
                OverflowPolicy::Allow => {
                    module.wcet_cycles = 0;
                }
            }
        }
        if module.wcmu_bytes == u32::MAX {
            let message = String::from(
                "module declared WCMU (bytes) overflowed to u32::MAX during compilation; the static analysis could not bound the cost",
            );
            match options.overflow_policy {
                OverflowPolicy::Reject => return Err(VmError::VerifyError(message)),
                OverflowPolicy::Warn => {
                    warnings.push(VerifyWarning {
                        message,
                        kind: WarningKind::WcmuOverflow,
                    });
                    module.wcmu_bytes = 0;
                }
                OverflowPolicy::Allow => {
                    module.wcmu_bytes = 0;
                }
            }
        }
        // Structural verification and resource-bound verification.
        // Gated behind the `verify` feature; when the feature is
        // off, `Vm::new_with_options` behaves like
        // `Vm::new_unchecked` from the caller's perspective.
        #[cfg(feature = "verify")]
        {
            verify::verify(&module)
                .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
            // R31. Verify worst-case memory usage fits within the
            // arena. The check is sound for programs without calls
            // and without variable-iteration loops. See
            // `verify_resource_bounds` for current limitations.
            //
            // B16 step 11: parametric runtimes pass the runtime's
            // actual `size_of::<GenericValue<W, F>>()` as the
            // bytes-per-slot multiplier so the bound matches the
            // narrow runtime's footprint rather than the default
            // 32-byte 64-bit-runtime conservative bound.
            let value_slot_bytes =
                core::mem::size_of::<crate::bytecode::GenericValue<W, F>>() as u32;
            verify::verify_resource_bounds_with_natives_and_value_slot_bytes(
                &module,
                arena.capacity(),
                &[],
                value_slot_bytes,
            )
            .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
        }
        let vm = Self::construct(module, arena)?;
        Ok((vm, warnings))
    }

    /// Create a VM that runs structural verification but skips WCET and
    /// WCMU resource bounds checks.
    ///
    /// Intended for hosts that load precompiled bytecode from a trusted
    /// source where the resource bounds were validated during the
    /// build pipeline rather than at load time. Skipping the bounds
    /// check shifts the bounded-memory and bounded-step guarantees onto
    /// the host's attestation that the bytecode was admitted by an
    /// equivalent verification step previously.
    ///
    /// Structural verification still runs because the VM execution loop
    /// relies on its invariants for memory safety. Specifically, block
    /// nesting depth, jump offset bounds, and the productivity rule
    /// must hold for the VM to step the bytecode without dereferencing
    /// invalid frame state.
    ///
    /// # Safety
    ///
    /// The caller attests that the bytecode was produced by a trusted
    /// compiler and that resource bounds were verified during the build
    /// pipeline, or that the host accepts the consequences of running
    /// bytecode whose worst-case stack and heap usage may exceed the
    /// arena capacity. Exceeding the bound at runtime produces an
    /// allocation failure error from the arena rather than memory
    /// unsafety, so the unsafe marker captures the loss of the
    /// bounded-memory contract rather than a memory-safety risk.
    pub unsafe fn new_unchecked(
        module: Module,
        arena: &'arena keleusma_arena::Arena,
    ) -> Result<Self, VmError> {
        if module.entry_point.is_none() {
            return Err(VmError::VerifyError(String::from(
                "module has no entry point: declare a `fn main`, `yield main`, or `loop main`",
            )));
        }
        // Structural verification is retained even in
        // `new_unchecked` because the VM execution loop relies on
        // its invariants (block nesting depth, jump bounds,
        // productivity rule) for memory safety. Gated behind
        // `verify` because the verifier itself is. With the
        // feature off the host attests the bytecode's structural
        // soundness through a build-time verification step.
        #[cfg(feature = "verify")]
        verify::verify(&module)
            .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
        Self::construct(module, arena)
    }

    /// Load and verify a module from a serialized byte slice.
    ///
    /// Convenience wrapper around [`Vm::new`]. The byte slice may
    /// originate from any addressable buffer including a file read,
    /// an in-memory `Vec<u8>`, or a `&'static [u8]` placed in
    /// `.rodata`. Runs full verification including resource bounds.
    #[cfg(feature = "verify")]
    pub fn load_bytes(bytes: &[u8], arena: &'arena keleusma_arena::Arena) -> Result<Self, VmError> {
        // Signed bytecode requires either the `signatures` cargo
        // feature plus a trust matrix (use `Vm::load_signed_bytes`)
        // or a build that explicitly skips verification (use
        // `Vm::load_bytes_unchecked`). Without the feature, surface
        // a dedicated `LoadError::SignaturesUnsupported` so the
        // operator sees an actionable diagnostic instead of the
        // generic "FLAG_REQUIRES_SIGNATURE" message that `Vm::new`
        // would otherwise produce.
        if crate::wire_format::header_requires_signature(bytes) {
            #[cfg(not(feature = "signatures"))]
            return Err(VmError::from(
                crate::bytecode::LoadError::SignaturesUnsupported,
            ));
            #[cfg(feature = "signatures")]
            return Err(VmError::from(crate::bytecode::LoadError::Codec(
                String::from(
                    "bytecode is signed; load through Vm::load_signed_bytes with a trust matrix",
                ),
            )));
        }
        let module = Module::from_bytes(bytes)?;
        Self::new(module, arena)
    }

    /// Load a signed module from serialized bytecode bytes,
    /// verifying the cryptographic signature against the supplied
    /// trust matrix before construction.
    ///
    /// Use this entry point for the initial load of a signed
    /// module. Hosts that bootstrap from an unsigned stub and
    /// later hot-swap to signed modules use
    /// [`Self::register_verifying_key`] followed by
    /// [`Self::replace_module_from_bytes`] instead.
    ///
    /// When the bytecode is unsigned and the trust matrix is non-empty,
    /// the module is rejected with
    /// [`crate::bytecode::LoadError::InvalidSignature`]: a host that
    /// supplies verifying keys requires signed execution, so enforcement
    /// is a property of host policy, not of the artefact's self-asserted
    /// flag bit (V0.2.1 security audit, finding 9). When the trust matrix
    /// is empty, an unsigned module loads like [`Self::load_bytes`]. When
    /// the bytecode is signed, the signature is verified through
    /// [`crate::wire_format::verify_module_signature`] against
    /// every key in `verifying_keys`. The first matching key
    /// admits the module; no match produces
    /// [`crate::bytecode::LoadError::InvalidSignature`]. The
    /// trust matrix is also copied onto the constructed VM so a
    /// subsequent hot-swap through
    /// [`Self::replace_module_from_bytes`] inherits the same
    /// keys.
    ///
    /// Requires the `signatures` cargo feature.
    #[cfg(all(feature = "signatures", feature = "verify"))]
    pub fn load_signed_bytes(
        bytes: &[u8],
        arena: &'arena keleusma_arena::Arena,
        verifying_keys: &[ed25519_dalek::VerifyingKey],
    ) -> Result<Self, VmError> {
        let signed = crate::wire_format::header_requires_signature(bytes);
        if signed {
            crate::wire_format::verify_module_signature(bytes, verifying_keys)
                .map_err(VmError::from)?;
        } else if !verifying_keys.is_empty() {
            // Finding 9 (V0.2.1 security audit): signature enforcement is a
            // host-policy decision, not a property of the self-asserted
            // FLAG_REQUIRES_SIGNATURE bit. A non-empty trust matrix means the
            // host requires signed execution, so an unsigned module -- which
            // an adversary forges by clearing the flag bit and recomputing the
            // CRC32 trailer -- is rejected rather than loaded.
            return Err(VmError::from(crate::bytecode::LoadError::InvalidSignature));
        }
        let mut module = Module::from_bytes(bytes).map_err(VmError::from)?;
        // The signed-module gate in `Vm::new_with_options` would
        // otherwise reject the verified module. Clear the flag
        // before construction; the trust matrix on the VM
        // perpetuates the host's policy for subsequent hot-swaps.
        let was_signed = (module.flags & crate::wire_format::FLAG_REQUIRES_SIGNATURE) != 0;
        if was_signed {
            module.flags &= !crate::wire_format::FLAG_REQUIRES_SIGNATURE;
        }
        let mut vm = Self::new(module, arena)?;
        for key in verifying_keys {
            vm.verifying_keys.push(*key);
        }
        Ok(vm)
    }

    /// Load a signed module and skip resource-bounds verification.
    ///
    /// The Ed25519 signature is still verified against `verifying_keys`
    /// under the same host policy as [`Vm::load_signed_bytes`] (a non-empty
    /// trust matrix requires a valid signature); only the worst-case
    /// resource-bounds check is skipped. This is the no-verify counterpart
    /// to `load_signed_bytes` (audit finding 22): a host built without the
    /// `verify` feature can still load signed bytecode while acknowledging
    /// the dropped bound through the `unsafe` marker.
    ///
    /// # Safety
    ///
    /// Same contract as [`Vm::new_unchecked`]: the host attests that the
    /// bytecode's worst-case stack and heap usage fit the arena, because the
    /// resource-bounds analysis is not run. Structural verification still
    /// runs when the `verify` feature is compiled in.
    #[cfg(feature = "signatures")]
    pub unsafe fn load_signed_bytes_unchecked(
        bytes: &[u8],
        arena: &'arena keleusma_arena::Arena,
        verifying_keys: &[ed25519_dalek::VerifyingKey],
    ) -> Result<Self, VmError> {
        let signed = crate::wire_format::header_requires_signature(bytes);
        if signed {
            crate::wire_format::verify_module_signature(bytes, verifying_keys)
                .map_err(VmError::from)?;
        } else if !verifying_keys.is_empty() {
            return Err(VmError::from(crate::bytecode::LoadError::InvalidSignature));
        }
        let mut module = Module::from_bytes(bytes).map_err(VmError::from)?;
        let was_signed = (module.flags & crate::wire_format::FLAG_REQUIRES_SIGNATURE) != 0;
        if was_signed {
            module.flags &= !crate::wire_format::FLAG_REQUIRES_SIGNATURE;
        }
        let mut vm = unsafe { Self::new_unchecked(module, arena) }?;
        for key in verifying_keys {
            vm.verifying_keys.push(*key);
        }
        Ok(vm)
    }

    /// Load a signed-and-encrypted module from a serialized byte
    /// slice. Verifies the Ed25519 signature, decrypts the body
    /// using the supplied X25519 private key, runs structural and
    /// resource-bounds verification on the decrypted plaintext,
    /// and constructs the VM.
    ///
    /// The signature is verified BEFORE decryption to authenticate
    /// origin before any decryption work runs. The signature
    /// covers the encrypted body, so an adversary cannot strip
    /// encryption and substitute cleartext while preserving
    /// signature validity.
    ///
    /// The `recipient_key_id` in the encryption metadata is checked
    /// against the SHA-256 of the local public key. Artefacts
    /// intended for a different recipient are rejected before
    /// expensive cryptographic operations.
    ///
    /// The trust matrix is also copied onto the constructed VM so
    /// a subsequent hot-swap through
    /// [`Self::replace_module_from_bytes`] inherits the same keys.
    ///
    /// Requires both the `signatures` and `encryption` cargo features.
    #[cfg(all(feature = "signatures", feature = "encryption", feature = "verify"))]
    pub fn load_encrypted_signed_bytes(
        bytes: &[u8],
        arena: &'arena keleusma_arena::Arena,
        verifying_keys: &[ed25519_dalek::VerifyingKey],
        decryption_key: &[u8; crate::encryption::X25519_PRIVATE_KEY_LEN],
    ) -> Result<Self, VmError> {
        let encrypted = crate::wire_format::header_requires_encryption(bytes);
        if !encrypted {
            return Err(VmError::from(crate::bytecode::LoadError::Codec(
                alloc::string::String::from(
                    "load_encrypted_signed_bytes called on bytes without FLAG_ENCRYPTED",
                ),
            )));
        }
        // Decrypt to a reconstructed signed-only buffer. This
        // function verifies the signature internally before
        // attempting decryption, so the caller does not need to
        // call verify_module_signature separately.
        let signed_buf = crate::wire_format::decrypt_encrypted_signed_to_signed_bytes(
            bytes,
            verifying_keys,
            decryption_key,
        )
        .map_err(VmError::from)?;
        // The reconstructed buffer has the signed-only flag still
        // set but is functionally equivalent to a never-encrypted
        // signed module. Parse and load through the existing path
        // which clears the signed-only flag before construction.
        let mut module = Module::from_bytes(&signed_buf).map_err(VmError::from)?;
        let was_signed = (module.flags & crate::wire_format::FLAG_REQUIRES_SIGNATURE) != 0;
        if was_signed {
            module.flags &= !crate::wire_format::FLAG_REQUIRES_SIGNATURE;
        }
        let mut vm = Self::new(module, arena)?;
        for key in verifying_keys {
            vm.verifying_keys.push(*key);
        }
        Ok(vm)
    }

    /// Load a signed-and-encrypted module and skip resource-bounds
    /// verification.
    ///
    /// The no-verify counterpart to [`Vm::load_encrypted_signed_bytes`]
    /// (audit finding 22): the Ed25519 signature is verified and the body
    /// decrypted exactly as in the checked path; only the worst-case
    /// resource-bounds check is skipped, which the `unsafe` marker records.
    ///
    /// Requires both the `signatures` and `encryption` cargo features.
    ///
    /// # Safety
    ///
    /// Same contract as [`Vm::new_unchecked`].
    #[cfg(all(feature = "signatures", feature = "encryption"))]
    pub unsafe fn load_encrypted_signed_bytes_unchecked(
        bytes: &[u8],
        arena: &'arena keleusma_arena::Arena,
        verifying_keys: &[ed25519_dalek::VerifyingKey],
        decryption_key: &[u8; crate::encryption::X25519_PRIVATE_KEY_LEN],
    ) -> Result<Self, VmError> {
        let encrypted = crate::wire_format::header_requires_encryption(bytes);
        if !encrypted {
            return Err(VmError::from(crate::bytecode::LoadError::Codec(
                alloc::string::String::from(
                    "load_encrypted_signed_bytes_unchecked called on bytes without FLAG_ENCRYPTED",
                ),
            )));
        }
        let signed_buf = crate::wire_format::decrypt_encrypted_signed_to_signed_bytes(
            bytes,
            verifying_keys,
            decryption_key,
        )
        .map_err(VmError::from)?;
        let mut module = Module::from_bytes(&signed_buf).map_err(VmError::from)?;
        let was_signed = (module.flags & crate::wire_format::FLAG_REQUIRES_SIGNATURE) != 0;
        if was_signed {
            module.flags &= !crate::wire_format::FLAG_REQUIRES_SIGNATURE;
        }
        let mut vm = unsafe { Self::new_unchecked(module, arena) }?;
        for key in verifying_keys {
            vm.verifying_keys.push(*key);
        }
        Ok(vm)
    }

    /// Load a module from a serialized byte slice and skip resource
    /// bounds verification.
    ///
    /// Convenience wrapper around [`Vm::new_unchecked`].
    ///
    /// # Safety
    ///
    /// Same contract as [`Vm::new_unchecked`].
    pub unsafe fn load_bytes_unchecked(
        bytes: &[u8],
        arena: &'arena keleusma_arena::Arena,
    ) -> Result<Self, VmError> {
        let module = Module::from_bytes(bytes)?;
        unsafe { Self::new_unchecked(module, arena) }
    }

    /// Load a module from an aligned byte slice and run full verification.
    ///
    /// The body of the framed bytecode must be 8-byte aligned within the
    /// slice. The runtime validates the framing in place via
    /// [`Module::access_bytes`] and deserializes the archived form via
    /// `rkyv::deserialize`. Compared to [`Vm::load_bytes`], this path
    /// skips the body copy that arbitrary unaligned slices require.
    ///
    /// Hosts that wish to execute bytecode directly from `.rodata` or
    /// from a flash region typically arrange alignment through linker
    /// scripts or by wrapping the buffer in `rkyv::util::AlignedVec`.
    /// See the documentation on [`Module::access_bytes`] for the
    /// alignment contract.
    ///
    /// True zero-copy execution against `&ArchivedModule` is the next
    /// iteration of P10. The current view path delivers in-place
    /// validation. The execution loop continues to operate on the
    /// deserialized owned `Module`.
    #[cfg(feature = "verify")]
    pub fn view_bytes(bytes: &[u8], arena: &'arena keleusma_arena::Arena) -> Result<Self, VmError> {
        let module = Module::view_bytes(bytes)?;
        Self::new(module, arena)
    }

    /// Load a module from an aligned byte slice and skip resource
    /// bounds verification.
    ///
    /// Convenience wrapper around [`Vm::new_unchecked`].
    ///
    /// # Safety
    ///
    /// Same contract as [`Vm::new_unchecked`].
    pub unsafe fn view_bytes_unchecked(
        bytes: &[u8],
        arena: &'arena keleusma_arena::Arena,
    ) -> Result<Self, VmError> {
        let module = Module::view_bytes(bytes)?;
        unsafe { Self::new_unchecked(module, arena) }
    }

    /// Construct a VM that borrows bytecode directly from `bytes` without
    /// any deserialization. True zero-copy execution.
    ///
    /// Validates the framing through [`Module::access_bytes`] and stores
    /// the slice. The execution loop reads from `&ArchivedModule` for
    /// every op-fetch and constant-load via the archived converters. No
    /// owned `Module` is materialized at any point.
    ///
    /// The lifetime parameter on the returned `Vm<'a>` ties the VM to
    /// the slice's lifetime. The slice must remain valid for as long as
    /// the VM is in use.
    ///
    /// Suitable for hosts that place bytecode in `.rodata` (a
    /// `&'static [u8]`) or in any addressable buffer where the host
    /// arranges 8-byte alignment of the body.
    ///
    /// Skips structural verification, resource bounds verification,
    /// and rkyv body validation. The host attests through the unsafe
    /// marker that the bytecode was previously verified or comes from
    /// a trusted compiler.
    ///
    /// # Safety
    ///
    /// The caller attests that the bytecode is well-formed: framing,
    /// rkyv structure, structural invariants (block nesting, jump
    /// offsets, productivity rule), and resource bounds. Violation may
    /// produce arbitrary VM behavior including reads or writes of
    /// invalid memory through the operand stack and the call frames.
    /// This is stronger than [`Vm::new_unchecked`] which still runs
    /// structural verification.
    ///
    /// Use [`Vm::view_bytes_unchecked`] for hosts that want the bytes
    /// borrowed but with structural verification still active. Use
    /// this constructor only when the bytecode is known good.
    pub unsafe fn view_bytes_zero_copy(
        bytes: &'a [u8],
        arena: &'arena keleusma_arena::Arena,
    ) -> Result<Self, VmError> {
        // Strip a leading shebang once, up front, so every read below operates
        // on the same wire-format bytes: framing validation, the width check at
        // bytes 12-14, op decode, and -- critically -- the slice stored in
        // `BytecodeStore::Borrowed`, which `archived()` later reads the aux-body
        // offset and length from. Validating the stripped slice while storing
        // the unstripped one was the desync that drove `rkyv::access_unchecked`
        // over a mis-located region (V0.2.1 security audit, findings 8 and 15).
        // `access_bytes` and `decode_all_ops` strip again internally, an
        // idempotent no-op on already-stripped bytes.
        let bytes = crate::wire_format::strip_shebang_prefix(bytes);
        // V0.2.0 Phase 7c routes zero-copy through the wire
        // format. `access_bytes` validates the framing and
        // returns the archived auxiliary body slice; we use the
        // same slice (via `archived()` after construction)
        // throughout the VM lifetime.
        let archived = Module::access_bytes(bytes)?;
        // B16 step 8: width validation against this VM's W/A/F
        // trait parameters. The wire-format header carries the
        // declared widths at bytes 12 (word), 13 (address), and
        // 14 (float).
        Self::check_runtime_widths(bytes[12], bytes[13], bytes[14])?;
        // Determine data segment slot counts from the archived
        // auxiliary body. The data layout structure is shared
        // with the legacy format; only the chunk-ops separation
        // is new.
        let (shared_count, private_count) = match archived.data_layout.as_ref() {
            None => (0u16, 0u16),
            Some(dl) => {
                let mut shared = 0u16;
                let mut private_ = 0u16;
                for slot in dl.slots.iter() {
                    match slot.visibility {
                        crate::bytecode::ArchivedSlotVisibility::Shared => {
                            shared = shared.saturating_add(1);
                        }
                        crate::bytecode::ArchivedSlotVisibility::Private => {
                            private_ = private_.saturating_add(1);
                        }
                    }
                }
                (shared, private_)
            }
        };
        let private_storage_bytes =
            private_count as usize * core::mem::size_of::<crate::bytecode::GenericValue<W, F>>();
        if arena.persistent_capacity() < private_storage_bytes {
            return Err(VmError::VerifyError(alloc::format!(
                "arena persistent_capacity ({} bytes) is too small for module's private data ({} bytes); call `arena.resize_persistent(required_persistent_capacity_for(&module))` before constructing the VM",
                arena.persistent_capacity(),
                private_storage_bytes,
            )));
        }
        if private_count > 0 {
            let base = arena.persistent_ptr().as_ptr() as *mut crate::bytecode::GenericValue<W, F>;
            for i in 0..private_count as usize {
                // SAFETY: same justification as in `Vm::construct`.
                unsafe {
                    base.add(i).write(crate::bytecode::GenericValue::Unit);
                }
            }
        }
        let decoded_ops = decode_all_ops(bytes)?;
        // The zero-copy view path receives raw bytes with no owned
        // `Module`, so the verifier's footprint analysis is not available
        // here; the operand stack and frames are reserved to the
        // conservative minimums and grow on demand. This is a documented
        // non-nominal path (the host attests bounds out of band); the
        // checked `Vm::new` path pre-sizes to the exact footprint (B28 P3
        // item 5, priority 1).
        let mut stack = ArenaVec::new_in(arena.bottom_handle());
        let mut frames = ArenaVec::new_in(arena.bottom_handle());
        stack
            .try_reserve(MIN_STACK_RESERVE_SLOTS)
            .map_err(|_| out_of_arena_min(arena.capacity()))?;
        frames
            .try_reserve(MIN_FRAMES_RESERVE)
            .map_err(|_| out_of_arena_min(arena.capacity()))?;
        let mut vm = Self {
            bytecode: BytecodeStore::Borrowed(bytes),
            _phantom_a: core::marker::PhantomData,
            decoded_ops,
            stack,
            frames,
            natives: Vec::new(),
            shared_slot_count: shared_count,
            private_slot_count: private_count,
            arena,
            started: false,
            breakpoints: alloc::vec::Vec::new(),
            skip_breakpoint_at: None,
            fault_location: None,
            native_classifications_verified: false,
            ephemeral_opaques: ArenaVec::new_in(arena.bottom_handle()),
            reserved_operand_slots: MIN_STACK_RESERVE_SLOTS,
            reserved_frame_depth: MIN_FRAMES_RESERVE,
            reserved_opaque_capacity: 0,
            const_pool: alloc::vec::Vec::new(),
            const_templates: alloc::vec::Vec::new(),
            shared_buf: crate::shared_buf::SharedBuf::new(),
            #[cfg(feature = "signatures")]
            verifying_keys: Vec::new(),
        };
        // The trust-skip view path also pools scalar const composites so a
        // composite const load is allocation-free here too; the build reads
        // only the trusted archived constant pool (B28 P3 item 2, Increment 2).
        vm.build_const_pool();
        Ok(vm)
    }

    /// Construct the VM struct without running any verification.
    ///
    /// Internal helper shared by the verifying and unchecked
    /// constructors. Serializes the owned module to an aligned vector
    /// for archived access during execution. The data segment is
    /// initialized to `Unit` for each declared slot.
    /// Validate that the module's declared widths are admissible by
    /// this VM's compile-time trait parameters `W`, `A`, `F`.
    ///
    /// The bytecode's `word_bits_log2`, `addr_bits_log2`, and
    /// `float_bits_log2` fields must each be no greater than the
    /// corresponding trait's `BITS_LOG2` constant. The VM's chosen
    /// widths act as an upper bound on bytecode it can run; narrower
    /// bytecode is admitted and wrapped through `Word::from_i64_wrap`
    /// at constant-load time. Wider bytecode would silently truncate
    /// runtime values and is rejected here.
    fn check_runtime_widths(
        word_bits_log2: u8,
        addr_bits_log2: u8,
        float_bits_log2: u8,
    ) -> Result<(), VmError> {
        if word_bits_log2 > <W as crate::word::Word>::BITS_LOG2 {
            return Err(VmError::VerifyError(alloc::format!(
                "bytecode declares word_bits_log2 = {} but this Vm runs at word_bits_log2 = {} (chosen Word type is narrower than the bytecode requires)",
                word_bits_log2,
                <W as crate::word::Word>::BITS_LOG2,
            )));
        }
        if addr_bits_log2 > <A as crate::address::Address>::BITS_LOG2 {
            return Err(VmError::VerifyError(alloc::format!(
                "bytecode declares addr_bits_log2 = {} but this Vm runs at addr_bits_log2 = {} (chosen Address type is narrower than the bytecode requires)",
                addr_bits_log2,
                <A as crate::address::Address>::BITS_LOG2,
            )));
        }
        if float_bits_log2 > <F as crate::float::Float>::BITS_LOG2 {
            return Err(VmError::VerifyError(alloc::format!(
                "bytecode declares float_bits_log2 = {} but this Vm runs at float_bits_log2 = {} (chosen Float type is narrower than the bytecode requires)",
                float_bits_log2,
                <F as crate::float::Float>::BITS_LOG2,
            )));
        }
        Ok(())
    }

    fn construct(module: Module, arena: &'arena keleusma_arena::Arena) -> Result<Self, VmError> {
        // Bottom-region reservation counts (operand-stack slots, call-frame
        // depth, opaque-registry capacity) captured before `module` is
        // consumed, so all three can be pre-sized at construction rather
        // than grown during execution (deterministic allocation: a
        // too-small arena fails here, at init, not mid-stream — JPL
        // Power-of-10 rule 3). The figures match what
        // `auto_arena_capacity_for` reports, so a host sizing its arena
        // from that figure constructs with zero margin (B28 P3 item 5,
        // priority 1).
        let (reserve_slots, reserve_frames, reserve_opaque) = module_bottom_reservations(&module);
        // B16 step 8: validate the module's declared widths against
        // this VM's compile-time W/A/F trait parameters. A narrower
        // Vm running wider bytecode would silently truncate values
        // through Word::from_i64_wrap; reject the mismatch instead.
        Self::check_runtime_widths(
            module.word_bits_log2,
            module.addr_bits_log2,
            module.float_bits_log2,
        )?;
        // Partition data slots by visibility. Shared slots live
        // in the Vm-owned vector; private slots live in the
        // arena's persistent region. The compiler emits shared
        // slots first in the unified slot index space, so the
        // partition reduces to a count.
        let (shared_count, private_count) = match module.data_layout.as_ref() {
            None => (0u16, 0u16),
            Some(dl) => {
                let mut shared = 0u16;
                let mut private_ = 0u16;
                for slot in &dl.slots {
                    match slot.visibility {
                        crate::bytecode::SlotVisibility::Shared => {
                            shared = shared.checked_add(1).ok_or_else(|| {
                                VmError::VerifyError(String::from(
                                    "data layout shared slot count exceeds u16::MAX",
                                ))
                            })?;
                        }
                        crate::bytecode::SlotVisibility::Private => {
                            private_ = private_.checked_add(1).ok_or_else(|| {
                                VmError::VerifyError(String::from(
                                    "data layout private slot count exceeds u16::MAX",
                                ))
                            })?;
                        }
                    }
                }
                (shared, private_)
            }
        };
        let private_storage_bytes =
            private_count as usize * core::mem::size_of::<crate::bytecode::GenericValue<W, F>>();
        // The persistent region must also hold the private composite body pool
        // that follows the slot array (B28 P3 item 5, item 3a). Rejecting an
        // undersized arena here surfaces the error at construction; the
        // per-write bounds check in `persist_composite_body` is the soundness
        // guard regardless.
        let required_persistent =
            private_storage_bytes + module.persistent_composite_bytes as usize;
        if arena.persistent_capacity() < required_persistent {
            return Err(VmError::VerifyError(alloc::format!(
                "arena persistent_capacity ({} bytes) is too small for module's private data ({} bytes: {} slot(s) at {} bytes each plus {} bytes of persistent composite bodies); call `arena.resize_persistent(required_persistent_capacity_for(&module))` before constructing the VM",
                arena.persistent_capacity(),
                required_persistent,
                private_count,
                core::mem::size_of::<crate::bytecode::GenericValue<W, F>>(),
                module.persistent_composite_bytes,
            )));
        }
        // Initialise each private slot to crate::bytecode::GenericValue::Unit via
        // `ptr::write` so the bytes hold a valid Value before
        // any subsequent reader clones or any subsequent writer
        // drops the old occupant. The arena's persistent region
        // is freshly zeroed when first resized, but those zero
        // bytes are not a valid `Value`, so write through `write`
        // not assignment.
        if private_count > 0 {
            let base = arena.persistent_ptr().as_ptr() as *mut crate::bytecode::GenericValue<W, F>;
            for i in 0..private_count as usize {
                // SAFETY: `i` is within the slot count just
                // verified to fit in the persistent capacity; the
                // arena owns the buffer for the VM's lifetime;
                // `Value` is properly aligned at every multiple
                // of its size on the 16-byte-aligned buffer base.
                unsafe {
                    base.add(i).write(crate::bytecode::GenericValue::Unit);
                }
            }
        }
        let bytes = module.to_bytes()?;
        let mut aligned = rkyv::util::AlignedVec::<8>::with_capacity(bytes.len());
        aligned.extend_from_slice(&bytes);
        let decoded_ops = decode_all_ops(aligned.as_slice())?;
        // Pre-size the operand stack, call frames, and opaque registry to
        // the module's exact worst-case footprint so the runtime performs
        // no allocation after construction (B28 P3 item 5, priority 1). An
        // arena too small to hold a reservation fails here, at
        // construction, with `VmError::OutOfArena` rather than aborting the
        // host process via `handle_alloc_error` on a later push. Pre-sizing
        // also avoids reallocation amplification in the bump allocator (a
        // growing `Vec` over a bump allocator consumes cumulative memory
        // across reallocations without freeing earlier capacity).
        let stack =
            pre_sized_bottom_vec::<crate::bytecode::GenericValue<W, F>>(arena, reserve_slots)?;
        let frames = pre_sized_bottom_vec::<CallFrame>(arena, reserve_frames)?;
        let ephemeral_opaques = pre_sized_bottom_vec::<
            alloc::sync::Arc<dyn crate::opaque::HostOpaque>,
        >(arena, reserve_opaque)?;
        let mut vm = Self {
            bytecode: BytecodeStore::Owned(aligned),
            _phantom_a: core::marker::PhantomData,
            decoded_ops,
            stack,
            frames,
            natives: Vec::new(),
            shared_slot_count: shared_count,
            private_slot_count: private_count,
            arena,
            started: false,
            breakpoints: alloc::vec::Vec::new(),
            skip_breakpoint_at: None,
            fault_location: None,
            native_classifications_verified: false,
            ephemeral_opaques,
            reserved_operand_slots: reserve_slots,
            reserved_frame_depth: reserve_frames,
            reserved_opaque_capacity: reserve_opaque,
            const_pool: alloc::vec::Vec::new(),
            const_templates: alloc::vec::Vec::new(),
            shared_buf: crate::shared_buf::SharedBuf::new(),
            #[cfg(feature = "signatures")]
            verifying_keys: Vec::new(),
        };
        // Materialise scalar const composites into the VM-owned rodata pool
        // now that the bytecode image is in place (B28 P3 item 2, Increment 2).
        vm.build_const_pool();
        Ok(vm)
    }

    /// Read a data slot's current value, cloning. Dispatches by
    /// the unified slot index: indices below `shared_slot_count`
    /// resolve to the Vm-owned `data` vector; higher indices
    /// resolve to the arena's persistent region.
    fn read_data_slot(&self, slot: usize) -> Result<crate::bytecode::GenericValue<W, F>, VmError> {
        if slot < self.shared_slot_count as usize {
            // A shared slot reads the borrowed host buffer (B28 item 2).
            // `enter_shared` guarantees a module with shared slots is entered
            // with an active buffer, so this is always reached with one.
            return self.read_shared_from_buffer(slot);
        }
        // SAFETY: the slot is within the partition checked at
        // construction; the persistent region was initialised
        // with `crate::bytecode::GenericValue::Unit` for every slot and updates flow
        // through `write_data_slot`, so the pointee is always
        // a valid `Value`.
        unsafe {
            let private_idx = slot - self.shared_slot_count as usize;
            let base =
                self.arena.persistent_ptr().as_ptr() as *const crate::bytecode::GenericValue<W, F>;
            Ok((*base.add(private_idx)).clone())
        }
    }

    /// The persistent composite pool offset for a private slot that holds a
    /// flat composite body recorded in the module's private-composite layout
    /// table (B28 item 2 step 6A). `None` for a scalar slot or an empty
    /// composite slot, neither of which has a table entry. The table is sorted
    /// ascending by slot, so this binary-searches it.
    fn private_composite_pool_offset(&self, slot: usize) -> Option<usize> {
        let dl = self.archived().data_layout.as_ref()?;
        let slot_u16 = u16::try_from(slot).ok()?;
        let table = &dl.private_composite_layout;
        table
            .binary_search_by_key(&slot_u16, |e| e.slot.to_native())
            .ok()
            .map(|i| table[i].offset.to_native() as usize)
    }

    /// The exclusive upper bound of the private-composite pool region that
    /// begins at `rel_offset` (audit D4). `validate_data_layout` proves the
    /// `private_composite_layout` offsets strictly ascending, so a slot's region
    /// ends at the next-higher table offset, or at the declared pool size for
    /// the highest slot. Bounding a composite write to this extent prevents one
    /// slot's body from overwriting the adjacent slot's region, which the
    /// ascending-offset check alone does not since per-slot body size is not
    /// carried in the wire format.
    fn private_composite_slot_end(&self, rel_offset: usize) -> usize {
        // The declared pool size is not mirrored on the aux body, so derive the
        // pool's upper bound from the persistent region past the private-slot
        // Value array. This is the exact bound for the highest slot; every
        // interior slot is bounded tightly by the next table offset below. The
        // arena-capacity check at the write independently bounds the physical
        // region.
        let private_storage = self.private_slot_count as usize
            * core::mem::size_of::<crate::bytecode::GenericValue<W, F>>();
        let pool = self
            .arena
            .persistent_capacity()
            .saturating_sub(private_storage);
        let Some(dl) = self.archived().data_layout.as_ref() else {
            return pool;
        };
        dl.private_composite_layout
            .iter()
            .map(|e| e.offset.to_native() as usize)
            .filter(|&o| o > rel_offset)
            .min()
            .unwrap_or(pool)
    }

    /// The shared layout entry for a shared slot, as `(byte offset, kind tag,
    /// composite body length)` copied out of the archived table so the borrow
    /// of the bytecode image does not outlive the read (B28 item 2).
    fn shared_layout_entry(&self, slot: usize) -> (usize, u8, usize) {
        let dl = self
            .archived()
            .data_layout
            .as_ref()
            .expect("shared slot access requires a data layout");
        let e = &dl.shared_layout[slot];
        (
            e.offset.to_native() as usize,
            e.kind,
            e.len.to_native() as usize,
        )
    }

    /// Read a shared slot in place from the borrowed host buffer (B28 item 2).
    /// A scalar slot decodes directly by offset (a plain owned value, no
    /// pointer into the buffer). A composite slot copies its byte range into a
    /// fresh arena body tagged with the current epoch, so the value is
    /// RESET-scoped and can never outlive the host's borrow.
    fn read_shared_from_buffer(
        &self,
        slot: usize,
    ) -> Result<crate::bytecode::GenericValue<W, F>, VmError> {
        use crate::bytecode::{ArrayBody, EnumBody, GenericValue, StructBody, TupleBody};
        use crate::value_layout::{CompositeKind, ScalarKind};
        let (offset, kind, len) = self.shared_layout_entry(slot);
        let wb = self.module_word_bytes();
        let fb = self.module_float_bytes();
        let buf = self
            .shared_buf
            .bytes()
            .expect("read_shared_from_buffer called with an active buffer");
        if kind & crate::bytecode::SHARED_SLOT_COMPOSITE_FLAG == 0 {
            let sk = ScalarKind::from_tag(kind)
                .ok_or_else(|| VmError::InvalidBytecode(String::from("bad shared scalar kind")))?;
            GenericValue::read_scalar_le(buf, offset, sk, wb, fb).map_err(VmError::from)
        } else {
            let ck = CompositeKind::from_tag(kind & !crate::bytecode::SHARED_SLOT_COMPOSITE_FLAG)
                .ok_or_else(|| {
                VmError::InvalidBytecode(String::from("bad shared composite kind"))
            })?;
            let src = &buf[offset..offset + len];
            let fc = crate::flat_value::FlatComposite::build_in_arena(self.arena, len, |dst| {
                dst.copy_from_slice(src);
                Ok(())
            })
            .map_err(|_| out_of_arena_push("shared composite read", self.arena.capacity()))?
            .ok_or_else(|| {
                VmError::InvalidBytecode(String::from("shared composite body fill failed"))
            })?;
            Ok(match ck {
                CompositeKind::Tuple => GenericValue::Tuple(TupleBody::Flat(fc)),
                CompositeKind::Array => GenericValue::Array(ArrayBody::Flat(fc)),
                CompositeKind::Struct => GenericValue::Struct(StructBody::Flat(fc)),
                CompositeKind::Enum => GenericValue::Enum(EnumBody::Flat(fc)),
            })
        }
    }

    /// Overwrite a data slot. Same dispatch as `read_data_slot`.
    /// Assignment via `*ptr = value` drops the previous occupant,
    /// which is valid because every private slot is initialised
    /// to `crate::bytecode::GenericValue::Unit` at construction.
    fn write_data_slot(
        &mut self,
        slot: usize,
        value: crate::bytecode::GenericValue<W, F>,
    ) -> Result<(), VmError> {
        if slot < self.shared_slot_count as usize {
            // A shared slot writes the borrowed host buffer (B28 item 2);
            // `enter_shared` guarantees an active buffer for any module with
            // shared slots.
            return self.write_shared_to_buffer(slot, value);
        }
        // A private slot holding a flat composite copies its body into the
        // persistent composite pool at the offset the private-composite layout
        // table records for the slot and stores a region-aware handle that
        // survives RESET in place (B28 item 2 step 6A), so no private composite
        // write needs a global-heap owned body. Every private composite slot,
        // a single composite field and each array-of-composite element alike,
        // has a table entry, so `SetData` and `SetDataIndexed` both persist
        // through this one path. A scalar, an empty composite, or a boxed value
        // has no table entry and is stored directly.
        let to_store = if crate::bytecode::flat_composite_ref(&value).is_some()
            && let Some(off) = self.private_composite_pool_offset(slot)
        {
            self.persist_composite_body(value, off)?
        } else {
            value
        };
        // SAFETY: the slot is within the partition checked at
        // construction; the pointee is a valid `Value` per
        // the construction-time initialisation, so dropping
        // it via the assignment is sound.
        unsafe {
            let private_idx = slot - self.shared_slot_count as usize;
            let base =
                self.arena.persistent_ptr().as_ptr() as *mut crate::bytecode::GenericValue<W, F>;
            *base.add(private_idx) = to_store;
        }
        Ok(())
    }

    /// Write a shared slot in place to the borrowed host buffer (B28 item 2).
    /// A scalar writes directly by offset. A composite resolves its flat body
    /// to an owned copy first, releasing the arena borrow before taking the
    /// mutable buffer slice, then copies the bytes into the field; the owned
    /// copy is the one transient allocation, on the rare composite-shared-write
    /// path (the common case is scalar slots).
    fn write_shared_to_buffer(
        &mut self,
        slot: usize,
        value: crate::bytecode::GenericValue<W, F>,
    ) -> Result<(), VmError> {
        let (offset, kind, len) = self.shared_layout_entry(slot);
        let wb = self.module_word_bytes();
        let fb = self.module_float_bytes();
        if kind & crate::bytecode::SHARED_SLOT_COMPOSITE_FLAG == 0 {
            // A scalar value writes its own bytes at the offset; the table kind
            // is only needed on the read path to decode.
            let buf = self
                .shared_buf
                .bytes_mut()
                .expect("write_shared_to_buffer called with an active buffer");
            value.write_scalar_le(buf, offset, wb, fb)?;
            Ok(())
        } else {
            // Resolve the composite body to an owned copy so the `self.arena`
            // borrow ends before the `&mut self` buffer slice is taken.
            let body: alloc::vec::Vec<u8> = {
                let fc = crate::bytecode::flat_composite_ref(&value).ok_or_else(|| {
                    VmError::TypeError(String::from(
                        "expected a flat composite for a shared composite slot",
                    ))
                })?;
                fc.resolve(self.arena)
                    .map_err(|_| stale_arena_body())?
                    .to_vec()
            };
            // Reconcile the resolved body length with the slot's validated
            // declared length (audit D1). `validate_data_layout` proved
            // `offset + len <= buffer`, so requiring `body.len() == len` keeps
            // the copy in bounds and prevents a mismatched body from
            // overwriting the adjacent slot. For a well-typed program the value
            // type matches the slot type and the two are equal; the guard bites
            // hostile bytecode whose Top-shaped operand deferred past the typed
            // pass, the same class as C2 on the shared composite write path.
            if body.len() != len {
                return Err(VmError::InvalidBytecode(alloc::format!(
                    "shared composite slot {slot} resolves to a {}-byte body but the slot declares {len} bytes",
                    body.len()
                )));
            }
            let buf = self
                .shared_buf
                .bytes_mut()
                .expect("write_shared_to_buffer called with an active buffer");
            buf[offset..offset + body.len()].copy_from_slice(&body);
            Ok(())
        }
    }

    /// Copy a flat composite's body into the arena persistent region at the
    /// compiler-assigned fixed offset and return the value rewrapped with a
    /// region-aware persistent handle (B28 P3 item 5, item 3a).
    ///
    /// `rel_offset` is the body's offset within the persistent composite body
    /// pool, which follows the private-slot `Value` array. The body is copied
    /// once into that fixed `.data`-style location. The resulting handle points
    /// into the persistent region, which a RESET never reclaims, so
    /// region-aware validity keeps it live across iterations with no global
    /// heap. The caller has verified `val` is a flat composite.
    fn persist_composite_body(
        &self,
        val: crate::bytecode::GenericValue<W, F>,
        rel_offset: usize,
    ) -> Result<crate::bytecode::GenericValue<W, F>, VmError> {
        let private_storage = self.private_slot_count as usize
            * core::mem::size_of::<crate::bytecode::GenericValue<W, F>>();
        let dst_off = private_storage + rel_offset;
        let handle = {
            let fc = crate::bytecode::flat_composite_ref(&val)
                .expect("persist_composite_body called on a non-flat-composite value");
            let bytes = fc.resolve(self.arena).map_err(|_| stale_arena_body())?;
            let len = bytes.len();
            // Bound the body within this slot's declared pool region (audit D4),
            // so a mismatched body cannot overwrite the adjacent slot's region.
            // The ascending-offset validation alone does not catch this, since
            // per-slot body size is not wire-carried.
            let slot_end = self.private_composite_slot_end(rel_offset);
            if rel_offset.checked_add(len).is_none_or(|end| end > slot_end) {
                return Err(VmError::InvalidBytecode(alloc::format!(
                    "private composite body of {len} bytes overruns its pool slot region ending at {slot_end}"
                )));
            }
            if dst_off
                .checked_add(len)
                .is_none_or(|end| end > self.arena.persistent_capacity())
            {
                return Err(out_of_arena_push(
                    "persistent composite data slot",
                    self.arena.capacity(),
                ));
            }
            let base = self.arena.persistent_ptr().as_ptr();
            // SAFETY: `dst_off + len <= persistent_capacity`, so the destination
            // lies wholly within the persistent region. It is disjoint from the
            // source (the value's arena-top or inline body) because the
            // compiler assigns each private composite slot a distinct pool
            // offset and the persistent region is a different arena range, so
            // the copy does not overlap.
            let dst = unsafe { base.add(dst_off) };
            unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), dst, len) };
            let raw: *mut [u8] = core::ptr::slice_from_raw_parts_mut(dst, len);
            // SAFETY: `dst` is a freshly written, non-null pointer into the
            // persistent region addressing `len` initialised bytes.
            let nn = unsafe { core::ptr::NonNull::new_unchecked(raw) };
            // SAFETY: the bytes live in the persistent region, which a RESET
            // never reclaims, so the handle stays valid (region-aware validity
            // treats a persistent pointer as always live).
            unsafe { keleusma_arena::ArenaHandle::from_raw_parts(nn, self.arena.epoch()) }
        };
        let persistent = crate::flat_value::FlatComposite::Arena(handle);
        Ok(rewrap_flat_body(val, persistent))
    }

    /// Materialise every scalar const composite once into the VM-owned const
    /// pool and cache a per-`(chunk, const)` template that loads it
    /// allocation-free (B28 P3 item 2, Increment 2).
    ///
    /// Called once at construction and again at each hot swap, after the new
    /// bytecode image is in place, so the templates reference the current
    /// module's constants. Both `const_pool` and `const_templates` are rebuilt
    /// wholesale; the previous pool's boxes are freed when the fields are
    /// reassigned. The build reads only the archived constant pool and writes
    /// no arena memory, so the const bodies stay outside the arena (const as
    /// rodata).
    fn build_const_pool(&mut self) {
        // Materialise at the module-declared scalar widths so a pooled body
        // matches the offsets the compiler baked into the access ops, exactly
        // as the direct `value_from_archived` path does.
        let wbytes = self.module_word_bytes();
        let fbytes = self.module_float_bytes();
        let mut pool: alloc::vec::Vec<alloc::boxed::Box<[u8]>> = alloc::vec::Vec::new();
        let mut templates: alloc::vec::Vec<
            alloc::vec::Vec<Option<crate::bytecode::GenericValue<W, F>>>,
        > = alloc::vec::Vec::new();
        {
            // Immutable borrow of the archived bytecode for the build. The
            // local `pool`/`templates` are written here, then moved into
            // `self` once the borrow ends, avoiding an aliasing conflict with
            // the `&self.bytecode` that `archived()` holds.
            let chunks = &self.archived().chunks;
            for chunk in chunks.iter() {
                let mut row: alloc::vec::Vec<Option<crate::bytecode::GenericValue<W, F>>> =
                    alloc::vec::Vec::with_capacity(chunk.constants.len());
                for c in chunk.constants.iter() {
                    row.push(Self::pool_const_template(c, wbytes, fbytes, &mut pool));
                }
                templates.push(row);
            }
        }
        self.const_pool = pool;
        self.const_templates = templates;
    }

    /// Pack one constant into the const pool if it is a transitively-scalar
    /// composite, returning the template that loads it (B28 P3 item 2,
    /// Increment 2). Returns `None` for any constant that is not pooled.
    ///
    /// A scalar or string constant is loaded directly and is never pooled. A
    /// composite that contains a string or opaque leaf materialises `Boxed`
    /// (it has no flat body to relocate) and is also not pooled; it keeps its
    /// existing direct-materialisation path. Only a `Flat(Inline)` composite
    /// with a non-empty body is relocated into a boxed pool body, whose handle
    /// is then returned as an `Arena` body. An empty composite body needs no
    /// handle and is left to the direct path.
    fn pool_const_template(
        c: &crate::bytecode::ArchivedConstValue,
        word_bytes: usize,
        float_bytes: usize,
        pool: &mut alloc::vec::Vec<alloc::boxed::Box<[u8]>>,
    ) -> Option<crate::bytecode::GenericValue<W, F>> {
        use crate::bytecode::{
            ArchivedConstValue as A, ArrayBody, EnumBody, StructBody, TupleBody,
        };
        // Only a composite constant can carry a flat body; a scalar or string
        // constant short-circuits without the packing cost.
        if !matches!(
            c,
            A::Tuple(_) | A::Array(_) | A::Struct { .. } | A::Enum { .. }
        ) {
            return None;
        }
        // Pack the flat body bytes directly from the archived constant (B28 item
        // 2 step 6B), with no owned `Inline` intermediate. A transitively-scalar
        // composite yields `Some(bytes)`; a string- or opaque-bearing one (or an
        // enum with an unresolved discriminant) yields `None` and keeps its
        // boxed direct path. An empty body needs no pooled allocation and is
        // left to the direct path (it materialises as the always-valid `Empty`
        // body).
        let bytes = crate::bytecode::const_flat_bytes(c, word_bytes, float_bytes)?;
        if bytes.is_empty() {
            return None;
        }
        let bx: alloc::boxed::Box<[u8]> = alloc::boxed::Box::from(bytes.as_slice());
        let ptr = bx.as_ptr() as *mut u8;
        let len = bx.len();
        pool.push(bx);
        // SAFETY: `ptr`/`len` address the `len` initialised bytes of the boxed
        // body just moved into `pool`, which the VM owns for its whole
        // lifetime. The box's heap buffer does not move when `pool` grows, so
        // the handle stays valid. The address lies in a separate heap
        // allocation outside the arena buffer, so region-aware validity treats
        // it as always live regardless of epoch; a sentinel zero epoch
        // documents that this is epoch-independent rodata, the same model as a
        // rodata `KStr` pointing into the bytecode image.
        let handle = unsafe {
            let raw: *mut [u8] = core::ptr::slice_from_raw_parts_mut(ptr, len);
            let nn = core::ptr::NonNull::new_unchecked(raw);
            keleusma_arena::ArenaHandle::<[u8]>::from_raw_parts(nn, 0)
        };
        let body = crate::flat_value::FlatComposite::Arena(handle);
        // Wrap the pooled body as the matching composite kind, read from the
        // archived constant's shape (the kind the baked access ops expect).
        Some(match c {
            A::Tuple(_) => crate::bytecode::GenericValue::Tuple(TupleBody::Flat(body)),
            A::Array(_) => crate::bytecode::GenericValue::Array(ArrayBody::Flat(body)),
            A::Struct { .. } => crate::bytecode::GenericValue::Struct(StructBody::Flat(body)),
            A::Enum { .. } => crate::bytecode::GenericValue::Enum(EnumBody::Flat(body)),
            // The leading `matches!` guard excludes every non-composite kind.
            _ => unreachable!("pool_const_template guarded to composite constants"),
        })
    }

    /// Total bytes of the VM-owned const-composite body pool (B28 P3 item 2,
    /// Increment 2).
    ///
    /// These bodies are materialised once at construction (and rebuilt at each
    /// hot swap) and live for the VM's lifetime outside the arena, so they
    /// consume no arena capacity and are not part of the arena worst-case
    /// memory bound. This accessor reports their footprint separately, the way
    /// a host accounts for the bytecode image, so the complete worst-case
    /// memory picture stays available. Returns zero for a module with no
    /// transitively-scalar const composites.
    pub fn const_pool_bytes(&self) -> usize {
        self.const_pool.iter().map(|b| b.len()).sum()
    }

    /// Total number of data slots in the loaded module (shared plus
    /// private). Internal helper for the op-handler bounds checks; the
    /// unified slot index space partitions into `[0, shared_slot_count)`
    /// (shared, in the host buffer) and the rest (private, in the arena).
    /// The retired `set_data`/`get_data`/`shared_slot_count` host API is gone;
    /// hosts size the shared buffer with [`Self::shared_data_bytes`] and read
    /// or write scalar shared fields with [`Self::get_shared`] /
    /// [`Self::set_shared`] (B28 item 2).
    fn data_len(&self) -> usize {
        self.shared_slot_count as usize + self.private_slot_count as usize
    }

    /// Flat byte length of the borrowed shared-data buffer this module
    /// expects (B28 item 2).
    ///
    /// The host allocates a `&mut [u8]` of exactly this length, zero-initialised
    /// for the program's first observation of each field, and lends it to the VM
    /// at every [`Self::call_with_shared`] / [`Self::resume_with_shared`]. The
    /// VM reads and writes shared fields in place by byte offset and retains no
    /// pointer into the buffer across a yield, so the host owns the buffer and
    /// may swap, mutate, or drop it between resumes. Returns `0` for a module
    /// with no shared data, for which the plain [`Self::call`] / [`Self::resume`]
    /// entry points suffice.
    ///
    /// Matches [`shared_data_bytes_for`] computed from the same module.
    pub fn shared_data_bytes(&self) -> usize {
        self.archived().shared_data_bytes.to_native() as usize
    }

    /// Read a scalar shared field out of a host-owned buffer between runs
    /// (B28 item 2).
    ///
    /// `buf` must be the module's [`Self::shared_data_bytes`] buffer; `slot` is
    /// a shared slot index in `[0, shared_slot_count)`. The field is decoded at
    /// the module's declared widths into an owned scalar `Value`, so the result
    /// carries no pointer into `buf`. This is the host-side counterpart to a
    /// script's `shared.field` read and replaces the retired per-slot
    /// `get_data` for the borrowed-buffer model.
    ///
    /// Errors when `slot` is out of range, names a private slot (private slots
    /// are script-only), when `buf` is the wrong length, or when the slot is a
    /// composite. Whole-composite shared fields are accessed from the script,
    /// not through this per-slot host accessor.
    pub fn get_shared(
        &self,
        buf: &[u8],
        slot: usize,
    ) -> Result<crate::bytecode::GenericValue<W, F>, VmError> {
        use crate::value_layout::ScalarKind;
        self.check_host_shared_slot(buf, slot)?;
        let (offset, kind, _len) = self.shared_layout_entry(slot);
        if kind & crate::bytecode::SHARED_SLOT_COMPOSITE_FLAG != 0 {
            return Err(VmError::NativeError(format!(
                "shared slot {} is a composite; composite shared fields are accessed from the script, not the per-slot host API",
                slot
            )));
        }
        let sk = ScalarKind::from_tag(kind)
            .ok_or_else(|| VmError::InvalidBytecode(String::from("bad shared scalar kind")))?;
        crate::bytecode::GenericValue::read_scalar_le(
            buf,
            offset,
            sk,
            self.module_word_bytes(),
            self.module_float_bytes(),
        )
        .map_err(VmError::from)
    }

    /// Write a scalar shared field into a host-owned buffer between runs
    /// (B28 item 2).
    ///
    /// The dual of [`Self::get_shared`]: the same slot, range, and width rules
    /// apply, and `value` is encoded at the module's declared widths at the
    /// field's offset. Replaces the retired per-slot `set_data` for the
    /// borrowed-buffer model. Errors on the same conditions as
    /// [`Self::get_shared`].
    pub fn set_shared(
        &self,
        buf: &mut [u8],
        slot: usize,
        value: crate::bytecode::GenericValue<W, F>,
    ) -> Result<(), VmError> {
        self.check_host_shared_slot(buf, slot)?;
        let (offset, kind, _len) = self.shared_layout_entry(slot);
        if kind & crate::bytecode::SHARED_SLOT_COMPOSITE_FLAG != 0 {
            return Err(VmError::NativeError(format!(
                "shared slot {} is a composite; composite shared fields are written from the script, not the per-slot host API",
                slot
            )));
        }
        value.write_scalar_le(
            buf,
            offset,
            self.module_word_bytes(),
            self.module_float_bytes(),
        )?;
        Ok(())
    }

    /// Write a host value mirroring the whole `shared data` segment into the
    /// buffer at the module's flat widths (B34).
    ///
    /// `T` derives [`crate::marshall::KeleusmaType`] and must match the
    /// segment's field types and declaration order; its flat byte size must
    /// equal [`Self::shared_data_bytes`], validated here. Unlike the per-slot
    /// [`Self::set_shared`] (scalar-only), this writes composite shared fields
    /// too, so a host can seed the entire segment in one call. The data-segment
    /// rules reject `Text` and opaque fields, so `T` is purely scalar and
    /// scalar-composite and the write needs no arena.
    pub fn marshal_shared_into<T: crate::marshall::KeleusmaType<W, F>>(
        &self,
        value: T,
        buf: &mut [u8],
    ) -> Result<(), VmError> {
        let wb = self.module_word_bytes();
        let fb = self.module_float_bytes();
        self.check_shared_marshal_layout::<T>(buf, wb, fb)?;
        <T as crate::marshall::KeleusmaType<W, F>>::to_flat_bytes(value, buf, wb, fb)
    }

    /// Read a host value mirroring the whole `shared data` segment from the
    /// buffer at the module's flat widths (B34); the dual of
    /// [`Self::marshal_shared_into`].
    pub fn unmarshal_shared<T: crate::marshall::KeleusmaType<W, F>>(
        &self,
        buf: &[u8],
    ) -> Result<T, VmError> {
        let wb = self.module_word_bytes();
        let fb = self.module_float_bytes();
        self.check_shared_marshal_layout::<T>(buf, wb, fb)?;
        <T as crate::marshall::KeleusmaType<W, F>>::from_flat_bytes(buf, wb, fb)
    }

    /// Validate that `T`'s flat layout matches the module's shared segment and
    /// that `buf` is the right length (B34, the original "validate against the
    /// keleusma layout"). A flat-size mismatch surfaces here as a clear error
    /// rather than a silent wrong read or write.
    fn check_shared_marshal_layout<T: crate::marshall::KeleusmaType<W, F>>(
        &self,
        buf: &[u8],
        wb: usize,
        fb: usize,
    ) -> Result<(), VmError> {
        let need = self.shared_data_bytes();
        let have = <T as crate::marshall::KeleusmaType<W, F>>::flat_byte_size(wb, fb).ok_or_else(
            || {
                VmError::TypeError(String::from(
                    "host type is not flat-eligible for shared-data marshalling",
                ))
            },
        )?;
        if have != need {
            return Err(VmError::TypeError(format!(
                "host type flat size {} does not match module's shared_data_bytes {}",
                have, need
            )));
        }
        if buf.len() != need {
            return Err(VmError::NativeError(format!(
                "shared buffer length {} does not match module's shared_data_bytes {}",
                buf.len(),
                need
            )));
        }
        Ok(())
    }

    /// Shared bounds, visibility, and buffer-length checks common to
    /// [`Self::get_shared`] and [`Self::set_shared`]. Rejects a private or
    /// out-of-range slot and a wrong-size buffer before any offset arithmetic.
    fn check_host_shared_slot(&self, buf: &[u8], slot: usize) -> Result<(), VmError> {
        if slot >= self.shared_slot_count as usize {
            return Err(VmError::NativeError(format!(
                "shared slot index {} out of range (module has {} shared slots)",
                slot, self.shared_slot_count
            )));
        }
        let need = self.shared_data_bytes();
        if buf.len() != need {
            return Err(VmError::NativeError(format!(
                "shared buffer length {} does not match module's shared_data_bytes {}",
                buf.len(),
                need
            )));
        }
        Ok(())
    }

    /// Borrow the VM's arena.
    ///
    /// The arena is the dual-end bump-allocated buffer described in R32. It
    /// is available to host-supplied native functions that wish to allocate
    /// dynamic strings or other arena-resident values. The arena is reset
    /// at every `Op::Reset` boundary, so host-allocated values do not
    /// survive across stream phases.
    pub fn arena(&self) -> &'arena keleusma_arena::Arena {
        self.arena
    }

    /// Decode a value produced at a host boundary (a yielded or returned
    /// value, or one read from data) into a host type `T`, resolving a flat
    /// composite's reference fields through the VM's arena and opaque
    /// registry (B28 P3).
    ///
    /// A flat `Text` field is rebuilt from its arena `(ptr, len)` and copied
    /// into an owned `String`; a flat opaque field is resolved to its
    /// `Arc<dyn HostOpaque>` through the ephemeral registry. Use this rather
    /// than `KeleusmaType::from_value` whenever the decoded type may contain
    /// a `String` or opaque field, since those need the resolution context.
    ///
    /// Like every arena read, the value must be decoded before the next
    /// `resume`/`RESET`: the arena may be reset at any resume, after which a
    /// still-arena-resident reference is stale and decoding returns a clean
    /// error. Owned results (a copied `String`, a cloned `Arc`) survive.
    pub fn decode<T>(&self, value: &crate::bytecode::GenericValue<W, F>) -> Result<T, VmError>
    where
        T: crate::marshall::KeleusmaType<W, F>,
    {
        let ctx = crate::marshall::RefContext {
            arena: self.arena,
            opaques: &self.ephemeral_opaques,
            word_bytes: self.module_word_bytes(),
            float_bytes: self.module_float_bytes(),
            // A decoded value may be held across a RESET (a returned or
            // yielded composite). Reattach the composite body's originating
            // epoch so a flat Text field resolves Stale after a reset rather
            // than dereferencing reclaimed memory; a non-composite value
            // carries its own epoch and ignores this (B28 P3 item 1).
            ref_epoch: value.flat_ref_epoch().unwrap_or_else(|| self.arena.epoch()),
        };
        T::from_value_ctx(value, &ctx)
    }

    /// Reset the arena's top region and advance the epoch, leaving
    /// the bottom region intact.
    ///
    /// Used by `Op::Reset` to invalidate scratch allocations and
    /// dynamic string handles between stream iterations while
    /// preserving the operand stack and call-frame stack. The bottom
    /// region holds the operand stack and frames, both of which carry
    /// state across the reset.
    ///
    /// Outstanding [`keleusma_arena::ArenaHandle`] values, regardless
    /// of which end produced them, return [`keleusma_arena::Stale`]
    /// on access after this call.
    ///
    /// Returns [`keleusma_arena::EpochSaturated`] when the epoch
    /// counter is exhausted.
    fn reset_arena_internal(&self) -> Result<(), keleusma_arena::EpochSaturated> {
        // SAFETY: The top region holds only short-lived scratch and
        // dynamic strings. No `Vec<T, TopHandle>` in the VM holds
        // non-zero capacity. The bottom-region operand stack and
        // frames are unaffected.
        unsafe { self.arena.reset_top_unchecked() }
    }

    /// Drop the operand and frame stacks, reset both arena ends, and
    /// advance the epoch.
    ///
    /// Used by error recovery and hot-swap where the VM transitions
    /// to a clean callable state with no retained execution context.
    /// The arena-backed stacks would otherwise hold storage in the
    /// bottom region whose addresses alias memory the bump allocator
    /// will return for subsequent allocations once the bump pointer
    /// is rewound, so they must be dropped before the bottom-region
    /// reset advances the bump pointer.
    fn full_reset_arena_internal(&mut self) -> Result<(), keleusma_arena::EpochSaturated> {
        // Drop the old arena-backed bottom-region structures before
        // rewinding the bottom bump pointer. Reassignment to fresh
        // zero-capacity vectors drops each old `ArenaVec` — running every
        // contained value's destructor (each `Arc`'s `Drop` for the opaque
        // registry, decrementing the host refcount) and calling
        // `BottomHandle::deallocate` (a no-op for the bump allocator) — and
        // allocates nothing, so the bottom region holds no live reservation
        // when the rewind below runs. The registry now lives in the bottom
        // region alongside the stacks (B28 P3 item 5, Phase C2), so it must
        // be recreated here too, not merely cleared, or its retained-
        // capacity backing would alias memory the rewound bump pointer hands
        // back.
        self.ephemeral_opaques = ArenaVec::new_in(self.arena.bottom_handle());
        self.stack = ArenaVec::new_in(self.arena.bottom_handle());
        self.frames = ArenaVec::new_in(self.arena.bottom_handle());
        // SAFETY: After the assignments above, no `Vec<T, BottomHandle>`
        // in the VM holds non-zero capacity. The data segment is
        // globally-allocated. Dynamic string handles produced through
        // `KString::alloc` are epoch-tagged and return `Stale` on
        // access after the reset rather than dereferencing reclaimed
        // memory.
        unsafe { self.arena.reset_unchecked() }?;
        // Re-reserve the bottom-region working set to the exact footprint
        // the VM was constructed with, now that the rewind has freed the old
        // reservations and returned the bump pointer to the base. This
        // preserves the no-allocation-after-init contract through error
        // recovery and hot swap: the recovered VM holds the identical
        // pre-sized working set and does not grow mid-stream (B28 P3 item 5,
        // priority 1). Re-reservation cannot fail because the arena already
        // held this footprint before the rewind freed it; a failure is
        // nonetheless absorbed by leaving the vector on-demand so a
        // degenerate arena degrades gracefully rather than aborting.
        let _ = self.stack.try_reserve_exact(self.reserved_operand_slots);
        let _ = self.frames.try_reserve_exact(self.reserved_frame_depth);
        let _ = self
            .ephemeral_opaques
            .try_reserve_exact(self.reserved_opaque_capacity);
        Ok(())
    }

    /// Intern an opaque host reference into the ephemeral registry and
    /// return its index (B28 P3).
    ///
    /// The index is what a flat composite body stores `word_bytes`-wide
    /// in place of the `Drop`-bearing `Arc`. The interned `Arc` is
    /// dropped at the next `RESET`, when the arena body holding the index
    /// is reclaimed.
    ///
    /// Interning deduplicates by pointer identity: an `Arc` already in the
    /// registry returns its existing index rather than a fresh one. This
    /// is correctness-critical, not an optimisation. Opaque equality is
    /// `Arc::ptr_eq` (see the `Value::Opaque` arm of `PartialEq`), and a
    /// flat composite body compares by bytes, so two bodies that hold the
    /// same opaque must store the same index for byte equality to coincide
    /// with pointer identity. Without dedup, `(o,) == (o,)` would be false.
    /// The scan is linear in the live opaque count, which the worst-case
    /// memory bound caps.
    pub(crate) fn intern_ephemeral_opaque(
        &mut self,
        opaque: alloc::sync::Arc<dyn crate::opaque::HostOpaque>,
    ) -> usize {
        if let Some(index) = self
            .ephemeral_opaques
            .iter()
            .position(|existing| alloc::sync::Arc::ptr_eq(existing, &opaque))
        {
            return index;
        }
        let index = self.ephemeral_opaques.len();
        self.ephemeral_opaques.push(opaque);
        index
    }

    /// Resolve an ephemeral opaque index back to a cloned `Arc` (B28 P3).
    ///
    /// Returns `None` if the index is out of range. A well-formed flat
    /// body never produces an out-of-range index because the index was
    /// issued by [`Self::intern_ephemeral_opaque`] under the same epoch,
    /// and a `RESET` that clears the registry also reclaims the arena
    /// body holding the index.
    ///
    pub(crate) fn resolve_ephemeral_opaque(
        &self,
        index: usize,
    ) -> Option<alloc::sync::Arc<dyn crate::opaque::HostOpaque>> {
        self.ephemeral_opaques
            .get(index)
            .map(alloc::sync::Arc::clone)
    }

    /// Materialise the internal `OpaqueRef` index form back into the host
    /// `Opaque(Arc)` form, recursively through boxed composites (B33).
    ///
    /// Applied at every boundary where a value crosses into host hands (native
    /// arguments, yield/finish, decode), so host code only ever observes
    /// `Value::Opaque(Arc)`. A flat composite carries its opaque as a byte
    /// index that `decode`/marshalling resolve through the `RefContext`, so a
    /// flat body passes through unchanged. An index that fails to resolve (a
    /// corrupt body, which a well-formed value never produces) is left as the
    /// ref rather than fabricated. The boxed bodies are rebuilt with the
    /// explicit boxed constructors so the body kind is preserved.
    fn materialise_opaque_refs(
        &self,
        value: crate::bytecode::GenericValue<W, F>,
    ) -> crate::bytecode::GenericValue<W, F> {
        use crate::bytecode::{
            ArrayBody, BoxedEnum, BoxedStruct, EnumBody, GenericValue as G, StructBody, TupleBody,
        };
        match value {
            G::OpaqueRef(i) => match self.resolve_ephemeral_opaque(i as usize) {
                Some(arc) => G::Opaque(arc),
                None => G::OpaqueRef(i),
            },
            G::Tuple(TupleBody::Boxed(items)) => G::Tuple(TupleBody::boxed(
                (*items)
                    .into_iter()
                    .map(|e| self.materialise_opaque_refs(e))
                    .collect(),
            )),
            G::Array(ArrayBody::Boxed(items)) => G::Array(ArrayBody::boxed(
                (*items)
                    .into_iter()
                    .map(|e| self.materialise_opaque_refs(e))
                    .collect(),
            )),
            G::Struct(StructBody::Boxed(b)) => {
                let BoxedStruct { type_name, fields } = *b;
                G::Struct(StructBody::boxed(
                    type_name,
                    fields
                        .into_iter()
                        .map(|(k, e)| (k, self.materialise_opaque_refs(e)))
                        .collect(),
                ))
            }
            G::Enum(EnumBody::Boxed(b)) => {
                let BoxedEnum {
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields,
                } = *b;
                G::Enum(EnumBody::boxed_with_layout(
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields
                        .into_iter()
                        .map(|e| self.materialise_opaque_refs(e))
                        .collect(),
                ))
            }
            other => other,
        }
    }

    /// Intern host `Opaque(Arc)` values, replacing each with its POD
    /// `OpaqueRef` index, recursively through boxed composites (B33). The
    /// inverse of [`Self::materialise_opaque_refs`], applied where a
    /// host-supplied value enters the VM (a native result, a host `call` or
    /// `resume` argument), so nothing global-heap-bearing reaches the operand
    /// stack.
    fn intern_opaque_arcs(
        &mut self,
        value: crate::bytecode::GenericValue<W, F>,
    ) -> crate::bytecode::GenericValue<W, F> {
        use crate::bytecode::{
            ArrayBody, BoxedEnum, BoxedStruct, EnumBody, GenericValue as G, StructBody, TupleBody,
        };
        match value {
            G::Opaque(arc) => G::OpaqueRef(self.intern_ephemeral_opaque(arc) as u32),
            G::Tuple(TupleBody::Boxed(items)) => G::Tuple(TupleBody::boxed(
                (*items)
                    .into_iter()
                    .map(|e| self.intern_opaque_arcs(e))
                    .collect(),
            )),
            G::Array(ArrayBody::Boxed(items)) => G::Array(ArrayBody::boxed(
                (*items)
                    .into_iter()
                    .map(|e| self.intern_opaque_arcs(e))
                    .collect(),
            )),
            G::Struct(StructBody::Boxed(b)) => {
                let BoxedStruct { type_name, fields } = *b;
                G::Struct(StructBody::boxed(
                    type_name,
                    fields
                        .into_iter()
                        .map(|(k, e)| (k, self.intern_opaque_arcs(e)))
                        .collect(),
                ))
            }
            G::Enum(EnumBody::Boxed(b)) => {
                let BoxedEnum {
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields,
                } = *b;
                G::Enum(EnumBody::boxed_with_layout(
                    type_name,
                    variant,
                    disc,
                    min_payload,
                    fields
                        .into_iter()
                        .map(|e| self.intern_opaque_arcs(e))
                        .collect(),
                ))
            }
            other => other,
        }
    }

    /// Read a flat scalar field at `offset` of kind `kind` from a resolved
    /// composite body, resolving an `Opaque` field's stored `word_bytes`
    /// index back to its `Arc` through the ephemeral registry (B28 P3).
    /// Non-reference kinds delegate to `read_scalar_le`.
    ///
    /// Returns an error if an opaque index does not resolve. A well-formed
    /// flat body issued under the current epoch always resolves; a failure
    /// indicates a stale body (already caught by the body resolve) or a
    /// corrupt index, and is surfaced rather than producing a wrong value.
    fn read_flat_scalar(
        &self,
        bytes: &[u8],
        offset: usize,
        kind: crate::value_layout::ScalarKind,
        word_bytes: usize,
        float_bytes: usize,
        ref_epoch: u64,
    ) -> Result<crate::bytecode::GenericValue<W, F>, VmError> {
        use crate::value_layout::ScalarKind;
        if matches!(kind, ScalarKind::Opaque) {
            let index = match crate::bytecode::GenericValue::<W, F>::read_scalar_le(
                bytes,
                offset,
                ScalarKind::Int,
                word_bytes,
                float_bytes,
            )? {
                crate::bytecode::GenericValue::Int(w) => w.to_i64() as usize,
                _ => unreachable!("read_scalar_le with Int kind yields Int"),
            };
            // B33: push the POD index form rather than resolving the `Arc`,
            // so the operand stack holds no global-heap pointer. The `Arc` is
            // materialised from the index only at a host boundary (native
            // call, yield, decode), where the registry is in hand and the
            // index is bounds-checked.
            return Ok(crate::bytecode::GenericValue::OpaqueRef(index as u32));
        }
        if matches!(kind, ScalarKind::Text) {
            // A flat Text field is two words: the arena data pointer then
            // the byte length, each read unsigned (a pointer must not be
            // sign-extended). The epoch is supplied by the composite body,
            // not read from the field, and is the epoch under which the
            // referenced string was allocated (B28 P3 item 1). Reattaching
            // that originating epoch (rather than the current arena epoch)
            // makes a read after a `RESET` resolve to a clean `Stale`
            // outcome rather than dereferencing reclaimed memory: the
            // composite's `ref_epoch` no longer matches the advanced arena
            // epoch, so the rebuilt `KString` resolves stale.
            // Bounds-checked, mirroring the non-Text path's `src.get(..)`: the
            // baked `offset` is a raw `u16` operand and may exceed the body, so
            // an unchecked slice would panic in release on untrusted or
            // Top-deferred bytecode (the typed pass bounds this read only for a
            // reconstructed flat shape). A short body faults cleanly instead.
            let read_word = |o: usize| -> Result<usize, VmError> {
                let src = bytes.get(o..o + word_bytes).ok_or_else(|| {
                    VmError::InvalidBytecode(alloc::string::String::from(
                        "flat Text field read out of bounds",
                    ))
                })?;
                let mut buf = [0u8; 8];
                buf[..word_bytes].copy_from_slice(src);
                Ok(u64::from_le_bytes(buf) as usize)
            };
            let ptr = read_word(offset)?;
            let len = read_word(offset + word_bytes)?;
            // A null data pointer is not a live allocation; it is the value a
            // zero-filled body decodes to (for example the persistent composite
            // body pool cleared on a module swap, B28 P3 item 4). Screen it as
            // an empty string rather than building a handle that
            // `addr_is_live` would treat as always-live (a null address is
            // outside the ephemeral region) and then dereference.
            if ptr == 0 {
                return Ok(crate::bytecode::GenericValue::StaticStr(
                    alloc::string::String::new(),
                ));
            }
            // SAFETY: `(ptr, len)` were packed from a `KStr` handle issued
            // under `ref_epoch`. The rebuilt handle carries that epoch, so
            // its `get` dereferences the region only while the arena epoch
            // still matches (the allocation is then intact and UTF-8) and
            // returns `Stale` otherwise.
            let ks = unsafe { crate::kstring::KString::from_raw_parts(ptr, len, ref_epoch) };
            return Ok(crate::bytecode::GenericValue::KStr(ks));
        }
        crate::bytecode::GenericValue::read_scalar_le(bytes, offset, kind, word_bytes, float_bytes)
            .map_err(VmError::from)
    }

    /// Recover from a runtime error and return the VM to a clean
    /// callable state.
    ///
    /// After [`Vm::call`] or [`Vm::resume`] returns `Err(VmError)` the
    /// VM is in an undefined intermediate state. The operand stack,
    /// call frames, and arena may all hold partial values from the
    /// failed iteration. This method clears the volatile state and
    /// returns the VM to the same shape it had before the failed
    /// call. The data segment is preserved so the host can retry
    /// the same iteration with the accumulated state intact.
    ///
    /// Behavior.
    ///
    /// - Operand stack cleared.
    /// - Call frames cleared.
    /// - Arena reset, releasing any dynamic strings or scratch
    ///   buffers from the failed iteration.
    /// - Data segment preserved.
    /// - Bytecode store preserved.
    ///
    /// After this call, [`Vm::call`] starts a fresh iteration of the
    /// entry point. Private data lives in the arena and is preserved;
    /// shared data is the host-owned buffer the host controls directly
    /// (B28 item 2). To reset private data, replace the module via
    /// [`Vm::replace_module`].
    ///
    /// This is the explicit recovery path (P3). Callers attest by
    /// invoking the method that they have inspected the error and
    /// decided to retry. Errors that violated bytecode invariants
    /// (such as `InvalidBytecode`) may indicate a corrupt module and
    /// the host should consider whether retrying is appropriate.
    pub fn reset_after_error(&mut self) {
        // `full_reset_arena_internal` drops and recreates the
        // arena-backed stacks and clears both arena ends. The volatile
        // state is cleared as a side effect.
        let _ = self.full_reset_arena_internal();
        self.started = false;
    }

    /// Replace the current module with a new one as a hot code update.
    ///
    /// This is the host-facing hot swap API (R26, R27). The host is
    /// expected to call this only between a `GenericVmState::Reset` and the
    /// next `call`. The Rust borrow checker enforces that the call
    /// cannot overlap with running execution because that would require
    /// concurrent mutable access to `self`.
    ///
    /// The new module is verified before replacement. `initial_data`
    /// supplies only the new module's **private** data slots, in
    /// declaration order; its length must equal the new module's private
    /// slot count (pass an empty vec for a module with no private data).
    /// Shared data is the host-owned buffer supplied at the next
    /// [`Self::call_with_shared`], not a hot-swap input, so it persists
    /// across the swap in the host's own buffer (B28 item 2).
    ///
    /// Frames and stack are cleared. The host should call `call` to
    /// start the new module's entry point. The old module's coroutine
    /// state, if any, is discarded.
    ///
    /// Dialogue type compatibility between the old and new modules is
    /// the host's responsibility. The VM does not check it because
    /// dialogue types are erased at the bytecode level.
    pub fn replace_module(
        &mut self,
        new_module: Module,
        initial_data: Vec<crate::bytecode::GenericValue<W, F>>,
    ) -> Result<(), VmError> {
        // Strict schema check. Reject hot swaps whose data-segment
        // layout differs from the currently loaded module's layout.
        // The hash covers slot names and visibility in declaration
        // order; modules with no data segment have hash zero and
        // therefore swap freely.
        //
        // The strict check is the safer default. Hosts that need to
        // swap across incompatible schemas (typically because the
        // new module declares a different `data` block by intent)
        // call [`Vm::replace_module_unchecked`] instead, which
        // bypasses this check and leaves the existing
        // size-and-arena verification as the only guard.
        let current_hash: u32 = self.archived().schema_hash.to_native();
        if current_hash != new_module.schema_hash {
            return Err(VmError::VerifyError(format!(
                "schema mismatch on hot swap: current module schema_hash = {:#x}, new module schema_hash = {:#x}. Use `Vm::replace_module_unchecked` to force the swap if the data layout change is intentional.",
                current_hash, new_module.schema_hash
            )));
        }
        self.replace_module_inner(new_module, initial_data)
    }

    /// Hot swap without the schema-compatibility check.
    ///
    /// Equivalent to [`Self::replace_module`] except that the
    /// schema-hash comparison is skipped. Hosts use this when the new
    /// module declares a different data layout from the currently
    /// loaded module by intent; the size check on `initial_data`
    /// continues to enforce that the host supplies the right number
    /// of initial slot values for the new layout.
    ///
    /// `unchecked` names the safety opt-out, not memory safety. The
    /// VM continues to enforce structural verification and resource
    /// bounds; only the schema-hash sanity check is bypassed.
    pub fn replace_module_unchecked(
        &mut self,
        new_module: Module,
        initial_data: Vec<crate::bytecode::GenericValue<W, F>>,
    ) -> Result<(), VmError> {
        self.replace_module_inner(new_module, initial_data)
    }

    /// Hot-swap to a new module loaded from its serialized
    /// bytecode bytes, verifying the cryptographic signature
    /// against the VM's host-supplied trust matrix before the
    /// swap takes effect.
    ///
    /// When the bytecode's framing header carries
    /// [`crate::wire_format::FLAG_REQUIRES_SIGNATURE`], the
    /// signature is verified through
    /// [`crate::wire_format::verify_module_signature`] against
    /// every key the host has registered via
    /// [`Self::register_verifying_key`]. The first matching key
    /// admits the swap; an empty trust matrix or no matching key
    /// produces [`crate::bytecode::LoadError::InvalidSignature`]
    /// and the existing module continues to run.
    ///
    /// When the bytecode is unsigned and the host has registered any
    /// verifying key, the swap is rejected with
    /// [`crate::bytecode::LoadError::InvalidSignature`] (V0.2.1 security
    /// audit, finding 9): a registered trust matrix requires signed
    /// hot-swaps, so enforcement does not depend on the artefact's
    /// self-asserted flag bit. With no registered key, an unsigned swap is
    /// equivalent to decoding the bytes through [`Module::from_bytes`] and
    /// calling [`Self::replace_module`].
    ///
    /// Requires the `signatures` cargo feature.
    #[cfg(feature = "signatures")]
    pub fn replace_module_from_bytes(
        &mut self,
        bytes: &[u8],
        initial_data: Vec<crate::bytecode::GenericValue<W, F>>,
    ) -> Result<(), VmError> {
        if crate::wire_format::header_requires_signature(bytes) {
            crate::wire_format::verify_module_signature(bytes, &self.verifying_keys)
                .map_err(VmError::from)?;
        } else if !self.verifying_keys.is_empty() {
            // Finding 9: a registered trust matrix requires signed hot-swaps.
            // Reject an unsigned (or flag-cleared) module rather than trusting
            // the self-asserted flag bit.
            return Err(VmError::from(crate::bytecode::LoadError::InvalidSignature));
        }
        let new_module = Module::from_bytes(bytes).map_err(VmError::from)?;
        self.replace_module(new_module, initial_data)
    }

    /// Register a verifying key with the VM's trust matrix.
    ///
    /// Subsequent calls to [`Self::replace_module_from_bytes`]
    /// consult the matrix when the incoming bytecode carries
    /// [`crate::wire_format::FLAG_REQUIRES_SIGNATURE`]. The matrix
    /// is additive; hosts that need to rotate trust call
    /// [`Self::clear_verifying_keys`] first and re-register the
    /// new key set.
    ///
    /// Requires the `signatures` cargo feature.
    #[cfg(feature = "signatures")]
    pub fn register_verifying_key(&mut self, key: ed25519_dalek::VerifyingKey) {
        self.verifying_keys.push(key);
    }

    /// Clear every key from the VM's trust matrix. Subsequent
    /// signed hot-swap attempts via
    /// [`Self::replace_module_from_bytes`] are rejected with
    /// [`crate::bytecode::LoadError::InvalidSignature`] until at
    /// least one key is re-registered through
    /// [`Self::register_verifying_key`].
    ///
    /// Requires the `signatures` cargo feature.
    #[cfg(feature = "signatures")]
    pub fn clear_verifying_keys(&mut self) {
        self.verifying_keys.clear();
    }

    /// Number of verifying keys currently in the trust matrix.
    /// Hosts use this for diagnostic logging at deployment time.
    ///
    /// Requires the `signatures` cargo feature.
    #[cfg(feature = "signatures")]
    pub fn verifying_keys_len(&self) -> usize {
        self.verifying_keys.len()
    }

    fn replace_module_inner(
        &mut self,
        new_module: Module,
        initial_data: Vec<crate::bytecode::GenericValue<W, F>>,
    ) -> Result<(), VmError> {
        // B16 step 8: the new module's declared widths must match
        // the runtime's W/A/F trait parameters, same as Vm::new.
        // Without this the hot-swap path would re-introduce the
        // silent-truncation foot-gun the construct path closed.
        Self::check_runtime_widths(
            new_module.word_bits_log2,
            new_module.addr_bits_log2,
            new_module.float_bits_log2,
        )?;
        #[cfg(feature = "verify")]
        {
            verify::verify(&new_module)
                .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
            // R31. Verify the new module's WCMU fits the existing arena.
            // B16 step 11: same parametric value_slot_bytes plumbing
            // as `new_with_options` so the hot-swap path tightens
            // the bound on narrow runtimes.
            let value_slot_bytes =
                core::mem::size_of::<crate::bytecode::GenericValue<W, F>>() as u32;
            verify::verify_resource_bounds_with_natives_and_value_slot_bytes(
                &new_module,
                self.arena.capacity(),
                &[],
                value_slot_bytes,
            )
            .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
        }

        // Partition the new module's slots. `initial_data` populates only the
        // private partition (the arena's persistent region); shared data is the
        // host-owned buffer supplied at the next call, not a hot-swap input
        // (B28 item 2).
        let (new_shared, new_private) = match new_module.data_layout.as_ref() {
            None => (0u16, 0u16),
            Some(dl) => {
                let mut shared = 0u16;
                let mut private_ = 0u16;
                for slot in &dl.slots {
                    match slot.visibility {
                        crate::bytecode::SlotVisibility::Shared => {
                            shared = shared.checked_add(1).ok_or_else(|| {
                                VmError::VerifyError(String::from(
                                    "data layout shared slot count exceeds u16::MAX",
                                ))
                            })?;
                        }
                        crate::bytecode::SlotVisibility::Private => {
                            private_ = private_.checked_add(1).ok_or_else(|| {
                                VmError::VerifyError(String::from(
                                    "data layout private slot count exceeds u16::MAX",
                                ))
                            })?;
                        }
                    }
                }
                (shared, private_)
            }
        };
        if initial_data.len() != new_private as usize {
            return Err(VmError::InvalidBytecode(format!(
                "private data segment size mismatch: new module declares {} private slot(s), host supplied {}",
                new_private,
                initial_data.len()
            )));
        }
        let new_private_storage =
            new_private as usize * core::mem::size_of::<crate::bytecode::GenericValue<W, F>>();
        // The persistent region must hold the new module's private-slot array
        // plus its persistent composite body pool (B28 P3 item 3a). Checking
        // both here surfaces an undersized arena before the swap commits.
        let new_required_persistent =
            new_private_storage + new_module.persistent_composite_bytes as usize;
        if self.arena.persistent_capacity() < new_required_persistent {
            return Err(VmError::VerifyError(format!(
                "arena persistent_capacity ({} bytes) is too small for new module's private data ({} bytes: {} bytes of slots plus {} bytes of persistent composite bodies); resize before hot swap",
                self.arena.persistent_capacity(),
                new_required_persistent,
                new_private_storage,
                new_module.persistent_composite_bytes,
            )));
        }
        // Build the new bytecode image and decode its ops BEFORE touching any
        // old state. These two `?` steps are the only remaining fallible work,
        // so performing them first makes the swap transactional: a failure here
        // returns with the current module fully intact, instead of dropping the
        // old private slots and only then erroring, which left
        // `private_slot_count` stale and made `Drop` double-drop the slots
        // (V0.2.1 security audit, finding 5: hot-swap double-drop /
        // use-after-free).
        let bytes = new_module.to_bytes()?;
        let mut aligned = rkyv::util::AlignedVec::<8>::with_capacity(bytes.len());
        aligned.extend_from_slice(&bytes);
        let decoded_ops = decode_all_ops(aligned.as_slice())?;

        // Commit point: every step below is infallible.
        // Drop the old private slots. Each was initialised at
        // construction or at a prior hot swap and may hold owned
        // resources whose destructor must run.
        let old_private_count = self.private_slot_count as usize;
        if old_private_count > 0 {
            let base =
                self.arena.persistent_ptr().as_ptr() as *mut crate::bytecode::GenericValue<W, F>;
            for i in 0..old_private_count {
                // SAFETY: every old private slot held a valid
                // `Value` initialised through `write_data_slot`
                // or `Vm::construct`. `drop_in_place` runs the
                // destructor in place; the bytes are then
                // uninitialised and ready for `ptr::write`.
                unsafe {
                    core::ptr::drop_in_place(base.add(i));
                }
            }
        }
        // The host-supplied initial values are exactly the new module's
        // private slots; shared slots live in the borrowed buffer.
        let private_init = initial_data;

        // Recompute the bottom-region footprint for the new module so the
        // `full_reset_arena_internal` below re-reserves the operand stack,
        // frames, and registry to the swapped-in module's exact worst case
        // rather than the retired module's (B28 P3 item 5, priority 1).
        let (reserve_slots, reserve_frames, reserve_opaque) =
            module_bottom_reservations(&new_module);
        self.reserved_operand_slots = reserve_slots;
        self.reserved_frame_depth = reserve_frames;
        self.reserved_opaque_capacity = reserve_opaque;
        // Install the new bytecode image and decoded ops built above (before
        // the drop), so the swap is transactional.
        self.bytecode = BytecodeStore::Owned(aligned);
        self.decoded_ops = decoded_ops;
        self.shared_slot_count = new_shared;
        self.private_slot_count = new_private;
        // New bytecode means the native-classification check must
        // re-run; the previous module's chunks are gone and the
        // new module's call sites have not yet been validated
        // against the host's registered classifications.
        self.native_classifications_verified = false;
        // Initialise the new private slots via `ptr::write` (no
        // drop on the destination, because we just dropped the
        // old occupants above).
        if new_private > 0 {
            let base =
                self.arena.persistent_ptr().as_ptr() as *mut crate::bytecode::GenericValue<W, F>;
            for (i, val) in private_init.into_iter().enumerate() {
                // SAFETY: the destination is within the
                // persistent region whose capacity was verified
                // above; the bytes are uninitialised after the
                // drop pass; `ptr::write` does not read the old
                // value.
                unsafe {
                    base.add(i).write(val);
                }
            }
        }
        // Clear the persistent composite body pool that follows the new
        // private-slot array (B28 P3 item 4). The old module's bytecode image
        // was just replaced, so any surviving persistent composite body that
        // embedded a rodata `(ptr, len)` into the freed image now dangles. The
        // body pool is not re-initialised by the private-slot writes above (it
        // holds composite bodies, not slot `Value`s), so it must be zeroed
        // explicitly. A zeroed body decodes its flat Text fields as
        // `(ptr=0, len=0)`, which the read path screens as an empty string, so
        // the new module reads a clean empty body rather than dereferencing the
        // freed image. The new module re-persists each composite slot on its
        // first write. The range is `[new_private_storage, persistent_capacity)`
        // because the new module reads composite bodies only within its own
        // pool, which lies in that tail; the leading slot array was just
        // overwritten.
        let pcap = self.arena.persistent_capacity();
        if pcap > new_private_storage {
            let _ = self
                .arena
                .zero_persistent_range(new_private_storage, pcap - new_private_storage);
        }
        // `full_reset_arena_internal` drops and recreates the
        // arena-backed stacks before clearing both ends. The
        // persistent region is preserved through the reset.
        let _ = self.full_reset_arena_internal();
        // Rebuild the const pool for the swapped-in module (B28 P3 item 2,
        // Increment 2). The old templates referenced the retired image's
        // constants and the old pool boxes; rebuilding reassigns both fields,
        // freeing the old boxes. This runs after `full_reset_arena_internal`
        // has cleared the operand stack, so no live clone of an old template
        // can reference a freed box at the moment it is dropped (and a dropped
        // `Flat(Arena)` handle reads no bytes in any case).
        self.build_const_pool();
        self.started = false;

        Ok(())
    }

    /// Register a native function by name using a function pointer.
    ///
    /// The supplied function does not receive arena context. Native
    /// functions that need arena access for [`crate::bytecode::GenericValue::KStr`] allocation
    /// register through [`Vm::register_native_with_ctx`] instead.
    #[allow(clippy::type_complexity)]
    pub fn register_native(
        &mut self,
        name: &str,
        func: fn(
            &[crate::bytecode::GenericValue<W, F>],
        ) -> Result<crate::bytecode::GenericValue<W, F>, VmError>,
    ) {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet: DEFAULT_NATIVE_WCET,
            wcmu_bytes: DEFAULT_NATIVE_WCMU_BYTES,
            name: String::from(name),
            func: Box::new(
                move |_ctx: &NativeCtx<'_>, args: &[crate::bytecode::GenericValue<W, F>]| {
                    func(args)
                },
            ),
            classification: NativeClassification::Verified,
            max_invocations_per_iteration: None,
        });
    }

    /// Register a native function by name using a closure.
    ///
    /// This allows closures that capture state, such as a shared command
    /// buffer for audio script integration. The closure does not receive
    /// arena context.
    pub fn register_native_closure<Func>(&mut self, name: &str, func: Func)
    where
        Func: Fn(
                &[crate::bytecode::GenericValue<W, F>],
            ) -> Result<crate::bytecode::GenericValue<W, F>, VmError>
            + 'static,
    {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet: DEFAULT_NATIVE_WCET,
            wcmu_bytes: DEFAULT_NATIVE_WCMU_BYTES,
            name: String::from(name),
            func: Box::new(
                move |_ctx: &NativeCtx<'_>, args: &[crate::bytecode::GenericValue<W, F>]| {
                    func(args)
                },
            ),
            classification: NativeClassification::Verified,
            max_invocations_per_iteration: None,
        });
    }

    /// Register a native function that receives arena context.
    ///
    /// The function gains access to the host-owned arena through the
    /// [`NativeCtx`] argument. Use this for natives that produce
    /// arena-allocated dynamic strings via
    /// [`crate::kstring::KString::alloc`] and return them as
    /// [`crate::bytecode::GenericValue::KStr`]. The boundary type carries epoch-tagged
    /// stale-pointer detection. Outstanding handles become
    /// [`keleusma_arena::Stale`] on the next reset.
    #[allow(clippy::type_complexity)]
    pub fn register_native_with_ctx(
        &mut self,
        name: &str,
        func: for<'b> fn(
            &NativeCtx<'b>,
            &[crate::bytecode::GenericValue<W, F>],
        ) -> Result<crate::bytecode::GenericValue<W, F>, VmError>,
    ) {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet: DEFAULT_NATIVE_WCET,
            wcmu_bytes: DEFAULT_NATIVE_WCMU_BYTES,
            name: String::from(name),
            func: Box::new(func),
            classification: NativeClassification::Verified,
            max_invocations_per_iteration: None,
        });
    }

    /// Register a native function that receives arena context using a
    /// closure.
    pub fn register_native_with_ctx_closure<Func>(&mut self, name: &str, func: Func)
    where
        Func: for<'b> Fn(
                &NativeCtx<'b>,
                &[crate::bytecode::GenericValue<W, F>],
            ) -> Result<crate::bytecode::GenericValue<W, F>, VmError>
            + 'static,
    {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet: DEFAULT_NATIVE_WCET,
            wcmu_bytes: DEFAULT_NATIVE_WCMU_BYTES,
            name: String::from(name),
            func: Box::new(func),
            classification: NativeClassification::Verified,
            max_invocations_per_iteration: None,
        });
    }

    /// Register an external native function with an attested upper
    /// bound on the per-iteration invocation count.
    ///
    /// External natives correspond to source-level
    /// `use external module::name` imports; the compiler emits
    /// `Op::CallExternalNative` for their call sites. The host
    /// attests `max_invocations_per_iteration` rather than the
    /// per-call WCET / WCMU budget. The attestation is recorded
    /// on the entry and consumed by future verifier passes; the
    /// current verifier admits external natives without folding
    /// per-call cost into the iteration budget. A mismatch
    /// between the registration classification and the call-site
    /// opcode is rejected at the call-site dispatch.
    #[allow(clippy::type_complexity)]
    pub fn register_external_native(
        &mut self,
        name: &str,
        func: fn(
            &[crate::bytecode::GenericValue<W, F>],
        ) -> Result<crate::bytecode::GenericValue<W, F>, VmError>,
        max_invocations_per_iteration: u32,
    ) {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet: DEFAULT_NATIVE_WCET,
            wcmu_bytes: DEFAULT_NATIVE_WCMU_BYTES,
            name: String::from(name),
            func: Box::new(
                move |_ctx: &NativeCtx<'_>, args: &[crate::bytecode::GenericValue<W, F>]| {
                    func(args)
                },
            ),
            classification: NativeClassification::External,
            max_invocations_per_iteration: Some(max_invocations_per_iteration),
        });
    }

    /// Register a verified native function with attested per-call
    /// WCET and WCMU bounds.
    ///
    /// Verified natives correspond to source-level
    /// `use module::name` imports; the compiler emits
    /// `Op::CallVerifiedNative` for their call sites. The verifier
    /// folds the per-call attested cost into the iteration's
    /// WCET / WCMU budget.
    #[allow(clippy::type_complexity)]
    pub fn register_verified_native(
        &mut self,
        name: &str,
        func: fn(
            &[crate::bytecode::GenericValue<W, F>],
        ) -> Result<crate::bytecode::GenericValue<W, F>, VmError>,
        wcet: u32,
        wcmu_bytes: u32,
    ) {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet,
            wcmu_bytes,
            name: String::from(name),
            func: Box::new(
                move |_ctx: &NativeCtx<'_>, args: &[crate::bytecode::GenericValue<W, F>]| {
                    func(args)
                },
            ),
            classification: NativeClassification::Verified,
            max_invocations_per_iteration: None,
        });
    }

    // register_fn, register_fn_fallible, register_library are
    // marshall-tied and live on a specialized impl<Vm<'a,
    // 'arena>> block below. The marshall layer's IntoNativeFn /
    // KeleusmaType / stddsl::Library traits are concrete on
    // Value; step 6 lifts them to be parametric and these
    // methods can move into this generic impl block.

    /// Re-verify resource bounds with current native attestations.
    ///
    /// Walks the module's call graph, computes per-chunk WCMU including
    /// transitive contributions from chunks and natives, and checks
    /// each Stream chunk against the configured arena capacity. The
    /// host calls this after registering natives and declaring their
    /// bounds via [`Vm::set_native_bounds`].
    ///
    /// Returns an error if any Stream chunk's WCMU exceeds the arena
    /// capacity.
    ///
    /// Available only when the `verify` feature is enabled.
    #[cfg(feature = "verify")]
    pub fn verify_resources(&self) -> Result<(), VmError> {
        let module = self.module_owned()?;
        // Per-native attestations carry both the per-call WCMU
        // bound and the external-native invocation count. The
        // verifier sums per-call WCMU over static call sites for
        // verified natives and applies
        // `max_invocations_per_iteration * per_call_wcmu` once
        // per chunk for external natives.
        let bounds = self.native_iteration_bounds();
        let value_slot_bytes = core::mem::size_of::<crate::bytecode::GenericValue<W, F>>() as u32;
        verify::verify_resource_bounds_with_bounds(
            &module,
            self.arena.capacity(),
            &bounds,
            value_slot_bytes,
        )
        .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))
    }

    /// Compute the smallest arena capacity that admits this VM's module
    /// under current native attestations.
    ///
    /// Returns the maximum WCMU sum across Stream chunks. If the module
    /// has no Stream chunk, returns zero. The host can use this to size
    /// a fresh VM appropriately.
    ///
    /// Available only when the `verify` feature is enabled.
    #[cfg(feature = "verify")]
    pub fn auto_arena_capacity(&self) -> Result<usize, VmError> {
        let module = self.module_owned()?;
        let bounds = self.native_iteration_bounds();
        let chunk_wcmu = verify::module_wcmu_with_bounds(
            &module,
            &bounds,
            crate::bytecode::VALUE_SLOT_SIZE_BYTES,
        )
        .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
        let mut max_total: usize = 0;
        for (chunk_idx, chunk) in module.chunks.iter().enumerate() {
            if chunk.block_type == crate::bytecode::BlockType::Stream {
                let (s, h) = chunk_wcmu[chunk_idx];
                let total = (s as usize).saturating_add(h as usize);
                if total > max_total {
                    max_total = total;
                }
            }
        }
        Ok(max_total)
    }

    /// Worst-case execution time of one Stream iteration including host-attested
    /// native body time, the WCET counterpart of [`Vm::auto_arena_capacity`]
    /// (#50).
    ///
    /// Returns the maximum per-iteration WCET across the module's Stream chunks
    /// in the nominal cost model's unitless cycle space (the same scale as
    /// `Op::cost`), with each native call folding in its attested per-call WCET
    /// (`Vm::set_native_bounds`, default [`DEFAULT_NATIVE_WCET`]): a verified
    /// native's per-call WCET is summed over its call sites and scaled by loop
    /// multiplicity, an external native's is `max_invocations * per_call` once
    /// per chunk. The module's compile-time `wcet_cycles` header is the
    /// script-only bound (natives are not known at compile time); this method is
    /// how a host folds in native body time after registration. Returns zero if
    /// the module has no Stream chunk, and an error if any Stream chunk's WCET is
    /// not statically boundable.
    ///
    /// Available only when the `verify` feature is enabled.
    #[cfg(feature = "verify")]
    pub fn wcet_per_iteration(&self) -> Result<u32, VmError> {
        let module = self.module_owned()?;
        let bounds = self.native_iteration_bounds();
        let per_chunk =
            verify::module_wcet_with_bounds(&module, &bounds, &crate::bytecode::NOMINAL_COST_MODEL)
                .map_err(|e| VmError::VerifyError(format!("{}: {}", e.chunk_name, e.message)))?;
        let mut max_wcet: u32 = 0;
        for (chunk_idx, chunk) in module.chunks.iter().enumerate() {
            if chunk.block_type == crate::bytecode::BlockType::Stream {
                max_wcet = max_wcet.max(per_chunk[chunk_idx]);
            }
        }
        Ok(max_wcet)
    }

    /// Build per-native attestations for the verifier. Verified
    /// natives carry `max_invocations: None` and the
    /// `wcmu_bytes` field set by `set_native_bounds` or the
    /// per-call argument to `register_verified_native`. External
    /// natives carry `max_invocations: Some(n)` set at
    /// `register_external_native`.
    #[cfg(feature = "verify")]
    fn native_iteration_bounds(&self) -> Vec<verify::NativeIterationBound> {
        self.natives
            .iter()
            .map(|n| verify::NativeIterationBound {
                per_call_wcmu_bytes: n.wcmu_bytes,
                per_call_wcet_cycles: n.wcet,
                max_invocations: match n.classification {
                    NativeClassification::Verified => None,
                    NativeClassification::External => {
                        Some(n.max_invocations_per_iteration.unwrap_or(0))
                    }
                },
            })
            .collect()
    }

    /// Verify that every native call site in the loaded module
    /// matches the classification of its registered host native.
    ///
    /// Walks the module's chunks and inspects each
    /// `Op::CallVerifiedNative` / `Op::CallExternalNative` site. For
    /// each site, looks up the native's name through the module's
    /// `native_names` table and finds the matching registered
    /// `NativeEntry`. If the registered classification disagrees
    /// with the opcode's classification, returns
    /// `VmError::VerifyError` with a diagnostic naming both sides.
    /// Native names referenced by the bytecode but not yet
    /// registered are skipped: the dispatch path surfaces them as
    /// `InvalidBytecode` at the first invocation, and the host may
    /// still register the missing native after this method returns.
    ///
    /// The check is run lazily on the first `call` after natives
    /// are registered. The result is cached so subsequent calls do
    /// not repeat the walk. Any `register_*` method or
    /// `replace_module` invalidates the cache. The host may call
    /// this method explicitly to detect mismatches before the
    /// first invocation; doing so eliminates the indirection
    /// through `call` and lets the host surface the diagnostic at
    /// a deployment-validation step rather than at use.
    pub fn verify_native_classifications(&mut self) -> Result<(), VmError> {
        if self.native_classifications_verified {
            return Ok(());
        }
        // Walk the decoded ops to collect native call sites.
        // The decoded_ops field is populated at construction
        // from the wire-format opcode stream and carries the
        // owned `Op` enum directly. The archived form's chunks
        // no longer hold the ops after the Phase 7c cutover.
        let mut sites: Vec<(u16, bool)> = Vec::new();
        {
            for chunk_ops in self.decoded_ops.iter() {
                for op in chunk_ops.iter() {
                    match op {
                        Op::CallVerifiedNative(idx, _) => {
                            sites.push((*idx, false));
                        }
                        Op::CallExternalNative(idx, _) => {
                            sites.push((*idx, true));
                        }
                        _ => {}
                    }
                }
            }
        }
        for (idx, expected_external) in sites {
            let native_name = match self.native_name(idx as usize) {
                Some(name) => name,
                None => {
                    return Err(VmError::InvalidBytecode(format!(
                        "invalid native index: {}",
                        idx
                    )));
                }
            };
            // Skip names that have no registration yet; the call-
            // site dispatch surfaces them as `InvalidBytecode`
            // when the bytecode reaches that site.
            let entry = match self.natives.iter().find(|e| e.name == native_name) {
                Some(e) => e,
                None => continue,
            };
            let entry_external = entry.classification == NativeClassification::External;
            if entry_external != expected_external {
                return Err(VmError::VerifyError(format!(
                    "native `{}` registered as {} but bytecode invokes it as {}",
                    native_name,
                    if entry_external {
                        "external"
                    } else {
                        "verified"
                    },
                    if expected_external {
                        "external"
                    } else {
                        "verified"
                    },
                )));
            }
        }
        self.native_classifications_verified = true;
        Ok(())
    }

    /// Set the worst-case execution time and memory usage attestation for
    /// a previously registered native function.
    ///
    /// The host calls this after `register_native`, `register_fn`, or any
    /// other registration method to provide the upper bounds used by the
    /// static analysis tooling. The bounds are part of the trust boundary
    /// described in R9.
    ///
    /// Returns an error if no native function is registered under the
    /// given name. Applies to all entries registered under that name in
    /// case the host has registered the same name multiple times.
    pub fn set_native_bounds(
        &mut self,
        name: &str,
        wcet: u32,
        wcmu_bytes: u32,
    ) -> Result<(), VmError> {
        let mut found = false;
        for entry in self.natives.iter_mut() {
            if entry.name == name {
                entry.wcet = wcet;
                entry.wcmu_bytes = wcmu_bytes;
                found = true;
            }
        }
        if found {
            Ok(())
        } else {
            Err(VmError::NativeError(format!(
                "no native function registered under name `{}`",
                name
            )))
        }
    }

    /// Call the module's entry point with the given arguments.
    pub fn call(
        &mut self,
        args: &[crate::bytecode::GenericValue<W, F>],
    ) -> Result<GenericVmState<W, F>, VmError> {
        self.call_with_shared(&mut [], args)
    }

    /// Like [`Self::call`], but the host lends a mutable view of its shared
    /// data buffer for the duration of the call (B28 item 2 shared-data
    /// re-architecture). The buffer must be exactly the module's declared
    /// `shared_data_bytes` long, or empty to use the slot model. The virtual
    /// machine reads and writes shared fields in place through the buffer and
    /// retains no reference to it past the return.
    pub fn call_with_shared(
        &mut self,
        shared: &mut [u8],
        args: &[crate::bytecode::GenericValue<W, F>],
    ) -> Result<GenericVmState<W, F>, VmError> {
        self.enter_shared(shared)?;
        let result = self.call_after_enter(args);
        self.shared_buf.clear();
        result
    }

    fn call_after_enter(
        &mut self,
        args: &[crate::bytecode::GenericValue<W, F>],
    ) -> Result<GenericVmState<W, F>, VmError> {
        let entry = self
            .archived()
            .entry_point
            .as_ref()
            .map(|e| e.to_native() as usize)
            .ok_or_else(|| VmError::InvalidBytecode(String::from("no entry point")))?;
        self.call_function(entry, args)
    }

    /// Capture the host shared-data buffer for the current call (B28 item 2).
    ///
    /// The buffer length must equal the module's declared `shared_data_bytes`.
    /// A module with shared data therefore requires a non-empty buffer of the
    /// exact size, so a shared-data module driven through the plain `call`
    /// (which forwards an empty slice) is rejected rather than silently
    /// reading uninitialised state. A module with no shared data
    /// (`shared_data_bytes == 0`) takes the empty buffer the plain `call`
    /// forwards. Cleared before the entry point returns so no captured pointer
    /// outlives the host's borrow.
    fn enter_shared(&mut self, shared: &mut [u8]) -> Result<(), VmError> {
        let need = self.archived().shared_data_bytes.to_native() as usize;
        if shared.len() != need {
            return Err(VmError::NativeError(format!(
                "shared data buffer is {} bytes but the module declares {}; drive a module with shared data through `call_with_shared`/`resume_with_shared` with a buffer of `shared_data_bytes()`",
                shared.len(),
                need
            )));
        }
        if need == 0 {
            self.shared_buf.clear();
        } else {
            self.shared_buf.set(shared);
        }
        Ok(())
    }

    /// Call a specific function by chunk index with the given arguments.
    pub fn call_function(
        &mut self,
        chunk_idx: usize,
        args: &[crate::bytecode::GenericValue<W, F>],
    ) -> Result<GenericVmState<W, F>, VmError> {
        // Native-classification check runs lazily before any
        // execution. The first call after natives are registered
        // (or after a hot swap) walks every native-call site and
        // verifies the bytecode-declared classification matches
        // the host's registered classification. Subsequent calls
        // skip the walk because the result is cached.
        self.verify_native_classifications()?;
        let archived = self.archived();
        let chunk = archived.chunks.get(chunk_idx).ok_or_else(|| {
            VmError::InvalidBytecode(format!("invalid chunk index: {}", chunk_idx))
        })?;
        let local_count = chunk.local_count.to_native() as usize;
        let param_count = chunk.param_count as usize;

        // Validate the argument count up front. Passing too few
        // arguments would default the missing parameter slots to
        // `crate::bytecode::GenericValue::Unit`, which the body then trips over at the
        // first use site with a confusing TypeError. Failing here
        // gives the host a clear signal that the call signature
        // is wrong before any bytecode runs.
        if args.len() != param_count {
            return Err(VmError::TypeError(format!(
                "function `{}` expected {} argument{}, got {}",
                chunk.name.as_str(),
                param_count,
                if param_count == 1 { "" } else { "s" },
                args.len()
            )));
        }

        // Validate each argument's runtime type against the
        // parameter's declared type tag. Composite types
        // (struct, enum, tuple, array, option, opaque) accept any
        // `Value`; primitive types accept only their matching
        // variant. The early rejection produces a clearer error
        // than the eventual TypeError at the first use site.
        for (i, (arg, tag)) in args.iter().zip(chunk.param_types.iter()).enumerate() {
            let tag = crate::bytecode::TypeTag::from_archived(tag);
            if !tag.admits(arg) {
                return Err(VmError::TypeError(format!(
                    "function `{}` parameter {} expected {}, got {}",
                    chunk.name.as_str(),
                    i,
                    tag.name(),
                    arg.type_name()
                )));
            }
        }

        let base = self.stack.len();
        // Push arguments as the first local slots. A host-built composite
        // argument is canonicalised to an arena-resident flat body so the
        // script's compiler-baked flat field access can read it; the host
        // constructors produce the boxed representation, which flat access
        // rejects (B28 item 2 step 6B). The widths are the module widths, the
        // cast contract of `from_value_ctx` (B36). A scalar or reference
        // argument, and a reference-bearing composite that stays boxed, are
        // returned unchanged.
        let arena = self.arena;
        let wb = self.module_word_bytes();
        let fb = self.module_float_bytes();
        for arg in args {
            let arg = self
                .correct_native_enum_hints(arg.clone())
                .into_arena_canonical(wb, fb, arena)
                .map_err(|_| out_of_arena_push("composite argument", arena.capacity()))?;
            // Intern a host-supplied opaque argument to the POD index form
            // before it reaches the operand stack (B33).
            let arg = self.intern_opaque_arcs(arg);
            sp!(self, arg);
        }
        // Extend stack for remaining local slots.
        let extra = local_count - args.len();
        for _ in 0..extra {
            sp!(self, crate::bytecode::GenericValue::Unit);
        }

        fp!(
            self,
            CallFrame {
                chunk_idx,
                ip: 0,
                base,
            }
        );
        self.started = true;

        self.run()
    }

    /// Resume execution and signal that the requested input could not
    /// be produced.
    ///
    /// This is a convenience over [`Vm::resume`] that documents the
    /// host's intent to propagate an error rather than supply a
    /// successful input. The supplied `error_value` flows through the
    /// script's yield expression unchanged. The script handles the
    /// error by pattern-matching against the value.
    ///
    /// Idiomatic usage. The script types its yield as `Option<T>` or a
    /// script-defined Result-like enum and pattern-matches:
    ///
    /// ```text
    /// let result: Option<i64> = yield request;
    /// match result {
    ///     Some(v) => { /* use v */ }
    ///     None => { /* recover from error */ }
    /// }
    /// ```
    ///
    /// The host then calls `resume(crate::bytecode::GenericValue::Int(v))` for success and
    /// [`Vm::resume_err`] (with `crate::bytecode::GenericValue::None`) for failure. For
    /// richer errors, the script defines an enum like
    /// `enum Reply { Ok(i64), Err(String) }` and the host resumes
    /// with the corresponding `crate::bytecode::GenericValue::Enum` variant.
    ///
    /// If the script does not handle the error case (does not match
    /// the error variant) the next operation that consumes the value
    /// traps with a runtime type error. This matches Keleusma's
    /// general dynamic-tag dispatch contract; it is not a new failure
    /// mode introduced by this API.
    ///
    /// The API does not perform any wrapping: the returned `VmState`
    /// reflects whatever the script does next. Hosts that want
    /// automatic propagation (Rust-like `?`) must implement that
    /// pattern in the script through pattern matching and early
    /// `return`.
    pub fn resume_err(
        &mut self,
        error_value: crate::bytecode::GenericValue<W, F>,
    ) -> Result<GenericVmState<W, F>, VmError> {
        self.resume(error_value)
    }

    /// Resume execution after a yield or reset, providing the input value.
    pub fn resume(
        &mut self,
        input: crate::bytecode::GenericValue<W, F>,
    ) -> Result<GenericVmState<W, F>, VmError> {
        self.resume_with_shared(&mut [], input)
    }

    /// Like [`Self::resume`], but the host lends a mutable view of its shared
    /// data buffer for the duration of the resume (B28 item 2). The buffer
    /// rules match [`Self::call_with_shared`]: exactly `shared_data_bytes`
    /// long, or empty for the slot model. Between resumes the host owns the
    /// buffer and may swap, mutate, or drop it; the virtual machine retains no
    /// reference across the yield.
    pub fn resume_with_shared(
        &mut self,
        shared: &mut [u8],
        input: crate::bytecode::GenericValue<W, F>,
    ) -> Result<GenericVmState<W, F>, VmError> {
        self.enter_shared(shared)?;
        let result = self.resume_after_enter(input);
        self.shared_buf.clear();
        result
    }

    fn resume_after_enter(
        &mut self,
        input: crate::bytecode::GenericValue<W, F>,
    ) -> Result<GenericVmState<W, F>, VmError> {
        if !self.started || self.frames.is_empty() {
            return Err(VmError::NotSuspended);
        }
        // Canonicalise a host-built composite resume value to an arena-resident
        // flat body, the same VM-entry treatment `call_function` applies to its
        // arguments, so the script's flat-baked field access reads the resumed
        // value (B28 item 2 step 6B). At module widths (the `from_value_ctx`
        // cast contract, B36). Scalars and reference-bearing composites pass
        // through unchanged.
        let arena = self.arena;
        let wb = self.module_word_bytes();
        let fb = self.module_float_bytes();
        let input = self
            .correct_native_enum_hints(input)
            .into_arena_canonical(wb, fb, arena)
            .map_err(|_| out_of_arena_push("composite resume value", arena.capacity()))?;
        // Intern a host-supplied opaque resume value to the POD index form (B33).
        let input = self.intern_opaque_arcs(input);
        // For stream functions, update the parameter slot with the new input.
        // This ensures the next iteration sees the latest input.
        if let Some(base_frame) = self.frames.first().copied() {
            let archived = self.archived();
            let chunk = &archived.chunks[base_frame.chunk_idx];
            let block_type = match &chunk.block_type {
                crate::bytecode::ArchivedBlockType::Stream => BlockType::Stream,
                crate::bytecode::ArchivedBlockType::Reentrant => BlockType::Reentrant,
                crate::bytecode::ArchivedBlockType::Func => BlockType::Func,
            };
            let param_count = chunk.param_count;
            if block_type == BlockType::Stream && param_count > 0 {
                // Validate the resume value against the loop's
                // parameter type. The yield expression inside the
                // loop body has the same static type as the
                // parameter (resume provides the next iteration's
                // input); rejecting a wrong-typed value here gives
                // the host a clear signal at the resume boundary
                // rather than a confusing TypeError when the body
                // first uses the resumed value.
                if let Some(tag) = chunk.param_types.first() {
                    let tag = crate::bytecode::TypeTag::from_archived(tag);
                    if !tag.admits(&input) {
                        return Err(VmError::TypeError(format!(
                            "loop `{}` resume expected {}, got {}",
                            chunk.name.as_str(),
                            tag.name(),
                            input.type_name()
                        )));
                    }
                }
                let base = base_frame.base;
                self.stack[base] = input.clone();
            }
        }
        // Push the input value onto the stack (it becomes the yield expression result).
        sp!(self, input);
        self.run()
    }

    /// Arm a breakpoint at `(chunk, op)`. When execution reaches that
    /// op the VM suspends with [`GenericVmState::BreakpointHit`] before
    /// executing it. Idempotent: arming an already-armed position is a
    /// no-op. A debugger obtains the position from a `BreakpointCandidate`
    /// debug record's op index (see [`crate::debug_meta`]). Breakpoints
    /// are runtime state and do not modify the bytecode, preserving
    /// signing, encryption, and verification.
    pub fn set_breakpoint(&mut self, chunk: usize, op: usize) {
        let pos = (chunk, op);
        if !self.breakpoints.contains(&pos) {
            self.breakpoints.push(pos);
        }
    }

    /// Disarm the breakpoint at `(chunk, op)`. Returns true if a
    /// breakpoint was present and removed.
    pub fn clear_breakpoint(&mut self, chunk: usize, op: usize) -> bool {
        let pos = (chunk, op);
        if let Some(i) = self.breakpoints.iter().position(|p| *p == pos) {
            self.breakpoints.swap_remove(i);
            if self.skip_breakpoint_at == Some(pos) {
                self.skip_breakpoint_at = None;
            }
            true
        } else {
            false
        }
    }

    /// Disarm all breakpoints.
    pub fn clear_breakpoints(&mut self) {
        self.breakpoints.clear();
        self.skip_breakpoint_at = None;
    }

    /// The number of armed breakpoints.
    pub fn breakpoint_count(&self) -> usize {
        self.breakpoints.len()
    }

    /// Resume execution after a [`GenericVmState::BreakpointHit`]. The
    /// op at the breakpoint position runs (the breakpoint does not
    /// re-trigger on this step), then execution continues to the next
    /// suspension or completion. Unlike [`resume`](Self::resume) this
    /// pushes no value, since a breakpoint is not a yield. Returns
    /// [`VmError::NotSuspended`] if the VM is not in a suspended state.
    pub fn resume_from_breakpoint(&mut self) -> Result<GenericVmState<W, F>, VmError> {
        if !self.started || self.frames.is_empty() {
            return Err(VmError::NotSuspended);
        }
        // The top frame's position is the breakpoint we paused before;
        // suppress it once so the op executes rather than re-triggering.
        let frame = *self.frames.last().ok_or(VmError::NotSuspended)?;
        self.skip_breakpoint_at = Some((frame.chunk_idx, frame.ip));
        self.run()
    }

    /// The position `(chunk_idx, op_index)` of the op the VM was
    /// executing when the most recent `call`/`resume` returned an error,
    /// or `None` after a successful run or before any run.
    ///
    /// This is the B29 read path into the trap path: a runtime trap (an
    /// unhandled partial operation, a failed debug `assert`, a type
    /// error) leaves the faulting op here so a host can map it back to
    /// source through the chunk's debug records, either directly with
    /// [`crate::debug_meta::DebugPool::records_at`] or through the
    /// convenience [`fault_source_location`](Self::fault_source_location).
    ///
    /// The location is meaningful for faults that arise while executing
    /// an op (the recoverable `SoftScript`/`SoftHost` traps and most
    /// `Halt` cases). It is `None` for failures that occur before any op
    /// is dispatched, such as a load- or verify-time rejection from
    /// [`Vm::new`], which never enters the run loop.
    pub fn fault_location(&self) -> Option<(usize, usize)> {
        self.fault_location
    }

    /// Decode the strippable debug pool of `chunk_idx` from the archived
    /// bytecode, or `None` when the chunk carries none (a release build,
    /// or after `strip`). Decoded on demand; this is a cold path used
    /// only when a host resolves a fault, so it is not cached.
    fn chunk_debug_pool(&self, chunk_idx: usize) -> Option<crate::debug_meta::DebugPool> {
        let chunk = self.archived().chunks.get(chunk_idx)?;
        let bytes = chunk.debug_pool_bytes.as_ref()?;
        crate::debug_meta::DebugPool::decode(bytes.as_slice()).ok()
    }

    /// Resolve the most recent fault to a [`FaultSource`] through the
    /// faulting chunk's debug records, or `None` when there is no fault,
    /// the chunk carries no debug pool (release build or stripped), or
    /// no record maps the position to a span.
    ///
    /// Resolution is two-tier and never fabricates a location. First,
    /// if a span-bearing record (`CallSite`, `SourceSpan`,
    /// `AssertionContext`, `BreakpointCandidate`) sits exactly at the
    /// faulting op, its span is returned with `exact = true`. Otherwise
    /// the nearest enclosing statement is used: the `SourceSpan` with
    /// the greatest op index at or before the fault, returned with
    /// `exact = false`. Because span-bearing records that do not land on
    /// the faulting op (most mid-statement partial-operation traps) only
    /// resolve to the enclosing statement, callers needing the precise
    /// site should consult `exact`.
    pub fn fault_source_location(&self) -> Option<FaultSource> {
        let (chunk_idx, op) = self.fault_location?;
        let pool = self.chunk_debug_pool(chunk_idx)?;
        let op_u32 = op as u32;

        // Tier 1: an exact span-bearing record at the faulting op.
        for record in pool.records_at(op_u32) {
            if let Some(loc) = pool.source_location(record) {
                return Some(FaultSource {
                    file: loc.file.map(alloc::string::String::from),
                    byte_offset: loc.byte_offset,
                    byte_length: loc.byte_length,
                    exact: true,
                });
            }
        }

        // Tier 2: the nearest enclosing statement's SourceSpan, i.e. the
        // SourceSpan record with the greatest op index at or before the
        // fault. SourceSpan records are emitted at each statement's
        // starting op in op order, so this is the statement covering the
        // fault, not a guess.
        let enclosing = pool
            .records
            .iter()
            .filter(|r| {
                r.kind == crate::debug_meta::DebugRecordKind::SourceSpan && r.op_index <= op_u32
            })
            .max_by_key(|r| r.op_index)?;
        let loc = pool.source_location(enclosing)?;
        Some(FaultSource {
            file: loc.file.map(alloc::string::String::from),
            byte_offset: loc.byte_offset,
            byte_length: loc.byte_length,
            exact: false,
        })
    }

    /// Execute bytecode until yield, return, reset, or error.
    /// Execute until the VM yields, finishes, resets, hits a
    /// breakpoint, or errors. Thin wrapper over [`run_inner`] that
    /// maintains [`fault_location`](Self::fault_location): the loop
    /// records the op it is about to dispatch in `self.fault_location`,
    /// so on an error return that field already names the faulting op.
    /// On a successful outcome the field is cleared, so it is `Some`
    /// only after a fault.
    fn run(&mut self) -> Result<GenericVmState<W, F>, VmError> {
        let result = self.run_inner();
        if result.is_ok() {
            self.fault_location = None;
        }
        result
    }

    fn run_inner(&mut self) -> Result<GenericVmState<W, F>, VmError> {
        loop {
            if self.frames.is_empty() {
                return Err(VmError::InvalidBytecode(String::from("empty call stack")));
            }

            let frame = self.frames.last().unwrap();
            let chunk_idx = frame.chunk_idx;
            let ip = frame.ip;
            let base = frame.base;

            if ip >= self.chunk_op_count(chunk_idx) {
                // End of chunk without explicit return: return Unit.
                let result = self
                    .stack
                    .pop()
                    .unwrap_or(crate::bytecode::GenericValue::Unit);
                self.frames.pop();
                if self.frames.is_empty() {
                    // Read-before-resume (B28 P3 item 5 C3): the returned value
                    // stays arena-resident rather than being copied to the
                    // global heap. The host decodes it through `Vm::decode`
                    // before the next `resume()` or before dropping the VM; a
                    // later read resolves to a clean stale error, never UB.
                    // Opaque indices are materialised to `Arc` so host code can
                    // pattern-match `Value::Opaque` directly without `decode`
                    // (B33); flat composites and `KStr` stay arena-resident.
                    return Ok(GenericVmState::Finished(
                        self.materialise_opaque_refs(result),
                    ));
                }
                sp!(self, result);
                continue;
            }

            // Breakpoint check. Suspend before executing the op at an
            // armed position, leaving the stacks and `ip` intact so a
            // later `resume_from_breakpoint` continues here. The
            // `is_empty` guard keeps this zero-cost when no breakpoints
            // are armed. `skip_breakpoint_at` is a one-shot suppression
            // so resuming runs the op rather than re-triggering.
            if !self.breakpoints.is_empty() {
                let pos = (chunk_idx, ip);
                if self.skip_breakpoint_at == Some(pos) {
                    self.skip_breakpoint_at = None;
                } else if self.breakpoints.contains(&pos) {
                    return Ok(GenericVmState::BreakpointHit {
                        chunk: chunk_idx,
                        op: ip,
                    });
                }
            }

            let op = self.chunk_op(chunk_idx, ip);
            // Record the op about to be dispatched as the candidate
            // fault location. If any arm below returns an error, the
            // `run` wrapper leaves this in place as the faulting op;
            // on success it clears it. A single `Option` write per op.
            self.fault_location = Some((chunk_idx, ip));
            // Advance IP.
            self.frames.last_mut().unwrap().ip += 1;

            match op {
                Op::Const(idx) => {
                    let val = self.chunk_const(chunk_idx, idx as usize);
                    sp!(self, val);
                }

                Op::GetLocal(slot) => {
                    let val = self.stack[base + slot as usize].clone();
                    sp!(self, val);
                }
                Op::SetLocal(slot) => {
                    let val = self.pop()?;
                    self.stack[base + slot as usize] = val;
                }

                Op::GetData(slot) => {
                    let idx = slot as usize;
                    let total = self.data_len();
                    if idx >= total {
                        return Err(VmError::InvalidBytecode(format!(
                            "data slot index {} out of bounds",
                            idx
                        )));
                    }
                    let val = self.read_data_slot(idx)?;
                    sp!(self, val);
                }
                Op::SetData(slot) => {
                    let idx = slot as usize;
                    let total = self.data_len();
                    if idx >= total {
                        return Err(VmError::InvalidBytecode(format!(
                            "data slot index {} out of bounds",
                            idx
                        )));
                    }
                    // A data slot lives in the persistent region and survives
                    // RESET. `write_data_slot` persists a flat composite body
                    // into the persistent composite pool at its compiler-baked
                    // offset (B28 item 2 step 6A), so no ephemeral arena handle
                    // is stored in a persistent slot and no global-heap owned
                    // body is needed; a scalar is stored directly.
                    let val = self.pop()?;
                    self.write_data_slot(idx, val)?;
                }
                Op::GetDataIndexed(base, len) => {
                    let index = match self.pop()? {
                        crate::bytecode::GenericValue::Int(n) => n,
                        other => {
                            return Err(VmError::TypeError(format!(
                                "GetDataIndexed expected Int index, got {}",
                                other.type_name()
                            )));
                        }
                    };
                    if index.to_i64() < 0 || index.to_i64() >= len as i64 {
                        return Err(VmError::IndexOutOfBounds(index.to_i64(), len as usize));
                    }
                    let slot = base as usize + index.to_i64() as usize;
                    let total = self.data_len();
                    if slot >= total {
                        return Err(VmError::InvalidBytecode(format!(
                            "GetDataIndexed slot {} out of bounds",
                            slot
                        )));
                    }
                    let val = self.read_data_slot(slot)?;
                    sp!(self, val);
                }
                Op::SetDataIndexed(base, len) => {
                    let index = match self.pop()? {
                        crate::bytecode::GenericValue::Int(n) => n,
                        other => {
                            return Err(VmError::TypeError(format!(
                                "SetDataIndexed expected Int index, got {}",
                                other.type_name()
                            )));
                        }
                    };
                    if index.to_i64() < 0 || index.to_i64() >= len as i64 {
                        return Err(VmError::IndexOutOfBounds(index.to_i64(), len as usize));
                    }
                    // `write_data_slot` persists a flat composite element into
                    // the persistent composite pool at the element slot's
                    // compiler-baked offset (B28 item 2 step 6A); an
                    // array-of-composite element therefore survives RESET in
                    // place with no global-heap owned body. A scalar element is
                    // stored directly.
                    let val = self.pop()?;
                    let slot = base as usize + index.to_i64() as usize;
                    let total = self.data_len();
                    if slot >= total {
                        return Err(VmError::InvalidBytecode(format!(
                            "SetDataIndexed slot {} out of bounds",
                            slot
                        )));
                    }
                    self.write_data_slot(slot, val)?;
                }
                Op::BoundsCheck(bound) => {
                    // Peek the top of the stack; trap if it is not a
                    // non-negative `Int` strictly less than `bound`.
                    // The stack is not modified.
                    let top = self.stack.last().ok_or(VmError::StackUnderflow)?;
                    let value = match top {
                        crate::bytecode::GenericValue::Int(n) => *n,
                        other => {
                            return Err(VmError::TypeError(format!(
                                "BoundsCheck expected Int, got {}",
                                other.type_name()
                            )));
                        }
                    };
                    if value.to_i64() < 0 || value.to_i64() >= bound as i64 {
                        return Err(VmError::IndexOutOfBounds(value.to_i64(), bound as usize));
                    }
                }

                Op::Add => {
                    // Consolidation B narrowed `Op::Add` away from
                    // `Int` operands. The compiler emits
                    // `CheckedAdd; PopN(2)` for any `Int + Int`
                    // expression and routes only `Byte`, `Fixed`,
                    // and `Float` through this opcode.
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            sp!(self, crate::bytecode::GenericValue::Byte(x.wrapping_add(y)));
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Fixed Add is integer add of the
                            // fixed-point bits; the fraction-bit
                            // count is the same for both operands
                            // by type-check invariant.
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Fixed(x.wrapping_add(y))
                            );
                        }
                        #[cfg(feature = "floats")]
                        (
                            crate::bytecode::GenericValue::Float(x),
                            crate::bytecode::GenericValue::Float(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Float(x + y)),
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "cannot add {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::Sub => self.binary_arith(|a: W, b: W| a.wrapping_sub(b), |a: F, b: F| a - b)?,
                Op::Mul => self.binary_arith(|a: W, b: W| a.wrapping_mul(b), |a: F, b: F| a * b)?,
                Op::Div => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(_),
                            crate::bytecode::GenericValue::Int(y),
                        ) if y == W::default() => {
                            return Err(VmError::DivisionByZero);
                        }
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Int(x.wrapping_div(y))),
                        (
                            crate::bytecode::GenericValue::Byte(_),
                            crate::bytecode::GenericValue::Byte(0),
                        ) => return Err(VmError::DivisionByZero),
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            sp!(self, crate::bytecode::GenericValue::Byte(x.wrapping_div(y)));
                        }
                        #[cfg(feature = "floats")]
                        (
                            crate::bytecode::GenericValue::Float(x),
                            crate::bytecode::GenericValue::Float(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Float(x / y)),
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "cannot divide {} by {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::Mod => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(_),
                            crate::bytecode::GenericValue::Int(y),
                        ) if y == W::default() => {
                            return Err(VmError::DivisionByZero);
                        }
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Int(x.wrapping_rem(y))),
                        (
                            crate::bytecode::GenericValue::Byte(_),
                            crate::bytecode::GenericValue::Byte(0),
                        ) => return Err(VmError::DivisionByZero),
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            sp!(self, crate::bytecode::GenericValue::Byte(x.wrapping_rem(y)));
                        }
                        #[cfg(feature = "floats")]
                        (
                            crate::bytecode::GenericValue::Float(x),
                            crate::bytecode::GenericValue::Float(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Float(x % y)),
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "cannot modulo {} by {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::Neg => {
                    // Consolidation B narrowed `Op::Neg` away from
                    // `Int` operands. The compiler emits
                    // `CheckedNeg; PopN(2)` for `-Int`. This opcode
                    // handles `Byte`, `Fixed`, and `Float`.
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Byte(x) => {
                            sp!(self, crate::bytecode::GenericValue::Byte(x.wrapping_neg()))
                        }
                        crate::bytecode::GenericValue::Fixed(x) => {
                            sp!(self, crate::bytecode::GenericValue::Fixed(x.wrapping_neg()))
                        }
                        #[cfg(feature = "floats")]
                        crate::bytecode::GenericValue::Float(x) => {
                            sp!(self, crate::bytecode::GenericValue::Float(-x))
                        }
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot negate {}",
                                v.type_name()
                            )));
                        }
                    }
                }

                Op::CmpEq => {
                    // No copy out of the arena (B28 P3 item 5 zero-copy). The
                    // compiler emits every nameable composite comparison
                    // field-wise, so a flat composite reaching `CmpEq` is one
                    // whose type the compiler could not determine (an
                    // unsignatured native's composite result); a raw-byte
                    // compare would silently mishandle IEEE floats, so two flat
                    // composites fault here on a variant check. Every surviving
                    // pair (a scalar, a flat composite against a non-composite,
                    // or a boxed composite) reaches a `PartialEq` arm that never
                    // reads a flat body, so the arena body is never dereferenced
                    // without the arena.
                    let b = self.pop()?;
                    let a = self.pop()?;
                    // Two strings compare by content (resolved through the
                    // arena), so a rodata or arena `KStr` is never compared by
                    // handle identity (B28 P3 item 4). Other operands keep the
                    // structural comparison.
                    if let Some(eq) = self.string_content_eq(&a, &b)? {
                        sp!(self, crate::bytecode::GenericValue::Bool(eq));
                    } else {
                        reject_untyped_flat_composite_cmp(&a, &b)?;
                        sp!(self, crate::bytecode::GenericValue::Bool(a == b));
                    }
                }
                Op::CmpNe => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    if let Some(eq) = self.string_content_eq(&a, &b)? {
                        sp!(self, crate::bytecode::GenericValue::Bool(!eq));
                    } else {
                        reject_untyped_flat_composite_cmp(&a, &b)?;
                        sp!(self, crate::bytecode::GenericValue::Bool(a != b));
                    }
                }
                Op::CmpLt => self.compare_op(|ord| ord.is_lt())?,
                Op::CmpGt => self.compare_op(|ord| ord.is_gt())?,
                Op::CmpLe => self.compare_op(|ord| ord.is_le())?,
                Op::CmpGe => self.compare_op(|ord| ord.is_ge())?,

                Op::Not => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Bool(b) => {
                            sp!(self, crate::bytecode::GenericValue::Bool(!b))
                        }
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot apply not to {}",
                                v.type_name()
                            )));
                        }
                    }
                }

                // -- Block-structured control flow --
                Op::If(target) => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Bool(false) => {
                            self.frames.last_mut().unwrap().ip = target as usize;
                        }
                        crate::bytecode::GenericValue::Bool(true) => {
                            // Continue to then-block.
                        }
                        v => {
                            return Err(VmError::TypeError(format!(
                                "condition must be Bool, got {}",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::Else(target) => {
                    // Reached when then-block completes. Skip else-block.
                    self.frames.last_mut().unwrap().ip = target as usize;
                }
                Op::EndIf => {
                    // No-op. Block delimiter.
                }

                Op::Loop(_) => {
                    // No-op at entry. Target is used by Break/BreakIf.
                }
                Op::EndLoop(target) => {
                    // Back-edge: jump to instruction after Loop.
                    self.frames.last_mut().unwrap().ip = target as usize;
                }
                Op::Break(target) => {
                    self.frames.last_mut().unwrap().ip = target as usize;
                }
                Op::BreakIf(target) => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Bool(true) => {
                            self.frames.last_mut().unwrap().ip = target as usize;
                        }
                        crate::bytecode::GenericValue::Bool(false) => {
                            // Continue loop body.
                        }
                        v => {
                            return Err(VmError::TypeError(format!(
                                "BreakIf condition must be Bool, got {}",
                                v.type_name()
                            )));
                        }
                    }
                }

                // -- Streaming --
                Op::Stream => {
                    // No-op. Marks the stream entry point.
                }
                Op::Reset => {
                    // Reset locals to Unit, truncate stack, reset arena pointers.
                    let (reset_base, reset_chunk_idx) = {
                        let frame = self.frames.last().unwrap();
                        (frame.base, frame.chunk_idx)
                    };
                    let local_count = self.chunk_local_count(reset_chunk_idx) as usize;

                    // Clear locals to Unit.
                    for i in 0..local_count {
                        self.stack[reset_base + i] = crate::bytecode::GenericValue::Unit;
                    }
                    // Truncate stack to just the locals.
                    self.stack.truncate(reset_base + local_count);

                    // Reset both arena bump pointers (R32). Host-allocated
                    // dynamic strings and other arena values are reclaimed
                    // here.
                    let _ = self.reset_arena_internal();
                    // Drop ephemeral opaque references reachable from the
                    // arena bodies just reclaimed (B28 P3); their `Drop`
                    // decrements the host refcount.
                    self.ephemeral_opaques.clear();

                    // Find Stream instruction and set IP to
                    // instruction after it. V0.2.0 Phase 7c reads
                    // decoded_ops instead of the archived chunk's
                    // (no longer present) ops field.
                    let stream_ip = self.decoded_ops[reset_chunk_idx]
                        .iter()
                        .position(|op| matches!(op, Op::Stream));
                    match stream_ip {
                        Some(pos) => self.frames.last_mut().unwrap().ip = pos + 1,
                        None => {
                            return Err(VmError::InvalidBytecode(String::from(
                                "Reset without Stream in chunk",
                            )));
                        }
                    }

                    return Ok(GenericVmState::Reset);
                }

                // -- Functions --
                Op::Call(idx, arg_count) => {
                    if idx as usize >= self.chunk_count() {
                        return Err(VmError::InvalidBytecode(format!("invalid chunk: {}", idx)));
                    }
                    let called_local_count = self.chunk_local_count(idx as usize) as usize;
                    // Guard both subtractions against malformed bytecode
                    // (audit findings 4, 16, 18). `new_base` underflows when
                    // the call claims more arguments than are on the stack;
                    // `extra` underflows when the argument count exceeds the
                    // callee's local-slot count (an arity mismatch). Both
                    // return a clean error instead of panicking or wrapping
                    // to a wild frame base.
                    let new_base = self
                        .stack
                        .len()
                        .checked_sub(arg_count as usize)
                        .ok_or(VmError::StackUnderflow)?;
                    let extra = called_local_count
                        .checked_sub(arg_count as usize)
                        .ok_or_else(|| {
                            VmError::InvalidBytecode(String::from(
                                "call argument count exceeds the callee's local slot count",
                            ))
                        })?;
                    for _ in 0..extra {
                        sp!(self, crate::bytecode::GenericValue::Unit);
                    }
                    fp!(
                        self,
                        CallFrame {
                            chunk_idx: idx as usize,
                            ip: 0,
                            base: new_base,
                        }
                    );
                }
                Op::Return => {
                    let result = self.pop()?;
                    let old_frame = self.frames.pop().unwrap();
                    self.stack.truncate(old_frame.base);
                    if self.frames.is_empty() {
                        // Read-before-resume (B28 P3 item 5 C3): the returned
                        // value stays arena-resident. The host decodes it before
                        // the next `resume()` or before dropping the VM. Opaque
                        // indices materialise to `Arc` (B33).
                        return Ok(GenericVmState::Finished(
                            self.materialise_opaque_refs(result),
                        ));
                    }
                    sp!(self, result);
                }

                Op::Yield => {
                    let output = self.pop()?;
                    // Reject a yielded value that transitively contains an
                    // EPHEMERAL dynamic string (R31, B28 P3 item 4). An
                    // ephemeral string is an arena pointer the next RESET
                    // reclaims, so it would dangle after the boundary. A rodata
                    // string constant, now a `KStr` pointing at the immortal
                    // bytecode image, is outside the ephemeral region and is
                    // free to cross. The check reads boxed bodies only; an
                    // ephemeral flat Text field inside a composite is governed
                    // by the read-before-resume contract instead.
                    if self.value_has_ephemeral_str(&output) {
                        return Err(VmError::TypeError(String::from(
                            "yielded value contains a dynamic (ephemeral arena) string, \
                             which cannot cross the yield boundary; use a static string \
                             or convert to a non-string representation in the host",
                        )));
                    }
                    // Read-before-resume (B28 P3 item 5 C3): the yielded value
                    // stays arena-resident rather than being copied to the
                    // global heap. The host must decode it (`Vm::decode`)
                    // before the next `resume()`, which RESETs the arena; a
                    // read afterward resolves to a clean stale error. Opaque
                    // indices materialise to `Arc` (B33).
                    return Ok(GenericVmState::Yielded(
                        self.materialise_opaque_refs(output),
                    ));
                }

                Op::Dup => {
                    let val = self.stack.last().ok_or(VmError::StackUnderflow)?.clone();
                    sp!(self, val);
                }

                Op::NewComposite(operand) => {
                    // The consolidated construction (B28 P4). Pop `count`
                    // materialised values; the flat form packs them into the
                    // baked `byte_size` and wraps as `kind`, the boxed form
                    // builds the named body. The result is migrated to the
                    // arena. `byte_size` is the explicit allocation the WCMU
                    // verifier sums; the runtime packs against it directly.
                    use crate::bytecode::NewCompositeOperand as NCO;
                    use crate::value_layout::CompositeKind as CK;
                    let count = operand.count() as usize;
                    if self.stack.len() < count {
                        return Err(VmError::StackUnderflow);
                    }
                    let arena = self.arena;
                    // Drain the operands without materialising them to owned
                    // `Inline` bodies. The flat path packs them directly into
                    // the arena (resolving any nested arena child in place), so
                    // the former per-operand `materialized` (Arena -> global
                    // heap `Inline`) read-back is gone; only the boxed path,
                    // which stores the operands as separate values, materialises
                    // them (B28 P3 item 5 C-residual 3b).
                    let mut values: Vec<crate::bytecode::GenericValue<W, F>> =
                        self.stack.drain(self.stack.len() - count..).collect();
                    let wb = self.module_word_bytes();
                    let fb = self.module_float_bytes();
                    // Intern opaque fields on the flat construction path
                    // (B28 P3). Decide flatness first. A struct/enum Flat
                    // operand is flat by the compiler's decision, which the
                    // named type makes reliable, so an opaque field is flat
                    // (interned). Tuple and array are value-driven and their
                    // access form is recovered by the compiler's lightweight
                    // inference, which cannot recover an opaque element type;
                    // to keep construction and access in agreement, an opaque
                    // element keeps the tuple/array boxed (`flat_field_size`
                    // is `None` for `Opaque`, so a tuple holding one is not
                    // flattened). On the flat path each `Opaque` is replaced
                    // by its registry index packed as a word.
                    // A struct/enum Flat operand is flat by the compiler's
                    // decision, which the named type makes reliable, so its
                    // reference fields are flat. Tuple and array are
                    // value-driven and keep a reference element boxed
                    // (opaque via `flat_field_size` being `None`, text via
                    // the explicit exclusion), because their access form is
                    // recovered by lightweight inference (B28 P3).
                    let flat = match operand {
                        NCO::Flat {
                            kind: CK::Struct | CK::Enum,
                            ..
                        } => true,
                        // Tuple and array are value-driven: flat iff every
                        // element is flat-eligible including the reference
                        // kinds (B28 P3 item 3). An eligible `Opaque` is
                        // interned and a `StaticStr` arena-copied below; the
                        // predicate applies the same narrow-word text gate the
                        // compiler bakes, so construction and access agree.
                        NCO::Flat { .. } => values
                            .iter()
                            .all(|v| crate::bytecode::flat_tuple_element_with_refs(v, wb, fb)),
                        NCO::Boxed { .. } => false,
                    };
                    if flat {
                        for v in values.iter_mut() {
                            match v {
                                // An opaque on the stack is the POD registry
                                // index (B33); convert it to the one-word `Int`
                                // the packer writes, with no re-intern.
                                crate::bytecode::GenericValue::OpaqueRef(idx) => {
                                    *v = crate::bytecode::GenericValue::Int(W::from_i64_wrap(
                                        *idx as i64,
                                    ));
                                }
                                // Defensive: a raw `Opaque` `Arc` reaching the
                                // pack path (not via the operand stack, which
                                // carries `OpaqueRef`) interns to its index.
                                crate::bytecode::GenericValue::Opaque(arc) => {
                                    let idx =
                                        self.intern_ephemeral_opaque(alloc::sync::Arc::clone(arc));
                                    *v = crate::bytecode::GenericValue::Int(W::from_i64_wrap(
                                        idx as i64,
                                    ));
                                }
                                // A genuinely-owned `StaticStr` (a host-supplied
                                // string, not a constant load, which now arrives
                                // already as a rodata `KStr`) is copied into the
                                // ephemeral arena so the flat field can hold a
                                // (ptr, len) `KStr` the packer writes as two
                                // words (B28 P3 item 4). Such a string is dynamic
                                // and valid only within the iteration. A `KStr`
                                // operand, whether rodata or arena, is left as-is
                                // by the wildcard arm and packed directly.
                                crate::bytecode::GenericValue::StaticStr(s) => {
                                    let ks =
                                        crate::kstring::KString::alloc(arena, s).map_err(|_| {
                                            out_of_arena_push("flat text field", arena.capacity())
                                        })?;
                                    *v = crate::bytecode::GenericValue::KStr(ks);
                                }
                                _ => {}
                            }
                        }
                    }
                    use crate::bytecode::{ArrayBody, EnumBody, StructBody, TupleBody};
                    let value = if flat {
                        // Pack the body directly into the arena. For a tuple or
                        // array the size is the value-driven sum of its element
                        // sizes (the operand `byte_size` is the verifier
                        // annotation only, so `min_bytes` is zero, no padding);
                        // for a struct or enum it is the compiler-baked
                        // `byte_size`, which pads an enum to its largest variant
                        // so every value of a uniformly-flat enum shares one
                        // body size.
                        let min_bytes = match operand {
                            NCO::Flat {
                                kind: CK::Tuple | CK::Array,
                                ..
                            } => 0usize,
                            NCO::Flat { byte_size, .. } => byte_size as usize,
                            NCO::Boxed { .. } => 0usize,
                        };
                        let packed = crate::bytecode::GenericValue::pack_flat_in_arena(
                            &values, min_bytes, wb, fb, arena,
                        )
                        .map_err(|_| out_of_arena_push("composite body", arena.capacity()))?;
                        let kind = operand.kind();
                        match packed {
                            Some(fc) => match kind {
                                CK::Tuple => {
                                    crate::bytecode::GenericValue::Tuple(TupleBody::Flat(fc))
                                }
                                CK::Array => {
                                    crate::bytecode::GenericValue::Array(ArrayBody::Flat(fc))
                                }
                                CK::Struct => {
                                    crate::bytecode::GenericValue::Struct(StructBody::Flat(fc))
                                }
                                CK::Enum => crate::bytecode::GenericValue::Enum(EnumBody::Flat(fc)),
                            },
                            // A value-driven tuple or array that exceeded the
                            // sixteen-bit access offset falls back to the boxed
                            // body. Its elements are already arena-resident from
                            // construction (B28 item 2 step 6B removed the owned
                            // `Inline` form), so they are stored directly; a
                            // boxed container held across a `RESET` resolves its
                            // children cleanly stale rather than dereferencing
                            // reclaimed memory. A struct or enum Flat operand is
                            // statically flat, so a packing failure there is
                            // malformed bytecode.
                            None => match kind {
                                CK::Tuple => {
                                    crate::bytecode::GenericValue::Tuple(TupleBody::boxed(values))
                                }
                                CK::Array => {
                                    crate::bytecode::GenericValue::Array(ArrayBody::boxed(values))
                                }
                                CK::Struct | CK::Enum => {
                                    return Err(VmError::InvalidBytecode(String::from(
                                        "NewComposite flat operand on non-flat values",
                                    )));
                                }
                            },
                        }
                    } else {
                        // The boxed path stores the operands as separate values.
                        // They are already arena-resident from construction (B28
                        // item 2 step 6B removed the owned `Inline` form), so the
                        // boxed container holds them directly; one held across a
                        // `RESET` resolves its children cleanly stale.
                        match operand {
                            NCO::Boxed { kind, meta, .. } => {
                                // Tuple/array boxed need no metadata; struct/enum
                                // read the (reused) template for the type name
                                // and field names (or, for an enum, the variant
                                // name).
                                let (type_name, names) = match kind {
                                    CK::Struct | CK::Enum => {
                                        self.struct_template(chunk_idx, meta as usize)
                                    }
                                    CK::Tuple | CK::Array => (String::new(), Vec::new()),
                                };
                                crate::bytecode::GenericValue::new_composite_boxed(
                                    kind, type_name, names, values,
                                )
                            }
                            // A value-driven tuple or array Flat operand whose
                            // elements are not all flat-eligible (a reference
                            // element the lightweight inference cannot flatten)
                            // boxes its elements.
                            NCO::Flat {
                                kind: CK::Tuple, ..
                            } => crate::bytecode::GenericValue::Tuple(TupleBody::boxed(values)),
                            NCO::Flat {
                                kind: CK::Array, ..
                            } => crate::bytecode::GenericValue::Array(ArrayBody::boxed(values)),
                            // A struct or enum Flat operand always takes the flat
                            // path above, so the non-flat branch never sees one.
                            NCO::Flat { .. } => {
                                return Err(VmError::InvalidBytecode(String::from(
                                    "NewComposite non-flat struct or enum operand",
                                )));
                            }
                        }
                    };
                    sp!(self, value);
                }
                Op::GetField(field) => {
                    use crate::bytecode::{StructBody, StructField};
                    let container = self.pop()?;
                    match container {
                        crate::bytecode::GenericValue::Struct(body) => match (field, &body) {
                            (StructField::Flat { offset, kind }, StructBody::Flat(fc)) => {
                                let wb = self.module_word_bytes();
                                let fb = self.module_float_bytes();
                                let ep = fc.ref_epoch();
                                let bytes =
                                    fc.resolve(self.arena).map_err(|_| stale_arena_body())?;
                                let val = self.read_flat_scalar(
                                    bytes,
                                    offset as usize,
                                    kind,
                                    wb,
                                    fb,
                                    ep,
                                )?;
                                sp!(self, val);
                            }
                            (
                                StructField::FlatNested {
                                    offset,
                                    size,
                                    variant,
                                },
                                StructBody::Flat(fc),
                            ) => {
                                // Extract the nested child's body bytes and
                                // re-wrap them as a flat composite (B28 P2).
                                // The child inherits the parent's epoch so its
                                // own Text reads resolve stale after a RESET
                                // (B28 P3 item 1).
                                // Zero-copy view of the nested child: an arena
                                // parent yields a sub-handle into its own arena
                                // storage, allocating nothing (B28 P3 item 5
                                // C-residual 3b). The child shares the parent's
                                // epoch, so a flat Text field still resolves
                                // Stale after a RESET.
                                let val = crate::bytecode::GenericValue::flat_nested_field(
                                    fc,
                                    offset as usize,
                                    size as usize,
                                    variant,
                                    self.arena,
                                )
                                .map_err(|_| stale_arena_body())?;
                                sp!(self, val);
                            }
                            (StructField::Boxed { name_const }, StructBody::Boxed(b)) => {
                                let field_name = self
                                    .chunk_const_str(chunk_idx, name_const as usize)
                                    .ok_or_else(|| {
                                        VmError::InvalidBytecode(String::from(
                                            "field name not a string",
                                        ))
                                    })?;
                                let val = b
                                    .fields
                                    .iter()
                                    .find(|(n, _)| n == &field_name)
                                    .map(|(_, v)| v.clone())
                                    .ok_or_else(|| {
                                        VmError::FieldNotFound(b.type_name.clone(), field_name)
                                    })?;
                                sp!(self, val);
                            }
                            // Construction and access agree on the body
                            // representation by static type, so a form
                            // mismatch is a corrupted or mis-compiled
                            // artefact rather than a script error.
                            _ => {
                                return Err(VmError::InvalidBytecode(String::from(
                                    "GetField operand form does not match struct body",
                                )));
                            }
                        },
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot access field on {}",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::GetIndex(elem) => {
                    // B28 P2: the baked `elem` selects a flat read at
                    // `index * element_size` (kind carried by the operand)
                    // or a positional index into the boxed body. The two
                    // forms agree with the construction handler by static
                    // type; the access dispatches on the runtime body.
                    use crate::bytecode::{ArrayBody, ArrayElem};
                    let index = self.pop()?;
                    let container = self.pop()?;
                    match (container, index) {
                        (
                            crate::bytecode::GenericValue::Array(body),
                            crate::bytecode::GenericValue::Int(i),
                        ) => {
                            let idx = i.to_i64();
                            match (elem, &body) {
                                (ArrayElem::Boxed, ArrayBody::Boxed(arr)) => {
                                    let len = arr.len();
                                    if idx < 0 || idx as usize >= len {
                                        return Err(VmError::IndexOutOfBounds(idx, len));
                                    }
                                    sp!(self, arr[idx as usize].clone());
                                }
                                (ArrayElem::Flat { kind }, ArrayBody::Flat(fc)) => {
                                    let wb = self.module_word_bytes();
                                    let fb = self.module_float_bytes();
                                    let ep = fc.ref_epoch();
                                    let esize = kind.size_in_bytes(wb, fb);
                                    let bytes =
                                        fc.resolve(self.arena).map_err(|_| stale_arena_body())?;
                                    match bytes.len().checked_div(esize) {
                                        // A zero-size element kind (`Unit`)
                                        // carries no bytes, so every element
                                        // is the same `Unit`; length and
                                        // offset are not byte-derivable.
                                        // Reject a negative index and read
                                        // the kind back directly.
                                        None => {
                                            if idx < 0 {
                                                return Err(VmError::IndexOutOfBounds(idx, 0));
                                            }
                                            let val =
                                                self.read_flat_scalar(bytes, 0, kind, wb, fb, ep)?;
                                            sp!(self, val);
                                        }
                                        Some(len) => {
                                            if idx < 0 || idx as usize >= len {
                                                return Err(VmError::IndexOutOfBounds(idx, len));
                                            }
                                            let off = idx as usize * esize;
                                            let val = self
                                                .read_flat_scalar(bytes, off, kind, wb, fb, ep)?;
                                            sp!(self, val);
                                        }
                                    }
                                }
                                (ArrayElem::FlatNested { size, variant }, ArrayBody::Flat(fc)) => {
                                    // Each element is a fixed-size nested
                                    // composite; the offset is `index * size`
                                    // (B28 P2). Extract the element body and
                                    // re-wrap it, inheriting the parent epoch
                                    // (B28 P3 item 1).
                                    let esize = size as usize;
                                    // `byte_len` reads the body length for both
                                    // forms without the arena, so the bounds
                                    // check needs no resolve; the child is then
                                    // viewed in place (B28 P3 item 5 C-residual
                                    // 3b).
                                    let len = fc.byte_len().checked_div(esize).unwrap_or(0);
                                    if idx < 0 || idx as usize >= len {
                                        return Err(VmError::IndexOutOfBounds(idx, len));
                                    }
                                    let off = idx as usize * esize;
                                    let val = crate::bytecode::GenericValue::flat_nested_field(
                                        fc, off, esize, variant, self.arena,
                                    )
                                    .map_err(|_| stale_arena_body())?;
                                    sp!(self, val);
                                }
                                // Construction and access agree on the body
                                // representation by static type, so a form
                                // mismatch is a corrupted or mis-compiled
                                // artefact rather than a script error.
                                _ => {
                                    return Err(VmError::InvalidBytecode(String::from(
                                        "GetIndex operand form does not match array body",
                                    )));
                                }
                            }
                        }
                        (c, i) => {
                            return Err(VmError::TypeError(format!(
                                "cannot index {} with {}",
                                c.type_name(),
                                i.type_name()
                            )));
                        }
                    }
                }
                Op::GetTupleField(field) => {
                    use crate::bytecode::{TupleBody, TupleField};
                    let container = self.pop()?;
                    match container {
                        crate::bytecode::GenericValue::Tuple(body) => match (field, &body) {
                            (TupleField::Boxed { index }, TupleBody::Boxed(elems)) => {
                                let i = index as usize;
                                if i >= elems.len() {
                                    return Err(VmError::IndexOutOfBounds(i as i64, elems.len()));
                                }
                                sp!(self, elems[i].clone());
                            }
                            (TupleField::Flat { offset, kind }, TupleBody::Flat(fc)) => {
                                let wb = self.module_word_bytes();
                                let fb = self.module_float_bytes();
                                let ep = fc.ref_epoch();
                                let bytes =
                                    fc.resolve(self.arena).map_err(|_| stale_arena_body())?;
                                let val = self.read_flat_scalar(
                                    bytes,
                                    offset as usize,
                                    kind,
                                    wb,
                                    fb,
                                    ep,
                                )?;
                                sp!(self, val);
                            }
                            (
                                TupleField::FlatNested {
                                    offset,
                                    size,
                                    variant,
                                },
                                TupleBody::Flat(fc),
                            ) => {
                                // Extract the nested child's body and re-wrap
                                // it as a flat composite, inheriting the parent
                                // epoch (B28 P3 item 1).
                                // Zero-copy view of the nested child: an arena
                                // parent yields a sub-handle into its own arena
                                // storage, allocating nothing (B28 P3 item 5
                                // C-residual 3b). The child shares the parent's
                                // epoch, so a flat Text field still resolves
                                // Stale after a RESET.
                                let val = crate::bytecode::GenericValue::flat_nested_field(
                                    fc,
                                    offset as usize,
                                    size as usize,
                                    variant,
                                    self.arena,
                                )
                                .map_err(|_| stale_arena_body())?;
                                sp!(self, val);
                            }
                            // Construction and access agree on the body
                            // representation by static type, so a form
                            // mismatch is a corrupted or mis-compiled
                            // artefact rather than a script error.
                            _ => {
                                return Err(VmError::InvalidBytecode(String::from(
                                    "GetTupleField operand form does not match tuple body",
                                )));
                            }
                        },
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot tuple-index {}",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::GetEnumField(field) => {
                    use crate::bytecode::{EnumBody, EnumField};
                    let container = self.pop()?;
                    match container {
                        crate::bytecode::GenericValue::Enum(body) => match (field, &body) {
                            (EnumField::Boxed { index }, EnumBody::Boxed(b)) => {
                                let i = index as usize;
                                if i >= b.fields.len() {
                                    return Err(VmError::IndexOutOfBounds(
                                        i as i64,
                                        b.fields.len(),
                                    ));
                                }
                                sp!(self, b.fields[i].clone());
                            }
                            (EnumField::Flat { offset, kind }, EnumBody::Flat(fc)) => {
                                let wb = self.module_word_bytes();
                                let fb = self.module_float_bytes();
                                let ep = fc.ref_epoch();
                                let bytes =
                                    fc.resolve(self.arena).map_err(|_| stale_arena_body())?;
                                let val = self.read_flat_scalar(
                                    bytes,
                                    offset as usize,
                                    kind,
                                    wb,
                                    fb,
                                    ep,
                                )?;
                                sp!(self, val);
                            }
                            (
                                EnumField::FlatNested {
                                    offset,
                                    size,
                                    variant,
                                },
                                EnumBody::Flat(fc),
                            ) => {
                                // Extract the nested payload child's body
                                // (past the discriminant word) and re-wrap it
                                // as a flat composite, inheriting the parent
                                // epoch (B28 P3 item 1).
                                // Zero-copy view of the nested child: an arena
                                // parent yields a sub-handle into its own arena
                                // storage, allocating nothing (B28 P3 item 5
                                // C-residual 3b). The child shares the parent's
                                // epoch, so a flat Text field still resolves
                                // Stale after a RESET.
                                let val = crate::bytecode::GenericValue::flat_nested_field(
                                    fc,
                                    offset as usize,
                                    size as usize,
                                    variant,
                                    self.arena,
                                )
                                .map_err(|_| stale_arena_body())?;
                                sp!(self, val);
                            }
                            // Construction and access agree on the body
                            // representation by static type; a form mismatch
                            // is a corrupted or mis-compiled artefact.
                            _ => {
                                return Err(VmError::InvalidBytecode(String::from(
                                    "GetEnumField operand form does not match enum body",
                                )));
                            }
                        },
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot enum-field {}",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::Len => {
                    let val = self.pop()?;
                    match val {
                        // A boxed array reports its element count directly.
                        // A flat array does not store its length in the
                        // bytes, but array length is a fixed-size, compile-
                        // time constant the compiler folds to a literal (it
                        // never emits `Op::Len` on an array), so a flat body
                        // here is a mis-compilation rather than a script
                        // error.
                        crate::bytecode::GenericValue::Array(
                            crate::bytecode::ArrayBody::Boxed(arr),
                        ) => {
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(arr.len() as i64)
                                )
                            );
                        }
                        crate::bytecode::GenericValue::Array(crate::bytecode::ArrayBody::Flat(
                            _,
                        )) => {
                            return Err(VmError::InvalidBytecode(String::from(
                                "Op::Len on a flat array; length is a compile-time constant",
                            )));
                        }
                        crate::bytecode::GenericValue::StaticStr(s) => {
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(
                                        s.chars().count() as i64
                                    )
                                )
                            );
                        }
                        crate::bytecode::GenericValue::KStr(h) => {
                            let s = h.get(self.arena).map_err(|_| {
                                VmError::TypeError(String::from(
                                    "KStr is stale (arena reset since allocation)",
                                ))
                            })?;
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(
                                        s.chars().count() as i64
                                    )
                                )
                            );
                        }
                        // A boxed tuple reports its element count directly.
                        // A flat tuple does not store its arity in the
                        // bytes, but tuple length is a compile-time constant
                        // that the compiler emits as a literal, so the flat
                        // body never reaches this arm in a well-formed
                        // artefact. A flat body here is therefore a
                        // mis-compilation rather than a script error.
                        crate::bytecode::GenericValue::Tuple(
                            crate::bytecode::TupleBody::Boxed(elems),
                        ) => {
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(elems.len() as i64)
                                )
                            );
                        }
                        crate::bytecode::GenericValue::Tuple(crate::bytecode::TupleBody::Flat(
                            _,
                        )) => {
                            return Err(VmError::InvalidBytecode(String::from(
                                "Op::Len on a flat tuple; arity is a compile-time constant",
                            )));
                        }
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot get length of {}",
                                v.type_name()
                            )));
                        }
                    }
                }

                // -- Type predicates (push bool, no jump) --
                Op::IsEnum(enum_const, var_const, disc_const) => {
                    let wb = self.module_word_bytes();
                    let fb = self.module_float_bytes();
                    // The expected discriminant constant (an Int) for the
                    // flat path.
                    let expected_disc = match self.chunk_const(chunk_idx, disc_const as usize) {
                        crate::bytecode::GenericValue::Int(w) => {
                            <W as crate::word::Word>::to_i64(w)
                        }
                        _ => {
                            return Err(VmError::InvalidBytecode(String::from(
                                "enum discriminant const must be an Int",
                            )));
                        }
                    };
                    let val = self.stack.last().ok_or(VmError::StackUnderflow)?;
                    let matches = match val {
                        // Boxed: compare the type and variant names.
                        crate::bytecode::GenericValue::Enum(crate::bytecode::EnumBody::Boxed(
                            b,
                        )) => {
                            let expected_type =
                                self.chunk_const_str(chunk_idx, enum_const as usize);
                            let expected_var = self.chunk_const_str(chunk_idx, var_const as usize);
                            expected_type.as_deref() == Some(b.type_name.as_str())
                                && expected_var.as_deref() == Some(b.variant.as_str())
                        }
                        // Flat: compare the leading discriminant word to the
                        // expected discriminant.
                        crate::bytecode::GenericValue::Enum(crate::bytecode::EnumBody::Flat(
                            fc,
                        )) => match fc.resolve(self.arena) {
                            Ok(bytes) => {
                                let stored =
                                    match crate::bytecode::GenericValue::<W, F>::read_scalar_le(
                                        bytes,
                                        0,
                                        crate::value_layout::ScalarKind::Int,
                                        wb,
                                        fb,
                                    )? {
                                        crate::bytecode::GenericValue::Int(w) => {
                                            <W as crate::word::Word>::to_i64(w)
                                        }
                                        _ => 0,
                                    };
                                stored == expected_disc
                            }
                            // A stale body no longer exists, so it is not the
                            // expected variant (B28 P2).
                            Err(_) => false,
                        },
                        // A scalar `Value::None` denotes `Option::None`. Recognize
                        // it here so a top-level or host-returned Option None
                        // matches the same `IsEnum(Option, None, 0)` test the
                        // compiler now emits for the `None` pattern, alongside a
                        // nested flat `[disc=0]` body handled by the Flat arm.
                        // Without this, an extracted flat `Option` None payload
                        // and a scalar `None` would need two different pattern
                        // lowerings, which is the nested-`Option` match bug.
                        crate::bytecode::GenericValue::None => {
                            let expected_type =
                                self.chunk_const_str(chunk_idx, enum_const as usize);
                            let expected_var = self.chunk_const_str(chunk_idx, var_const as usize);
                            expected_type.as_deref() == Some("Option")
                                && expected_var.as_deref() == Some("None")
                        }
                        _ => false,
                    };
                    sp!(self, crate::bytecode::GenericValue::Bool(matches));
                }
                Op::IsStruct(type_const) => {
                    let expected = self
                        .chunk_const_str(chunk_idx, type_const as usize)
                        .ok_or_else(|| {
                            VmError::InvalidBytecode(String::from("type const not string"))
                        })?;
                    let val = self.stack.last().ok_or(VmError::StackUnderflow)?;
                    let matches = match val {
                        crate::bytecode::GenericValue::Struct(
                            crate::bytecode::StructBody::Boxed(b),
                        ) => b.type_name == expected,
                        // A struct pattern's type test is irrefutable (the
                        // scrutinee type is statically known), so the
                        // compiler folds it and a flat struct never reaches
                        // here; a flat body is therefore a mis-compilation.
                        crate::bytecode::GenericValue::Struct(
                            crate::bytecode::StructBody::Flat(_),
                        ) => {
                            return Err(VmError::InvalidBytecode(String::from(
                                "Op::IsStruct on a flat struct; the type test is a compile-time constant",
                            )));
                        }
                        _ => false,
                    };
                    sp!(self, crate::bytecode::GenericValue::Bool(matches));
                }

                #[cfg(feature = "floats")]
                Op::IntToFloat => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Int(i) => sp!(
                            self,
                            crate::bytecode::GenericValue::Float(
                                <F as crate::float::Float>::from_f64(i.to_i64() as f64)
                            )
                        ),
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot cast {} to Float",
                                v.type_name()
                            )));
                        }
                    }
                }
                #[cfg(not(feature = "floats"))]
                Op::IntToFloat => {
                    return Err(VmError::InvalidBytecode(String::from(
                        "Op::IntToFloat requires the `floats` feature",
                    )));
                }
                #[cfg(feature = "floats")]
                Op::FloatToInt => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Float(f) => sp!(
                            self,
                            crate::bytecode::GenericValue::Int(
                                <W as crate::word::Word>::from_i64_wrap(f.to_f64() as i64)
                            )
                        ),
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot cast {} to Word",
                                v.type_name()
                            )));
                        }
                    }
                }
                #[cfg(not(feature = "floats"))]
                Op::FloatToInt => {
                    return Err(VmError::InvalidBytecode(String::from(
                        "Op::FloatToInt requires the `floats` feature",
                    )));
                }
                Op::WordToByte => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Int(i) => sp!(
                            self,
                            crate::bytecode::GenericValue::Byte((i.to_i64() & 0xFF) as u8)
                        ),
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot cast {} to Byte",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::ByteToWord => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Byte(b) => sp!(
                            self,
                            crate::bytecode::GenericValue::Int(
                                <W as crate::word::Word>::from_i64_wrap(b as i64)
                            )
                        ),
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot cast {} to Word",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::WordToFixed(frac_bits) => {
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Int(i) => {
                            // Left-shift the word into the fixed
                            // representation. Saturate at i64::MAX/MIN on
                            // overflow. A fraction-bit count at or beyond
                            // the wide width would overflow the shift
                            // itself; the structural verifier rejects such
                            // a count on a safe load, and this guard keeps
                            // the VM panic-free on new_unchecked or corrupt
                            // bytecode by saturating by sign (zero stays
                            // zero).
                            let wide_bits = 1u32 << (<W as crate::word::Word>::BITS_LOG2 + 1);
                            let bits = if (frac_bits as u32) >= wide_bits {
                                let v = i.to_i64();
                                if v > 0 {
                                    <W as crate::word::Word>::MAX
                                } else if v < 0 {
                                    <W as crate::word::Word>::MIN
                                } else {
                                    <W as crate::word::Word>::from_i64_wrap(0)
                                }
                            } else {
                                let shifted = i.widen() << (frac_bits as u32);
                                if shifted > <W as crate::word::Word>::MAX.widen() {
                                    <W as crate::word::Word>::MAX
                                } else if shifted < <W as crate::word::Word>::MIN.widen() {
                                    <W as crate::word::Word>::MIN
                                } else {
                                    <W as crate::word::Word>::from_wide_wrap(shifted)
                                }
                            };
                            sp!(self, crate::bytecode::GenericValue::Fixed(bits));
                        }
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot cast {} to Fixed",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::FixedToWord(frac_bits) => {
                    // Defense in depth. The structural verifier bounds a
                    // Fixed's fraction-bit count below the word width, so a
                    // safe load never reaches here out of range. Under a
                    // no-verify `new_unchecked` or corrupt bytecode an
                    // out-of-range count would overflow the shift below;
                    // fail closed rather than panic. WordToFixed saturates
                    // instead, but that arm converts an in-range integer
                    // whose result merely overflows the Fixed range, whereas
                    // an out-of-range fraction count is corrupt input, for
                    // which the fail-closed response is the honest one.
                    let word_bits = 1u32 << <W as crate::word::Word>::BITS_LOG2;
                    if frac_bits as u32 >= word_bits {
                        return Err(VmError::InvalidBytecode(format!(
                            "Fixed fraction bits {frac_bits} exceed word width {word_bits}"
                        )));
                    }
                    let val = self.pop()?;
                    match val {
                        crate::bytecode::GenericValue::Fixed(bits) => {
                            // Arithmetic-right-shift to drop the
                            // fraction bits. Negative values keep
                            // their sign through the shift.
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(bits >> (frac_bits as u32))
                            );
                        }
                        v => {
                            return Err(VmError::TypeError(format!(
                                "cannot cast {} to Word",
                                v.type_name()
                            )));
                        }
                    }
                }
                Op::FixedMul(frac_bits) => {
                    // See FixedToWord: fail closed on an out-of-range
                    // fraction count the verifier would have rejected.
                    let word_bits = 1u32 << <W as crate::word::Word>::BITS_LOG2;
                    if frac_bits as u32 >= word_bits {
                        return Err(VmError::InvalidBytecode(format!(
                            "Fixed fraction bits {frac_bits} exceed word width {word_bits}"
                        )));
                    }
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Q-format multiply: extend to i128 to
                            // avoid intermediate overflow, multiply,
                            // shift right by `frac_bits`, saturate
                            // back to i64.
                            let product = x.widen() * y.widen();
                            let shifted = product >> (frac_bits as u32);
                            let bits = if shifted > <W as crate::word::Word>::MAX.widen() {
                                <W as crate::word::Word>::MAX
                            } else if shifted < <W as crate::word::Word>::MIN.widen() {
                                <W as crate::word::Word>::MIN
                            } else {
                                <W as crate::word::Word>::from_wide_wrap(shifted)
                            };
                            sp!(self, crate::bytecode::GenericValue::Fixed(bits));
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "FixedMul requires two Fixed operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::FixedDiv(frac_bits) => {
                    // See FixedToWord: fail closed on an out-of-range
                    // fraction count the verifier would have rejected.
                    let word_bits = 1u32 << <W as crate::word::Word>::BITS_LOG2;
                    if frac_bits as u32 >= word_bits {
                        return Err(VmError::InvalidBytecode(format!(
                            "Fixed fraction bits {frac_bits} exceed word width {word_bits}"
                        )));
                    }
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Fixed(_),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) if y == W::default() => {
                            return Err(VmError::DivisionByZero);
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Q-format divide: extend the dividend to
                            // i128 and left-shift by frac_bits before
                            // dividing, so the result retains the
                            // Q-format precision.
                            let dividend = x.widen() << (frac_bits as u32);
                            let quotient = dividend / y.widen();
                            let bits = if quotient > <W as crate::word::Word>::MAX.widen() {
                                <W as crate::word::Word>::MAX
                            } else if quotient < <W as crate::word::Word>::MIN.widen() {
                                <W as crate::word::Word>::MIN
                            } else {
                                <W as crate::word::Word>::from_wide_wrap(quotient)
                            };
                            sp!(self, crate::bytecode::GenericValue::Fixed(bits));
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "FixedDiv requires two Fixed operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }

                Op::Trap(kind_code) => {
                    use crate::bytecode::TrapKind;
                    return Err(match TrapKind::from_code(kind_code) {
                        Some(TrapKind::RefinementFailed) => VmError::RefinementFailed,
                        Some(TrapKind::NoMatchingHead) => VmError::NoMatchingHead,
                        Some(TrapKind::NoMatchingArm) => VmError::NoMatchingArm,
                        Some(TrapKind::CheckedArithNoArm) => VmError::CheckedArithNoArm,
                        Some(TrapKind::EnumVariantUnmapped) => VmError::EnumVariantUnmapped,
                        // An unhandled zero divisor in a checked
                        // construct surfaces as the same error a plain
                        // division by zero produces.
                        Some(TrapKind::ZeroDivisor) => VmError::DivisionByZero,
                        Some(TrapKind::AssertionFailed) => VmError::AssertionFailed,
                        None => VmError::InvalidBytecode(alloc::format!(
                            "Op::Trap carried an unknown trap-kind code {}",
                            kind_code
                        )),
                    });
                }
                Op::CheckedAdd => {
                    let word_bits_log2 = self.word_bits_log2();
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => {
                            let r = x.widen() + y.widen();
                            let (low, high, flag) = checked_arith_outputs::<W>(r, word_bits_log2);
                            // Push order is (low, high, flag) so the
                            // wrapping-arithmetic synthesis emitted by
                            // the compiler — `CheckedAdd; PopN(2)` —
                            // discards the top two slots (flag and
                            // high) and leaves `low` on the stack.
                            sp!(self, crate::bytecode::GenericValue::Int(low));
                            sp!(self, crate::bytecode::GenericValue::Int(high));
                            sp!(self, crate::bytecode::GenericValue::Int(flag));
                        }
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            // Unsigned Byte addition: overflow above
                            // 255, never underflow. The wrapped result
                            // (low 8 bits) is the low slot; the high
                            // slot is unused for Byte.
                            let r = x as i64 + y as i64;
                            let flag: i64 = if r > 0xFF { 1 } else { 0 };
                            sp!(self, crate::bytecode::GenericValue::Byte(r as u8));
                            sp!(self, crate::bytecode::GenericValue::Byte(0));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        #[cfg(feature = "floats")]
                        (
                            crate::bytecode::GenericValue::Float(x),
                            crate::bytecode::GenericValue::Float(y),
                        ) => {
                            // Float addition is total (IEEE 754): the
                            // result is finite, an infinity, or NaN,
                            // classified into the flag. The result is
                            // the low slot; the high slot is unused.
                            let r = x + y;
                            let flag = float_checked_flag(<F as crate::float::Float>::to_f64(r));
                            sp!(self, crate::bytecode::GenericValue::Float(r));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Float(
                                    <F as crate::float::Float>::from_f64(0.0)
                                )
                            );
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Q-format addition shares the operands'
                            // fraction-bit count, so it is a raw sum.
                            // The wide result is wrapped to the low
                            // slot; the high slot is unused.
                            let r = x.widen() + y.widen();
                            let (low, flag) = fixed_checked_outputs::<W>(r);
                            sp!(self, crate::bytecode::GenericValue::Fixed(low));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::CheckedAdd expects Word, Byte, Float, or Fixed operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::CheckedSub => {
                    let word_bits_log2 = self.word_bits_log2();
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => {
                            let r = x.widen() - y.widen();
                            let (low, high, flag) = checked_arith_outputs::<W>(r, word_bits_log2);
                            sp!(self, crate::bytecode::GenericValue::Int(low));
                            sp!(self, crate::bytecode::GenericValue::Int(high));
                            sp!(self, crate::bytecode::GenericValue::Int(flag));
                        }
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            // Unsigned Byte subtraction: underflow below
                            // 0, never overflow. `r as u8` wraps modulo
                            // 256 for the low slot.
                            let r = x as i64 - y as i64;
                            let flag: i64 = if r < 0 { 2 } else { 0 };
                            sp!(self, crate::bytecode::GenericValue::Byte(r as u8));
                            sp!(self, crate::bytecode::GenericValue::Byte(0));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        #[cfg(feature = "floats")]
                        (
                            crate::bytecode::GenericValue::Float(x),
                            crate::bytecode::GenericValue::Float(y),
                        ) => {
                            let r = x - y;
                            let flag = float_checked_flag(<F as crate::float::Float>::to_f64(r));
                            sp!(self, crate::bytecode::GenericValue::Float(r));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Float(
                                    <F as crate::float::Float>::from_f64(0.0)
                                )
                            );
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Q-format subtraction is a raw difference
                            // sharing the fraction-bit count.
                            let r = x.widen() - y.widen();
                            let (low, flag) = fixed_checked_outputs::<W>(r);
                            sp!(self, crate::bytecode::GenericValue::Fixed(low));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::CheckedSub expects Word, Byte, Float, or Fixed operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::CheckedMul(frac_bits) => {
                    let word_bits_log2 = self.word_bits_log2();
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => {
                            // Integer multiply. The compiler emits
                            // `frac_bits = 0` for this case; the field
                            // is the Q-format shift used only by the
                            // Fixed arm below, so 0 fraction bits is
                            // exactly integer multiply. Both halves of
                            // the i128 product are load-bearing for
                            // big-number multiplication.
                            let r = x.widen() * y.widen();
                            let (low, high, flag) = checked_arith_outputs::<W>(r, word_bits_log2);
                            sp!(self, crate::bytecode::GenericValue::Int(low));
                            sp!(self, crate::bytecode::GenericValue::Int(high));
                            sp!(self, crate::bytecode::GenericValue::Int(flag));
                        }
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            // Unsigned Byte multiplication: overflow
                            // above 255, never underflow.
                            let r = x as i64 * y as i64;
                            let flag: i64 = if r > 0xFF { 1 } else { 0 };
                            sp!(self, crate::bytecode::GenericValue::Byte(r as u8));
                            sp!(self, crate::bytecode::GenericValue::Byte(0));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        #[cfg(feature = "floats")]
                        (
                            crate::bytecode::GenericValue::Float(x),
                            crate::bytecode::GenericValue::Float(y),
                        ) => {
                            let r = x * y;
                            let flag = float_checked_flag(<F as crate::float::Float>::to_f64(r));
                            sp!(self, crate::bytecode::GenericValue::Float(r));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Float(
                                    <F as crate::float::Float>::from_f64(0.0)
                                )
                            );
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Q-format multiply: widen to avoid the
                            // intermediate overflow, multiply, shift
                            // right by the fraction-bit count, then
                            // classify against the Word range. The
                            // checked form wraps the low slot, unlike
                            // the saturating `Op::FixedMul`.
                            // Fail closed on an out-of-range fraction count
                            // (audit D5, parity with the FixedMul/FixedDiv guard
                            // of C9): the verifier bounds it, so this bites only
                            // corrupt or no-verify bytecode, keeping the shift
                            // panic-free.
                            let word_bits = 1u32 << <W as crate::word::Word>::BITS_LOG2;
                            if frac_bits as u32 >= word_bits {
                                return Err(VmError::InvalidBytecode(alloc::format!(
                                    "Fixed fraction bits {frac_bits} exceed word width {word_bits}"
                                )));
                            }
                            let product = x.widen() * y.widen();
                            let shifted = product >> (frac_bits as u32);
                            let (low, flag) = fixed_checked_outputs::<W>(shifted);
                            sp!(self, crate::bytecode::GenericValue::Fixed(low));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::CheckedMul expects Word, Byte, Float, or Fixed operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::CheckedNeg => {
                    let word_bits_log2 = self.word_bits_log2();
                    let a = self.pop()?;
                    match a {
                        crate::bytecode::GenericValue::Int(x) => {
                            // The only runtime-width overflow is
                            // `-i64::MIN`. At a narrower declared
                            // width, both `-declared_min` and
                            // every value of `x` that lands outside
                            // the declared range surface as
                            // overflow/underflow through the
                            // shared helper.
                            let r = -x.widen();
                            let (low, high, flag) = checked_arith_outputs::<W>(r, word_bits_log2);
                            sp!(self, crate::bytecode::GenericValue::Int(low));
                            sp!(self, crate::bytecode::GenericValue::Int(high));
                            sp!(self, crate::bytecode::GenericValue::Int(flag));
                        }
                        crate::bytecode::GenericValue::Fixed(x) => {
                            // Q-format negation is a raw negation; the
                            // only overflow case is `-i64::MIN`.
                            let r = -x.widen();
                            let (low, flag) = fixed_checked_outputs::<W>(r);
                            sp!(self, crate::bytecode::GenericValue::Fixed(low));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        a => {
                            return Err(VmError::TypeError(format!(
                                "Op::CheckedNeg expects a Word or Fixed operand, got {}",
                                a.type_name()
                            )));
                        }
                    }
                }
                Op::CheckedDiv(frac_bits) => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) if y == W::default() => {
                            // Zero divisor: reify as flag 3
                            // (zero_divisor) rather than trapping. The
                            // numerator goes in the low slot so the
                            // construct's `zero_divisor(numerator)` arm
                            // binds it; an unhandled zero divisor traps
                            // as DivisionByZero in the compiled dispatch.
                            sp!(self, crate::bytecode::GenericValue::Int(x));
                            sp!(self, crate::bytecode::GenericValue::Int(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(3)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => {
                            // Only `i64::MIN / -1` overflows. The
                            // true result is `2^63`, which in i128
                            // is (high=0, low=i64::MIN). All other
                            // divisions fit in `Word`; the wrapped
                            // quotient becomes the low slot and the
                            // high slot is zero.
                            let r = x.widen() / y.widen();
                            let high = <W as crate::word::Word>::from_wide_wrap(r.high_half());
                            let low = <W as crate::word::Word>::from_wide_wrap(r);
                            let flag: i64 = if r >= <W as crate::word::Word>::MIN.widen()
                                && r <= <W as crate::word::Word>::MAX.widen()
                            {
                                0
                            } else if r > <W as crate::word::Word>::MAX.widen() {
                                1
                            } else {
                                2
                            };
                            sp!(self, crate::bytecode::GenericValue::Int(low));
                            sp!(self, crate::bytecode::GenericValue::Int(high));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(0),
                        ) => {
                            // Byte zero divisor: flag 3, numerator in
                            // the low slot.
                            sp!(self, crate::bytecode::GenericValue::Byte(x));
                            sp!(self, crate::bytecode::GenericValue::Byte(0));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(3)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            // Unsigned Byte division never overflows.
                            sp!(self, crate::bytecode::GenericValue::Byte(x / y));
                            sp!(self, crate::bytecode::GenericValue::Byte(0));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(0)
                                )
                            );
                        }
                        #[cfg(feature = "floats")]
                        (
                            crate::bytecode::GenericValue::Float(x),
                            crate::bytecode::GenericValue::Float(y),
                        ) => {
                            // Float division is total: division by zero
                            // yields a signed infinity (x != 0) or NaN
                            // (0 / 0), classified into the flag. There
                            // is no zero-divisor trap for floats.
                            let r = x / y;
                            let flag = float_checked_flag(<F as crate::float::Float>::to_f64(r));
                            sp!(self, crate::bytecode::GenericValue::Float(r));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Float(
                                    <F as crate::float::Float>::from_f64(0.0)
                                )
                            );
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) if y == W::default() => {
                            // Fixed zero divisor: flag 3, numerator in
                            // the low slot, mirroring the Int case.
                            sp!(self, crate::bytecode::GenericValue::Fixed(x));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(3)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Q-format quotient: left-shift the
                            // dividend by the fraction-bit count in the
                            // wide domain, divide, then classify. The
                            // checked form wraps the low slot, unlike
                            // the saturating `Op::FixedDiv`.
                            // Fail closed on an out-of-range fraction count
                            // (audit D5, parity with the C9 guard).
                            let word_bits = 1u32 << <W as crate::word::Word>::BITS_LOG2;
                            if frac_bits as u32 >= word_bits {
                                return Err(VmError::InvalidBytecode(alloc::format!(
                                    "Fixed fraction bits {frac_bits} exceed word width {word_bits}"
                                )));
                            }
                            let dividend = x.widen() << (frac_bits as u32);
                            let quotient = dividend / y.widen();
                            let (low, flag) = fixed_checked_outputs::<W>(quotient);
                            sp!(self, crate::bytecode::GenericValue::Fixed(low));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::CheckedDiv expects Word, Byte, Float, or Fixed operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::CheckedMod => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) if y == W::default() => {
                            // Zero divisor: reify as flag 3, numerator
                            // in the low slot, mirroring CheckedDiv.
                            sp!(self, crate::bytecode::GenericValue::Int(x));
                            sp!(self, crate::bytecode::GenericValue::Int(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(3)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => {
                            // A remainder is always in range, including
                            // the `i64::MIN % -1` corner whose true
                            // result is `0`, so modulo never overflows
                            // or underflows; the only non-`ok` outcome
                            // is the zero divisor handled above. The
                            // type checker forbids `overflow` and
                            // `underflow` arms on `%` (B35 P3c).
                            let r = x.widen() % y.widen();
                            let high = <W as crate::word::Word>::from_wide_wrap(r.high_half());
                            let low = <W as crate::word::Word>::from_wide_wrap(r);
                            let flag: i64 = 0;
                            sp!(self, crate::bytecode::GenericValue::Int(low));
                            sp!(self, crate::bytecode::GenericValue::Int(high));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(flag)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(0),
                        ) => {
                            // Byte zero divisor: flag 3, numerator in
                            // the low slot.
                            sp!(self, crate::bytecode::GenericValue::Byte(x));
                            sp!(self, crate::bytecode::GenericValue::Byte(0));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(3)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Byte(x),
                            crate::bytecode::GenericValue::Byte(y),
                        ) => {
                            // A Byte remainder is always in range.
                            sp!(self, crate::bytecode::GenericValue::Byte(x % y));
                            sp!(self, crate::bytecode::GenericValue::Byte(0));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(0)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) if y == W::default() => {
                            // Fixed zero divisor: flag 3, numerator in
                            // the low slot, mirroring CheckedDiv.
                            sp!(self, crate::bytecode::GenericValue::Fixed(x));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(3)
                                )
                            );
                        }
                        (
                            crate::bytecode::GenericValue::Fixed(x),
                            crate::bytecode::GenericValue::Fixed(y),
                        ) => {
                            // Q-format remainder is the raw remainder
                            // at the shared scale and is always in
                            // range, so modulo never overflows.
                            let r = x.widen() % y.widen();
                            let low = <W as crate::word::Word>::from_wide_wrap(r);
                            sp!(self, crate::bytecode::GenericValue::Fixed(low));
                            sp!(self, crate::bytecode::GenericValue::Fixed(W::default()));
                            sp!(
                                self,
                                crate::bytecode::GenericValue::Int(
                                    <W as crate::word::Word>::from_i64_wrap(0)
                                )
                            );
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::CheckedMod expects Word, Byte, or Fixed operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }

                // V0.2.0 ISA additions (B20). Phase 1: dispatch
                // implemented; compiler emission and migration land
                // in later phases.
                Op::PushImmediate(value) => {
                    let v = match value {
                        0 => crate::bytecode::GenericValue::Unit,
                        1 => crate::bytecode::GenericValue::Bool(true),
                        2 => crate::bytecode::GenericValue::Bool(false),
                        3 => crate::bytecode::GenericValue::None,
                        n @ 4..=19 => crate::bytecode::GenericValue::Int(
                            <W as crate::word::Word>::from_i64_wrap((n - 4) as i64),
                        ),
                        other => {
                            return Err(VmError::InvalidBytecode(format!(
                                "Op::PushImmediate({}) operand is reserved; valid range is 0..=19",
                                other
                            )));
                        }
                    };
                    sp!(self, v);
                }
                Op::PopN(n) => {
                    let count = n as usize;
                    if self.stack.len() < count {
                        return Err(VmError::StackUnderflow);
                    }
                    let new_len = self.stack.len() - count;
                    self.stack.truncate(new_len);
                }
                Op::BitAnd => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Int(x & y)),
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::BitAnd expects Word operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::BitOr => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Int(x | y)),
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::BitOr expects Word operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::BitXor => {
                    let b = self.pop()?;
                    let a = self.pop()?;
                    match (a, b) {
                        (
                            crate::bytecode::GenericValue::Int(x),
                            crate::bytecode::GenericValue::Int(y),
                        ) => sp!(self, crate::bytecode::GenericValue::Int(x ^ y)),
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::BitXor expects Word operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::Shl => {
                    let count = self.pop()?;
                    let value = self.pop()?;
                    match (value, count) {
                        (
                            crate::bytecode::GenericValue::Int(v),
                            crate::bytecode::GenericValue::Int(c),
                        ) => {
                            let word_bits = 1u32 << <W as crate::word::Word>::BITS_LOG2;
                            let shift = (<W as crate::word::Word>::to_i64(c) as u32)
                                & word_bits.saturating_sub(1);
                            sp!(self, crate::bytecode::GenericValue::Int(v << shift));
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::Shl expects Word operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                Op::Shr => {
                    let count = self.pop()?;
                    let value = self.pop()?;
                    match (value, count) {
                        (
                            crate::bytecode::GenericValue::Int(v),
                            crate::bytecode::GenericValue::Int(c),
                        ) => {
                            let word_bits = 1u32 << <W as crate::word::Word>::BITS_LOG2;
                            let shift = (<W as crate::word::Word>::to_i64(c) as u32)
                                & word_bits.saturating_sub(1);
                            sp!(self, crate::bytecode::GenericValue::Int(v >> shift));
                        }
                        (a, b) => {
                            return Err(VmError::TypeError(format!(
                                "Op::Shr expects Word operands, got {} and {}",
                                a.type_name(),
                                b.type_name()
                            )));
                        }
                    }
                }
                // Verified and external native dispatch share the
                // value-pop / arg-marshal sequence. The split
                // opcodes carry the structural classification; the
                // verifier observes the same classification to
                // decide between per-call WCET/WCMU attestation
                // (verified) and per-iteration invocation count
                // (external). The classification cross-check
                // against the registered native runs lazily at
                // `call_function` entry through
                // `verify_native_classifications`; the dispatch
                // arm here trusts the load-time check.
                Op::CallVerifiedNative(idx, arg_count) | Op::CallExternalNative(idx, arg_count) => {
                    // The high bit of the argument-count byte is the
                    // error-reify flag (B35 P7). When set, the
                    // native-error-handling construct surrounds the
                    // call, so a soft host failure is reified onto the
                    // stack as a `(code, flag)` pair rather than
                    // propagated; the construct dispatches `ok`/`error`.
                    let reify = arg_count & 0x80 != 0;
                    let n = (arg_count & 0x7F) as usize;
                    if self.stack.len() < n {
                        return Err(VmError::StackUnderflow);
                    }
                    // Native arguments stay arena-resident: the native wrapper
                    // decodes each one through `from_value_ctx` with a
                    // `RefContext` built from the `NativeCtx`, which resolves an
                    // arena composite body in place, so no copy to an owned
                    // `Inline` body is needed (B28 P3 item 5 zero-copy; the
                    // earlier `from_value` boundary required the copy).
                    let arena = self.arena;
                    let drained: Vec<crate::bytecode::GenericValue<W, F>> =
                        self.stack.drain(self.stack.len() - n..).collect();
                    // Materialise each opaque argument's registry index back to
                    // its `Arc` so the native receives `Value::Opaque(Arc)`; the
                    // operand stack carries the POD `OpaqueRef` form (B33). A
                    // flat composite argument keeps its byte index, which the
                    // marshalling `RefContext` resolves through `ctx.opaques`.
                    let args: Vec<crate::bytecode::GenericValue<W, F>> = drained
                        .into_iter()
                        .map(|a| self.materialise_opaque_refs(a))
                        .collect();
                    let native_name = self.native_name(idx as usize).ok_or_else(|| {
                        VmError::InvalidBytecode(format!("invalid native index: {}", idx))
                    })?;
                    let entry = self
                        .natives
                        .iter()
                        .find(|e| e.name == native_name)
                        .ok_or_else(|| {
                            VmError::InvalidBytecode(format!(
                                "unregistered native: {}",
                                native_name
                            ))
                        })?;
                    let wb = self.module_word_bytes();
                    let fb = self.module_float_bytes();
                    let ctx = NativeCtx {
                        arena: self.arena,
                        opaques: &self.ephemeral_opaques,
                        word_bytes: wb,
                        float_bytes: fb,
                    };
                    let result = (entry.func)(&ctx, &args);
                    if reify {
                        match result {
                            Ok(v) => {
                                // Canonicalise a host-returned composite into an
                                // arena-resident flat body, the same VM-entry
                                // treatment call arguments and resume values
                                // receive (B28 item 2 step 6B). A raw-closure
                                // native that builds a transitively-scalar
                                // struct/tuple/array/enum with no arena returns
                                // the boxed form, which the script's flat-baked
                                // access rejects; canonicalisation re-packs it
                                // flat. An already-flat result (the `_ctx`
                                // marshalling path), a scalar, string, opaque,
                                // or a reference-bearing composite that stays
                                // boxed is returned unchanged.
                                let v = self
                                    .correct_native_enum_hints(v)
                                    .into_arena_canonical(wb, fb, arena)
                                    .map_err(|_| {
                                        out_of_arena_push("native result", arena.capacity())
                                    })?;
                                // Intern any host `Opaque(Arc)` the result
                                // carries into the registry, so the stack form
                                // is the POD `OpaqueRef` index (B33).
                                let v = self.intern_opaque_arcs(v);
                                // Success: value, then flag 0.
                                sp!(self, v);
                                sp!(self, crate::bytecode::GenericValue::Int(W::default()));
                            }
                            // Reify only soft host failures into the
                            // construct; VM-internal faults still
                            // propagate.
                            Err(e) if matches!(e.category(), VmErrorCategory::SoftHost) => {
                                let code = match &e {
                                    VmError::NativeErrorCode { code, .. } => *code,
                                    // A message-only native error has
                                    // no code; surface the sentinel -1.
                                    _ => -1,
                                };
                                sp!(
                                    self,
                                    crate::bytecode::GenericValue::Int(
                                        <W as crate::word::Word>::from_i64_wrap(code)
                                    )
                                );
                                sp!(
                                    self,
                                    crate::bytecode::GenericValue::Int(
                                        <W as crate::word::Word>::from_i64_wrap(1)
                                    )
                                );
                            }
                            Err(e) => return Err(e),
                        }
                    } else {
                        // Canonicalise a host-returned composite into an
                        // arena-resident flat body (B28 item 2 step 6B; see the
                        // reify arm above). No-op for a scalar, string, opaque,
                        // already-flat, or reference-bearing boxed value.
                        let v = self
                            .correct_native_enum_hints(result?)
                            .into_arena_canonical(wb, fb, arena)
                            .map_err(|_| out_of_arena_push("native result", arena.capacity()))?;
                        // Intern host `Opaque(Arc)` values to the POD index
                        // form for the operand stack (B33).
                        let v = self.intern_opaque_arcs(v);
                        sp!(self, v);
                    }
                }
            }
        }
    }

    fn pop(&mut self) -> Result<crate::bytecode::GenericValue<W, F>, VmError> {
        self.stack.pop().ok_or(VmError::StackUnderflow)
    }

    fn binary_arith<IntOp, FloatOp>(
        &mut self,
        int_op: IntOp,
        // `float_op` is kept regardless of the `floats` feature so
        // existing call sites compile unchanged.
        #[allow(unused_variables)] float_op: FloatOp,
    ) -> Result<(), VmError>
    where
        IntOp: Fn(W, W) -> W,
        FloatOp: Fn(F, F) -> F,
    {
        // Consolidation B narrowed `Op::Sub` and `Op::Mul` away
        // from `Int` operands. The compiler emits the
        // `CheckedXxx; PopN(2)` synthesis for `Int + Int`
        // expressions. This helper retains the `Byte` and `Float`
        // arms only; `Op::Mul` on `Fixed` goes through
        // `Op::FixedMul(n)` rather than this helper, but `Op::Sub`
        // on `Fixed` (which the compiler still emits via the
        // generic `Op::Sub`) is admitted by widening the `Byte`
        // arm pattern to include `Fixed`. The `int_op` closure is
        // reused for `Byte` and `Fixed` arithmetic since both are
        // wrapping integer operations on the underlying bit
        // representation.
        let b = self.pop()?;
        let a = self.pop()?;
        match (a, b) {
            (crate::bytecode::GenericValue::Byte(x), crate::bytecode::GenericValue::Byte(y)) => {
                // Byte arithmetic via i64 then mask: simulate the
                // operand widening and post-result truncation that
                // the i64 default runtime performs.
                let result = int_op(
                    <W as crate::word::Word>::from_i64_wrap(x as i64),
                    <W as crate::word::Word>::from_i64_wrap(y as i64),
                );
                sp!(
                    self,
                    crate::bytecode::GenericValue::Byte((result.to_i64() & 0xFF) as u8)
                );
            }
            (crate::bytecode::GenericValue::Fixed(x), crate::bytecode::GenericValue::Fixed(y)) => {
                let result = int_op(x, y);
                sp!(self, crate::bytecode::GenericValue::Fixed(result));
            }
            #[cfg(feature = "floats")]
            (crate::bytecode::GenericValue::Float(x), crate::bytecode::GenericValue::Float(y)) => {
                sp!(self, crate::bytecode::GenericValue::Float(float_op(x, y)))
            }
            (a, b) => {
                return Err(VmError::TypeError(format!(
                    "type mismatch: {} and {}",
                    a.type_name(),
                    b.type_name()
                )));
            }
        }
        Ok(())
    }

    /// Compare two values by string content when both are strings, returning
    /// `Some(equal)` (B28 P3 item 4). Each operand is resolved through the
    /// arena, so a `KStr` (a rodata or arena handle) compares by content rather
    /// than by the handle identity the structural `PartialEq` would use; this
    /// is required once a string constant loads as a rodata `KStr` rather than
    /// an owned `StaticStr`, so `"a" == "a"` (two distinct handles) is still
    /// content-correct. Returns `None` when the operands are not both strings,
    /// so the caller falls back to the structural comparison.
    fn string_content_eq(
        &self,
        a: &crate::bytecode::GenericValue<W, F>,
        b: &crate::bytecode::GenericValue<W, F>,
    ) -> Result<Option<bool>, VmError> {
        use crate::bytecode::GenericValue::{KStr, StaticStr};
        if matches!(a, StaticStr(_) | KStr(_)) && matches!(b, StaticStr(_) | KStr(_)) {
            let stale =
                || VmError::TypeError(String::from("KStr is stale (arena reset since allocation)"));
            let xs = a
                .as_str_with_arena(self.arena)
                .map_err(|_| stale())?
                .unwrap_or("");
            let ys = b
                .as_str_with_arena(self.arena)
                .map_err(|_| stale())?
                .unwrap_or("");
            Ok(Some(xs == ys))
        } else {
            Ok(None)
        }
    }

    /// Whether a yielded value transitively contains an EPHEMERAL dynamic
    /// string, the case the read-before-resume contract cannot cover because
    /// the arena reclaims it at the iteration boundary (B28 P3 item 4).
    ///
    /// A `KStr` whose pointer lies outside the ephemeral region is immortal (a
    /// rodata string constant or host-owned bytes) and is free to cross the
    /// boundary, so only an ephemeral `KStr` is flagged. This mirrors the boxed-
    /// only recursion of [`GenericValue::contains_dynstr`]; a flat body is not
    /// read here, so an ephemeral flat Text field is governed by the read-
    /// before-resume contract (the host decodes it before the next `resume()`)
    /// rather than a yield-time rejection.
    fn value_has_ephemeral_str(&self, v: &crate::bytecode::GenericValue<W, F>) -> bool {
        use crate::bytecode::{ArrayBody, EnumBody, GenericValue, StructBody, TupleBody};
        match v {
            GenericValue::KStr(ks) => self.arena.addr_is_ephemeral(ks.raw_parts().0),
            GenericValue::Tuple(TupleBody::Boxed(items)) => {
                items.iter().any(|x| self.value_has_ephemeral_str(x))
            }
            GenericValue::Array(ArrayBody::Boxed(items)) => {
                items.iter().any(|x| self.value_has_ephemeral_str(x))
            }
            GenericValue::Struct(StructBody::Boxed(b)) => b
                .fields
                .iter()
                .any(|(_, x)| self.value_has_ephemeral_str(x)),
            GenericValue::Enum(EnumBody::Boxed(b)) => {
                b.fields.iter().any(|x| self.value_has_ephemeral_str(x))
            }
            _ => false,
        }
    }

    fn compare_op<Pred>(&mut self, pred: Pred) -> Result<(), VmError>
    where
        Pred: FnOnce(core::cmp::Ordering) -> bool,
    {
        let b = self.pop()?;
        let a = self.pop()?;
        let ord = match (&a, &b) {
            (crate::bytecode::GenericValue::Int(x), crate::bytecode::GenericValue::Int(y)) => {
                x.cmp(y)
            }
            (crate::bytecode::GenericValue::Byte(x), crate::bytecode::GenericValue::Byte(y)) => {
                x.cmp(y)
            }
            (crate::bytecode::GenericValue::Fixed(x), crate::bytecode::GenericValue::Fixed(y)) => {
                x.cmp(y)
            }
            #[cfg(feature = "floats")]
            (crate::bytecode::GenericValue::Float(x), crate::bytecode::GenericValue::Float(y)) => {
                x.partial_cmp(y).unwrap_or(core::cmp::Ordering::Equal)
            }
            (
                a @ (crate::bytecode::GenericValue::StaticStr(_)
                | crate::bytecode::GenericValue::KStr(_)),
                b @ (crate::bytecode::GenericValue::StaticStr(_)
                | crate::bytecode::GenericValue::KStr(_)),
            ) => {
                let arena = self.arena;
                let xs = a
                    .as_str_with_arena(arena)
                    .map_err(|_| {
                        VmError::TypeError(String::from(
                            "KStr is stale (arena reset since allocation)",
                        ))
                    })?
                    .unwrap_or("");
                let ys = b
                    .as_str_with_arena(arena)
                    .map_err(|_| {
                        VmError::TypeError(String::from(
                            "KStr is stale (arena reset since allocation)",
                        ))
                    })?
                    .unwrap_or("");
                xs.cmp(ys)
            }
            _ => {
                return Err(VmError::TypeError(format!(
                    "cannot compare {} and {}",
                    a.type_name(),
                    b.type_name()
                )));
            }
        };
        sp!(self, crate::bytecode::GenericValue::Bool(pred(ord)));
        Ok(())
    }
}

// Marshall-integration methods. The marshall layer's
// IntoNativeFn / KeleusmaType / stddsl::Library traits are
// parametric over (W, F); these methods quantify the same way
// so any `GenericVm<W, A, F>` can register host functions.
impl<'a, 'arena, W: crate::word::Word, A: crate::address::Address, F: crate::float::Float>
    GenericVm<'a, 'arena, W, A, F>
{
    /// Register an infallible host function with automatic argument and
    /// return-value marshalling.
    pub fn register_fn<Func, Args, R>(&mut self, name: &str, func: Func)
    where
        Func: crate::marshall::IntoNativeFn<W, F, Args, R>,
    {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet: DEFAULT_NATIVE_WCET,
            wcmu_bytes: DEFAULT_NATIVE_WCMU_BYTES,
            name: String::from(name),
            func: func.into_native_fn(),
            classification: NativeClassification::Verified,
            max_invocations_per_iteration: None,
        });
    }

    /// Register a fallible host function with automatic argument and
    /// return-value marshalling.
    pub fn register_fn_fallible<Func, Args, R>(&mut self, name: &str, func: Func)
    where
        Func: crate::marshall::IntoFallibleNativeFn<W, F, Args, R>,
    {
        self.native_classifications_verified = false;
        // Deduplicate: a re-registration of the same name replaces
        // the prior entry rather than shadowing it. Without this
        // the dispatch `find` would return the first match
        // regardless of subsequent registrations, making the
        // re-registration silently no-op.
        self.natives.retain(|e| e.name != name);
        self.natives.push(NativeEntry {
            wcet: DEFAULT_NATIVE_WCET,
            wcmu_bytes: DEFAULT_NATIVE_WCMU_BYTES,
            name: String::from(name),
            func: func.into_native_fn(),
            classification: NativeClassification::Verified,
            max_invocations_per_iteration: None,
        });
    }

    /// Register a [`crate::stddsl::Library`] bundle on the VM.
    #[cfg(feature = "floats")]
    pub fn register_library<L: crate::stddsl::Library<W, A, F>>(&mut self, library: L) {
        library.register(self);
    }
}

// The test module exercises the full pipeline (source through
// VM execution) and therefore requires both the `compile` and
// `verify` features.
#[cfg(all(test, feature = "compile", feature = "verify"))]
mod tests {
    use super::*;
    use crate::compiler::compile;
    use crate::lexer::tokenize;
    use crate::parser::parse;

    #[test]
    fn vm_error_category_three_way_split() {
        // Sanity-check that each VmError variant maps to the
        // expected category. Halt covers the unrecoverable cases
        // where the VM's state is undefined after the error; soft
        // script covers the recoverable-via-resume_err cases; soft
        // host covers the host-native error surface.
        let halt: alloc::vec::Vec<VmError> = alloc::vec![
            VmError::StackUnderflow,
            VmError::InvalidBytecode(alloc::string::String::from("oops")),
            VmError::VerifyError(alloc::string::String::from("oops")),
            VmError::LoadError(alloc::string::String::from("oops")),
            VmError::OutOfArena(alloc::string::String::from("oops")),
            VmError::NotSuspended,
        ];
        for e in &halt {
            assert_eq!(
                e.category(),
                VmErrorCategory::Halt,
                "expected Halt for {:?}",
                e
            );
        }
        let soft_script: alloc::vec::Vec<VmError> = alloc::vec![
            VmError::TypeError(alloc::string::String::from("oops")),
            VmError::DivisionByZero,
            VmError::IndexOutOfBounds(0, 0),
            VmError::FieldNotFound(
                alloc::string::String::from("S"),
                alloc::string::String::from("f"),
            ),
            VmError::RefinementFailed,
            VmError::NoMatchingHead,
            VmError::NoMatchingArm,
            VmError::CheckedArithNoArm,
            VmError::EnumVariantUnmapped,
        ];
        for e in &soft_script {
            assert_eq!(
                e.category(),
                VmErrorCategory::SoftScript,
                "expected SoftScript for {:?}",
                e
            );
        }
        assert_eq!(
            VmError::NativeError(alloc::string::String::from("oops")).category(),
            VmErrorCategory::SoftHost,
        );
    }

    fn run_program(src: &str, args: &[Value]) -> Result<VmState, VmError> {
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena)?;
        vm.call(args)
    }

    /// Compile `src` with debug metadata (B29) so each chunk carries a
    /// `debug_pool` the fault-localization read path can consult.
    fn compile_debug(src: &str) -> Module {
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let (module, _warnings) = crate::compiler::compile_with_options(
            &program,
            &crate::target::Target::host(),
            &crate::compiler::CompileOptions { emit_debug: true },
        )
        .expect("compile error");
        module
    }

    #[test]
    fn fault_location_records_trapping_op_and_maps_to_source() {
        // A division by a runtime zero traps inside a `let` statement;
        // the VM records the faulting op (the Div), which now carries an
        // exact SourceSpan at the operator site (B29 items 2/3), so the
        // fault resolves exactly to the division sub-expression.
        let module = compile_debug("fn main(d: Word) -> Word { let x = 1 / d; x }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm constructs");
        let err = vm
            .call(&[Value::Int(0)])
            .expect_err("division by zero traps");
        assert!(matches!(err, VmError::DivisionByZero));
        let (chunk, _op) = vm.fault_location().expect("fault location recorded");
        assert_eq!(chunk, 0, "the fault is in main, chunk 0");
        let src = vm
            .fault_source_location()
            .expect("the fault maps to the division sub-expression");
        assert!(
            src.exact,
            "the Div op carries an exact operator-site SourceSpan"
        );
    }

    #[test]
    fn fault_source_is_exact_for_failed_assert() {
        // A failed debug `assert` traps; its AssertionContext record
        // sits exactly at the assert op, so resolution is exact.
        let module = compile_debug("fn main() -> Word { assert false, \"boom\"; 0 }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm constructs");
        let err = vm.call(&[]).expect_err("assert false traps");
        assert!(matches!(err, VmError::AssertionFailed));
        let src = vm
            .fault_source_location()
            .expect("the assert maps to a source span");
        assert!(
            src.exact,
            "an AssertionContext record sits exactly at the assert op"
        );
    }

    #[test]
    fn fault_in_newtype_construction_resolves_exactly() {
        // A refinement-predicate failure traps RefinementFailed at the
        // construction's Trap op, which now carries an operator-site
        // SourceSpan (B29 item 2), so the fault resolves exactly.
        let module = compile_debug(
            "fn is_pos(x: Word) -> bool { x > 0 }\n\
             newtype Positive = Word where is_pos;\n\
             fn main() -> Word { Positive(0 - 7) { ok(p) => 1 } }",
        );
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm constructs");
        let err = vm.call(&[]).expect_err("refinement failure traps");
        assert!(matches!(err, VmError::RefinementFailed));
        let src = vm
            .fault_source_location()
            .expect("the refinement failure resolves to source");
        assert!(src.exact, "the refinement Trap carries an exact span");
    }

    #[test]
    fn fault_in_array_index_resolves_exactly() {
        // An out-of-bounds data-array index traps IndexOutOfBounds at
        // the GetDataIndexed op, which now carries an operator-site
        // SourceSpan (B29 item 2), so the fault resolves exactly.
        let module = compile_debug(
            "data state { items: [Word; 3] }\n\
             fn main() -> Word { state.items[5] }",
        );
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm constructs");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        let err = vm
            .call_with_shared(&mut shared, &[])
            .expect_err("out-of-bounds index traps");
        assert!(matches!(err, VmError::IndexOutOfBounds(_, _)));
        let src = vm
            .fault_source_location()
            .expect("the index fault resolves to source");
        assert!(src.exact, "the index op carries an exact span");
    }

    #[test]
    fn fault_location_cleared_after_successful_run() {
        let module = compile_debug("fn main() -> Word { 21 + 21 }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm constructs");
        let state = vm.call(&[]).expect("runs to completion");
        assert!(matches!(state, VmState::Finished(Value::Int(42))));
        assert!(
            vm.fault_location().is_none(),
            "a successful run leaves no fault location"
        );
        assert!(vm.fault_source_location().is_none());
    }

    #[test]
    fn fault_in_tail_expression_resolves_to_its_span() {
        // A function whose whole body is one tail expression now carries
        // a SourceSpan for that expression (B29 item 2), so a fault in it
        // resolves to the tail expression's span rather than to nothing.
        let module = compile_debug("fn main(d: Word) -> Word { 1 / d }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm constructs");
        let err = vm
            .call(&[Value::Int(0)])
            .expect_err("division by zero traps");
        assert!(matches!(err, VmError::DivisionByZero));
        let src = vm
            .fault_source_location()
            .expect("the tail-expression fault now resolves");
        // The Div operator site now carries an exact SourceSpan, so the
        // tail-expression fault resolves exactly (B29 items 2/3). The
        // tail-expression span (item 2) additionally guarantees a
        // resolution even for non-operator tail faults.
        assert!(src.exact);
    }

    #[test]
    fn fault_source_location_none_without_debug_pool() {
        // A release build carries no debug pool, so even though the
        // fault op is recorded, it does not resolve to source.
        let tokens = tokenize("fn main(d: Word) -> Word { 1 / d }").expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm constructs");
        let err = vm
            .call(&[Value::Int(0)])
            .expect_err("division by zero traps");
        assert!(matches!(err, VmError::DivisionByZero));
        assert!(
            vm.fault_location().is_some(),
            "the op position is recorded regardless of debug metadata"
        );
        assert!(
            vm.fault_source_location().is_none(),
            "without a debug pool there is no source mapping"
        );
    }

    fn run_expect(src: &str, args: &[Value]) -> Value {
        match run_program(src, args).unwrap() {
            VmState::Finished(v) => v,
            VmState::Yielded(v) => panic!("unexpected yield: {:?}", v),
            VmState::Reset => panic!("unexpected reset"),
            VmState::BreakpointHit { chunk, op } => {
                panic!("unexpected breakpoint at chunk {} op {}", chunk, op)
            }
        }
    }

    #[test]
    fn generic_with_underscored_origin_name_specializes() {
        // Finding 26 (V0.2.1 audit): the monomorphizer recovers a
        // specialization's origin from the authoritative specs map, not by
        // splitting the mangled `origin__type_args` name on "__". A generic whose
        // own name contains "__" must still specialize correctly -- the old split
        // recovered `foo` for `foo__bar`, misattributing its per-function
        // specialization count. Exercised alongside a plain `foo` generic so a
        // miscount would conflate the two origins' counts. Both must resolve.
        let v = run_expect(
            "fn foo__bar<T>(x: T) -> T { x }\n\
             fn foo<T>(x: T) -> T { x }\n\
             fn main() -> Word { foo__bar(5) + foo(7) }",
            &[],
        );
        assert_eq!(v, Value::Int(12));
    }

    /// Run `src` and resolve the finished value's string content to an owned
    /// `String` while the VM and arena are still alive. A string constant now
    /// loads as a rodata `KStr` pointing into the VM-owned bytecode image, so a
    /// returned `Value` would dangle once the local VM drops; resolving here
    /// captures the content first (B28 P3 item 4).
    fn run_expect_text(src: &str, args: &[Value]) -> alloc::string::String {
        use alloc::string::ToString;
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let v = match vm.call(args).unwrap() {
            VmState::Finished(v) => v,
            other => panic!("expected finished, got {:?}", other),
        };
        v.as_str_with_arena(&arena)
            .expect("resolve string")
            .unwrap_or("")
            .to_string()
    }

    #[test]
    fn qif_labels_are_erased_at_runtime() {
        // The information-flow labels are a compile-time
        // discipline. Both classify and declassify compile to
        // identity at the bytecode layer; the runtime value
        // produced is identical to the unlabeled equivalent.
        let val = run_expect(
            "fn produce() -> Word@Secret { 42 }\n\
             fn main() -> Word { declassify produce()@Secret }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn qif_classify_runtime_value_is_unchanged() {
        let val = run_expect("fn main() -> Word@Secret { classify 99@Secret }", &[]);
        assert_eq!(val, Value::Int(99));
    }

    #[test]
    fn checked_overflow_ok_arm_passes_result() {
        // `1 + 2` does not overflow, so the construct evaluates
        // to the `ok` arm's body which binds the successful
        // result and returns it.
        let val = run_expect(
            "fn main() -> Word {\n\
                let y = 1 + 2 {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => saturate_max,\n\
                    underflow(_, _) => saturate_min,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(3));
    }

    #[test]
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    fn checked_overflow_without_arm_wraps_by_default() {
        // B35 P3: with no `overflow` arm, a positive overflow defaults
        // to the two's-complement wrapped result. `Word::MAX + 1`
        // wraps to `Word::MIN`. The `i64::MAX` literal and the
        // `i64::MIN` expectation are specific to the default 64-bit
        // declared width, so this is gated off the narrow-word runtimes
        // where the wrap occurs at a smaller width (matching the
        // sibling checked-arithmetic tests).
        let val = run_expect(
            "fn main() -> Word {\n\
                let y = 9223372036854775807 + 1 {\n\
                    ok(v) => v,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(i64::MIN));
    }

    #[test]
    fn checked_overflow_arm_returns_saturate_max() {
        // A positive overflow (Word::MAX + 1) dispatches to the
        // overflow arm; `saturate_max` evaluates to Word::MAX.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 9223372036854775807;\n\
                let y = m + 1 {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => saturate_max,\n\
                    underflow(_, _) => saturate_min,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(i64::MAX));
    }

    // B16 step 12: this test exercises i64-specific boundary
    // arithmetic. Narrowed binary builds reject the wider literals
    // at the framing or compile level; the test is gated to the
    // default 64-bit runtime configuration.
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn checked_underflow_arm_returns_saturate_min() {
        // A negative overflow ((Word::MIN + 1) - 2) dispatches
        // to the underflow arm. The minuend is constructed as
        // `0 - 9223372036854775807` because the bare literal
        // `-9223372036854775808` would not lex (the absolute
        // value is one past `i64::MAX`).
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 0 - 9223372036854775807;\n\
                let y = m - 2 {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => saturate_max,\n\
                    underflow(_, _) => saturate_min,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(i64::MIN));
    }

    #[test]
    fn checked_mul_overflow_detected() {
        // Multiplication of two large positives overflows;
        // the construct routes to the overflow arm.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 9223372036854775807;\n\
                let y = m * 2 {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => 1,\n\
                    underflow(_, _) => 2,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(1));
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn checked_neg_min_overflows() {
        // Negation of Word::MIN overflows because no positive
        // counterpart exists in signed 64-bit.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 0 - 9223372036854775807;\n\
                let y = -(m - 1) {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => 1,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(1));
    }

    #[test]
    fn checked_div_ok_path() {
        // Division of in-range operands routes through the ok arm
        // with the quotient as the bound value.
        let val = run_expect(
            "fn main() -> Word {\n\
                let y = 10 / 3 {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => 0,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(3));
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn checked_div_min_by_neg_one_overflows() {
        // `i64::MIN / -1` is the only overflow case in signed
        // 64-bit division because the true result is `2^63` and
        // does not fit in `Word`. The construct routes to the
        // overflow arm; the high half is zero (the true result
        // fits in 65 bits) and the low half is `i64::MIN` (the
        // wrapped quotient).
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 0 - 9223372036854775807 - 1;\n\
                let y = m / (0 - 1) {\n\
                    ok(_) => 0,\n\
                    overflow(h, l) => h + l,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        // h = 0, l = i64::MIN; sum is i64::MIN.
        assert_eq!(val, Value::Int(i64::MIN));
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn checked_mod_min_by_neg_one_is_in_range_zero() {
        // `i64::MIN % -1` is mathematically `0`. A remainder is
        // always in range, so modulo never overflows or underflows
        // (B35 P3c forbids those arms on `%`); the corner surfaces
        // through the `ok` arm as `0`.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 0 - 9223372036854775807 - 1;\n\
                let y = m % (0 - 1) {\n\
                    ok(r) => r,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(0));
    }

    #[test]
    fn checked_div_by_zero_traps() {
        // With no `zero_divisor` arm, a zero divisor is reified by
        // the opcode (flag 3) and the dispatch's default traps with
        // VmError::DivisionByZero, the same error plain division by
        // zero produces.
        let result = run_program(
            "fn main() -> Word {\n\
                let y = 10 / 0 {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => 0,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert!(matches!(result, Err(VmError::DivisionByZero)));
    }

    #[test]
    fn checked_div_zero_divisor_arm_binds_numerator() {
        // B35 P3b: a handled zero divisor runs the `zero_divisor`
        // arm, which binds the numerator.
        let val = run_expect(
            "fn main() -> Word {\n\
                let y = 42 / 0 {\n\
                    ok(q) => q,\n\
                    zero_divisor(n) => n,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn checked_mod_zero_divisor_arm_handled() {
        // Modulo by zero is reified and handled the same way.
        let val = run_expect(
            "fn main() -> Word {\n\
                let y = 7 % 0 {\n\
                    ok(r) => r,\n\
                    zero_divisor(_) => 99,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(99));
    }

    #[test]
    fn checked_byte_add_overflow_binds_wrapped() {
        // B35 P3d-i: unsigned Byte addition overflows above 255; the
        // single-pattern overflow arm binds the wrapped result.
        let val = run_expect(
            "fn main() -> Byte {\n\
                let y = 200Byte + 100Byte {\n\
                    ok(v) => v,\n\
                    overflow(w) => w,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Byte(44));
    }

    #[test]
    fn checked_byte_add_ok_in_range() {
        let val = run_expect(
            "fn main() -> Byte {\n\
                let y = 100Byte + 50Byte {\n\
                    ok(v) => v,\n\
                    overflow(_) => 255Byte,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Byte(150));
    }

    #[test]
    fn checked_byte_sub_underflow_binds_wrapped() {
        // 5 - 10 underflows; the wrapped result is 251 (modulo 256).
        let val = run_expect(
            "fn main() -> Byte {\n\
                let y = 5Byte - 10Byte {\n\
                    ok(v) => v,\n\
                    underflow(w) => w,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Byte(251));
    }

    #[test]
    fn checked_byte_div_zero_divisor_binds_numerator() {
        let val = run_expect(
            "fn main() -> Byte {\n\
                let y = 42Byte / 0Byte {\n\
                    ok(q) => q,\n\
                    zero_divisor(n) => n,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Byte(42));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn checked_float_div_zero_is_infinity_overflow() {
        // B35 P3d-ii: float `1.0 / 0.0` is +inf, classified as the
        // overflow outcome (IEEE 754, no trap).
        let val = run_expect(
            "fn main() -> Float {\n\
                1.0Float / 0.0Float {\n\
                    ok(v) => v,\n\
                    overflow(_) => 1.0Float,\n\
                    underflow(_) => 2.0Float,\n\
                    nan(_) => 3.0Float,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Float(1.0));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn checked_float_zero_over_zero_is_nan() {
        let val = run_expect(
            "fn main() -> Float {\n\
                0.0Float / 0.0Float {\n\
                    ok(v) => v,\n\
                    overflow(_) => 1.0Float,\n\
                    underflow(_) => 2.0Float,\n\
                    nan(_) => 3.0Float,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Float(3.0));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn checked_float_negative_over_zero_is_underflow() {
        // (0.0 - 1.0) / 0.0 is -inf, the underflow outcome.
        let val = run_expect(
            "fn main() -> Float {\n\
                let n = 0.0Float - 1.0Float;\n\
                n / 0.0Float {\n\
                    ok(v) => v,\n\
                    overflow(_) => 1.0Float,\n\
                    underflow(_) => 2.0Float,\n\
                    nan(_) => 3.0Float,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Float(2.0));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn checked_float_ok_finite_result() {
        let val = run_expect(
            "fn main() -> Float {\n\
                6.0Float / 2.0Float {\n\
                    ok(v) => v,\n\
                    overflow(_) => 0.0Float,\n\
                    underflow(_) => 0.0Float,\n\
                    nan(_) => 0.0Float,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Float(3.0));
    }

    // B35 P3d-iii: Fixed checked arithmetic. `6Fixed<16>` has raw
    // bits `6 << 16 = 393216`. Fixed is signed, so its admissibility
    // mirrors Word; its arms bind a single result like Byte/Float;
    // and `*`/`/` route through the Q-format-aware opcodes that carry
    // the fraction-bit shift. Overflow/underflow wrap (the wrapping
    // default), unlike the saturating plain `FixedMul`/`FixedDiv`.

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn checked_fixed_div_zero_divisor_binds_numerator() {
        // 6 / 0 reifies as zero_divisor; the numerator (raw 393216)
        // binds through the single pattern.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                6Fixed<16> / 0Fixed<16> {\n\
                    ok(q) => q,\n\
                    zero_divisor(n) => n,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(393216));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn checked_fixed_div_ok_in_range() {
        // 6 / 2 = 3; raw 3 << 16 = 196608.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                6Fixed<16> / 2Fixed<16> {\n\
                    ok(q) => q,\n\
                    zero_divisor(n) => n,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(196608));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn checked_fixed_div_unhandled_zero_traps() {
        // An unhandled zero divisor traps as DivisionByZero, matching
        // the contract that a partial operation with no in-band result
        // traps when unhandled.
        let err = run_program(
            "fn main() -> Fixed<16> {\n\
                6Fixed<16> / 0Fixed<16> {\n\
                    ok(q) => q,\n\
                }\n\
             }",
            &[],
        )
        .unwrap_err();
        assert!(matches!(err, VmError::DivisionByZero));
    }

    #[test]
    fn checked_fixed_mod_zero_divisor_binds_numerator() {
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                6Fixed<16> % 0Fixed<16> {\n\
                    ok(r) => r,\n\
                    zero_divisor(n) => n,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(393216));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn checked_fixed_mul_overflow_routes_overflow() {
        // raw(16777216Fixed<16>) = 2^24 << 16 = 2^40; the Q-format
        // product is 2^80 >> 16 = 2^64, which exceeds i64::MAX, so the
        // overflow arm fires. The sentinel distinguishes it from ok.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                16777216Fixed<16> * 16777216Fixed<16> {\n\
                    ok(v) => v,\n\
                    overflow(_) => 1Fixed<16>,\n\
                    underflow(_) => 2Fixed<16>,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(65536));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn checked_fixed_mul_underflow_routes_underflow() {
        // A large negative times a large positive lands below
        // i64::MIN after the shift, routing to underflow.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                let a = 0Fixed<16> - 16777216Fixed<16>;\n\
                a * 16777216Fixed<16> {\n\
                    ok(v) => v,\n\
                    overflow(_) => 1Fixed<16>,\n\
                    underflow(_) => 2Fixed<16>,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(131072));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn checked_fixed_mul_unhandled_overflow_wraps() {
        // With no overflow arm, the out-of-range product wraps to the
        // low slot (2^64 mod 2^64 = 0) and does not trap.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                16777216Fixed<16> * 16777216Fixed<16> {\n\
                    ok(v) => v,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(0));
    }

    #[test]
    fn checked_fixed_add_overflow_routes_overflow() {
        // raw(70368744177664Fixed<16>) = 2^46 << 16 = 2^62; the sum is
        // 2^63, which exceeds i64::MAX, so the overflow arm fires.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                let big = 70368744177664Fixed<16>;\n\
                big + big {\n\
                    ok(v) => v,\n\
                    overflow(_) => 1Fixed<16>,\n\
                    underflow(_) => 2Fixed<16>,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(65536));
    }

    #[test]
    fn checked_fixed_neg_ok() {
        // Negation of `-5` is `5`; raw 5 << 16 = 327680.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                let m = 0Fixed<16> - 5Fixed<16>;\n\
                -m {\n\
                    ok(v) => v,\n\
                    overflow(_) => 1Fixed<16>,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(327680));
    }

    // B35 P4: the indexing construct `array[i] { ok(v) => ...,
    // invalid_index(idx) => ... }`. The `ok` arm binds the element;
    // `invalid_index` binds the offending index. An unhandled
    // out-of-bounds index re-issues the plain index and traps with
    // the precise IndexOutOfBounds payload.

    #[test]
    fn checked_index_ok_in_bounds_binds_element() {
        let val = run_expect(
            "fn main() -> Word {\n\
                let a = [10, 20, 30];\n\
                a[1] {\n\
                    ok(v) => v,\n\
                    invalid_index(i) => i,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(20));
    }

    #[test]
    fn checked_index_oob_binds_index() {
        let val = run_expect(
            "fn main() -> Word {\n\
                let a = [10, 20, 30];\n\
                a[7] {\n\
                    ok(v) => v,\n\
                    invalid_index(i) => i,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn checked_index_negative_routes_to_invalid_index() {
        let val = run_expect(
            "fn main() -> Word {\n\
                let a = [10, 20, 30];\n\
                a[0 - 5] {\n\
                    ok(v) => v,\n\
                    invalid_index(i) => i,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(-5));
    }

    #[test]
    fn checked_index_unhandled_oob_traps_with_payload() {
        // No invalid_index arm: an out-of-bounds index re-issues the
        // plain index, trapping with the precise (index, len).
        let err = run_program(
            "fn main() -> Word {\n\
                let a = [10, 20, 30];\n\
                a[7] {\n\
                    ok(v) => v,\n\
                }\n\
             }",
            &[],
        )
        .unwrap_err();
        assert!(matches!(err, VmError::IndexOutOfBounds(7, 3)), "{:?}", err);
    }

    #[test]
    fn checked_index_element_binds_at_element_type() {
        // A Byte array's `ok` binding is typed Byte, so the body
        // returns a Byte without a coercion error.
        let val = run_expect(
            "fn main() -> Byte {\n\
                let a = [10Byte, 20Byte, 30Byte];\n\
                a[2] {\n\
                    ok(v) => v,\n\
                    invalid_index(_) => 0Byte,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Byte(30));
    }

    // B35 P5: the newtype-construction construct `Name(v) { ok(p) =>
    // ..., invalid_newtype(x) => ... }`. The `ok` arm binds the
    // constructed newtype; `invalid_newtype` binds the underlying
    // value the refinement rejected. An unhandled failure traps with
    // RefinementFailed.

    #[test]
    fn checked_newtype_ok_when_predicate_passes() {
        let val = run_expect(
            "fn is_pos(x: Word) -> bool { x > 0 }\n\
             newtype Positive = Word where is_pos;\n\
             fn main() -> Word {\n\
                Positive(5) {\n\
                    ok(p) => 1,\n\
                    invalid_newtype(x) => x,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(1));
    }

    #[test]
    fn checked_newtype_invalid_binds_underlying() {
        // The predicate rejects -7; the invalid_newtype arm binds the
        // underlying value.
        let val = run_expect(
            "fn is_pos(x: Word) -> bool { x > 0 }\n\
             newtype Positive = Word where is_pos;\n\
             fn main() -> Word {\n\
                Positive(0 - 7) {\n\
                    ok(p) => 1,\n\
                    invalid_newtype(x) => x,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(-7));
    }

    #[test]
    fn checked_newtype_unhandled_failure_traps() {
        let err = run_program(
            "fn is_pos(x: Word) -> bool { x > 0 }\n\
             newtype Positive = Word where is_pos;\n\
             fn main() -> Word {\n\
                Positive(0 - 7) {\n\
                    ok(p) => 1,\n\
                }\n\
             }",
            &[],
        )
        .unwrap_err();
        assert!(matches!(err, VmError::RefinementFailed), "{:?}", err);
    }

    // B35 P6: the discriminant-to-enum construct `d as Enum { ok(V)
    // => ..., payload_discriminant(V) => ..., invalid_discriminant(r)
    // => ... }`. A unit variant converts to itself by default; an `ok`
    // arm overrides; a payload variant's payload comes from the
    // payload_discriminant arm body; an unmapped discriminant runs the
    // invalid_discriminant arm or traps.

    const DISC_ENUM: &str = "enum Color { Red = 0, Green = 1, Custom(Word) = 2 }\n";

    #[test]
    fn checked_discriminant_unit_converts_to_itself() {
        // Discriminant 1 maps to the unit variant Green with no `ok`
        // arm, so it converts to itself; the `as Word` reads it back.
        let src = alloc::format!(
            "{}fn main() -> Word {{ let c = 1 as Color {{ payload_discriminant(Custom) => Color::Custom(0), invalid_discriminant(r) => Color::Red }}; c as Word }}",
            DISC_ENUM
        );
        assert_eq!(run_expect(&src, &[]), Value::Int(1));
    }

    #[test]
    fn checked_discriminant_payload_arm_supplies_payload() {
        let src = alloc::format!(
            "{}fn main() -> Word {{ let c = 2 as Color {{ payload_discriminant(Custom) => Color::Custom(99), invalid_discriminant(r) => Color::Red }}; c as Word }}",
            DISC_ENUM
        );
        // Custom has discriminant 2; the value reads back to 2.
        assert_eq!(run_expect(&src, &[]), Value::Int(2));
    }

    #[test]
    fn checked_discriminant_ok_override() {
        // Discriminant 0 is Red; the ok(Red) arm overrides to Green.
        let src = alloc::format!(
            "{}fn main() -> Word {{ let c = 0 as Color {{ ok(Red) => Color::Green, payload_discriminant(Custom) => Color::Custom(0) }}; c as Word }}",
            DISC_ENUM
        );
        assert_eq!(run_expect(&src, &[]), Value::Int(1));
    }

    #[test]
    fn checked_discriminant_invalid_binds_raw() {
        // Discriminant 7 maps to no variant; invalid_discriminant
        // binds the raw Word and the body uses it.
        let src = alloc::format!(
            "{}fn main() -> Word {{ let c = 7 as Color {{ payload_discriminant(Custom) => Color::Custom(0), invalid_discriminant(r) => Color::Custom(r) }}; c as Word }}",
            DISC_ENUM
        );
        // Custom discriminant is 2 regardless of payload.
        assert_eq!(run_expect(&src, &[]), Value::Int(2));
    }

    #[test]
    fn checked_discriminant_unhandled_invalid_traps() {
        let src = alloc::format!(
            "{}fn main() -> Color {{ 9 as Color {{ payload_discriminant(_) => Color::Red }} }}",
            DISC_ENUM
        );
        let err = run_program(&src, &[]).unwrap_err();
        assert!(matches!(err, VmError::EnumVariantUnmapped), "{:?}", err);
    }

    // B35 P9 follow-up: `saturate_max`/`saturate_min` resolve at the
    // construct's operand type, not only `Word`. Each rewrites to that
    // type's saturating bound.

    #[test]
    fn checked_byte_saturate_max_clamps_to_255() {
        let val = run_expect(
            "fn main() -> Byte {\n\
                200Byte + 100Byte { ok(v) => v, overflow(_) => saturate_max }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Byte(255));
    }

    #[test]
    fn checked_byte_saturate_min_clamps_to_0() {
        let val = run_expect(
            "fn main() -> Byte {\n\
                5Byte - 10Byte { ok(v) => v, underflow(_) => saturate_min }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Byte(0));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn checked_fixed_saturate_max_clamps_to_max_raw() {
        // The Q-format saturating maximum is the largest raw bit
        // pattern, i64::MAX.
        let val = run_expect(
            "fn main() -> Fixed<16> {\n\
                16777216Fixed<16> * 16777216Fixed<16> {\n\
                    ok(v) => v,\n\
                    overflow(_) => saturate_max,\n\
                    underflow(_) => saturate_min,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Fixed(i64::MAX));
    }

    // The next three checked-overflow tests embed integer literals
    // (4294967296 = 2^32, large guard values, literal-high patterns)
    // sized for an i64 Word. Under any of the `narrow-word-*`
    // features the runtime Word is i32 or smaller and the constant
    // either fails to fit or wraps to a value the test does not
    // expect. Gated so they only run on the default i64 runtime.

    #[test]
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    fn checked_mul_overflow_exposes_high_half() {
        // The high half of the i128 intermediate is the load-
        // bearing value for big-number multiplication. `2^32 *
        // 2^32 == 2^64`, which in i128 is (high=1, low=0); the
        // construct binds both and the body returns the high
        // half.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 4294967296;\n\
                let y = m * m {\n\
                    ok(v) => 0 - 1,\n\
                    overflow(h, _) => h,\n\
                    underflow(_, _) => 0 - 2,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(1));
    }

    #[test]
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    fn checked_overflow_arm_pattern_matches_literal_high() {
        // A literal `0` in the high position selects the small-
        // overflow specialization. For signed addition of two
        // positive operands at i64::MAX, the true sum is
        // (high=0, low=-2 wrapped), so the `overflow(0, l)` arm
        // fires.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 9223372036854775807;\n\
                let y = m + m {\n\
                    ok(v) => v,\n\
                    overflow(0, l) => l,\n\
                    overflow(h, _) => h,\n\
                    underflow(_, _) => 0,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        // i64::MAX + i64::MAX == -2 wrapped (low half).
        assert_eq!(val, Value::Int(-2));
    }

    #[test]
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    fn checked_overflow_arm_guard_falls_through() {
        // The first arm's pattern matches but its guard returns
        // false; dispatch falls through to the catch-all.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = 9223372036854775807;\n\
                let y = m + 1 {\n\
                    ok(v) => v,\n\
                    overflow(h, l) when h == 99 => 0,\n\
                    overflow(_, l) => l,\n\
                    underflow(_, _) => 0 - 1,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        // i64::MAX + 1 == i64::MIN wrapped (low half).
        assert_eq!(val, Value::Int(i64::MIN));
    }

    #[test]
    fn newtype_construction_returns_underlying_at_runtime() {
        // Newtype `Percent` is transparent at runtime; the value
        // produced is the underlying Word.
        let val = run_expect(
            "newtype Percent = Word;\n\
             fn main() -> Percent { Percent(42) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_passes_when_argument_in_range() {
        // The predicate `nonneg` returns true for non-negative
        // arguments; the construction succeeds and the value
        // passes through.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn main() -> Counter { Counter(42) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_eliminated_when_literal_proves_satisfaction() {
        // The predicate `nonneg(x) = x >= 0` is statically true
        // for the literal `42`. The compiler elides the runtime
        // call and trap; the construction reduces to the inner
        // value. The runtime result is unchanged.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn main() -> Counter { Counter(42) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_rejected_at_compile_time_when_literal_provably_fails() {
        // The predicate `nonneg(x) = x >= 0` is statically false
        // for a literal that the evaluator can prove out of range.
        // Use a parser-level negative literal: `nonneg(-1)` is
        // parsed as a unary-neg over a literal, which the
        // evaluator handles. The compiler rejects the construction.
        let src = "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn always_negative() -> Word { 0 - 1 }\n\
             fn main() -> Counter { Counter(0 - always_negative()) }";
        // The compile-time check only fires for direct literal
        // arguments; the above keeps the runtime path active.
        // Sanity-check that the runtime path still works (this
        // arg is computed and evaluates to +1 at runtime).
        let val = run_expect(src, &[]);
        assert_eq!(val, Value::Int(1));
    }

    #[test]
    fn refinement_predicate_compile_error_when_literal_out_of_range() {
        // A direct literal argument that statically violates the
        // predicate is rejected at compile time. The diagnostic
        // names the predicate, the newtype, and the offending
        // argument.
        let src = "fn small(x: Word) -> bool { x < 10 }\n\
             newtype Tiny = Word where small;\n\
             fn main() -> Tiny { Tiny(42) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("small")
                && err.message.contains("Tiny")
                && err.message.contains("42"),
            "expected compile-time diagnostic naming predicate / newtype / argument, got: {}",
            err.message
        );
    }

    #[test]
    fn refinement_predicate_traps_when_argument_out_of_range() {
        // The predicate `nonneg` returns false for -1; the
        // newtype construction traps at runtime when neither
        // constant folding nor the cross-function range summary
        // can decide the argument statically. The body of
        // `mystery` uses an if-expression which the summary
        // computer does not handle, so the call site falls
        // through to the runtime check.
        let err = run_program(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn mystery() -> Word { if 0 == 0 { 0 - 1 } else { 1 } }\n\
             fn main() -> Counter { Counter(mystery()) }",
            &[],
        )
        .unwrap_err();
        assert!(
            matches!(err, VmError::RefinementFailed),
            "expected VmError::RefinementFailed, got {:?}",
            err
        );
    }

    #[test]
    fn refinement_predicate_folded_arithmetic_argument_eliminated() {
        // Tier 1: arithmetic over literal arguments folds to a
        // compile-time constant and routes through the predicate
        // evaluator. `Counter(2 + 40)` reduces to `Counter(42)`
        // statically; the predicate `nonneg(42)` is true and the
        // runtime check is elided.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn main() -> Counter { Counter(2 + 40) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_let_bound_constant_eliminated() {
        // Tier 2: a let-bound local that constant-folds to an
        // integer at compile time resolves through the elision
        // pass. The runtime predicate call and trap are skipped.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn main() -> Counter {\n\
                let n = 42;\n\
                Counter(n)\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_let_bound_arithmetic_chain_eliminated() {
        // Tier 2: chained let-bound constants. Each binding folds
        // through the previous one's recorded value.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn main() -> Counter {\n\
                let a = 2;\n\
                let b = a * 21;\n\
                Counter(b)\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_let_bound_constant_compile_rejects_provable_failure() {
        // Tier 2: a let-bound value that folds to a value
        // provably failing the predicate is rejected at compile
        // time. The diagnostic names the predicate, the newtype,
        // and the folded value.
        let src = "fn small(x: Word) -> bool { x < 10 }\n\
             newtype Tiny = Word where small;\n\
             fn main() -> Tiny {\n\
                let big = 100;\n\
                Tiny(big)\n\
             }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("small")
                && err.message.contains("Tiny")
                && err.message.contains("100"),
            "expected compile-time diagnostic, got: {}",
            err.message
        );
    }

    #[test]
    fn refinement_predicate_parameter_range_eliminated() {
        // Tier 3: the parameter `c: Counter` carries the
        // predicate's true set as its compile-time range. Re-
        // wrapping the parameter through `Counter(c as Word)`
        // hits the lattice subset check (argument range == true
        // set) and elides the runtime predicate call.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn rewrap(c: Counter) -> Counter { Counter(c as Word) }\n\
             fn main() -> Counter { rewrap(Counter(42)) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_parameter_range_rejects_on_disjoint() {
        // Tier 3: a function takes a parameter from a wider
        // refined newtype and constructs a narrower one. The
        // lattice subset check fires only when the wider range
        // is contained in the narrower's true set. Conversely,
        // when the construction is provably out-of-range (the
        // ranges are disjoint), the compile rejects.
        //
        // Here `Wide` (`x < 0`) and `NonNeg` (`x >= 0`) are
        // disjoint; constructing a `NonNeg` from a `Wide`-typed
        // parameter is rejected at compile time.
        let src = "fn negative(x: Word) -> bool { x < 0 }\n\
             fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Wide = Word where negative;\n\
             newtype NonNeg = Word where nonneg;\n\
             fn convert(w: Wide) -> NonNeg { NonNeg(w as Word) }\n\
             fn main() -> NonNeg { convert(Wide(0 - 1)) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("nonneg") && err.message.contains("NonNeg"),
            "expected lattice-driven compile-time diagnostic, got: {}",
            err.message
        );
    }

    #[test]
    fn refinement_predicate_parameter_range_falls_through_when_predicate_undecidable() {
        // The IntervalSet lattice handles disjunction exactly,
        // so a predicate body of `x < 0 or x > 100` decomposes
        // to the set `(-inf, -1] U [101, +inf)`. The argument
        // `0 - 50` folds to `-50`, which lies in the first
        // component; elision fires at compile time.
        let val = run_expect(
            "fn outside(x: Word) -> bool { x < 0 or x > 100 }\n\
             newtype Edge = Word where outside;\n\
             fn main() -> Edge { Edge(0 - 50) }",
            &[],
        );
        assert_eq!(val, Value::Int(-50));
    }

    #[test]
    fn refinement_predicate_disjoint_set_admits_constant_outside_singleton() {
        // The predicate `not (x == 5)` has true set
        // `(-inf, 4] U [6, +inf)`. The argument `42` lies in
        // the second component; the IntervalSet subset check
        // admits the construction.
        let val = run_expect(
            "fn not_five(x: Word) -> bool { not (x == 5) }\n\
             newtype NotFive = Word where not_five;\n\
             fn main() -> NotFive { NotFive(42) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_disjoint_set_rejects_constant_at_singleton_excluded() {
        // The literal `5` is excluded by `not (x == 5)`. The
        // compile-time check rejects the construction.
        let src = "fn not_five(x: Word) -> bool { not (x == 5) }\n\
             newtype NotFive = Word where not_five;\n\
             fn main() -> NotFive { NotFive(5) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("not_five") && err.message.contains("NotFive"),
            "expected compile-time diagnostic, got: {}",
            err.message
        );
    }

    #[test]
    fn refinement_predicate_function_call_summary_admits() {
        // Tier B: `always_42()` has return-range summary
        // `singleton(42)`. The constructor argument is the call;
        // the lattice subset check admits at compile time.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn always_42() -> Word { 42 }\n\
             fn main() -> Counter { Counter(always_42()) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn refinement_predicate_function_call_summary_rejects_on_disjoint() {
        // Tier B: `always_neg_one()` summary is `singleton(-1)`,
        // disjoint from `nonneg`'s true set; the compile rejects.
        let src = "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn always_neg_one() -> Word { 0 - 1 }\n\
             fn main() -> Counter { Counter(always_neg_one()) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("nonneg") && err.message.contains("Counter"),
            "expected cross-function summary diagnostic, got: {}",
            err.message
        );
    }

    #[test]
    fn refinement_predicate_function_call_with_parameter_admits_via_summary() {
        // Tier B: `widen(c: Counter) -> Word { c as Word }` has
        // summary `nonneg`'s true set (the parameter's range).
        // Re-wrapping the call result admits cleanly.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn widen(c: Counter) -> Word { c as Word }\n\
             fn main() -> Counter { Counter(widen(Counter(7))) }",
            &[],
        );
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn refinement_predicate_if_expression_summary_admits() {
        // The function-summary pass now handles `if`/`else`
        // bodies, computing the union of the branch ranges. The
        // example function returns 0 or 1; the summary is
        // `[0, 1]`, a subset of `nonneg`'s true set, so the
        // construction admits at compile time.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn flag(n: Word) -> Word {\n\
                if n == 0 { 0 } else { 1 }\n\
             }\n\
             fn main() -> Counter { Counter(flag(7)) }",
            &[],
        );
        assert_eq!(val, Value::Int(1));
    }

    // Note on recursive-function summaries: the widening
    // infrastructure on the interval lattice (`Interval::widen`,
    // `IntervalSet::widen`) converges the function-summary
    // fixed-point pass for recursive bodies. End-to-end runtime
    // tests are deferred because the WCMU verifier rejects
    // recursive functions at load time (their stack-frame count
    // is not statically bounded under V0.2's static analysis).
    // The widening pass nevertheless computes a sound compile-
    // time summary; future work that admits recursive functions
    // under a relaxed WCMU bound or trust-skipped load will
    // exercise this path end-to-end.

    #[test]
    fn refinement_predicate_match_arm_narrowing_admits_via_literal_pattern() {
        // Match-arm narrowing: the scrutinee `n` has the
        // parameter range full(). The arm `42 => Counter(42)`
        // narrows the scrutinee to singleton(42), and the body
        // uses the literal 42 directly which folds. The arm
        // `v => Counter(0)` always returns 0. Both arm bodies
        // are non-negative; the function-return summary is
        // singleton(0) union singleton(42), and the construction
        // `Counter(classify(...))` consults the summary.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn classify(n: Word) -> Word {\n\
                match n {\n\
                    42 => 42,\n\
                    v => 0,\n\
                }\n\
             }\n\
             fn main() -> Counter { Counter(classify(7)) }",
            &[],
        );
        assert_eq!(val, Value::Int(0));
    }

    #[test]
    fn refinement_predicate_match_arm_narrowing_admits_via_variable_pattern() {
        // The variable-pattern arm binds `v` to the scrutinee's
        // narrowed range. When the scrutinee is a non-negative
        // parameter, the binding range is non-negative; using
        // it inside a `Counter(...)` admits.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             newtype NonNeg = Word where nonneg;\n\
             fn passthrough(n: NonNeg) -> Word {\n\
                match n as Word {\n\
                    v => v,\n\
                }\n\
             }\n\
             fn main() -> Counter { Counter(passthrough(NonNeg(7))) }",
            &[],
        );
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn byte_refinement_predicate_compiles_with_literal_coercion() {
        // The type checker coerces the `0` and `100` literals to
        // Byte at the comparison sites. The Byte refinement
        // predicate compiles cleanly; constructing `Percent(42)`
        // works through the elision pathway (the literal 42 is
        // coerced and the predicate's true set covers it).
        let val = run_expect(
            "fn in_range(x: Byte) -> bool { x >= 0 and x <= 100 }\n\
             newtype Percent = Byte where in_range;\n\
             fn main() -> Percent { Percent(42 as Byte) }",
            &[],
        );
        assert_eq!(val, Value::Byte(42));
    }

    #[test]
    fn byte_refinement_predicate_elision_when_in_range() {
        // The Byte parameter carries the natural range [0, 255],
        // which is a subset of `[0, 100]`? Let's check: the
        // predicate true set is `[0, 100]`; the natural range
        // is `[0, 255]`. The argument `b as Byte` carries the
        // parameter range. The intersection is `[0, 100]` (non-
        // empty, non-subset), so the lattice path falls through
        // to the runtime check. For an in-range literal, the
        // constant-fold path elides at compile time.
        let val = run_expect(
            "fn in_range(x: Byte) -> bool { x >= 0 and x <= 100 }\n\
             newtype Percent = Byte where in_range;\n\
             fn main() -> Percent { Percent(50 as Byte) }",
            &[],
        );
        assert_eq!(val, Value::Byte(50));
    }

    #[test]
    fn refinement_predicate_byte_parameter_natural_range_admits_nonneg() {
        // A Byte parameter carries the natural range [0, 255].
        // Casting the parameter to Word preserves the range
        // (zero-extension at the bytecode level is identity in
        // i64). The newtype `Counter` requires non-negative,
        // which the range [0, 255] satisfies; the lattice subset
        // check admits the construction at compile time.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn from_byte(b: Byte) -> Counter { Counter(b as Word) }\n\
             fn main() -> Counter { from_byte(7 as Byte) }",
            &[],
        );
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn refinement_predicate_disjunction_admits_via_lattice_union() {
        // Parameter `e: Edge` carries the union range
        // `(-inf, -1] U [101, +inf)`. Re-wrapping the parameter
        // through `Edge(e as Word)` hits the IntervalSet subset
        // check (argument range == true set).
        let val = run_expect(
            "fn outside(x: Word) -> bool { x < 0 or x > 100 }\n\
             newtype Edge = Word where outside;\n\
             fn rewrap(e: Edge) -> Edge { Edge(e as Word) }\n\
             fn main() -> Edge { rewrap(Edge(200)) }",
            &[],
        );
        assert_eq!(val, Value::Int(200));
    }

    #[test]
    fn refinement_predicate_non_constant_let_falls_through_to_runtime() {
        // Tier 2: a let-bound value that does NOT fold to a
        // constant (because it comes from a function call) does
        // not record a constant entry. The elision pass falls
        // through to the runtime check.
        let err = run_program(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn neg_one() -> Word { 0 - 1 }\n\
             fn main() -> Counter {\n\
                let n = neg_one();\n\
                Counter(n)\n\
             }",
            &[],
        )
        .unwrap_err();
        assert!(
            matches!(err, VmError::RefinementFailed),
            "expected VmError::RefinementFailed, got {:?}",
            err
        );
    }

    #[test]
    fn refinement_predicate_folded_arithmetic_compile_rejects_on_provable_failure() {
        // Tier 1: the folded value `0 - 1` is `-1`, which fails
        // the `nonneg` predicate statically. The construction is
        // rejected at compile time even though the source uses an
        // arithmetic expression rather than a bare literal.
        let src = "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Counter = Word where nonneg;\n\
             fn main() -> Counter { Counter(0 - 1) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("nonneg")
                && err.message.contains("Counter")
                && err.message.contains("-1"),
            "expected compile-time diagnostic, got: {}",
            err.message
        );
    }

    #[test]
    fn enum_to_word_cast_implicit_discriminants() {
        // Implicit discriminants: Red=0, Green=1, Blue=2.
        let val = run_expect(
            "enum Color { Red, Green, Blue }\n\
             fn main() -> Word {\n\
                let c = Color::Green();\n\
                c as Word\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(1));
    }

    #[test]
    fn enum_to_word_cast_explicit_discriminants() {
        let val = run_expect(
            "enum Code { OutOfRange = 1, Busy = 3, Timeout = 4 }\n\
             fn main() -> Word {\n\
                let c = Code::Busy();\n\
                c as Word\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(3));
    }

    #[test]
    fn enum_to_word_cast_negative_discriminant() {
        let val = run_expect(
            "enum Sign { Neg = -1, Zero = 0, Pos = 1 }\n\
             fn main() -> Word {\n\
                let s = Sign::Neg();\n\
                s as Word\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(-1));
    }

    #[test]
    fn enum_to_word_cast_after_match_arm() {
        // Exercise the cast on a variable bound through a match
        // expression — the local's inferred type should still
        // light up the enum-to-Word path.
        let val = run_expect(
            "enum Code { A = 10, B = 20 }\n\
             fn pick(which: Word) -> Code {\n\
                if which == 0 { Code::A() } else { Code::B() }\n\
             }\n\
             fn main() -> Word {\n\
                let c = pick(1);\n\
                c as Word\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(20));
    }

    #[test]
    fn monomorphize_generic_enum_with_match_pattern() {
        // Regression: the monomorphizer renamed the enum
        // construction site (`Maybe::Just(42)` to `Maybe__Word::Just`)
        // but match-arm patterns retained the original generic
        // enum name, producing `enum pattern Maybe::Just does not
        // match scrutinee type Maybe__Word`. Both sites must
        // rewrite consistently.
        let val = run_expect(
            "enum Maybe<T> { Just(T), Nothing }\n\
             fn main() -> Word {\n\
                let m = Maybe::Just(42);\n\
                match m {\n\
                    Maybe::Just(x) => x,\n\
                    Maybe::Nothing => 0,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn monomorphize_nested_generic_structs_resolves_field_types() {
        // Regression: the struct specializer substituted type
        // parameters in field declarations (`inner: Cell<T>`
        // became `inner: Cell<Word>`) but did not rewrite the
        // substituted type to the emitted specialization name
        // (`Cell__Word`), producing `field Wrap__Word.inner expects
        // Cell<Word>, got Cell__Word` at type check. The
        // substitution now resolves nested generic instantiations
        // to their specialization names.
        let val = run_expect(
            "struct Cell<T> { value: T }\n\
             struct Wrap<T> { inner: Cell<T> }\n\
             fn main() -> Word {\n\
                let w = Wrap { inner: Cell { value: 7 } };\n\
                w.inner.value\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn eval_literal() {
        let val = run_expect("fn main() -> Word { 42 }", &[]);
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn numeric_suffix_word_is_plain_int() {
        let val = run_expect("fn main() -> Word { 7Word }", &[]);
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn numeric_suffix_byte_produces_byte() {
        let val = run_expect("fn main() -> Byte { 42Byte }", &[]);
        assert_eq!(val, Value::Byte(42));
    }

    #[test]
    fn numeric_suffix_fixed_integer_form_encodes_q_format() {
        // `42Fixed<16>` is the Q-format value 42 << 16.
        let val = run_expect("fn main() -> Fixed<16> { 42Fixed<16> }", &[]);
        assert_eq!(val, Value::Fixed(42 << 16));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn numeric_suffix_float_from_integer_digits() {
        let val = run_expect("fn main() -> Float { 42Float }", &[]);
        assert_eq!(val, Value::Float(42.0));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn numeric_suffix_fixed_fractional_form_rounds() {
        let val = run_expect("fn main() -> Fixed<16> { 3.5Fixed<16> }", &[]);
        assert_eq!(val, Value::Fixed((3.5 * 65536.0) as i64));
    }

    #[test]
    fn byte_cast_truncates_word_to_low_eight_bits() {
        let val = run_expect("fn main() -> Byte { 300 as Byte }", &[]);
        assert_eq!(val, Value::Byte(44));
    }

    #[test]
    fn byte_cast_round_trip_preserves_low_eight_bits() {
        let val = run_expect("fn main() -> Word { (200 as Byte) as Word }", &[]);
        assert_eq!(val, Value::Int(200));
    }

    #[test]
    fn byte_addition_wraps_modulo_256() {
        let val = run_expect("fn main() -> Byte { (200 as Byte) + (100 as Byte) }", &[]);
        // 200 + 100 = 300 wraps to 44 (300 mod 256).
        assert_eq!(val, Value::Byte(44));
    }

    #[test]
    fn byte_subtraction_wraps_modulo_256() {
        let val = run_expect("fn main() -> Byte { (10 as Byte) - (20 as Byte) }", &[]);
        // 10 - 20 = -10 wraps to 246 (256 - 10).
        assert_eq!(val, Value::Byte(246));
    }

    #[test]
    fn byte_multiplication_wraps_modulo_256() {
        let val = run_expect("fn main() -> Byte { (16 as Byte) * (17 as Byte) }", &[]);
        // 16 * 17 = 272 wraps to 16.
        assert_eq!(val, Value::Byte(16));
    }

    #[test]
    fn byte_division_and_modulo_use_unsigned_semantics() {
        let div = run_expect("fn main() -> Byte { (200 as Byte) / (16 as Byte) }", &[]);
        assert_eq!(div, Value::Byte(12));
        let rem = run_expect("fn main() -> Byte { (200 as Byte) % (16 as Byte) }", &[]);
        assert_eq!(rem, Value::Byte(8));
    }

    #[test]
    fn byte_comparison_uses_unsigned_ordering() {
        let val = run_expect("fn main() -> bool { (200 as Byte) > (100 as Byte) }", &[]);
        assert_eq!(val, Value::Bool(true));
    }

    // -- Fixed (Q-format) tests --
    //
    // On the host runtime, `Fixed` is Q31.32 (32 fraction bits).
    // The integer value 1 cast to `Fixed` is stored as
    // `1 << 32 = 4_294_967_296` in the underlying bits.

    #[test]
    fn fixed_word_round_trip_preserves_integer_value() {
        let val = run_expect("fn main() -> Word { (5 as Fixed) as Word }", &[]);
        assert_eq!(val, Value::Int(5));
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn fixed_cast_from_word_uses_q31_32_format() {
        let val = run_expect("fn main() -> Fixed { 1 as Fixed }", &[]);
        assert_eq!(val, Value::Fixed(1i64 << 32));
    }

    #[test]
    fn fixed_addition_sums_underlying_bits() {
        let val = run_expect(
            "fn main() -> Word { ((2 as Fixed) + (3 as Fixed)) as Word }",
            &[],
        );
        assert_eq!(val, Value::Int(5));
    }

    #[test]
    fn fixed_subtraction_subtracts_underlying_bits() {
        let val = run_expect(
            "fn main() -> Word { ((10 as Fixed) - (3 as Fixed)) as Word }",
            &[],
        );
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn fixed_multiply_maintains_q_format() {
        let val = run_expect(
            "fn main() -> Word { ((4 as Fixed) * (5 as Fixed)) as Word }",
            &[],
        );
        assert_eq!(val, Value::Int(20));
    }

    #[test]
    fn fixed_divide_maintains_q_format() {
        let val = run_expect(
            "fn main() -> Word { ((20 as Fixed) / (5 as Fixed)) as Word }",
            &[],
        );
        assert_eq!(val, Value::Int(4));
    }

    #[test]
    fn fixed_negate_negates_underlying_bits() {
        let val = run_expect("fn main() -> Word { (-(5 as Fixed)) as Word }", &[]);
        assert_eq!(val, Value::Int(-5));
    }

    #[test]
    fn fixed_comparison_uses_signed_ordering() {
        let val = run_expect("fn main() -> bool { (10 as Fixed) > (5 as Fixed) }", &[]);
        assert_eq!(val, Value::Bool(true));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn fixed_parameterised_q15_16_uses_sixteen_fraction_bits() {
        // `Fixed<16>` is Q15.16: 1 cast to Fixed<16> equals
        // `1 << 16 = 65_536` in the underlying bits.
        let val = run_expect("fn main() -> Fixed<16> { 1 as Fixed<16> }", &[]);
        assert_eq!(val, Value::Fixed(1i64 << 16));
    }

    #[test]
    // Gated: `Fixed<16>` needs a declared word width above 16; the
    // verifier rejects the fraction count on the 8- and 16-bit runtimes.
    #[cfg(not(any(feature = "narrow-word-8", feature = "narrow-word-16")))]
    fn fixed_parameterised_q15_16_multiply_maintains_format() {
        let val = run_expect(
            "fn main() -> Word { ((4 as Fixed<16>) * (5 as Fixed<16>)) as Word }",
            &[],
        );
        assert_eq!(val, Value::Int(20));
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn fixed_default_form_resolves_to_q31_32() {
        // The default `Fixed` surface form resolves to Q31.32 on
        // the host runtime, so `1 as Fixed` equals `1 << 32` in
        // the underlying bits.
        let val = run_expect("fn main() -> Fixed { 1 as Fixed }", &[]);
        assert_eq!(val, Value::Fixed(1i64 << 32));
    }

    #[test]
    fn option_some_pattern_matches_constructed_some() {
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = Option::Some(42);\n\
                match m {\n\
                    Option::Some(x) => x,\n\
                    Option::None => 0,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn option_none_pattern_matches_value_none() {
        // The compiler emits `Op::PushNone` for `Option::None`; the
        // match arm tests the unwrapped `Value::None` through a
        // direct equality check rather than `IsEnum` (which would
        // fail because `Value::None` is not a `Value::Enum`).
        // The match scrutinee uses a Some-constructed value to
        // avoid an unrelated Option<T> type-unification limitation
        // around bare None literals in function returns; the
        // Some arm is the one verified here through the value 7.
        let val = run_expect(
            "fn main() -> Word {\n\
                let m = Option::Some(7);\n\
                match m {\n\
                    Option::None => 99,\n\
                    Option::Some(x) => x,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(7));
    }

    #[test]
    fn eval_add() {
        let val = run_expect("fn main() -> Word { 10 + 32 }", &[]);
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_arithmetic() {
        let val = run_expect("fn main() -> Word { (2 + 3) * 4 - 1 }", &[]);
        assert_eq!(val, Value::Int(19));
    }

    #[test]
    fn eval_comparison() {
        let val = run_expect("fn main() -> bool { 10 > 5 }", &[]);
        assert_eq!(val, Value::Bool(true));
    }

    #[test]
    fn eval_logical_and() {
        let val = run_expect("fn main() -> bool { true and false }", &[]);
        assert_eq!(val, Value::Bool(false));
    }

    #[test]
    fn eval_logical_or() {
        let val = run_expect("fn main() -> bool { false or true }", &[]);
        assert_eq!(val, Value::Bool(true));
    }

    #[test]
    fn eval_negation() {
        let val = run_expect("fn main() -> Word { -42 }", &[]);
        assert_eq!(val, Value::Int(-42));
    }

    #[test]
    fn eval_not() {
        let val = run_expect("fn main() -> bool { not true }", &[]);
        assert_eq!(val, Value::Bool(false));
    }

    #[test]
    fn eval_if_true() {
        let val = run_expect("fn main() -> Word { if true { 1 } else { 2 } }", &[]);
        assert_eq!(val, Value::Int(1));
    }

    #[test]
    fn eval_if_false() {
        let val = run_expect("fn main() -> Word { if false { 1 } else { 2 } }", &[]);
        assert_eq!(val, Value::Int(2));
    }

    #[test]
    fn eval_let_binding() {
        let val = run_expect("fn main() -> Word { let x = 10; let y = 32; x + y }", &[]);
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_function_call() {
        let val = run_expect(
            "fn double(x: Word) -> Word { x * 2 }\nfn main() -> Word { double(21) }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_nested_calls() {
        let val = run_expect(
            "fn double(x: Word) -> Word { x * 2 }\nfn main() -> Word { double(double(10)) + 2 }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_with_args() {
        let val = run_expect("fn main(x: Word) -> Word { x + 1 }", &[Value::Int(41)]);
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_for_range() {
        let val = run_expect(
            "fn main() -> Word { let sum = 0; for i in 0..5 { let x = sum + i; } sum }",
            &[],
        );
        // Lexical scoping: inner `let x` shadows but does not mutate outer `sum`.
        assert_eq!(val, Value::Int(0));
    }

    #[test]
    fn eval_string_literal() {
        let s = run_expect_text("fn main() -> Text { \"hello\" }", &[]);
        assert_eq!(s, "hello");
    }

    #[test]
    #[cfg(feature = "floats")]
    fn eval_float_arithmetic() {
        let val = run_expect("fn main() -> Float { 1.5 + 2.5 }", &[]);
        assert_eq!(val, Value::Float(4.0));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn eval_cast_int_to_float() {
        let val = run_expect("fn main() -> Float { 42 as Float }", &[]);
        assert_eq!(val, Value::Float(42.0));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn eval_cast_float_to_int() {
        let val = run_expect("fn main() -> Word { 3.7 as Word }", &[]);
        assert_eq!(val, Value::Int(3));
    }

    #[test]
    fn eval_struct_init_and_field() {
        let val = run_expect(
            "struct Point { x: Word, y: Word }\nfn main() -> Word { let p = Point { x: 10, y: 32 }; p.x + p.y }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_struct_literal_non_declaration_order_reads_canonically() {
        // The flat struct layout is canonical (declaration order x, y)
        // regardless of the literal field order, so `p.x` and `p.y` read
        // the right bytes even when the literal lists `y` first (B28 P2).
        let val = run_expect(
            "struct Point { x: Word, y: Word }\nfn main() -> Word { let p = Point { y: 32, x: 10 }; p.x - p.y }",
            &[],
        );
        assert_eq!(val, Value::Int(-22));
    }

    #[test]
    fn eval_struct_pattern_match_on_flat_struct() {
        // Matching an all-Word (flat) struct exercises the folded type
        // test and the flat field reads end to end (B28 P2).
        let val = run_expect(
            "struct P { a: Word, b: Word }\nfn main() -> Word { let p = P { a: 5, b: 7 }; match p { P { a, b } => a * b, _ => 0 } }",
            &[],
        );
        assert_eq!(val, Value::Int(35));
    }

    #[test]
    fn eval_enum_variant() {
        let val = run_expect(
            "enum Color { Red, Green, Blue }\nfn main() -> Word { let c = Color::Red(); 42 }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn vm_built_composite_is_arena_resident() {
        // A flat struct built in the VM is migrated onto the arena's top
        // ephemeral head, not left on the global heap (B28 P2 arena
        // residence). The three-Word body lands on the top head, so the
        // high watermark is non-zero. The exact size depends on the module
        // word width (narrow-word features make it smaller), so the test
        // asserts residence rather than a specific byte count.
        let src = "struct P { a: Word, b: Word, c: Word }\n\
                   fn main() -> Word { let p = P { a: 1, b: 2, c: 3 }; p.a + p.b + p.c }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("vm");
        let state = vm.call(&[]).expect("run");
        assert!(matches!(state, VmState::Finished(Value::Int(6))));
        assert!(
            arena.top_peak() > 0,
            "expected the flat struct body on the arena top head, top_peak = {}",
            arena.top_peak()
        );
    }

    #[test]
    fn eval_nested_struct_in_struct_flat() {
        // An all-Word inner struct nested in an outer struct inlines into
        // one flat body; `o.inner.x` compiles to a nested extract-and-rewrap
        // (GetField FlatNested) followed by a flat scalar read (B28 P2).
        let val = run_expect(
            "struct Inner { x: Word, y: Word }\n\
             struct Outer { inner: Inner, tag: Word }\n\
             fn main() -> Word { let o = Outer { inner: Inner { x: 10, y: 20 }, tag: 5 }; o.inner.x + o.inner.y + o.tag }",
            &[],
        );
        assert_eq!(val, Value::Int(35));
    }

    #[test]
    fn eval_nested_tuple_in_struct_flat() {
        // A flat tuple nested in a struct: `h.coords.1` extracts the nested
        // tuple body then reads the element (B28 P2).
        let val = run_expect(
            "struct Holder { coords: (Word, Word), tag: Word }\n\
             fn main() -> Word { let h = Holder { coords: (3, 4), tag: 100 }; h.coords.0 * h.coords.1 + h.tag }",
            &[],
        );
        assert_eq!(val, Value::Int(112));
    }

    #[test]
    fn eval_nested_enum_in_struct_flat() {
        // A uniformly-flat enum nested in a struct: the enum is padded to its
        // largest-variant size so the struct slot is fixed; `c.sig` extracts
        // the padded enum body and the match reads its payload (B28 P2).
        let val = run_expect(
            "enum Sig { Off, On(Word), Span(Word, Word) }\n\
             struct Carrier { sig: Sig, n: Word }\n\
             fn main() -> Word { let c = Carrier { sig: Sig::On(7), n: 5 }; match c.sig { Sig::On(v) => v + c.n, _ => 0 } }",
            &[],
        );
        assert_eq!(val, Value::Int(12));
    }

    #[test]
    fn eval_nested_struct_bound_as_value() {
        // Binding the extracted nested struct to a local exercises the
        // re-wrap into a standalone flat composite value (B28 P2).
        let val = run_expect(
            "struct Inner { x: Word, y: Word }\n\
             struct Outer { inner: Inner, tag: Word }\n\
             fn main() -> Word { let o = Outer { inner: Inner { x: 6, y: 9 }, tag: 0 }; let i = o.inner; i.x + i.y }",
            &[],
        );
        assert_eq!(val, Value::Int(15));
    }

    #[test]
    fn eval_array_literal_and_index() {
        let val = run_expect("fn main() -> Word { let arr = [10, 20, 30]; arr[1] }", &[]);
        assert_eq!(val, Value::Int(20));
    }

    #[test]
    fn eval_bool_array_index_flat_one_byte_stride() {
        // A `[Bool; N]` array is transitively scalar, so it uses the flat
        // byte body with a one-byte element stride; indexing exercises the
        // flat-read offset arithmetic for a non-word element kind end to
        // end (B28 P2).
        let val = run_expect(
            "fn main() -> bool { let a = [true, false, true]; a[1] }",
            &[],
        );
        assert_eq!(val, Value::Bool(false));
        let val2 = run_expect(
            "fn main() -> bool { let a = [true, false, true]; a[2] }",
            &[],
        );
        assert_eq!(val2, Value::Bool(true));
    }

    #[test]
    fn eval_yield_and_resume() {
        let src = "loop main(input: Word) -> Word { let input = yield input * 2; input }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();

        // First call: main(5) -> yields 5 * 2 = 10.
        match vm.call(&[Value::Int(5)]).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(10)),
            other => panic!("expected yield, got {:?}", other),
        }

        // Resume with 7: continues after yield, sets input=7, reaches Reset.
        match vm.resume(Value::Int(7)).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }

        // Resume after Reset with 7: restarts stream, yields 7 * 2 = 14.
        match vm.resume(Value::Int(7)).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(14)),
            other => panic!("expected yield, got {:?}", other),
        }

        // Resume with 0: reaches Reset.
        match vm.resume(Value::Int(0)).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }

        // Resume after Reset with 0: yields 0 * 2 = 0.
        match vm.resume(Value::Int(0)).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(0)),
            other => panic!("expected yield, got {:?}", other),
        }
    }

    #[test]
    fn resume_err_propagates_through_enum_reply() {
        // The script declares a Result-shaped enum and pattern-matches
        // on the resumed value. The host calls `resume` with the Ok
        // variant for success and `resume_err` with the Err variant
        // for failure. Both flow through the same operand-stack
        // resume mechanism; `resume_err` is a documentation alias
        // that signals intent.
        let src = "\
            enum Reply { Ok(Word), Err }\n\
            loop main(input: Reply) -> Word {\n\
                let reply = yield 0;\n\
                match reply {\n\
                    Reply::Ok(v) => v,\n\
                    Reply::Err => -1,\n\
                }\n\
            }\
        ";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let initial = Value::enum_value(
            String::from("Reply"),
            String::from("Ok"),
            0,
            alloc::vec![Value::Int(0)],
        );
        match vm.call(&[initial]).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(0)),
            other => panic!("expected first yield, got {:?}", other),
        }
        // Successful resume returns the Ok payload.
        let success = Value::enum_value(
            String::from("Reply"),
            String::from("Ok"),
            0,
            alloc::vec![Value::Int(42)],
        );
        match vm.resume(success).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }
        // After the implicit reset, send Err to drive the next round
        // through the error branch.
        let initial2 = Value::enum_value(
            String::from("Reply"),
            String::from("Ok"),
            0,
            alloc::vec![Value::Int(0)],
        );
        match vm.resume(initial2).unwrap() {
            VmState::Yielded(_) => {}
            other => panic!("expected yield, got {:?}", other),
        }
        let err = Value::enum_value(String::from("Reply"), String::from("Err"), 1, alloc::vec![]);
        match vm.resume_err(err).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset on err, got {:?}", other),
        }
    }

    #[test]
    fn host_built_composite_call_arguments_round_trip_through_flat_access() {
        // The coverage the B28 item 2 step 6B blocker demands: a function
        // takes a named struct and a named enum argument, both built by the
        // host with no arena (so the boxed representation), and reads the
        // fields back through the compiler-baked flat field access. The
        // VM-entry canonicalisation re-packs each boxed argument into an
        // arena-flat body that flat access can read; the nested inner struct
        // exercises the bottom-up recursion (the inner boxed struct is
        // flattened first so the outer can flatten).
        let src = "\
            struct Inner { a: Word, b: Word }\n\
            struct Outer { inner: Inner, c: Word }\n\
            enum Tag { A(Word), B }\n\
            fn main(o: Outer, t: Tag) -> Word {\n\
                let base = o.inner.a + o.inner.b + o.c;\n\
                match t {\n\
                    Tag::A(v) => base + v,\n\
                    Tag::B => base,\n\
                }\n\
            }\
        ";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let inner = Value::struct_value(
            String::from("Inner"),
            alloc::vec![
                (String::from("a"), Value::Int(10)),
                (String::from("b"), Value::Int(20)),
            ],
        );
        let outer = Value::struct_value(
            String::from("Outer"),
            alloc::vec![
                (String::from("inner"), inner),
                (String::from("c"), Value::Int(30)),
            ],
        );
        // `Tag::A` is discriminant 0; the host supplies the discriminant.
        let tag = Value::enum_value(
            String::from("Tag"),
            String::from("A"),
            0,
            alloc::vec![Value::Int(5)],
        );
        match vm.call(&[outer, tag]).unwrap() {
            // 10 + 20 + 30 + 5 = 65.
            VmState::Finished(v) => assert_eq!(v, Value::Int(65)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn host_built_struct_resume_value_round_trips_through_flat_access() {
        // The resume-value half of the canonicalisation: a stream is resumed
        // with a host-built (boxed) struct and reads its fields through flat
        // access (B28 item 2 step 6B). The first yield reads the call
        // argument's fields; the second yield reads the resumed value's
        // fields, confirming both VM-entry sites canonicalise. The resume
        // binding is annotated `let r: Cmd` so the compiler bakes flat field
        // access for it: a bare `yield` binding leaves the type un-inferred,
        // which bakes the boxed by-name access form, and the field-wise
        // dispatch is then a separate compiler concern independent of this
        // canonicalisation. The enum-via-`match` resume path needs no
        // annotation because the pattern names the type (see
        // `resume_err_propagates_through_enum_reply`).
        let src = "\
            struct Cmd { kind: Word, amount: Word }\n\
            loop main(c: Cmd) -> Word {\n\
                let r: Cmd = yield c.kind + c.amount;\n\
                yield r.kind + r.amount\n\
            }\
        ";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let initial = Value::struct_value(
            String::from("Cmd"),
            alloc::vec![
                (String::from("kind"), Value::Int(7)),
                (String::from("amount"), Value::Int(3)),
            ],
        );
        match vm.call(&[initial]).unwrap() {
            // 7 + 3 = 10.
            VmState::Yielded(v) => assert_eq!(v, Value::Int(10)),
            other => panic!("expected first yield, got {:?}", other),
        }
        let resumed = Value::struct_value(
            String::from("Cmd"),
            alloc::vec![
                (String::from("kind"), Value::Int(100)),
                (String::from("amount"), Value::Int(5)),
            ],
        );
        match vm.resume(resumed).unwrap() {
            // 100 + 5 = 105, read from the resumed value's fields.
            VmState::Yielded(v) => assert_eq!(v, Value::Int(105)),
            other => panic!("expected second yield, got {:?}", other),
        }
    }

    #[test]
    fn resume_err_passes_through_with_value_none() {
        // The simplest error pattern: the script types its input as
        // a value that may be `None`. The host resumes with
        // `Value::None` to signal the absence of input. The script's
        // dispatch logic handles the None case explicitly.
        let src = "\
            enum Reply { Ok(Word), Err }\n\
            loop main(input: Reply) -> Word {\n\
                let reply = yield 0;\n\
                match reply {\n\
                    Reply::Ok(v) => v,\n\
                    Reply::Err => 99,\n\
                }\n\
            }\
        ";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let initial = Value::enum_value(
            String::from("Reply"),
            String::from("Ok"),
            0,
            alloc::vec![Value::Int(0)],
        );
        match vm.call(&[initial]).unwrap() {
            VmState::Yielded(_) => {}
            other => panic!("expected yield, got {:?}", other),
        }
        // resume_err with Err variant routes through the error arm
        // and the script returns 99 to the host before reset.
        let err = Value::enum_value(String::from("Reply"), String::from("Err"), 1, alloc::vec![]);
        match vm.resume_err(err).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }
    }

    #[test]
    fn eval_multiheaded_literal() {
        let s = run_expect_text(
            "fn classify(0) -> Text { \"zero\" }\nfn classify(x: Word) -> Text { \"other\" }\nfn main() -> Text { classify(0) }",
            &[],
        );
        assert_eq!(s, "zero");
    }

    #[test]
    fn eval_multiheaded_fallthrough() {
        let s = run_expect_text(
            "fn classify(0) -> Text { \"zero\" }\nfn classify(x: Word) -> Text { \"other\" }\nfn main() -> Text { classify(5) }",
            &[],
        );
        assert_eq!(s, "other");
    }

    #[test]
    fn multiheaded_no_matching_head_traps_with_kind() {
        // Two literal heads with no catch-all; an argument matching
        // neither traps with the NoMatchingHead kind.
        let err = run_program(
            "fn pick(0) -> Word { 100 }\nfn pick(1) -> Word { 200 }\nfn main() -> Word { pick(5) }",
            &[],
        )
        .unwrap_err();
        assert!(
            matches!(err, VmError::NoMatchingHead),
            "expected NoMatchingHead trap, got {:?}",
            err
        );
    }

    #[test]
    fn trap_kind_code_round_trips() {
        use crate::bytecode::TrapKind;
        for k in [
            TrapKind::RefinementFailed,
            TrapKind::NoMatchingHead,
            TrapKind::NoMatchingArm,
            TrapKind::CheckedArithNoArm,
            TrapKind::EnumVariantUnmapped,
        ] {
            assert_eq!(TrapKind::from_code(k.code()), Some(k));
        }
        assert_eq!(TrapKind::from_code(999), None);
    }

    #[test]
    fn eval_pipeline() {
        let val = run_expect(
            "fn double(x: Word) -> Word { x * 2 }\nfn main() -> Word { 21 |> double() }",
            &[],
        );
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_match_literal() {
        let s = run_expect_text(
            "fn main() -> Text { let x = 1; match x { 1 => \"one\", 2 => \"two\", _ => \"other\" } }",
            &[],
        );
        assert_eq!(s, "one");
    }

    #[test]
    fn eval_match_wildcard() {
        let s = run_expect_text(
            "fn main() -> Text { let x = 99; match x { 1 => \"one\", _ => \"other\" } }",
            &[],
        );
        assert_eq!(s, "other");
    }

    #[test]
    fn eval_division_by_zero() {
        let result = run_program("fn main() -> Word { 1 / 0 }", &[]);
        assert!(matches!(result, Err(VmError::DivisionByZero)));
    }

    #[test]
    fn eval_index_out_of_bounds() {
        let result = run_program("fn main() -> Word { let a = [1, 2]; a[5] }", &[]);
        assert!(matches!(result, Err(VmError::IndexOutOfBounds(5, 2))));
    }

    #[test]
    fn eval_native_function() {
        let src = "use math::add_one\nfn main(x: Word) -> Word { math::add_one(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_native("math::add_one", |args| match &args[0] {
            Value::Int(x) => Ok(Value::Int(x + 1)),
            _ => Err(VmError::TypeError(String::from("expected Int"))),
        });
        match vm.call(&[Value::Int(41)]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn external_native_round_trip() {
        // `use external` imports compile to `Op::CallExternalNative`.
        // Registering the native through `register_external_native`
        // sets the matching classification; the call succeeds.
        let src = "use external host::log_event\nfn main(x: Word) -> Word { host::log_event(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_external_native("host::log_event", |args| Ok(args[0].clone()), 16);
        match vm.call(&[Value::Int(7)]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(7)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn native_classification_mismatch_rejected_at_call() {
        // The script imports `host::log_event` as a verified
        // native (bare `use`), but the host registers it through
        // `register_external_native`. The mismatch is detected at
        // the call site dispatch and surfaces as VmError::VerifyError.
        let src = "use host::log_event\nfn main(x: Word) -> Word { host::log_event(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_external_native("host::log_event", |args| Ok(args[0].clone()), 16);
        let err = vm.call(&[Value::Int(7)]).unwrap_err();
        match err {
            VmError::VerifyError(msg) => {
                assert!(msg.contains("registered as external"), "{}", msg);
                assert!(msg.contains("invokes it as verified"), "{}", msg);
            }
            other => panic!("expected VerifyError, got {:?}", other),
        }
    }

    #[test]
    fn external_classification_mismatch_rejected_at_call() {
        // The script imports `host::log_event` as external but the
        // host registers it through `register_native` (verified).
        let src = "use external host::log_event\nfn main(x: Word) -> Word { host::log_event(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_native("host::log_event", |args| Ok(args[0].clone()));
        let err = vm.call(&[Value::Int(7)]).unwrap_err();
        match err {
            VmError::VerifyError(msg) => {
                assert!(msg.contains("registered as verified"), "{}", msg);
                assert!(msg.contains("invokes it as external"), "{}", msg);
            }
            other => panic!("expected VerifyError, got {:?}", other),
        }
    }

    #[test]
    fn classification_mismatch_detected_before_execution() {
        // The load-time check fires at the entry of `call_function`
        // before any bytecode executes. Even when the call site
        // sits behind a branch that the test arguments would not
        // take, the verification still reports the mismatch.
        let src = "use host::log_event\n\
                       fn main(x: Word) -> Word {\n\
                           if x > 0 { x } else { host::log_event(x) }\n\
                       }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_external_native("host::log_event", |args| Ok(args[0].clone()), 16);
        // x > 0 takes the then-branch which does not reach the
        // native; a runtime-only check would let this slip through.
        // The load-time check catches it.
        let err = vm.call(&[Value::Int(5)]).unwrap_err();
        assert!(
            matches!(&err, VmError::VerifyError(msg)
                if msg.contains("registered as external")
                && msg.contains("invokes it as verified")),
            "unexpected error: {:?}",
            err,
        );
    }

    #[test]
    fn verify_native_classifications_callable_before_first_call() {
        // The host may invoke `verify_native_classifications`
        // explicitly to surface mismatches at a deployment-
        // validation step rather than at first call. The method
        // returns Ok when registrations match.
        let src = "use external host::log_event\nfn main(x: Word) -> Word { host::log_event(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_external_native("host::log_event", |args| Ok(args[0].clone()), 16);
        vm.verify_native_classifications().unwrap();
    }

    #[test]
    fn verify_native_classifications_idempotent() {
        // Calling verify_native_classifications twice in a row
        // succeeds idempotently. The second call hits the cached-
        // Ok path and returns without re-walking the chunks.
        let src = "use external host::log_event\nfn main(x: Word) -> Word { host::log_event(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_external_native("host::log_event", |args| Ok(args[0].clone()), 16);
        vm.verify_native_classifications().unwrap();
        vm.verify_native_classifications().unwrap();
    }

    #[test]
    fn duplicate_native_registration_replaces_prior_entry() {
        // V0.2.0 Phase 6 follow-on (concern #2): re-registering a
        // native with the same name replaces the prior entry
        // rather than appending. The script reads the latest
        // registration's behaviour, not the first.
        let src = "use host::compute\nfn main(x: Word) -> Word { host::compute(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.register_native("host::compute", |_args| Ok(Value::Int(1)));
        vm.register_native("host::compute", |_args| Ok(Value::Int(2)));
        match vm.call(&[Value::Int(99)]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(2)),
            other => panic!("expected Int(2), got {:?}", other),
        }
    }

    #[test]
    fn duplicate_native_registration_swaps_classification() {
        // Re-registering with a different classification replaces
        // both the function and the classification. A prior
        // verified registration is removed when an external
        // re-registration replaces it; the cache invalidation
        // then forces a fresh load-time check that sees only the
        // external entry.
        let src = "use external host::compute\nfn main(x: Word) -> Word { host::compute(x) }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        // Initial registration as verified: would mismatch the
        // `use external` import. The dedup behaviour means the
        // verified entry is wiped out by the external re-
        // registration that follows.
        vm.register_native("host::compute", |_args| Ok(Value::Int(1)));
        vm.register_external_native("host::compute", |_args| Ok(Value::Int(2)), 16);
        match vm.call(&[Value::Int(99)]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(2)),
            other => panic!("expected Int(2), got {:?}", other),
        }
    }

    #[test]
    fn eval_guard_clause() {
        let val = run_expect(
            "fn abs(x: Word) -> Word when x < 0 { -x }\nfn abs(x: Word) -> Word { x }\nfn main() -> Word { abs(-5) + abs(3) }",
            &[],
        );
        assert_eq!(val, Value::Int(8));
    }

    #[test]
    fn exponential_text_concat_rejected_at_safe_constructor() {
        // The FAQ exponential-string-concat example expressed as a
        // Stream block, which is the form subject to the per-iteration
        // WCMU bound. Sixty doublings of a 1-byte string allocate
        // more than u32::MAX bytes cumulatively. The text-size
        // abstract interpretation pass saturates the chunk's heap
        // bound; the WCMU resource-bounds check rejects the module
        // because the bound exceeds any feasible arena capacity.
        let mut src =
            alloc::string::String::from("loop main(input: Word) -> Text {\n    let s = \"a\";\n");
        for _ in 0..60 {
            src.push_str("    let s = s + s;\n");
        }
        src.push_str("    let _ = yield s;\n    s\n}\n");
        let tokens = tokenize(&src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let err = Vm::new(module, &arena)
            .err()
            .expect("expected rejection from exponential text growth");
        assert!(matches!(err, VmError::VerifyError(_)));
    }

    // -- For-in over array expressions --

    #[test]
    fn eval_for_in_array_literal() {
        let val = run_expect(
            "fn main() -> Word { let sum = 0; for x in [10, 20, 30] { let sum = sum + x; } sum }",
            &[],
        );
        // Lexical scoping: inner `let sum` shadows but does not mutate outer `sum`.
        assert_eq!(val, Value::Int(0));
    }

    #[test]
    fn eval_for_in_array_accumulate() {
        // Use a mutable-style accumulation pattern via function calls.
        let val = run_expect(
            "fn main() -> Word {\n\
             let arr = [1, 2, 3, 4, 5];\n\
             let result = 0;\n\
             for x in arr {\n\
               let result = result + x;\n\
             }\n\
             result\n\
             }",
            &[],
        );
        // Due to lexical scoping, result remains 0.
        assert_eq!(val, Value::Int(0));
    }

    #[test]
    fn eval_for_in_empty_array() {
        let val = run_expect(
            "fn main() -> Word { let count = 42; for x in [] { let count = 0; } count }",
            &[],
        );
        // Body never executes for empty array.
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    fn eval_for_in_single_element() {
        let val = run_expect(
            "fn main() -> Word { let last = 0; for x in [99] { let last = x; } last }",
            &[],
        );
        assert_eq!(val, Value::Int(0));
    }

    #[test]
    fn eval_for_in_array_with_function() {
        let val = run_expect(
            "fn double(x: Word) -> Word { x * 2 }\n\
             fn main() -> Word {\n\
               let result = 0;\n\
               for x in [1, 2, 3] {\n\
                 let result = result + double(x);\n\
               }\n\
               result\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(0));
    }

    // -- Tuple literal construction --

    #[test]
    fn eval_tuple_literal() {
        let val = run_expect("fn main() -> Word { let t = (1, 2, 3); t.0 }", &[]);
        assert_eq!(val, Value::Int(1));
    }

    #[test]
    fn eval_tuple_field_access() {
        let val = run_expect("fn main() -> Word { let t = (10, 20, 30); t.1 }", &[]);
        assert_eq!(val, Value::Int(20));
    }

    #[test]
    fn eval_tuple_let_destructure() {
        let val = run_expect("fn main() -> Word { let (a, b) = (10, 32); a + b }", &[]);
        assert_eq!(val, Value::Int(42));
    }

    #[test]
    #[cfg(feature = "floats")]
    fn eval_tuple_mixed_types() {
        let val = run_expect("fn main() -> Float { let t = (42, 2.5, true); t.1 }", &[]);
        assert_eq!(val, Value::Float(2.5));
    }

    // -- Len instruction --

    #[test]
    fn eval_len_via_for_in() {
        // Len is used internally by for-in. Verify via a known array size.
        let val = run_expect(
            "fn main() -> Word { let n = 0; for x in [1, 1, 1, 1] { let n = n + 1; } n }",
            &[],
        );
        assert_eq!(val, Value::Int(0));
    }

    // -- Data segment --

    #[test]
    fn eval_data_read() {
        // Read a host-initialized data slot from script.
        let src = "data ctx {\n    score: Word,\n}\nfn main() -> Word { ctx.score }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        vm.set_shared(&mut shared, 0, Value::Int(42)).unwrap();
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn eval_data_write() {
        // Write to a data slot and read it back.
        let src = "\
            data ctx {\n\
                score: Word,\n\
            }\n\
            fn main() -> Word {\n\
                ctx.score = 100;\n\
                ctx.score\n\
            }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(100)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn eval_data_survives_reset() {
        // Write to data before reset, verify it persists after.
        let src = "\
            data ctx {\n\
                counter: Word,\n\
            }\n\
            loop main(input: Word) -> Word {\n\
                ctx.counter = ctx.counter + 1;\n\
                let input = yield ctx.counter;\n\
                input\n\
            }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        // Zeroed shared buffer; the script's counter starts at 0 and the host
        // owns the buffer across the whole stream (B28 item 2).
        let mut shared = vec![0u8; vm.shared_data_bytes()];

        // First call: counter 0 + 1 = 1, yield 1.
        match vm.call_with_shared(&mut shared, &[Value::Int(0)]).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(1)),
            other => panic!("expected yield, got {:?}", other),
        }

        // Resume: reaches Reset. Counter is still 1.
        match vm.resume_with_shared(&mut shared, Value::Int(0)).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }

        // Resume after Reset: counter 1 + 1 = 2, yield 2.
        // Data survived the reset.
        match vm.resume_with_shared(&mut shared, Value::Int(0)).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(2)),
            other => panic!("expected yield, got {:?}", other),
        }

        // Resume: reaches Reset.
        match vm.resume_with_shared(&mut shared, Value::Int(0)).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }

        // Resume after second Reset: counter 2 + 1 = 3.
        match vm.resume_with_shared(&mut shared, Value::Int(0)).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(3)),
            other => panic!("expected yield, got {:?}", other),
        }
    }

    #[test]
    fn eval_data_survives_yield() {
        // Write to data, yield, resume, verify data persists across yield.
        let src = "\
            data ctx {\n\
                value: Word,\n\
            }\n\
            loop main(input: Word) -> Word {\n\
                ctx.value = 99;\n\
                let input = yield ctx.value;\n\
                let input = yield ctx.value + 1;\n\
                input\n\
            }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];

        // First yield: ctx.value = 99, yield 99.
        match vm.call_with_shared(&mut shared, &[Value::Int(0)]).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(99)),
            other => panic!("expected yield, got {:?}", other),
        }

        // Second yield: ctx.value still 99, yield 99 + 1 = 100.
        match vm.resume_with_shared(&mut shared, Value::Int(0)).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(100)),
            other => panic!("expected yield, got {:?}", other),
        }
    }

    #[test]
    fn eval_data_multiple_slots() {
        // Multiple named data slots with independent values.
        let src = "\
            data ctx {\n\
                a: Word,\n\
                b: Word,\n\
                c: Word,\n\
            }\n\
            fn main() -> Word {\n\
                ctx.a = 10;\n\
                ctx.b = 20;\n\
                ctx.c = 30;\n\
                ctx.a + ctx.b + ctx.c\n\
            }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(60)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    // B16 step 12: integer-magnitude test that fits i16/i32/i64 but
    // not i8; the narrow-word-8 binary masks 100 + 200 = 300 to 8
    // bits and the test's expected value no longer holds.
    #[cfg(not(feature = "narrow-word-8"))]
    fn eval_data_host_initialized() {
        // Host initializes data, script reads it.
        let src = "\
            data ctx {\n\
                x: Word,\n\
                y: Word,\n\
            }\n\
            fn main() -> Word { ctx.x + ctx.y }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        vm.set_shared(&mut shared, 0, Value::Int(100)).unwrap();
        vm.set_shared(&mut shared, 1, Value::Int(200)).unwrap();
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(300)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    fn build_module(src: &str) -> Module {
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        compile(&program).expect("compile error")
    }

    // -- Hot swap (replace_module) --

    #[test]
    fn hot_swap_same_schema_preserved() {
        // Module A: ctx { score: i64 }, returns ctx.score + 10.
        let src_a = "data ctx { score: Word }\nfn main() -> Word { ctx.score + 10 }";
        // Module B: ctx { score: i64 }, returns ctx.score * 2.
        let src_b = "data ctx { score: Word }\nfn main() -> Word { ctx.score * 2 }";

        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);

        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        // The shared score lives in the host-owned buffer, which persists
        // across the hot swap; the host preserves the value by reusing the
        // same buffer rather than by passing it to `replace_module` (B28
        // item 2).
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        vm.set_shared(&mut shared, 0, Value::Int(5)).unwrap();
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(15)),
            other => panic!("expected finished, got {:?}", other),
        }

        // Hot swap to module B. `replace_module` takes only private initial
        // data (here none); the shared buffer keeps score = 5.
        vm.replace_module(mod_b, alloc::vec![]).unwrap();
        shared.resize(vm.shared_data_bytes(), 0);
        assert_eq!(vm.data_len(), 1);
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(10)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn hot_swap_strict_rejects_schema_mismatch() {
        // Replaces the previous `hot_swap_new_schema_replaced` test
        // under the strict-by-default schema policy added in Item 6
        // of the V0.2 design pass. Modules A and B declare different
        // data layouts; `replace_module` now rejects the swap with a
        // `VmError::VerifyError` whose message names the two
        // schema_hash values. Hosts that intend to swap across
        // incompatible schemas call `replace_module_unchecked`
        // (covered by `hot_swap_unchecked_admits_new_schema` below).
        let src_a = "data ctx { score: Word }\nfn main() -> Word { ctx.score }";
        let src_b =
            "data ctx { x: Word, y: Word, z: Word }\nfn main() -> Word { ctx.x + ctx.y + ctx.z }";

        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);

        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        let err = vm
            .replace_module(
                mod_b,
                alloc::vec![Value::Int(1), Value::Int(2), Value::Int(3)],
            )
            .unwrap_err();
        match err {
            VmError::VerifyError(msg) => assert!(
                msg.contains("schema mismatch"),
                "expected schema-mismatch error, got: {}",
                msg
            ),
            other => panic!("expected VerifyError(schema mismatch), got {:?}", other),
        }
    }

    #[test]
    fn hot_swap_unchecked_admits_new_schema() {
        // The escape hatch: `replace_module_unchecked` bypasses the
        // schema check and admits a swap to a module with a different
        // data layout, retaining the previous V0.1 behaviour.
        let src_a = "data ctx { score: Word }\nfn main() -> Word { ctx.score }";
        let src_b =
            "data ctx { x: Word, y: Word, z: Word }\nfn main() -> Word { ctx.x + ctx.y + ctx.z }";

        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);

        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        vm.set_shared(&mut shared, 0, Value::Int(7)).unwrap();
        assert_eq!(vm.data_len(), 1);

        // The new module declares no private data, so `replace_module` takes an
        // empty vec; the wider shared layout is supplied through the resized
        // host buffer (B28 item 2).
        vm.replace_module_unchecked(mod_b, alloc::vec![]).unwrap();
        shared.resize(vm.shared_data_bytes(), 0);
        vm.set_shared(&mut shared, 0, Value::Int(1)).unwrap();
        vm.set_shared(&mut shared, 1, Value::Int(2)).unwrap();
        vm.set_shared(&mut shared, 2, Value::Int(3)).unwrap();
        assert_eq!(vm.data_len(), 3);

        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(6)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn hot_swap_size_mismatch_rejected() {
        // Schema-compatible swap that fails the size check. With the
        // strict policy now in effect, the new and old modules must
        // share a schema_hash for `replace_module` to even reach the
        // size check; this test therefore uses
        // `replace_module_unchecked` to bypass the schema check and
        // exercise the size-mismatch path directly.
        let src_a = "data ctx { x: Word }\nfn main() -> Word { ctx.x }";
        let src_b = "data ctx { x: Word, y: Word }\nfn main() -> Word { ctx.x + ctx.y }";

        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);

        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        let err = vm
            .replace_module_unchecked(mod_b, alloc::vec![Value::Int(99)])
            .unwrap_err();
        match err {
            VmError::InvalidBytecode(msg) => assert!(msg.contains("size mismatch")),
            other => panic!("expected size mismatch error, got {:?}", other),
        }
    }

    #[test]
    fn hot_swap_no_data_module_accepts_empty_vec() {
        // Hot swap from a module with a data block to one without.
        // The two schemas differ (the source module's data block
        // produces a non-zero schema_hash; the target's absence
        // produces zero), so this is a schema-incompatible swap that
        // routes through `replace_module_unchecked`.
        let src_a = "data ctx { x: Word }\nfn main() -> Word { ctx.x }";
        let src_b = "fn main() -> Word { 42 }";

        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);

        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        vm.replace_module_unchecked(mod_b, Vec::new()).unwrap();
        assert_eq!(vm.data_len(), 0);
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn hot_swap_strict_admits_schema_compatible() {
        // Two modules with identical data layouts: same slot names,
        // same visibility, same declaration order. The default
        // `replace_module` admits the swap because the schema hashes
        // match.
        let src_a = "data ctx { x: Word }\nfn main() -> Word { ctx.x }";
        let src_b = "data ctx { x: Word }\nfn main() -> Word { ctx.x + 1 }";

        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);

        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        vm.set_shared(&mut shared, 0, Value::Int(5)).unwrap();
        vm.replace_module(mod_b, alloc::vec![]).unwrap();
        shared.resize(vm.shared_data_bytes(), 0);
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(6)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn hot_swap_at_reset_starts_new_module() {
        // Module A: streaming counter. Module B: streaming doubler.
        let src_a = "data ctx { n: Word }\n\
                     loop main(input: Word) -> Word {\n\
                         ctx.n = ctx.n + 1;\n\
                         let input = yield ctx.n;\n\
                         input\n\
                     }";
        let src_b = "data ctx { n: Word }\n\
                     loop main(input: Word) -> Word {\n\
                         let input = yield ctx.n * 10;\n\
                         input\n\
                     }";

        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);

        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];

        // Run module A: yield 1 (the script writes n = 1 into the buffer).
        match vm.call_with_shared(&mut shared, &[Value::Int(0)]).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(1)),
            other => panic!("expected yield, got {:?}", other),
        }

        // Resume to reach Reset.
        match vm.resume_with_shared(&mut shared, Value::Int(0)).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }

        // Hot swap to module B. The host buffer keeps n = 1 across the swap;
        // `replace_module` takes no private data.
        vm.replace_module(mod_b, alloc::vec![]).unwrap();
        shared.resize(vm.shared_data_bytes(), 0);

        // Run module B: yield 1 * 10 = 10.
        match vm.call_with_shared(&mut shared, &[Value::Int(0)]).unwrap() {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(10)),
            other => panic!("expected yield, got {:?}", other),
        }
    }

    #[test]
    fn hot_swap_rollback_to_prior_version() {
        // Demonstrate rollback by treating the older module as the swap target.
        let src_v1 = "data ctx { n: Word }\nfn main() -> Word { ctx.n + 1 }";
        let src_v2 = "data ctx { n: Word }\nfn main() -> Word { ctx.n + 100 }";

        let mod_v1 = build_module(src_v1);
        let mod_v2 = build_module(src_v2);

        // Start with v1, snapshot the value 5.
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_v1.clone(), &arena).unwrap();
        // The shared n = 5 lives in the host buffer and persists across both
        // swaps; `replace_module` carries no private data here (B28 item 2).
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        vm.set_shared(&mut shared, 0, Value::Int(5)).unwrap();
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(6)),
            other => panic!("expected finished, got {:?}", other),
        }

        // Forward update to v2.
        vm.replace_module(mod_v2, alloc::vec![]).unwrap();
        shared.resize(vm.shared_data_bytes(), 0);
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(105)),
            other => panic!("expected finished, got {:?}", other),
        }

        // Rollback to v1 with the same value.
        vm.replace_module(mod_v1, alloc::vec![]).unwrap();
        shared.resize(vm.shared_data_bytes(), 0);
        match vm.call_with_shared(&mut shared, &[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(6)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    // -- Cross-yield prohibition on dynamic strings (R31) --

    #[test]
    fn yield_static_string_succeeds() {
        // Static string literals can be yielded.
        let src = "loop main(input: Word) -> Text { let input = yield \"static\"; \"static\" }";
        let tokens = tokenize(src).expect("lex error");
        let program = parse(&tokens).expect("parse error");
        let module = compile(&program).expect("compile error");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        match vm.call(&[Value::Int(0)]).unwrap() {
            // A yielded string constant is now a rodata `KStr`; resolve its
            // content through the arena while the VM is alive (B28 P3 item 4).
            VmState::Yielded(v) => {
                let s = v.as_str_with_arena(&arena).expect("resolve").unwrap_or("");
                assert_eq!(s, "static");
            }
            other => panic!("expected yield, got {:?}", other),
        }
    }

    // V0.2.0 removed the `to_string`, `concat`, `slice`, and `length`
    // utility natives that previously produced KStr values from
    // script-level operations. The cross-yield prohibition for
    // `Value::KStr` is still enforced at runtime; tests for that path
    // now need a host-registered native that produces a KStr. The
    // `yield_dynamic_string_fails` and
    // `yield_tuple_with_dynamic_string_fails` tests were removed in
    // this transition; they should be reinstated alongside the
    // Phase 5 work that introduces the verified/external native ABI
    // split (and a test native that produces a KStr).

    // -- Arena integration --

    #[test]
    fn vm_has_arena_with_default_capacity() {
        let module = build_module("fn main() -> Word { 42 }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let vm = Vm::new(module, &arena).unwrap();
        assert_eq!(vm.arena().capacity(), DEFAULT_ARENA_CAPACITY);
        // V0.2.0: Vm::new pre-reserves the operand stack and call
        // frames so the runtime fails fast with `OutOfArena` rather
        // than aborting on a later push. The bottom region is therefore
        // non-empty at construction.
        assert!(vm.arena().bottom_used() > 0);
        assert_eq!(vm.arena().top_used(), 0);
    }

    #[test]
    fn vm_arena_capacity_configurable() {
        let module = build_module("fn main() -> Word { 42 }");
        let arena = keleusma_arena::Arena::with_capacity(4096);
        let vm = Vm::new(module, &arena).unwrap();
        assert_eq!(vm.arena().capacity(), 4096);
    }

    #[test]
    fn vm_arena_reset_at_op_reset() {
        // Stream function that allocates from the arena's top region
        // before yield. The arena is not reset at yield. At the
        // Op::Reset boundary the top region is cleared and the epoch
        // advances. The bottom region is preserved because the
        // operand stack and call frames are bottom-allocated and
        // carry state across the reset.
        use crate::kstring::KString;

        let src = "loop main(input: Word) -> Word { let input = yield input; input }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();

        // Host allocates a string from the arena's top region. The
        // KString is the boundary type that becomes stale on reset.
        let handle = KString::alloc(vm.arena(), "scratch").unwrap();
        assert!(vm.arena().top_used() > 0);

        // First call yields, arena not reset at yield.
        match vm.call(&[Value::Int(0)]).unwrap() {
            VmState::Yielded(_) => {}
            other => panic!("expected yield, got {:?}", other),
        }
        assert!(vm.arena().top_used() > 0);
        // The handle resolves while the epoch matches.
        assert_eq!(handle.get(vm.arena()).unwrap(), "scratch");

        // Resume to reach Reset. Top region is cleared and the epoch
        // advances. Bottom region is preserved (operand stack and
        // frames remain).
        let pre_epoch = vm.arena().epoch();
        match vm.resume(Value::Int(0)).unwrap() {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }
        assert_eq!(vm.arena().top_used(), 0);
        assert_eq!(vm.arena().epoch(), pre_epoch + 1);
        // The handle is now stale.
        assert!(handle.get(vm.arena()).is_err());
    }

    #[test]
    fn ephemeral_opaque_registry_drops_at_reset() {
        // B28 P3 foundation: the ephemeral opaque registry holds the
        // `Drop`-bearing `Arc` that a flat composite body refers to by
        // index, and a RESET drops it. The host refcount is observed
        // through an external `Arc` clone.
        struct Handle;
        impl crate::opaque::HostOpaque for Handle {
            fn type_name(&self) -> &'static str {
                "Handle"
            }
        }

        let module = build_module("fn main() -> Word { 42 }");
        let arena = keleusma_arena::Arena::with_capacity(4096);
        let mut vm = Vm::new(module, &arena).unwrap();

        let arc = crate::opaque::host_arc(Handle);
        let external = alloc::sync::Arc::clone(&arc);
        assert_eq!(alloc::sync::Arc::strong_count(&external), 2);

        // Interning moves the `Arc` into the registry; the external
        // clone still observes two strong references.
        let idx = vm.intern_ephemeral_opaque(arc);
        assert_eq!(alloc::sync::Arc::strong_count(&external), 2);

        // Resolving yields a fresh clone (transiently three), dropped
        // back to two when the resolved handle is released.
        let resolved = vm.resolve_ephemeral_opaque(idx).expect("index in range");
        assert_eq!(alloc::sync::Arc::strong_count(&external), 3);
        assert_eq!(resolved.type_name(), "Handle");
        drop(resolved);
        assert_eq!(alloc::sync::Arc::strong_count(&external), 2);

        // RESET clears the registry, running the registry `Arc`'s
        // `Drop`; the external clone is the sole remaining reference and
        // the index no longer resolves.
        vm.reset_after_error();
        assert_eq!(alloc::sync::Arc::strong_count(&external), 1);
        assert!(vm.resolve_ephemeral_opaque(idx).is_none());
    }

    #[test]
    fn ephemeral_opaque_intern_dedups_by_pointer_identity() {
        // Interning the same `Arc` twice returns the same index, so the
        // byte equality of two flat composite bodies that hold the same
        // opaque coincides with `Arc::ptr_eq`. Distinct `Arc`s, even of
        // the same host type, get distinct indices.
        struct Handle;
        impl crate::opaque::HostOpaque for Handle {
            fn type_name(&self) -> &'static str {
                "Handle"
            }
        }

        let module = build_module("fn main() -> Word { 42 }");
        let arena = keleusma_arena::Arena::with_capacity(4096);
        let mut vm = Vm::new(module, &arena).unwrap();

        let a = crate::opaque::host_arc(Handle);
        let b = crate::opaque::host_arc(Handle);

        let ia0 = vm.intern_ephemeral_opaque(alloc::sync::Arc::clone(&a));
        let ib = vm.intern_ephemeral_opaque(alloc::sync::Arc::clone(&b));
        let ia1 = vm.intern_ephemeral_opaque(alloc::sync::Arc::clone(&a));

        assert_eq!(ia0, ia1, "same Arc dedups to one index");
        assert_ne!(ia0, ib, "distinct Arcs get distinct indices");
        // The dedup did not grow the registry on the third intern.
        assert!(vm.resolve_ephemeral_opaque(ia1).is_some());
        assert!(vm.resolve_ephemeral_opaque(ib).is_some());
        assert!(vm.resolve_ephemeral_opaque(2).is_none());
    }

    #[test]
    fn bytecode_roundtrip() {
        let src = "fn double(x: Word) -> Word { x * 2 }\nfn main() -> Word { double(21) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        // Header is correctly stamped.
        assert_eq!(&bytes[0..4], &crate::bytecode::BYTECODE_MAGIC);
        assert_eq!(
            u16::from_le_bytes([bytes[4], bytes[5]]),
            crate::bytecode::BYTECODE_VERSION
        );
        // Decoded module runs and produces the same result as the original.
        let decoded = Module::from_bytes(&bytes).expect("decode");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(decoded, &arena).unwrap();
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_load_bytes_end_to_end() {
        let src = "fn main() -> Word { 7 + 35 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::load_bytes(&bytes, &arena).expect("load");
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_bad_magic() {
        // Pad to the V0.2.0 wire-format minimum framing length
        // (64-byte header + 4-byte CRC = 68 bytes) so the slice
        // passes the truncation check and reaches the magic
        // check. The body fields after the magic do not matter
        // because the wire-format reader rejects on the magic
        // mismatch before reading further.
        let mut bytes = alloc::vec![b'X', b'X', b'X', b'X']; // bad magic
        bytes.resize(68, 0);
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::BadMagic) => {}
            other => panic!("expected BadMagic, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_truncated() {
        let bytes = alloc::vec![b'K', b'E', b'L'];
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::Truncated) => {}
            other => panic!("expected Truncated, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_oversized_length_field() {
        // Construct a slice whose length field claims more bytes than
        // the slice actually contains. The truncation check catches
        // this before any further validation.
        let mut bytes = alloc::vec![
            b'K', b'E', b'L', b'E', // magic
            0x04, 0x00, // version
            0xFF, 0xFF, 0xFF, 0xFF, // length = 4 GiB, far above slice length
            6, 6, // word_bits_log2, addr_bits_log2
            0x00, 0x00, 0x00, 0x00, // reserved
            0x00, 0x00, 0x00, 0x00, // CRC placeholder
        ];
        // Pad to clearly less than the claimed length.
        bytes.push(0);
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::Truncated) => {}
            other => panic!("expected Truncated, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_undersized_length_field() {
        // Construct a slice whose length field is below the minimum
        // framing size.
        let bytes = alloc::vec![
            b'K', b'E', b'L', b'E', // magic
            0x04, 0x00, // version
            0x05, 0x00, 0x00, 0x00, // length = 5, below minimum framing
            6, 6, // word_bits_log2, addr_bits_log2
            0x00, 0x00, 0x00, 0x00, // reserved
            0x00, 0x00, 0x00, 0x00, // CRC placeholder
        ];
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::Truncated) => {}
            other => panic!("expected Truncated, got {:?}", other),
        }
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32",
        feature = "narrow-address-8",
        feature = "narrow-address-16",
        feature = "narrow-address-32",
        feature = "narrow-float-32"
    )))]
    #[test]
    fn bytecode_golden_bytes_for_main_returning_one() {
        // Pin the exact serialized form of a minimal Keleusma program
        // under the V0.2.0 wire format (Phase 7c).
        //
        // Source: `fn main() -> Word { 1 }`
        //
        // Layout: 64-byte framing header + opcode stream (8 bytes:
        // PushImmediate(5) + Return as 4-byte records) + empty
        // operand pool + rkyv-archived WireAuxBody + 4-byte CRC.
        // Total length: 308 bytes.
        //
        // The aux body grew by the optional per-chunk
        // `WireChunk::debug_pool_bytes` field added for B29 (strippable
        // debug metadata) and again for the `ConstValue::Enum`
        // `discriminant: Option<i64>` field added for B28 P2 (flat-enum
        // constants), and again for the `DataLayout::shared_layout` table of
        // the B28 item 2 shared-data re-architecture (the no-new-opcode
        // per-shared-slot layout): rkyv reserves space for the wider
        // `ArchivedDataLayout` inside `Option<DataLayout>` even when it is
        // `None`, which accounted for the increase to 252 bytes, and again for
        // the `DataLayout::private_composite_layout` table of B28 item 2 step
        // 6A (the linker-style fixed-address placement of every private
        // composite slot, array elements included): rkyv reserves one more
        // `ArchivedVec` (8 bytes) in the inline `ArchivedDataLayout` even when
        // `None`, raising the total to 260 bytes, and again for the
        // `WireAuxBody::enum_layouts` table (B37 / audit finding 25 follow-up:
        // the per-enum variant-discriminant and padded-body sizes that let the
        // runtime make a native-returned enum's flat body type-driven), whose
        // empty `ArchivedVec` adds 8 more bytes for a total of 268, and again
        // for the `WireAuxBody::signatures` table (A.2.1 Phase 2b: the typed
        // operand-stack verifier's per-chunk parameter, return, and resume
        // flat-shape descriptors), which for this one-chunk module carries one
        // signature (no parameters, a scalar `Word` return, `Top` resume),
        // raising the total to 300 bytes, and again for the
        // `WireAuxBody::native_return_shapes` table (A.2.1 native-result
        // seeding), whose empty `ArchivedVec` adds 8 more bytes for a total of
        // 308. Per B28 the format may change freely without a BYTECODE_VERSION
        // bump (no production traction; programs are recompiled).
        let expected: alloc::vec::Vec<u8> = alloc::vec![
            75, 69, 76, 69, 1, 0, 64, 0, 52, 1, 0, 0, 6, 6, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 64, 0, 0, 0, 8, 0, 0, 0, 72, 0, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 232, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 109, 97, 105, 110, 255, 255, 255, 255, 200, 255, 255, 255,
            1, 0, 0, 0, 240, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 228, 255, 255, 255, 0, 0, 0, 0,
            0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 176, 255, 255, 255, 1, 0, 0, 0, 224, 255,
            255, 255, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 152, 255, 255, 255, 0, 0, 0, 0, 144, 255, 255,
            255, 1, 0, 0, 0, 160, 255, 255, 255, 0, 0, 0, 0, 190, 251, 115, 118,
        ];
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        assert_eq!(
            bytes, expected,
            "wire format drift detected. Update the expected bytes deliberately and bump BYTECODE_VERSION if not backwards compatible."
        );
        // Round-trip verifies the deserializer reads the golden bytes
        // correctly and the resulting program executes.
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::load_bytes(&expected, &arena).expect("load");
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(1)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_view_bytes_runs_aligned_input() {
        // Compile, serialize, and copy into an AlignedVec to obtain an
        // aligned slice. view_bytes validates in place via
        // Module::access_bytes and deserializes without the AlignedVec
        // copy that load_bytes performs internally.
        let src = "fn main() -> Word { 7 + 35 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let mut aligned = rkyv::util::AlignedVec::<8>::with_capacity(bytes.len());
        aligned.extend_from_slice(&bytes);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::view_bytes(&aligned, &arena).expect("view");
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_view_bytes_handles_unaligned_input() {
        // `Module::view_bytes` and `Module::from_bytes` both route
        // through `wire_format::module_from_wire_bytes`, which copies
        // the rkyv-archived auxiliary body into an `AlignedVec<8>`
        // before deserialization. Unaligned input is therefore
        // handled gracefully without requiring the caller to align
        // the buffer. The zero-copy alignment contract is preserved
        // by the distinct `Module::access_bytes` and
        // `Vm::view_bytes_zero_copy` entry points; this test pins
        // the owned-decode tolerance.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        // Force unaligned by prepending one byte then taking bytes[1..].
        let mut shifted = alloc::vec![0u8];
        shifted.extend_from_slice(&bytes);
        let unaligned = &shifted[1..];
        let decoded = Module::view_bytes(unaligned).expect("decode unaligned");
        // Round-trip soundness: the entry chunk is reachable and the
        // module's declared widths survive the decode.
        assert!(decoded.entry_point.is_some());
        assert_eq!(decoded.word_bits_log2, module.word_bits_log2);
    }

    #[test]
    fn vm_view_bytes_zero_copy_executes_against_borrowed_buffer() {
        // True zero-copy execution. Compile a program, serialize to
        // bytes inside an AlignedVec, then construct a VM that borrows
        // the bytes directly. The execution loop reads the entire
        // module through `&ArchivedModule` with no owned `Module`
        // materialized.
        let src = "fn double(x: Word) -> Word { x * 2 }\nfn main() -> Word { double(21) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let mut aligned = rkyv::util::AlignedVec::<8>::with_capacity(bytes.len());
        aligned.extend_from_slice(&bytes);
        // Construct a VM that borrows from `aligned`. The lifetime
        // parameter on Vm is tied to the slice.
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm: Vm<'_, '_> =
            unsafe { Vm::view_bytes_zero_copy(&aligned[..], &arena).expect("view") };
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn view_bytes_zero_copy_strips_a_shebang_prefix() {
        // Findings 8/15: the zero-copy constructor strips the shebang before
        // validating widths/framing and storing the slice, so the stored bytes
        // that `archived()` reads aux-body offsets from are the wire-format
        // bytes, not a shebang-mislocated region (`rkyv::access_unchecked` UB).
        // The 24-byte shebang keeps the wire start 8-byte aligned inside the
        // AlignedVec so the archived aux body stays aligned after stripping.
        let src = "fn double(x: Word) -> Word { x * 2 }\nfn main() -> Word { double(21) }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let shebang: &[u8] = b"#!/usr/bin/env keleusma\n"; // 24 bytes, keeps 8-byte alignment
        let mut aligned = rkyv::util::AlignedVec::<8>::with_capacity(shebang.len() + bytes.len());
        aligned.extend_from_slice(shebang);
        aligned.extend_from_slice(&bytes);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // SAFETY: the bytes are a freshly compiled module behind a shebang.
        let mut vm: Vm<'_, '_> =
            unsafe { Vm::view_bytes_zero_copy(&aligned[..], &arena).expect("view shebang") };
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!(
                "expected Finished(42) from shebang-prefixed zero-copy, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn bytecode_op_round_trip_matches_owned() {
        // V0.2.0 Phase 7c moves the per-op encoding from the
        // rkyv archive into the wire-format opcode stream. The
        // round-trip equivalence between an in-memory `Op` and
        // its on-the-wire form is now exercised through
        // `Module::to_bytes` and `Module::from_bytes` in this
        // test; the wire_format crate carries direct unit tests
        // for every variant in `module_roundtrip_*` and the
        // `opcode_record_roundtrip_*` suite.
        let src = "fn main() -> Word { 1 + 2 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let decoded = Module::from_bytes(&bytes).expect("decode");
        assert_eq!(module.chunks.len(), decoded.chunks.len());
        for (chunk_idx, (orig, dec)) in module.chunks.iter().zip(decoded.chunks.iter()).enumerate()
        {
            assert_eq!(
                orig.ops, dec.ops,
                "chunk {} ops mismatch across wire-format round trip",
                chunk_idx
            );
        }
    }

    #[test]
    fn bytecode_archived_value_round_trip_matches_owned() {
        // value_from_archived materializes an owned Value from an
        // archived Value. Verify constants survive the round trip.
        use crate::bytecode::value_from_archived;
        let src = "fn main() -> Word { 42 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let mut aligned = rkyv::util::AlignedVec::<8>::with_capacity(bytes.len());
        aligned.extend_from_slice(&bytes);
        let archived: &crate::wire_format::ArchivedWireAuxBody =
            Module::access_bytes(&aligned).expect("access");
        let main_chunk = &archived.chunks[0];
        for (i, archived_val) in main_chunk.constants.iter().enumerate() {
            // The bundled runtime is i64/f64, eight-byte scalars; the
            // into_value comparand uses the same widths (B28 P2).
            let owned = value_from_archived(archived_val, 8, 8);
            let original = module.chunks[0].constants[i].clone().into_value();
            assert_eq!(
                owned, original,
                "constant at index {} mismatches across archive round trip",
                i
            );
        }
    }

    #[test]
    fn bytecode_access_bytes_returns_archived_view() {
        // access_bytes returns a borrowed `ArchivedWireAuxBody`
        // under the V0.2.0 wire format. The archived form
        // preserves the chunk count, the entry point, and the
        // word and address sizes through native conversions.
        let src = "fn double(x: Word) -> Word { x * 2 }\nfn main() -> Word { double(21) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let mut aligned = rkyv::util::AlignedVec::<8>::with_capacity(bytes.len());
        aligned.extend_from_slice(&bytes);
        let archived: &crate::wire_format::ArchivedWireAuxBody =
            Module::access_bytes(&aligned).expect("access");
        assert_eq!(archived.chunks.len(), 2);
        assert_eq!(
            archived.word_bits_log2,
            crate::bytecode::RUNTIME_WORD_BITS_LOG2
        );
        assert_eq!(
            archived.addr_bits_log2,
            crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2
        );
    }

    #[test]
    fn bytecode_admits_trailing_padding() {
        // The recorded length is authoritative. Trailing bytes after
        // the recorded length are ignored, so bytecode embedded in a
        // larger buffer is accepted.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let mut bytes = module.to_bytes().expect("encode");
        bytes.extend_from_slice(&[0xAA; 32]);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let module = Module::from_bytes(&bytes).expect("decode");
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(1)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_unsupported_version() {
        // Compile a real module, patch the version field to an
        // unsupported value, then recompute the CRC trailer so the
        // residue check still passes. This isolates the version
        // rejection path from the checksum rejection path.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let mut bytes = module.to_bytes().expect("encode");
        bytes[4] = 0xFF;
        bytes[5] = 0xFF;
        let trailer_start = bytes.len() - 4;
        let new_crc = crate::bytecode::crc32(&bytes[..trailer_start]);
        bytes[trailer_start..].copy_from_slice(&new_crc.to_le_bytes());
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::UnsupportedVersion { got, expected }) => {
                assert_eq!(got, 0xFFFF);
                assert_eq!(expected, crate::bytecode::BYTECODE_VERSION);
            }
            other => panic!("expected UnsupportedVersion, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_bad_checksum() {
        // Compile a real module, then flip a byte deep inside the body
        // so the CRC residue check fails. The flipped byte must lie
        // beyond the length field (offsets 6..10) so it does not change
        // the recorded length and trip the truncation check first.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let mut bytes = module.to_bytes().expect("encode");
        // Flip a byte in the postcard body, just past the header.
        let body_byte = bytes.len() - 5;
        bytes[body_byte] ^= 0xFF;
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::BadChecksum) => {}
            other => panic!("expected BadChecksum, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_word_size_mismatch() {
        // Compile a real module, patch the header's word_bits_log2
        // field to a value greater than the runtime supports, and
        // recompute the CRC trailer so the residue check passes.
        // The V0.2.0 wire format places word_bits_log2 at byte 12.
        // The width validation runs before the header-vs-aux
        // cross-check, so the patched header surfaces as
        // WordSizeMismatch.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let mut bytes = module.to_bytes().expect("encode");
        bytes[12] = crate::bytecode::RUNTIME_WORD_BITS_LOG2 + 1;
        let trailer_start = bytes.len() - 4;
        let new_crc = crate::bytecode::crc32(&bytes[..trailer_start]);
        bytes[trailer_start..].copy_from_slice(&new_crc.to_le_bytes());
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::WordSizeMismatch { got, max_supported }) => {
                assert_eq!(got, crate::bytecode::RUNTIME_WORD_BITS_LOG2 + 1);
                assert_eq!(max_supported, crate::bytecode::RUNTIME_WORD_BITS_LOG2);
            }
            other => panic!("expected WordSizeMismatch, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_rejects_address_size_mismatch() {
        // Header's addr_bits_log2 is at byte 13 in the V0.2.0
        // wire format.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let mut bytes = module.to_bytes().expect("encode");
        bytes[13] = crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2 + 1;
        let trailer_start = bytes.len() - 4;
        let new_crc = crate::bytecode::crc32(&bytes[..trailer_start]);
        bytes[trailer_start..].copy_from_slice(&new_crc.to_le_bytes());
        match Module::from_bytes(&bytes) {
            Err(crate::bytecode::LoadError::AddressSizeMismatch { got, max_supported }) => {
                assert_eq!(got, crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2 + 1);
                assert_eq!(max_supported, crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2);
            }
            other => panic!("expected AddressSizeMismatch, got {:?}", other),
        }
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn bytecode_admits_narrower_word_size() {
        // The runtime accepts narrower-than-runtime bytecode
        // under the relaxed-width policy. With the V0.2.0 wire
        // format, the auxiliary body also mirrors the
        // word_bits_log2 field, so simply patching the header
        // byte produces a header-vs-aux mismatch. Build a
        // narrower-target module through `compile_with_target`
        // instead; both the header and the auxiliary body carry
        // the matching narrower width.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module =
            crate::compiler::compile_with_target(&program, &crate::target::Target::embedded_16())
                .expect("compile");
        let bytes = module.to_bytes().expect("encode");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::load_bytes(&bytes, &arena).expect("narrower bytecode should be admitted");
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(1)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn bytecode_masking_truncates_to_declared_width() {
        // Construct a Module with word_bits_log2 = 5 (32-bit) and an
        // arithmetic that would not overflow at 64 bits but would at
        // 32 bits. Verify that the runtime applies sign-extending
        // truncation. The expression `2147483647 + 1` produces
        // 2147483648 at 64 bits but i32::MIN = -2147483648 at 32 bits.
        let src = "fn main() -> Word { 2147483647 + 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let mut module = compile(&program).expect("compile");
        module.word_bits_log2 = 5;
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(-2147483648)),
            other => panic!("expected finished, got {:?}", other),
        }
    }

    #[test]
    fn bytecode_residue_property_holds() {
        // The CRC-32 residue property states that for any byte sequence
        // D and its CRC C, the CRC of D followed by the little-endian
        // encoding of C equals 0x2144DF1C. Verify against the reference
        // value crc32("123456789") = 0xCBF43926 and confirm the residue.
        let data = b"123456789";
        let c = crate::bytecode::crc32(data);
        assert_eq!(c, 0xCBF43926);
        let mut combined = alloc::vec![];
        combined.extend_from_slice(data);
        combined.extend_from_slice(&c.to_le_bytes());
        let residue = crate::bytecode::crc32(&combined);
        assert_eq!(residue, 0x2144DF1C);
    }

    #[test]
    fn bytecode_load_via_vm_propagates_load_error() {
        // Twenty bytes is the minimum framing size. The magic is
        // intentionally wrong so the magic-check path triggers. The
        // length field is set to 20 so the truncation check passes.
        let bytes = alloc::vec![
            b'X', b'X', b'X', b'X', 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 6, 6, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        match Vm::load_bytes(&bytes, &arena) {
            Err(VmError::LoadError(_)) => {}
            Err(other) => panic!("expected VmError::LoadError, got {:?}", other),
            Ok(_) => panic!("expected error, got VM"),
        }
    }

    #[test]
    fn vm_new_returns_out_of_arena_when_capacity_too_small_for_minimum() {
        // A trivial program should still report `OutOfArena` rather
        // than aborting the host when the arena cannot hold the
        // minimum operand-stack and call-frame reservation.
        let module = build_module("fn main() -> Word { 1 }");
        let arena = keleusma_arena::Arena::with_capacity(0);
        let result = Vm::new(module, &arena);
        match result {
            Err(VmError::OutOfArena(_)) | Err(VmError::VerifyError(_)) => {}
            Err(other) => panic!("expected OutOfArena or VerifyError, got {:?}", other),
            Ok(_) => panic!("expected OutOfArena or VerifyError, got Ok"),
        }
    }

    #[test]
    fn vm_new_unchecked_returns_out_of_arena_when_capacity_too_small() {
        // The trust-skip constructor also returns OutOfArena rather
        // than aborting when the arena is too small for the minimum
        // runtime reservation.
        let module = build_module("fn main() -> Word { 1 }");
        let arena = keleusma_arena::Arena::with_capacity(0);
        let result = unsafe { Vm::new_unchecked(module, &arena) };
        assert!(matches!(result, Err(VmError::OutOfArena(_))));
    }

    #[test]
    fn unchecked_still_runs_structural_verification() {
        // Construct a module that fails structural verification by
        // manually corrupting the chunk's block type. A `Stream` chunk
        // without a yield is rejected.
        use crate::bytecode::{BlockType, Chunk, ConstValue, Module, Op};
        let chunk = Chunk {
            name: alloc::string::String::from("main"),
            ops: alloc::vec![Op::Const(0), Op::Reset],
            constants: alloc::vec![ConstValue::Int(0)],
            struct_templates: alloc::vec![],
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Stream,
            param_types: alloc::vec![],
            debug_pool: None,
        };
        let module = Module {
            schema_hash: 0,
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            chunks: alloc::vec![chunk],
            native_names: alloc::vec![],
            entry_point: Some(0),
            data_layout: None,
            word_bits_log2: crate::bytecode::RUNTIME_WORD_BITS_LOG2,
            addr_bits_log2: crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2,
            float_bits_log2: crate::bytecode::RUNTIME_FLOAT_BITS_LOG2,
            wcet_cycles: 0,
            wcmu_bytes: 0,
            aux_arena_bytes: 0,
            persistent_composite_bytes: 0,
            flags: 0,
            shared_data_bytes: 0,
            private_data_bytes: 0,
        };
        // The unchecked constructor still rejects on structural grounds.
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let result = unsafe { Vm::new_unchecked(module, &arena) };
        assert!(matches!(result, Err(VmError::VerifyError(_))));
    }

    // Audit remediation (SECURITY_AUDIT_V0_2_1, poc_wordtofixed). The
    // verifier now rejects a WordToFixed whose fraction-bit count is not
    // less than the word width, so the overshift cannot reach the VM on a
    // safe load. The VM also saturates such a shift as defense in depth
    // for new_unchecked loads.
    #[test]
    fn wordtofixed_overshift_rejected_by_verifier() {
        use crate::bytecode::{BlockType, Chunk, ConstValue, Module, Op};
        let chunk = Chunk {
            name: alloc::string::String::from("main"),
            ops: alloc::vec![Op::Const(0), Op::WordToFixed(200), Op::Return],
            constants: alloc::vec![ConstValue::Int(0)],
            struct_templates: alloc::vec![],
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec![],
            debug_pool: None,
        };
        let module = Module {
            schema_hash: 0,
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            chunks: alloc::vec![chunk],
            native_names: alloc::vec![],
            entry_point: Some(0),
            data_layout: None,
            word_bits_log2: crate::bytecode::RUNTIME_WORD_BITS_LOG2,
            addr_bits_log2: crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2,
            float_bits_log2: crate::bytecode::RUNTIME_FLOAT_BITS_LOG2,
            wcet_cycles: 0,
            wcmu_bytes: 0,
            aux_arena_bytes: 0,
            persistent_composite_bytes: 0,
            flags: 0,
            shared_data_bytes: 0,
            private_data_bytes: 0,
        };
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // The verifier rejects the out-of-range fraction-bit count, so the
        // safe loader never admits the overshift.
        let res = Vm::new(module, &arena);
        assert!(
            matches!(res, Err(VmError::VerifyError(_))),
            "expected VerifyError for WordToFixed(200), got {:?}",
            res.map(|_| "Ok")
        );
    }

    /// Build a single-chunk module from `ops` and assert the safe loader
    /// rejects it with a fraction-bit-count verify error. Shared by the
    /// Fixed-opcode overshift tests (audit C9): the verifier is the primary
    /// gate that keeps an out-of-range Q-format fraction count from reaching
    /// the VM's shift, so a safe load never exercises the fail-closed runtime
    /// guard added to the FixedToWord / FixedMul / FixedDiv arms.
    #[cfg(feature = "verify")]
    fn assert_verify_rejects_fraction(ops: alloc::vec::Vec<crate::bytecode::Op>) {
        use crate::bytecode::{BlockType, Chunk, ConstValue, Module};
        let chunk = Chunk {
            name: alloc::string::String::from("main"),
            ops,
            constants: alloc::vec![ConstValue::Int(0)],
            struct_templates: alloc::vec![],
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec![],
            debug_pool: None,
        };
        let module = Module {
            schema_hash: 0,
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            chunks: alloc::vec![chunk],
            native_names: alloc::vec![],
            entry_point: Some(0),
            data_layout: None,
            word_bits_log2: crate::bytecode::RUNTIME_WORD_BITS_LOG2,
            addr_bits_log2: crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2,
            float_bits_log2: crate::bytecode::RUNTIME_FLOAT_BITS_LOG2,
            wcet_cycles: 0,
            wcmu_bytes: 0,
            aux_arena_bytes: 0,
            persistent_composite_bytes: 0,
            flags: 0,
            shared_data_bytes: 0,
            private_data_bytes: 0,
        };
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        match Vm::new(module, &arena) {
            Err(VmError::VerifyError(m)) => assert!(
                m.contains("fraction"),
                "expected a fraction-bit-count rejection, got: {m}"
            ),
            other => panic!(
                "expected VerifyError, got {:?}",
                other.map(|_| "Ok").map_err(|e| format!("{e:?}"))
            ),
        }
    }

    #[test]
    #[cfg(feature = "verify")]
    fn fixedtoword_overshift_rejected_by_verifier() {
        use crate::bytecode::Op;
        // `WordToFixed(1)` yields a valid Fixed operand; the overshift is the
        // `FixedToWord(200)` fraction count, not a type mismatch.
        assert_verify_rejects_fraction(alloc::vec![
            Op::Const(0),
            Op::WordToFixed(1),
            Op::FixedToWord(200),
            Op::Return,
        ]);
    }

    #[test]
    #[cfg(feature = "verify")]
    fn fixedmul_overshift_rejected_by_verifier() {
        use crate::bytecode::Op;
        assert_verify_rejects_fraction(alloc::vec![
            Op::Const(0),
            Op::WordToFixed(1),
            Op::Const(0),
            Op::WordToFixed(1),
            Op::FixedMul(200),
            Op::Return,
        ]);
    }

    #[test]
    #[cfg(feature = "verify")]
    fn fixeddiv_overshift_rejected_by_verifier() {
        use crate::bytecode::Op;
        assert_verify_rejects_fraction(alloc::vec![
            Op::Const(0),
            Op::WordToFixed(1),
            Op::Const(0),
            Op::WordToFixed(1),
            Op::FixedDiv(200),
            Op::Return,
        ]);
    }

    #[test]
    #[cfg(feature = "verify")]
    fn checkedmul_overshift_rejected_by_verifier() {
        // Audit D5: the CheckedMul Fixed arm gained the same fail-closed guard
        // as FixedMul; the verifier is the primary gate that bounds the count.
        use crate::bytecode::Op;
        assert_verify_rejects_fraction(alloc::vec![
            Op::Const(0),
            Op::WordToFixed(1),
            Op::Const(0),
            Op::WordToFixed(1),
            Op::CheckedMul(200),
            Op::Return,
        ]);
    }

    #[test]
    #[cfg(feature = "verify")]
    fn checkeddiv_overshift_rejected_by_verifier() {
        use crate::bytecode::Op;
        assert_verify_rejects_fraction(alloc::vec![
            Op::Const(0),
            Op::WordToFixed(1),
            Op::Const(0),
            Op::WordToFixed(1),
            Op::CheckedDiv(200),
            Op::Return,
        ]);
    }

    #[test]
    fn contains_dynstr_helper() {
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let h = crate::kstring::KString::alloc(&arena, "hi").unwrap();
        let kstr = Value::KStr(h);
        assert!(!Value::Int(1).contains_dynstr());
        assert!(!Value::StaticStr(String::from("hi")).contains_dynstr());
        assert!(kstr.contains_dynstr());
        // A `KStr` tuple element now flattens (B28 P3 item 5 C4). The runtime
        // `contains_dynstr` walk reads only boxed bodies, so a boxed tuple
        // holding a `KStr` is detected here, while a flat-text tuple is not
        // (the same as a flat-text struct). Flat-text composites are governed
        // by the read-before-resume contract rather than a cross-yield
        // rejection (B28 P3 item 4).
        assert!(
            Value::Tuple(crate::bytecode::TupleBody::boxed(alloc::vec![
                Value::Int(1),
                kstr.clone()
            ]))
            .contains_dynstr()
        );
        assert!(
            !Value::tuple(alloc::vec![
                Value::Int(1),
                Value::StaticStr(String::from("x"))
            ])
            .contains_dynstr()
        );
        // A boxed struct holding a `KStr` is detected. (A struct whose
        // fields are all flat now flattens, B28 P3; a flat struct's text
        // field is an arena reference that crosses yield epoch-gated, so it
        // is intentionally not flagged here — `contains_dynstr` walks the
        // boxed value tree and does not read flat bytes.)
        assert!(
            Value::Struct(crate::bytecode::StructBody::boxed(
                String::from("Foo"),
                alloc::vec![(String::from("x"), kstr.clone())],
            ))
            .contains_dynstr()
        );
        // The arena-less `struct_value` now produces the boxed representation
        // (B28 item 2 step 6B), so its `KStr` field is walked and flagged, the
        // same as the explicit boxed struct above. The flat form (built only
        // through the runtime's arena-direct path) keeps its text as a two-word
        // arena reference that `contains_dynstr` does not read.
        assert!(
            Value::struct_value(String::from("Foo"), alloc::vec![(String::from("x"), kstr)])
                .contains_dynstr()
        );
    }

    // -- P3 error recovery --

    #[test]
    fn reset_after_error_preserves_data() {
        // After a runtime error the data segment persists. The host
        // can call reset_after_error and retry without losing
        // accumulated state.
        let src = "data ctx { count: Word }\n\
                   loop main(input: Word) -> Word {\n\
                       ctx.count = ctx.count + 1;\n\
                       let next = yield ctx.count;\n\
                       next\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        vm.set_shared(&mut shared, 0, Value::Int(5)).unwrap();

        // First iteration: yield 6.
        match vm.call_with_shared(&mut shared, &[Value::Int(0)]).unwrap() {
            VmState::Yielded(Value::Int(6)) => {}
            other => panic!("expected yield 6, got {:?}", other),
        }

        // Simulate an error: pretend the host got an Err from resume.
        // We do not actually trigger one here because the test would
        // need to provide bytecode that traps. The recovery contract
        // is that reset_after_error returns the VM to a callable state
        // regardless of how the failed call left things. Verify that
        // calling it after a normal yield still produces a valid
        // post-recovery state.
        vm.reset_after_error();

        // The host buffer preserves the shared count across error recovery.
        assert_eq!(vm.get_shared(&shared, 0).unwrap(), Value::Int(6));

        // Fresh call works.
        match vm.call_with_shared(&mut shared, &[Value::Int(0)]).unwrap() {
            VmState::Yielded(Value::Int(7)) => {}
            other => panic!("expected yield 7 after recovery, got {:?}", other),
        }
    }

    #[test]
    fn reset_after_trap_clears_volatile_state() {
        // A program that traps. The host catches the error, calls
        // reset_after_error, then runs the program again successfully.
        let trap_src = "fn main() -> Word { let x = 0; if x == 0 { 1 / x } else { 0 } }";
        match run_program(trap_src, &[]) {
            Err(VmError::DivisionByZero) => {}
            other => panic!("expected DivisionByZero precheck, got {:?}", other),
        }
        // Build the VM directly so we own its lifetime here and can
        // recover after the error.
        let tokens = tokenize(trap_src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();

        // First run produces the error.
        match vm.call(&[]) {
            Err(VmError::DivisionByZero) => {}
            other => panic!("expected DivisionByZero, got {:?}", other),
        }

        // Recover and verify volatile state is clean.
        vm.reset_after_error();

        // Calling again still produces the same error because the
        // bytecode is unchanged. The point is that the call goes
        // through cleanly without corruption from the prior failed
        // run.
        match vm.call(&[]) {
            Err(VmError::DivisionByZero) => {}
            other => panic!("expected DivisionByZero on second call, got {:?}", other),
        }
    }

    #[test]
    fn reset_after_error_idempotent() {
        // Calling reset_after_error multiple times is harmless.
        let src = "fn main() -> Word { 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).unwrap();
        vm.reset_after_error();
        vm.reset_after_error();
        vm.reset_after_error();
        match vm.call(&[]).unwrap() {
            VmState::Finished(Value::Int(1)) => {}
            other => panic!("expected finished 1, got {:?}", other),
        }
    }

    // -- P2 for-in over typed expressions --

    #[test]
    fn for_in_over_function_return_passes_strict_verify() {
        // The for-in iteration bound is extracted from the called
        // function's declared return type [i64; 3]. The verifier
        // accepts the loop because the end bound is a Const(3).
        // Without static type info the same source would be rejected
        // by strict-mode WCMU.
        let src = "fn make() -> [Word; 3] { [1, 2, 3] }\n\
                   fn main() -> Word {\n\
                       let last = 0;\n\
                       for x in make() { let last = x; }\n\
                       last\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        // Constructing the VM runs the strict-mode verifier. A
        // successful construction confirms the iteration bound was
        // extractable from the typed return.
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let _vm = Vm::new(module, &arena).expect("verify");
    }

    #[test]
    fn for_in_over_data_segment_field_passes_strict_verify() {
        // For-in over a data segment field whose declared type is
        // [i64; N] is admissible because the field type provides the
        // static iteration bound.
        let src = "data ctx { items: [Word; 4] }\n\
                   fn main() -> Word {\n\
                       let last = 0;\n\
                       for x in ctx.items { let last = x; }\n\
                       last\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let _vm = Vm::new(module, &arena).expect("verify");
    }

    #[test]
    fn for_in_over_struct_field_from_local_passes_strict_verify() {
        // For-in over a struct field accessed through a local
        // variable. The compiler tracks the local's declared or
        // inferred type and resolves `b.items` to `[i64; 3]` from
        // the struct definition. The verifier accepts the
        // resulting Const(3) end bound.
        let src = "struct Box { items: [Word; 3] }\n\
                   fn main() -> Word {\n\
                       let b = Box { items: [1, 2, 3] };\n\
                       let last = 0;\n\
                       for x in b.items { let last = x; }\n\
                       last\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let _vm = Vm::new(module, &arena).expect("verify");
    }

    #[test]
    fn for_in_over_param_array_passes_strict_verify() {
        // For-in over an array parameter typed `[T; N]`. The
        // compiler records the parameter's declared type on the
        // local and the for-in source resolves to a typed array.
        let src = "fn sum_n(arr: [Word; 4]) -> Word {\n\
                       let s = 0;\n\
                       for x in arr { let s = s + x; }\n\
                       s\n\
                   }\n\
                   fn main() -> Word { sum_n([1, 2, 3, 4]) }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let _vm = Vm::new(module, &arena).expect("verify");
    }

    #[test]
    fn for_in_over_nested_array_index_passes_strict_verify() {
        // For-in over the result of indexing a nested array. The
        // compiler infers `m[0]` to have the matrix's element type
        // `[i64; 3]` and emits `Const(3)` for the iteration bound.
        let src = "fn main() -> Word {\n\
                       let m: [[Word; 3]; 2] = [[1, 2, 3], [4, 5, 6]];\n\
                       let last = 0;\n\
                       for x in m[0] { let last = x; }\n\
                       last\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let _vm = Vm::new(module, &arena).expect("verify");
    }

    #[test]
    fn for_in_over_match_array_result_passes_strict_verify() {
        // For-in over a match expression that returns an array. The
        // compiler infers the match result type from the first arm's
        // expression and uses it for the iteration bound.
        let src = "fn main() -> Word {\n\
                       let cond = 1;\n\
                       let last = 0;\n\
                       for x in match cond { 0 => [1, 2, 3], _ => [4, 5, 6] } {\n\
                           let last = x;\n\
                       }\n\
                       last\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let _vm = Vm::new(module, &arena).expect("verify");
    }

    #[test]
    fn for_in_three_level_nested_passes_strict_verify() {
        // Three nested for-in loops over a 3D array. Each level
        // resolves its iteration bound from the binding's element
        // type. The outer loop reads the matrix's outer length.
        // Each subsequent loop reads the element type's length from
        // the iteration variable's type recorded by the compiler.
        let src = "fn main() -> Word {\n\
                       let map: [[[Word; 2]; 2]; 2] = [\n\
                           [[1, 2], [3, 4]],\n\
                           [[5, 6], [7, 8]],\n\
                       ];\n\
                       let last = 0;\n\
                       for z in map {\n\
                           for y in z {\n\
                               for x in y {\n\
                                   let last = x;\n\
                               }\n\
                           }\n\
                       }\n\
                       last\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let _vm = Vm::new(module, &arena).expect("verify");
    }

    #[test]
    fn match_on_inner_value_inside_three_level_nested_for_in() {
        // A match expression inside three nested for-in loops over a
        // 3D array of i64. The match arms evaluate to integer values
        // and the result accumulates into a data segment field. The
        // value 1 contributes 100; every other value contributes 1.
        // The matrix has values 1..=8 so the total is 100 + 7 = 107.
        let src = "data ctx { sum: Word }\n\
                   fn main() -> Word {\n\
                       let map: [[[Word; 2]; 2]; 2] = [\n\
                           [[1, 2], [3, 4]],\n\
                           [[5, 6], [7, 8]],\n\
                       ];\n\
                       for z in map {\n\
                           for y in z {\n\
                               for x in y {\n\
                                   let v = match x {\n\
                                       1 => 100,\n\
                                       _ => 1,\n\
                                   };\n\
                                   ctx.sum = ctx.sum + v;\n\
                               }\n\
                           }\n\
                       }\n\
                       ctx.sum\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        match vm.call_with_shared(&mut shared, &[]) {
            Ok(VmState::Finished(Value::Int(v))) => assert_eq!(v, 107),
            other => panic!("unexpected {:?}", other),
        }
    }

    #[test]
    fn tuple_match_across_three_loop_variables() {
        // Three independent 1D arrays, nested for-in, with a match
        // on the tuple `(x, y, z)`. The corner case `(0, 0, 0)`
        // contributes 100; every other coordinate contributes 1.
        // The 2x2x2 coordinate space has 8 cells so the total is
        // 100 + 7 = 107.
        let src = "data ctx { hits: Word }\n\
                   fn main() -> Word {\n\
                       let xs: [Word; 2] = [0, 1];\n\
                       let ys: [Word; 2] = [0, 1];\n\
                       let zs: [Word; 2] = [0, 1];\n\
                       for z in zs {\n\
                           for y in ys {\n\
                               for x in xs {\n\
                                   let v = match (x, y, z) {\n\
                                       (0, 0, 0) => 100,\n\
                                       _ => 1,\n\
                                   };\n\
                                   ctx.hits = ctx.hits + v;\n\
                               }\n\
                           }\n\
                       }\n\
                       ctx.hits\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        match vm.call_with_shared(&mut shared, &[]) {
            Ok(VmState::Finished(Value::Int(v))) => assert_eq!(v, 107),
            other => panic!("unexpected {:?}", other),
        }
    }

    #[test]
    fn for_in_three_level_nested_runs() {
        // Same shape as the verify test but exercises full execution
        // through a native function call. The native sums all
        // visited values. The data segment carries the running total
        // because let bindings shadow rather than mutate.
        let src = "data ctx { total: Word }\n\
                   fn main() -> Word {\n\
                       let map: [[[Word; 2]; 2]; 2] = [\n\
                           [[1, 2], [3, 4]],\n\
                           [[5, 6], [7, 8]],\n\
                       ];\n\
                       for z in map {\n\
                           for y in z {\n\
                               for x in y {\n\
                                   ctx.total = ctx.total + x;\n\
                               }\n\
                           }\n\
                       }\n\
                       ctx.total\n\
                   }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        match vm.call_with_shared(&mut shared, &[]) {
            Ok(VmState::Finished(Value::Int(v))) => {
                // Sum of 1..=8 is 36.
                assert_eq!(v, 36);
            }
            other => panic!("unexpected {:?}", other),
        }
    }

    #[test]
    fn for_in_over_array_literal_runs() {
        let val = run_expect(
            "fn main() -> Word {\n\
                 let last = 0;\n\
                 for x in [10, 20, 30] { let last = x; }\n\
                 last\n\
             }",
            &[],
        );
        // The body's `let last = x;` shadows in the inner scope.
        // Outer `last` remains 0.
        assert_eq!(val, Value::Int(0));
    }

    // -- Overflow policy knob --

    fn build_module_with_overflow(wcet: u32, wcmu: u32) -> Module {
        // Build a trivial module then mutate the declared header
        // fields to simulate a compile-time saturation.
        let mut module = build_module("fn main() -> Word { 0 }");
        module.wcet_cycles = wcet;
        module.wcmu_bytes = wcmu;
        module
    }

    #[test]
    fn new_rejects_module_without_entry_point() {
        // Compile a module that has functions but no `main`. The
        // entry-point absence should surface as a clear VerifyError
        // at the boundary, not as InvalidBytecode at the first
        // Vm::call use site.
        let src = "fn helper(x: Word) -> Word { x + 1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert!(
            module.entry_point.is_none(),
            "test precondition: module has no entry point"
        );
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        match Vm::new(module, &arena) {
            Err(VmError::VerifyError(msg)) => {
                assert!(
                    msg.contains("no entry point"),
                    "expected entry-point diagnostic, got {:?}",
                    msg
                );
            }
            Ok(_) => panic!("expected VerifyError for missing entry point"),
            Err(other) => panic!("expected VerifyError, got {:?}", other),
        }
    }

    #[test]
    fn new_with_options_default_rejects_wcet_overflow() {
        let module = build_module_with_overflow(u32::MAX, 0);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let err = Vm::new_with_options(module, &arena, VmOptions::default())
            .err()
            .expect("expected overflow rejection");
        match err {
            VmError::VerifyError(msg) => assert!(msg.contains("WCET")),
            other => panic!("expected VerifyError, got {:?}", other),
        }
    }

    #[test]
    fn new_with_options_default_rejects_wcmu_overflow() {
        let module = build_module_with_overflow(0, u32::MAX);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let err = Vm::new_with_options(module, &arena, VmOptions::default())
            .err()
            .expect("expected overflow rejection");
        match err {
            VmError::VerifyError(msg) => assert!(msg.contains("WCMU")),
            other => panic!("expected VerifyError, got {:?}", other),
        }
    }

    #[test]
    fn new_with_options_warn_admits_and_returns_warning() {
        let module = build_module_with_overflow(u32::MAX, 0);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let options = VmOptions {
            overflow_policy: OverflowPolicy::Warn,
        };
        let warnings = match Vm::new_with_options(module, &arena, options) {
            Ok((_vm, w)) => w,
            Err(e) => panic!("expected Ok, got {:?}", e),
        };
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].kind, WarningKind::WcetOverflow);
    }

    #[test]
    fn new_with_options_warn_returns_both_warnings_for_both_overflows() {
        let module = build_module_with_overflow(u32::MAX, u32::MAX);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let options = VmOptions {
            overflow_policy: OverflowPolicy::Warn,
        };
        let warnings = match Vm::new_with_options(module, &arena, options) {
            Ok((_vm, w)) => w,
            Err(e) => panic!("expected Ok, got {:?}", e),
        };
        assert_eq!(warnings.len(), 2);
        let kinds: Vec<WarningKind> = warnings.iter().map(|w| w.kind).collect();
        assert!(kinds.contains(&WarningKind::WcetOverflow));
        assert!(kinds.contains(&WarningKind::WcmuOverflow));
    }

    #[test]
    fn new_with_options_allow_admits_silently() {
        let module = build_module_with_overflow(u32::MAX, u32::MAX);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let options = VmOptions {
            overflow_policy: OverflowPolicy::Allow,
        };
        let warnings = match Vm::new_with_options(module, &arena, options) {
            Ok((_vm, w)) => w,
            Err(e) => panic!("expected Ok, got {:?}", e),
        };
        assert!(warnings.is_empty());
    }

    #[test]
    fn new_with_options_no_overflow_returns_empty_warnings() {
        let module = build_module_with_overflow(100, 1000);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let options = VmOptions {
            overflow_policy: OverflowPolicy::Warn,
        };
        let warnings = match Vm::new_with_options(module, &arena, options) {
            Ok((_vm, w)) => w,
            Err(e) => panic!("expected Ok, got {:?}", e),
        };
        assert!(warnings.is_empty());
    }

    #[test]
    fn vm_new_remains_strict_under_overflow() {
        // `Vm::new` is a thin wrapper around `new_with_options` with
        // the default (Reject) policy, so it must reject overflow.
        let module = build_module_with_overflow(u32::MAX, 0);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let err = Vm::new(module, &arena).err().expect("expected rejection");
        assert!(matches!(err, VmError::VerifyError(_)));
    }

    #[test]
    fn call_with_too_few_args_returns_typed_error() {
        // Reviewer reproduction: `fn main(a: Word, b: Word) -> Word { a + b }`
        // called with only one argument used to default `b` to
        // `Value::Unit`, which then failed at `a + b` with the
        // misleading message "cannot add Int and Unit". The call
        // now rejects the wrong arg count before any bytecode runs.
        let src = "fn main(a: Word, b: Word) -> Word { a + b }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let err = vm.call(&[Value::Int(1)]).expect_err("expected rejection");
        match err {
            VmError::TypeError(msg) => {
                assert!(msg.contains("expected 2"), "got: {}", msg);
                assert!(msg.contains("got 1"), "got: {}", msg);
            }
            other => panic!("expected TypeError, got {:?}", other),
        }
    }

    #[test]
    #[cfg(feature = "floats")]
    fn call_with_wrong_arg_type_returns_typed_error() {
        // The runtime validates each argument against the
        // parameter's declared type tag and rejects mismatches
        // before any bytecode runs.
        let src = "fn main(a: Word) -> Word { a + 1 }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let err = vm
            .call(&[Value::Float(1.5)])
            .expect_err("expected rejection");
        match err {
            VmError::TypeError(msg) => {
                assert!(msg.contains("expected Word"), "got: {}", msg);
                assert!(msg.contains("got Float"), "got: {}", msg);
            }
            other => panic!("expected TypeError, got {:?}", other),
        }
    }

    #[test]
    fn breakpoint_suspends_before_op_then_resumes() {
        let module = build_module("fn main() -> Word { 7 + 35 }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        vm.set_breakpoint(0, 0);
        assert_eq!(vm.breakpoint_count(), 1);
        match vm.call(&[]).expect("call") {
            VmState::BreakpointHit { chunk, op } => assert_eq!((chunk, op), (0, 0)),
            other => panic!("expected BreakpointHit, got {:?}", other),
        }
        // Resume runs the op at the breakpoint (no re-trigger) and
        // continues to completion.
        match vm.resume_from_breakpoint().expect("resume") {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected Finished(42), got {:?}", other),
        }
    }

    #[test]
    fn no_breakpoint_runs_straight_to_completion() {
        let module = build_module("fn main() -> Word { 7 + 35 }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected Finished(42), got {:?}", other),
        }
    }

    #[test]
    fn clear_breakpoint_disarms() {
        let module = build_module("fn main() -> Word { 7 + 35 }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        vm.set_breakpoint(0, 0);
        assert!(vm.clear_breakpoint(0, 0), "first clear removes it");
        assert!(!vm.clear_breakpoint(0, 0), "second clear is a no-op");
        assert_eq!(vm.breakpoint_count(), 0);
        match vm.call(&[]).expect("call") {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected Finished(42), got {:?}", other),
        }
    }

    #[test]
    fn resume_from_breakpoint_when_not_suspended_errors() {
        let module = build_module("fn main() -> Word { 7 + 35 }");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.resume_from_breakpoint() {
            Err(VmError::NotSuspended) => {}
            other => panic!("expected NotSuspended, got {:?}", other),
        }
    }

    #[test]
    #[cfg(feature = "floats")]
    fn resume_with_wrong_type_returns_typed_error() {
        // Reviewer reproduction: a loop with `x: Word` parameter
        // could be resumed with a Float without complaint. The
        // wrong type would then trip an arithmetic op at the
        // first use site. The runtime now validates the resume
        // value at the boundary.
        let src = "loop main(x: Word) -> Word { let z = yield x; z }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[Value::Int(11)]).expect("call") {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(11)),
            other => panic!("expected yield, got {:?}", other),
        }
        let err = vm
            .resume(Value::Float(1.5))
            .expect_err("expected rejection");
        match err {
            VmError::TypeError(msg) => {
                assert!(msg.contains("expected Word"), "got: {}", msg);
                assert!(msg.contains("got Float"), "got: {}", msg);
            }
            other => panic!("expected TypeError, got {:?}", other),
        }
    }

    #[test]
    fn premature_resume_returns_not_suspended() {
        // Reviewer reproduction: calling `resume` before `call`
        // previously surfaced as `InvalidBytecode("cannot resume:
        // VM not suspended")`, which conflated API misuse with
        // corrupt bytecode. The runtime now returns the dedicated
        // `VmError::NotSuspended` variant.
        let src = "loop main(x: Word) -> Word { let z = yield x; z }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let err = vm.resume(Value::Int(0)).expect_err("expected NotSuspended");
        match err {
            VmError::NotSuspended => {}
            other => panic!("expected NotSuspended, got {:?}", other),
        }
    }

    #[test]
    fn resume_after_finished_returns_not_suspended() {
        // After a Stream block reaches Finished (or any non-yielded
        // terminal state), the VM is no longer suspended and resume
        // must surface NotSuspended rather than InvalidBytecode.
        let src = "fn main() -> Word { 7 }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 7),
            other => panic!("expected Finished, got {:?}", other),
        }
        let err = vm.resume(Value::Int(0)).expect_err("expected NotSuspended");
        match err {
            VmError::NotSuspended => {}
            other => panic!("expected NotSuspended, got {:?}", other),
        }
    }

    #[test]
    #[cfg(feature = "floats")]
    fn untyped_param_inferred_rejects_wrong_type_at_call() {
        // `fn main(x) -> Word { x }` infers `x: Word`. The chunk's
        // param_types must carry that inferred tag so Vm::call
        // rejects a Float argument with a typed error rather than
        // silently accepting and tripping arithmetic later.
        let src = "fn main(x) -> Word { x }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[Value::Int(7)]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 7),
            other => panic!("expected Finished, got {:?}", other),
        }
        let err = vm.call(&[Value::Float(1.5)]).expect_err("expected reject");
        match err {
            VmError::TypeError(msg) => {
                assert!(msg.contains("expected Word"), "got: {}", msg);
                assert!(msg.contains("got Float"), "got: {}", msg);
            }
            other => panic!("expected TypeError, got {:?}", other),
        }
    }

    #[test]
    fn multiheaded_loop_main_executes() {
        // Two heads: the literal `0` head yields a constant; the
        // `x: Word` head yields the input. The runtime dispatches
        // per iteration and resumes correctly across the
        // Stream...Reset boundary.
        let src = "loop main(0) -> Word { yield 100 }\n\
                   loop main(x: Word) -> Word { let z = yield x; z }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[Value::Int(0)]).expect("call") {
            VmState::Yielded(Value::Int(v)) => assert_eq!(v, 100),
            other => panic!("expected Yielded(100), got {:?}", other),
        }
        // Resume to reach the Reset epilogue for the matched head.
        let _ = vm.resume(Value::Int(0));
        // Second iteration: input 7 takes the second head.
        match vm.call(&[Value::Int(7)]).expect("call") {
            VmState::Yielded(Value::Int(v)) => assert_eq!(v, 7),
            other => panic!("expected Yielded(7), got {:?}", other),
        }
    }

    #[test]
    fn data_segment_indexed_array_round_trip() {
        // A `data state { idx: [Word; 4] }` block compiles to four
        // consecutive slots. The script writes through indexed
        // assignment and reads through indexed access; the loop
        // accumulates a sum across the array.
        let src = "data state { items: [Word; 4] }\n\
                   fn main() -> Word {\n\
                       state.items[0] = 10;\n\
                       state.items[1] = 20;\n\
                       state.items[2] = 30;\n\
                       state.items[3] = 40;\n\
                       state.items[0] + state.items[3]\n\
                   }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        match vm.call_with_shared(&mut shared, &[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 50),
            other => panic!("unexpected state: {:?}", other),
        }
        // The slots were written through `Op::SetDataIndexed` into the host
        // buffer and persist there after the call returns.
        assert_eq!(vm.get_shared(&shared, 0).unwrap(), Value::Int(10));
        assert_eq!(vm.get_shared(&shared, 1).unwrap(), Value::Int(20));
        assert_eq!(vm.get_shared(&shared, 2).unwrap(), Value::Int(30));
        assert_eq!(vm.get_shared(&shared, 3).unwrap(), Value::Int(40));
    }

    #[test]
    fn data_segment_indexed_out_of_bounds_traps() {
        // An index past the declared length triggers a typed
        // `VmError::IndexOutOfBounds`. The compiler's single-level
        // path elides the explicit `BoundsCheck` and relies on
        // `Op::GetDataIndexed` to perform the check.
        let src = "data state { items: [Word; 3] }\n\
                   fn main() -> Word { state.items[5] }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        let err = vm
            .call_with_shared(&mut shared, &[])
            .expect_err("expected out-of-bounds trap");
        match err {
            VmError::IndexOutOfBounds(i, len) => {
                assert_eq!(i, 5);
                assert_eq!(len, 3);
            }
            other => panic!("expected IndexOutOfBounds, got {:?}", other),
        }
    }

    #[test]
    fn data_segment_indexed_multidim_round_trip() {
        // Nested arrays flatten to a single contiguous slab. The
        // compiler emits per-level `Op::BoundsCheck` followed by
        // stride arithmetic and a final `Op::GetDataIndexed` /
        // `Op::SetDataIndexed`. Both writes and reads round-trip.
        let src = "data state { grid: [[Word; 3]; 2] }\n\
                   fn main() -> Word {\n\
                       state.grid[0][0] = 1;\n\
                       state.grid[0][1] = 2;\n\
                       state.grid[0][2] = 3;\n\
                       state.grid[1][0] = 4;\n\
                       state.grid[1][1] = 5;\n\
                       state.grid[1][2] = 6;\n\
                       state.grid[1][2] - state.grid[0][0]\n\
                   }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        match vm.call_with_shared(&mut shared, &[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 5),
            other => panic!("unexpected state: {:?}", other),
        }
        // Slot layout walks the inner dimension first: grid[0][0],
        // grid[0][1], grid[0][2], grid[1][0], grid[1][1], grid[1][2].
        assert_eq!(vm.get_shared(&shared, 0).unwrap(), Value::Int(1));
        assert_eq!(vm.get_shared(&shared, 3).unwrap(), Value::Int(4));
        assert_eq!(vm.get_shared(&shared, 5).unwrap(), Value::Int(6));
    }

    #[test]
    fn data_segment_multidim_inner_bounds_check_traps() {
        // A multi-dimensional access whose inner index exceeds the
        // inner dimension length must trap even when the
        // mathematically computed flat offset stays inside the
        // total slab. Without a per-level `BoundsCheck` the access
        // would silently land on a different "row".
        let src = "data state { grid: [[Word; 3]; 2] }\n\
                   fn main() -> Word { state.grid[0][5] }";
        let module = build_module(src);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        let mut shared = vec![0u8; vm.shared_data_bytes()];
        let err = vm
            .call_with_shared(&mut shared, &[])
            .expect_err("expected inner-bound trap");
        match err {
            VmError::IndexOutOfBounds(i, len) => {
                assert_eq!(i, 5);
                assert_eq!(len, 3);
            }
            other => panic!("expected IndexOutOfBounds, got {:?}", other),
        }
    }

    // --- Data partition (shared vs private) and ephemeral flag ---

    #[test]
    fn shared_data_byte_count_in_header() {
        let src = "\
            data ctx { a: Word, b: Word }\n\
            fn main() -> Word { ctx.a + ctx.b }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        // Two shared `Word` fields laid out flat at the module's word width
        // (B28 item 2: `shared_data_bytes` is the borrowed host buffer's flat
        // size, not a slot-count-scaled figure). Computed from the module's
        // declared width so it holds on narrow-word builds too.
        let wb = (1u32 << module.word_bits_log2) / 8;
        assert_eq!(module.shared_data_bytes, 2 * wb);
        assert_eq!(module.private_data_bytes, 0);
    }

    #[test]
    fn private_data_byte_count_in_header() {
        // Private data must be mutated to satisfy the unmutated-
        // private rejection rule introduced in phase 6.
        let src = "\
            private data state { counter: Word }\n\
            fn main() -> Word { state.counter = 1; state.counter }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert_eq!(module.shared_data_bytes, 0);
        assert_eq!(
            module.private_data_bytes,
            crate::bytecode::VALUE_SLOT_SIZE_BYTES
        );
    }

    #[test]
    fn mixed_data_partitions_correctly() {
        let src = "\
            data shared_ctx { x: Word }\n\
            private data priv_ctx { y: Word, z: Word }\n\
            fn main() -> Word { priv_ctx.y = 1; priv_ctx.z = 2; shared_ctx.x + priv_ctx.y + priv_ctx.z }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        // One shared `Word` field, flat-sized at the module word width (B28
        // item 2). Private stays slot-scaled.
        let wb = (1u32 << module.word_bits_log2) / 8;
        assert_eq!(module.shared_data_bytes, wb);
        assert_eq!(
            module.private_data_bytes,
            2 * crate::bytecode::VALUE_SLOT_SIZE_BYTES
        );
    }

    #[test]
    fn ephemeral_bit_set_for_atomic_total_no_data() {
        let src = "fn main() -> Word { 42 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert!(
            module.flags & crate::bytecode::FLAG_EPHEMERAL != 0,
            "expected FLAG_EPHEMERAL bit set, got flags = {:#04x}",
            module.flags
        );
    }

    #[test]
    fn ephemeral_bit_clear_when_private_data_present() {
        let src = "\
            private data state { counter: Word }\n\
            fn main() -> Word { state.counter = state.counter + 1; state.counter }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert!(
            module.flags & crate::bytecode::FLAG_EPHEMERAL == 0,
            "expected FLAG_EPHEMERAL cleared for module with private data; flags = {:#04x}",
            module.flags
        );
    }

    #[test]
    fn explicit_ephemeral_modifier_accepted_when_proof_holds() {
        let src = "ephemeral fn main() -> Word { 0 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile accepts ephemeral main");
        assert!(module.flags & crate::bytecode::FLAG_EPHEMERAL != 0);
    }

    #[test]
    fn private_slots_round_trip_through_arena() {
        // Construct a module with one private slot. Write the
        // slot from the script, then read it back. The value
        // lives in the arena's persistent region; this test
        // confirms the arena routing works end to end.
        let src = "\
            private data state { counter: Word }\n\
            fn main() -> Word {\n\
                state.counter = 42;\n\
                state.counter\n\
            }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let mut arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        arena
            .resize_persistent(required_persistent_capacity_for(&module))
            .expect("resize persistent");
        assert_eq!(arena.persistent_capacity(), core::mem::size_of::<Value>());
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected Finished(42), got {:?}", other),
        }
    }

    #[test]
    fn vm_new_rejects_insufficient_persistent_capacity() {
        // The arena has zero persistent capacity. The module
        // declares private data. `Vm::new` rejects with a
        // helpful message.
        let src = "\
            private data state { x: Word }\n\
            fn main() -> Word { state.x = 1; state.x }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // Note: no resize_persistent call. Default persistent
        // capacity is 0.
        let err = match Vm::new(module, &arena) {
            Ok(_) => panic!("Vm::new should have rejected the module"),
            Err(e) => e,
        };
        match err {
            VmError::VerifyError(msg) => {
                assert!(
                    msg.contains("persistent_capacity") && msg.contains("private"),
                    "unexpected error message: {}",
                    msg
                );
            }
            other => panic!("expected VerifyError, got {:?}", other),
        }
    }

    #[test]
    fn vm_drop_runs_destructors_on_private_slots() {
        // Sanity check: dropping a VM with multiple private
        // slots iterates them all without overrunning the slot
        // count. The slots hold `Value::Unit` (the default
        // initialisation), whose Drop is a no-op; the test
        // exercises the iteration bound, not the destructor
        // body. A bug that miscomputed the slot count would
        // either UAF or leak; this test does neither, which is
        // the implicit assertion.
        let src = "\
            private data state { a: Word, b: Word, c: Word }\n\
            fn main() -> Word { state.a = 1; state.b = 2; state.c = 3; 0 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let mut arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        arena
            .resize_persistent(required_persistent_capacity_for(&module))
            .expect("resize persistent");
        {
            let vm = Vm::new(module, &arena).expect("verify");
            assert_eq!(vm.data_len(), 3);
            // Drop happens at end of scope.
            drop(vm);
        }
    }

    #[test]
    fn ephemeral_bit_set_when_text_param_is_unused() {
        // A `Text` parameter that the body never references
        // cannot carry arena-resident data across the
        // host-VM boundary. The verifier admits the module as
        // ephemeral. This is the parameter-usage refinement of
        // the dialogue-type rule.
        let src = "fn main(unused_name: Text) -> Word { 42 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert!(
            module.flags & crate::bytecode::FLAG_EPHEMERAL != 0,
            "expected FLAG_EPHEMERAL set; unused Text param should not disqualify, flags = {:#04x}",
            module.flags
        );
    }

    #[test]
    fn ephemeral_bit_set_when_declared_text_return_never_produced() {
        // The entry's declared return type carries `Text` through
        // `Option<Text>`, but every concrete return path produces
        // `Option::None` (a non-text discriminant). The per-yield
        // arena dataflow refinement walks the compiled chunk in
        // topological call order, observes that `Op::Return` peeks a
        // non-text value, and admits the module as ephemeral despite
        // the declared signature. The previous signature-only rule
        // would have disqualified this program even though it never
        // crosses the host-VM boundary with an arena-resident string.
        //
        // The test exercises both the per-yield dataflow refinement
        // and the type-checker tightening that admits bare
        // `Option::None` in a function-return position by unifying
        // its inner type with the declared return type.
        let src = "fn main() -> Option<Text> { Option::None }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert!(
            module.flags & crate::bytecode::FLAG_EPHEMERAL != 0,
            "expected FLAG_EPHEMERAL set; declared Text return with no concrete text path should not disqualify, flags = {:#04x}",
            module.flags
        );
    }

    #[test]
    fn ephemeral_bit_clear_when_declared_text_return_actually_produced() {
        // The entry's declared return type is `Text` and the body
        // actually produces a text value at the return site. The
        // dataflow refinement confirms the boundary-crossing op
        // peeks a text value, so the module is correctly disqualified
        // from ephemerality. This is a regression guard that the
        // refinement does not become permissive in cases where the
        // conservative rule already disqualified.
        let src = "fn main() -> Text { \"hello\" }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert!(
            module.flags & crate::bytecode::FLAG_EPHEMERAL == 0,
            "expected FLAG_EPHEMERAL clear; declared Text return with actual text path must disqualify, flags = {:#04x}",
            module.flags
        );
    }

    #[test]
    #[cfg(feature = "verify")]
    fn module_chunk_text_analyses_distinguishes_yield_and_return() {
        // Direct unit test of the per-yield dataflow analysis. The
        // analysis must peek at the value being yielded or returned
        // and report `yields_text`/`returns_text` accordingly.
        //
        // The source-level positive test for the ephemerality
        // refinement is blocked by an unrelated type-unification
        // limitation around bare `Option::None` literals in function
        // returns. This test exercises the analysis directly against
        // hand-crafted chunks so that the dataflow path stays under
        // automated coverage even when the surface language cannot
        // express the relevant program.
        use crate::bytecode::{BlockType, Chunk, ConstValue, Module, Op};

        let mut text_returning_chunk = Chunk {
            name: alloc::string::String::from("text_return"),
            ops: alloc::vec![Op::Const(0), Op::Return],
            constants: alloc::vec![ConstValue::StaticStr(alloc::string::String::from("hi"))],
            struct_templates: alloc::vec::Vec::new(),
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec::Vec::new(),
            debug_pool: None,
        };
        // Suppress the compiler's per-chunk field defaults that may
        // differ across builds. Module-level fields below are also
        // populated explicitly for determinism.
        text_returning_chunk.ops.shrink_to_fit();

        let int_returning_chunk = Chunk {
            name: alloc::string::String::from("int_return"),
            ops: alloc::vec![Op::Const(0), Op::Return],
            constants: alloc::vec![ConstValue::Int(0)],
            struct_templates: alloc::vec::Vec::new(),
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Func,
            param_types: alloc::vec::Vec::new(),
            debug_pool: None,
        };

        let module = Module {
            schema_hash: 0,
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            chunks: alloc::vec![text_returning_chunk, int_returning_chunk],
            native_names: alloc::vec::Vec::new(),
            entry_point: Some(0),
            data_layout: None,
            word_bits_log2: 6,
            addr_bits_log2: 5,
            float_bits_log2: 6,
            shared_data_bytes: 0,
            private_data_bytes: 0,
            flags: 0,
            wcet_cycles: 0,
            wcmu_bytes: 0,
            aux_arena_bytes: 0,
            persistent_composite_bytes: 0,
        };

        let analyses = crate::verify::module_chunk_text_analyses(&module).expect("analyse");
        assert_eq!(analyses.len(), 2);
        assert!(
            analyses[0].returns_text,
            "chunk 0 returns a static string and must be flagged returns_text"
        );
        assert!(
            !analyses[1].returns_text,
            "chunk 1 returns an integer and must not be flagged returns_text"
        );
        assert!(
            !analyses[0].yields_text && !analyses[1].yields_text,
            "neither chunk contains Op::Yield"
        );
    }

    #[test]
    fn ephemeral_bit_clear_when_text_param_is_used() {
        // The same shape but the body actually references the
        // Text param. The verifier conservatively assumes the
        // param could flow back to the host through a yield or
        // return and disqualifies the module from ephemerality.
        // The body returns 0 unconditionally; the only purpose
        // of referencing `name` is to mark it as used.
        let src = "fn main(name: Text) -> Word { let _ignored = name; 0 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert!(
            module.flags & crate::bytecode::FLAG_EPHEMERAL == 0,
            "expected FLAG_EPHEMERAL clear; used Text param must disqualify, flags = {:#04x}",
            module.flags
        );
    }

    #[test]
    fn const_data_struct_initializer() {
        // Struct-typed const data field with a struct literal
        // initializer. The struct is declared elsewhere; the
        // const field references it by name.
        let src = "\
            struct Point { x: Word, y: Word }\n\
            const data origin {\n\
                pt: Point = Point { x: 3, y: 4 },\n\
            }\n\
            fn main() -> Word { origin.pt.x + origin.pt.y }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 7),
            other => panic!("expected Int(7), got {:?}", other),
        }
    }

    #[test]
    fn const_data_enum_initializer() {
        // Enum-typed const data field with a variant
        // construction initializer. Tests both unit and tuple-
        // payload variants through a Word cast.
        let src = "\
            enum Color { Red = 1, Green = 2, Blue = 3 }\n\
            const data palette {\n\
                primary: Color = Color::Red,\n\
            }\n\
            fn main() -> Word { palette.primary as Word }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 1),
            other => panic!("expected Int(1), got {:?}", other),
        }
    }

    #[test]
    fn const_data_enum_tuple_variant_initializer() {
        let src = "\
            enum Shape { Square(Word), Rect(Word, Word) }\n\
            const data shapes {\n\
                a: Shape = Shape::Rect(4, 5),\n\
            }\n\
            fn main() -> Word {\n\
                match shapes.a {\n\
                    Shape::Rect(w, h) => w * h,\n\
                    Shape::Square(s) => s * s,\n\
                }\n\
            }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 20),
            other => panic!("expected Int(20), got {:?}", other),
        }
    }

    #[test]
    fn const_data_tuple_initializer() {
        // Tuple-typed const data field with a tuple initializer.
        let src = "\
            const data pt {\n\
                origin: (Word, Word) = (3, 4),\n\
            }\n\
            fn main() -> Word { pt.origin.0 + pt.origin.1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 7),
            other => panic!("expected Int(7), got {:?}", other),
        }
    }

    #[test]
    fn const_data_array_initializer() {
        // Array-typed const data field with an array initializer.
        let src = "\
            const data lut {\n\
                table: [Word; 3] = [10, 20, 30],\n\
            }\n\
            fn main() -> Word { lut.table[0] + lut.table[1] + lut.table[2] }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 60),
            other => panic!("expected Int(60), got {:?}", other),
        }
    }

    #[test]
    fn const_composite_pools_a_scalar_composite() {
        // A transitively-scalar const composite is pooled off-arena, so
        // `const_pool_bytes` reports a non-empty flat body (its exact size is
        // two `Word`s, which is width-dependent, so the assertion checks only
        // that the scalar composite was pooled, not a fixed byte count). The
        // field reads still resolve through the pooled `Arena` handle (B28 P3
        // item 2, Increment 2).
        let src = "\
            struct Point { x: Word, y: Word }\n\
            const data origin {\n\
                pt: Point = Point { x: 3, y: 4 },\n\
            }\n\
            fn main() -> Word { origin.pt.x + origin.pt.y }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        assert!(
            vm.const_pool_bytes() > 0,
            "expected the scalar const struct to be pooled, got {} bytes",
            vm.const_pool_bytes()
        );
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 7),
            other => panic!("expected Int(7), got {:?}", other),
        }
    }

    #[test]
    fn const_composite_pool_empty_without_composites() {
        // A scalar const field bakes a scalar constant, not a composite, so
        // nothing is pooled and the off-arena pool reports zero bytes (B28 P3
        // item 2, Increment 2).
        let src = "\
            const data c {\n\
                n: Word = 42,\n\
            }\n\
            fn main() -> Word { c.n }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        assert_eq!(vm.const_pool_bytes(), 0);
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 42),
            other => panic!("expected Int(42), got {:?}", other),
        }
    }

    #[test]
    fn const_composite_survives_reset() {
        // The pooled const body lives outside the arena for the VM's
        // lifetime, so a stream that reads a const composite field on every
        // iteration reads it correctly after a RESET, when the arena's
        // ephemeral region has been reclaimed (B28 P3 item 2, Increment 2).
        let src = "\
            struct Point { x: Word, y: Word }\n\
            const data origin {\n\
                pt: Point = Point { x: 3, y: 4 },\n\
            }\n\
            loop main(tick: Word) -> Word {\n\
                let next = yield origin.pt.x + origin.pt.y;\n\
                next\n\
            }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");

        // Iteration 1: read the const composite, yield 3 + 4 = 7.
        match vm.call(&[Value::Int(0)]).expect("call") {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(7)),
            other => panic!("expected yield 7, got {:?}", other),
        }
        // Resume drives the stream to its RESET, reclaiming the ephemeral
        // arena region. The pooled const body is off-arena and untouched.
        match vm.resume(Value::Int(0)).expect("resume") {
            VmState::Reset => {}
            other => panic!("expected reset, got {:?}", other),
        }
        // Iteration 2 restarts the stream and re-reads the const composite
        // after the RESET, proving the pooled handle stays live.
        match vm.resume(Value::Int(0)).expect("resume") {
            VmState::Yielded(v) => assert_eq!(v, Value::Int(7)),
            other => panic!("expected yield 7 after reset, got {:?}", other),
        }
    }

    #[test]
    fn const_composite_pool_rebuilt_on_hot_swap() {
        // A hot swap rebuilds the const pool for the new module. The retired
        // module's pooled body is freed and the swapped-in module's const
        // composite reads correctly through its own freshly-pooled handle
        // (B28 P3 item 2, Increment 2).
        let src_a = "\
            struct P { x: Word, y: Word }\n\
            const data o {\n\
                p: P = P { x: 3, y: 4 },\n\
            }\n\
            fn main() -> Word { o.p.x + o.p.y }";
        let src_b = "\
            struct P { x: Word, y: Word }\n\
            const data o {\n\
                p: P = P { x: 10, y: 20 },\n\
            }\n\
            fn main() -> Word { o.p.x + o.p.y }";
        let mod_a = build_module(src_a);
        let mod_b = build_module(src_b);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(mod_a, &arena).unwrap();
        assert!(vm.const_pool_bytes() > 0);
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(7)),
            other => panic!("expected Int(7), got {:?}", other),
        }

        vm.replace_module(mod_b, alloc::vec![]).unwrap();
        assert!(vm.const_pool_bytes() > 0);
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(30)),
            other => panic!("expected Int(30) after swap, got {:?}", other),
        }
    }

    #[test]
    fn const_data_array_length_mismatch_rejected() {
        let src = "\
            const data lut {\n\
                table: [Word; 5] = [1, 2, 3],\n\
            }\n\
            fn main() -> Word { lut.table[0] }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("3 element") && err.message.contains("expected 5"),
            "unexpected error: {}",
            err.message
        );
    }

    #[test]
    fn const_data_field_compiles_to_constant_load() {
        // `const data` fields bake their initializer into the
        // per-chunk constant pool. The runtime reads them through
        // `Op::Const`; no data-segment slot is allocated.
        let src = "\
            const data palette {\n\
                red: Byte = 255,\n\
                green: Byte = 128,\n\
            }\n\
            fn main() -> Byte { palette.red }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        // No runtime slots for const data; byte counts stay zero.
        assert_eq!(module.shared_data_bytes, 0);
        assert_eq!(module.private_data_bytes, 0);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");
        match vm.call(&[]).expect("call") {
            VmState::Finished(Value::Byte(b)) => assert_eq!(b, 255),
            other => panic!("expected Byte(255), got {:?}", other),
        }
    }

    #[test]
    fn const_data_field_write_rejected() {
        let src = "\
            const data k { v: Word = 7 }\n\
            fn main() -> Word { k.v = 9; k.v }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("const data") && err.message.contains("immutable"),
            "unexpected error: {}",
            err.message
        );
    }

    #[test]
    fn const_data_missing_initializer_rejected() {
        let src = "\
            const data k { v: Word }\n\
            fn main() -> Word { k.v }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("initializer"),
            "unexpected error: {}",
            err.message
        );
    }

    #[test]
    fn shared_data_initializer_rejected() {
        let src = "\
            data ctx { x: Word = 5 }\n\
            fn main() -> Word { ctx.x }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("initializer") && err.message.contains("const data"),
            "unexpected error: {}",
            err.message
        );
    }

    #[test]
    fn three_data_blocks_one_each_visibility_accepted() {
        let src = "\
            data shared_ctx { a: Word }\n\
            private data priv_ctx { b: Word }\n\
            const data const_ctx { c: Word = 42 }\n\
            fn main() -> Word { priv_ctx.b = 1; shared_ctx.a + priv_ctx.b + const_ctx.c }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        // One shared `Word` field, flat-sized at the module word width (B28
        // item 2). Private stays slot-scaled.
        let wb = (1u32 << module.word_bits_log2) / 8;
        assert_eq!(module.shared_data_bytes, wb);
        assert_eq!(
            module.private_data_bytes,
            crate::bytecode::VALUE_SLOT_SIZE_BYTES
        );
    }

    #[test]
    fn shared_layout_table_in_module_and_wire() {
        // The shared data segment carries a per-slot layout table (B28 item 2,
        // the no-new-opcode mechanism): a scalar slot records its byte offset
        // and `ScalarKind` tag; a composite slot records its offset and flat
        // body length with the composite marker. The table survives the wire
        // roundtrip. No opcodes are added.
        let src = "\
            data ctx { a: Word, pair: (Word, Word) }\n\
            fn main() -> Word { ctx.a + ctx.pair.0 + ctx.pair.1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let wb = (1u32 << module.word_bits_log2) / 8;
        let dl = module.data_layout.as_ref().expect("data layout");
        assert_eq!(dl.shared_layout.len(), 2, "one entry per shared slot");
        // Slot 0: scalar `Word` at offset 0, kind tag 3 (Int), no body length.
        assert_eq!(dl.shared_layout[0].offset, 0);
        assert_eq!(
            dl.shared_layout[0].kind,
            crate::value_layout::ScalarKind::Int.to_tag()
        );
        assert_eq!(dl.shared_layout[0].len, 0);
        // Slot 1: composite `(Word, Word)` at offset `wb`, body `2*wb` bytes,
        // tagged as a tuple via the composite flag plus the CompositeKind tag.
        assert_eq!(dl.shared_layout[1].offset as u32, wb);
        assert_eq!(
            dl.shared_layout[1].kind,
            crate::bytecode::SHARED_SLOT_COMPOSITE_FLAG
                | crate::value_layout::CompositeKind::Tuple.to_tag()
        );
        assert_eq!(dl.shared_layout[1].len as u32, 2 * wb);
        assert_eq!(module.shared_data_bytes, 3 * wb);
        // Wire roundtrip preserves the table.
        let bytes = module.to_bytes().expect("to_bytes");
        let decoded = crate::bytecode::Module::from_bytes(&bytes).expect("from_bytes");
        assert_eq!(
            decoded.data_layout.as_ref().unwrap().shared_layout,
            dl.shared_layout
        );
    }

    #[test]
    fn shared_data_text_field_rejected() {
        // A reference-typed shared field cannot live in the flat host buffer
        // (B28 item 2). `Text` in shared data is rejected at compile time.
        let src = "\
            data ctx { label: Text }\n\
            fn main() -> Word { 0 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("shared Text must be rejected");
        assert!(
            err.message.contains("Text") || err.message.contains("reference"),
            "unexpected error: {}",
            err.message
        );
    }

    // Bundled runtime only: the test writes raw width-specific bytes into the
    // host buffer, so the byte offsets assume an eight-byte word.
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32",
        feature = "narrow-float-32"
    )))]
    #[test]
    fn shared_data_read_write_through_host_buffer() {
        // The host lends a byte buffer; the script reads and writes shared
        // fields in place through it, including a composite read that copies
        // out of the buffer, and the host owns the buffer across calls (B28
        // item 2, step 3b).
        let src = "\
            data ctx { hp: Word, pos: (Word, Word) }\n\
            fn main() -> Word { ctx.hp = ctx.hp + 100; ctx.hp + ctx.pos.0 + ctx.pos.1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let sdb = module.shared_data_bytes as usize;
        assert_eq!(sdb, 3 * core::mem::size_of::<i64>(), "hp + a two-word pos");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");

        // Host-owned buffer: hp=10 at offset 0, pos=(3,4) at offsets 8 and 16.
        let mut buf = alloc::vec![0u8; sdb];
        buf[0..8].copy_from_slice(&10i64.to_le_bytes());
        buf[8..16].copy_from_slice(&3i64.to_le_bytes());
        buf[16..24].copy_from_slice(&4i64.to_le_bytes());

        // hp becomes 110 (written in place); returns 110 + 3 + 4 = 117.
        match vm.call_with_shared(&mut buf, &[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 117),
            other => panic!("expected Int(117), got {:?}", other),
        }
        assert_eq!(
            i64::from_le_bytes(buf[0..8].try_into().unwrap()),
            110,
            "the write reached the host buffer in place"
        );

        // The host owns the buffer across calls: a second call accumulates hp.
        match vm.call_with_shared(&mut buf, &[]).expect("call 2") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 217),
            other => panic!("expected Int(217), got {:?}", other),
        }
        assert_eq!(i64::from_le_bytes(buf[0..8].try_into().unwrap()), 210);

        // A wrong-size buffer is rejected, not silently misread.
        let mut wrong = alloc::vec![0u8; sdb - 1];
        assert!(vm.call_with_shared(&mut wrong, &[]).is_err());
    }

    // Bundled runtime only (raw width-specific bytes; see the read/write test).
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32",
        feature = "narrow-float-32"
    )))]
    #[test]
    fn shared_data_composite_write_through_host_buffer() {
        // Writing a composite shared field copies its flat bytes into the host
        // buffer (the copy-in path); reading it back copies out (B28 item 2,
        // step 3b).
        let src = "\
            data ctx { pos: (Word, Word) }\n\
            fn main() -> Word { ctx.pos = (7, 8); ctx.pos.0 + ctx.pos.1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let sdb = module.shared_data_bytes as usize;
        assert_eq!(sdb, 2 * core::mem::size_of::<i64>());
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("verify");

        let mut buf = alloc::vec![0u8; sdb];
        match vm.call_with_shared(&mut buf, &[]).expect("call") {
            VmState::Finished(Value::Int(v)) => assert_eq!(v, 15),
            other => panic!("expected Int(15), got {:?}", other),
        }
        // The composite write reached the host buffer in place.
        assert_eq!(i64::from_le_bytes(buf[0..8].try_into().unwrap()), 7);
        assert_eq!(i64::from_le_bytes(buf[8..16].try_into().unwrap()), 8);
    }

    // Bundled runtime only (raw width-specific bytes; see the read/write test).
    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32",
        feature = "narrow-float-32"
    )))]
    #[test]
    fn host_get_set_shared_round_trips_scalar_fields() {
        // The host-side per-slot accessors read and write scalar shared fields
        // through a host-owned buffer between runs (B28 item 2, step 4),
        // replacing the retired set_data / get_data for the buffer model.
        let src = "\
            data ctx { hp: Word, pos: (Word, Word) }\n\
            fn main() -> Word { ctx.hp + ctx.pos.0 + ctx.pos.1 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let sdb = module.shared_data_bytes as usize;
        assert_eq!(crate::vm::shared_data_bytes_for(&module), sdb);
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let vm = Vm::new(module, &arena).expect("verify");
        assert_eq!(vm.shared_data_bytes(), sdb);

        // Slot 0 is the scalar hp; set it through the host accessor.
        let mut buf = alloc::vec![0u8; sdb];
        vm.set_shared(&mut buf, 0, Value::Int(42)).expect("set hp");
        assert_eq!(i64::from_le_bytes(buf[0..8].try_into().unwrap()), 42);
        match vm.get_shared(&buf, 0).expect("get hp") {
            Value::Int(v) => assert_eq!(v, 42),
            other => panic!("expected Int(42), got {:?}", other),
        }

        // The composite pos slot is rejected through the per-slot host API.
        assert!(
            vm.get_shared(&buf, 1).is_err(),
            "a composite shared slot is not a per-slot host scalar"
        );
        assert!(vm.set_shared(&mut buf, 1, Value::Int(0)).is_err());

        // An out-of-range slot and a wrong-size buffer are both rejected.
        // The module declares two shared slots (hp at 0, pos at 1), so any
        // larger index is out of range.
        assert!(vm.get_shared(&buf, 99).is_err());
        let short = alloc::vec![0u8; sdb - 1];
        assert!(vm.get_shared(&short, 0).is_err());
    }

    #[test]
    fn private_data_never_mutated_rejected() {
        // The verifier rejects a private data block whose
        // slots are never written. The diagnostic suggests
        // `const data` as the rewrite.
        let src = "\
            private data state { x: Word }\n\
            fn main() -> Word { state.x }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("never mutated") && err.message.contains("const data"),
            "unexpected error: {}",
            err.message
        );
    }

    #[test]
    fn explicit_ephemeral_modifier_rejected_when_private_data_present() {
        let src = "\
            private data state { x: Word }\n\
            ephemeral fn main() -> Word { state.x = 1; state.x }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("ephemeral") && err.message.contains("private data"),
            "unexpected error message: {}",
            err.message
        );
    }

    // The `with saturate_max = N, saturate_min = M` clause on a refined
    // newtype declaration defines context-determined values for the
    // `saturate_max` and `saturate_min` keywords. When the surrounding
    // expected type is the refined newtype, the keywords resolve to a
    // constructor call wrapping the declared literal. When the
    // surrounding expected type is the underlying primitive, the
    // keywords retain the legacy behaviour of evaluating to
    // `Word::MAX` / `Word::MIN`.
    #[test]
    fn saturate_keywords_resolve_to_newtype_contract_via_function_return() {
        // The function's declared return type drives the resolution.
        // The overflow path produces the declared `saturate_max` value
        // (100), wrapped by the `Limited` constructor. The refinement
        // predicate `nonneg` is satisfied at runtime because 100 >= 0.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Limited = Word where nonneg with saturate_max = 100, saturate_min = 0;\n\
             fn main() -> Limited {\n\
                let m = 9223372036854775807;\n\
                m + 1 {\n\
                    ok(v) => Limited(v),\n\
                    overflow(_, _) => saturate_max,\n\
                    underflow(_, _) => saturate_min,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(100));
    }

    #[cfg(not(any(
        feature = "narrow-word-8",
        feature = "narrow-word-16",
        feature = "narrow-word-32"
    )))]
    #[test]
    fn saturate_keywords_resolve_to_newtype_contract_via_let_annotation() {
        // The `let y: Limited = ...` annotation pushes `Limited` onto
        // the expected-type stack so the underflow arm's `saturate_min`
        // resolves to 0 (the declared contract).
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Limited = Word where nonneg with saturate_max = 100, saturate_min = 0;\n\
             fn main() -> Word {\n\
                let m = 0 - 9223372036854775807;\n\
                let y: Limited = m - 2 {\n\
                    ok(v) => Limited(v),\n\
                    overflow(_, _) => saturate_max,\n\
                    underflow(_, _) => saturate_min,\n\
                };\n\
                y as Word\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(0));
    }

    #[test]
    fn saturate_keywords_fall_back_to_word_extrema_without_newtype_context() {
        // The function return type is `Word`, so the saturate keywords
        // retain the legacy semantics: `saturate_max` evaluates to
        // `Word::MAX`, not any newtype's declared contract.
        let val = run_expect(
            "fn nonneg(x: Word) -> bool { x >= 0 }\n\
             newtype Limited = Word where nonneg with saturate_max = 100, saturate_min = 0;\n\
             fn main() -> Word {\n\
                let m = 9223372036854775807;\n\
                let y = m + 1 {\n\
                    ok(v) => v,\n\
                    overflow(_, _) => saturate_max,\n\
                    underflow(_, _) => saturate_min,\n\
                };\n\
                y\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(i64::MAX));
    }

    // Match-arm guard tests. A guard is an optional `when expr`
    // clause between the pattern and the `=>`; the arm fires only
    // when the pattern matches *and* the guard evaluates to true.
    // The exhaustiveness check treats guarded arms as non-catch-all
    // regardless of pattern shape.
    #[test]
    fn match_arm_guard_dispatches_on_runtime_predicate() {
        // Three arms differing only in guard select the correct
        // branch based on the bound value at runtime.
        let val = run_expect(
            "fn classify(n: Word) -> Word {\n\
                match n {\n\
                    v when v < 0 => 0 - 1,\n\
                    v when v == 0 => 0,\n\
                    v => 1,\n\
                }\n\
             }\n\
             fn main() -> Word { classify(0) + classify(5) + classify(0 - 3) }",
            &[],
        );
        assert_eq!(val, Value::Int(1 - 1));
    }

    #[test]
    fn match_arm_guard_falls_through_to_next_arm_when_false() {
        // The first arm's pattern matches but its guard returns
        // false; dispatch falls through to the unguarded catch-all.
        let val = run_expect(
            "fn main() -> Word {\n\
                match 5 {\n\
                    v when v > 10 => 999,\n\
                    v => v,\n\
                }\n\
             }",
            &[],
        );
        assert_eq!(val, Value::Int(5));
    }

    #[test]
    fn match_arm_guarded_pattern_is_not_a_catchall() {
        // A guarded bare-variable arm does not satisfy the
        // exhaustiveness requirement for a bool scrutinee.
        let src = "fn main() -> Word {\n\
                match true {\n\
                    v when v == true => 1,\n\
                }\n\
             }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("non-exhaustive"),
            "expected non-exhaustive diagnostic, got: {}",
            err.message
        );
    }

    // The narrow-bytecode CheckedXxx tests directly exercise
    // `checked_arith_outputs` at every supported declared word
    // width to confirm that the `(low, high, flag)` triple is
    // computed at the bytecode-declared width rather than the
    // runtime width. This addresses the unresolved concern
    // documented in REVERSE_PROMPT for V0.2.0 Phase 8.

    #[test]
    fn checked_arith_outputs_runtime_width_in_range() {
        // Declared width matches the runtime: `100 + 50 = 150`
        // fits in i64, so flag = 0, high = 0, low = 150.
        let r: i128 = 100i64.widen() + 50i64.widen();
        let (low, high, flag) = super::checked_arith_outputs::<i64>(r, 6);
        assert_eq!(low, 150);
        assert_eq!(high, 0);
        assert_eq!(flag, 0);
    }

    #[test]
    fn checked_arith_outputs_runtime_width_overflow() {
        // `i64::MAX + 1` overflows the runtime range; flag = 1,
        // low wraps to `i64::MIN`, high carries the i128 high
        // half (zero in this case because the result fits in 65
        // bits but is positive).
        let r: i128 = i64::MAX.widen() + 1i64.widen();
        let (low, high, flag) = super::checked_arith_outputs::<i64>(r, 6);
        assert_eq!(low, i64::MIN);
        assert_eq!(high, 0);
        assert_eq!(flag, 1);
    }

    #[test]
    fn checked_arith_outputs_runtime_width_underflow() {
        // `i64::MIN + i64::MIN` underflows; flag = 2.
        let r: i128 = i64::MIN.widen() + i64::MIN.widen();
        let (_low, high, flag) = super::checked_arith_outputs::<i64>(r, 6);
        // High half: -2 * 2^63 == -(2^64), shifted right by 64
        // is -1.
        assert_eq!(high, -1);
        assert_eq!(flag, 2);
    }

    #[test]
    fn checked_arith_outputs_narrow_declared_32_in_range() {
        // Declared 32-bit on a 64-bit runtime: a value that fits
        // i32 reports flag = 0, low = the value sign-extended at
        // 32, high = 0.
        let r: i128 = (i32::MAX as i64).widen() + 0i64.widen();
        let (low, high, flag) = super::checked_arith_outputs::<i64>(r, 5);
        assert_eq!(low, i32::MAX as i64);
        assert_eq!(high, 0);
        assert_eq!(flag, 0);
    }

    #[test]
    fn checked_arith_outputs_narrow_declared_32_overflow() {
        // `i32::MAX + 1` overflows the declared 32-bit range.
        // Flag = 1; the low half is `i32::MIN` (the truncated
        // sign-extended value); the high half is 1.
        let r: i128 = (i32::MAX as i64).widen() + 1i64.widen();
        let (low, high, flag) = super::checked_arith_outputs::<i64>(r, 5);
        assert_eq!(low, i32::MIN as i64);
        assert_eq!(high, 1);
        assert_eq!(flag, 1);
    }

    #[test]
    fn checked_arith_outputs_narrow_declared_32_underflow() {
        // `i32::MIN - 1` underflows the declared 32-bit range.
        // Flag = 2; low half is `i32::MAX`; high half is -1.
        let r: i128 = (i32::MIN as i64).widen() - 1i64.widen();
        let (low, high, flag) = super::checked_arith_outputs::<i64>(r, 5);
        assert_eq!(low, i32::MAX as i64);
        assert_eq!(high, -1);
        assert_eq!(flag, 2);
    }

    #[test]
    fn checked_arith_outputs_narrow_declared_16_overflow() {
        // `i16::MAX + 1` overflows the declared 16-bit range.
        let r: i128 = (i16::MAX as i64).widen() + 1i64.widen();
        let (low, high, flag) = super::checked_arith_outputs::<i64>(r, 4);
        assert_eq!(low, i16::MIN as i64);
        assert_eq!(high, 1);
        assert_eq!(flag, 1);
    }

    #[test]
    fn checked_arith_outputs_narrow_declared_8_underflow() {
        // `i8::MIN - 1` underflows the declared 8-bit range.
        let r: i128 = (i8::MIN as i64).widen() - 1i64.widen();
        let (low, high, flag) = super::checked_arith_outputs::<i64>(r, 3);
        assert_eq!(low, i8::MAX as i64);
        assert_eq!(high, -1);
        assert_eq!(flag, 2);
    }

    #[test]
    fn checked_arith_outputs_narrow_declared_reconstructs_true_value() {
        // The (low, high) pair reconstructs the true value via
        // `r == (high << declared_bits) + low_signed`. Verify
        // this invariant at 32-bit declared width with a value
        // that crosses the declared boundary.
        let true_value: i128 = (i32::MAX as i128) + 100;
        let (low, high, _flag) = super::checked_arith_outputs::<i64>(true_value, 5);
        let reconstructed = ((high as i128) << 32) + (low as i128);
        assert_eq!(reconstructed, true_value);
    }

    #[test]
    fn signed_keyword_parses_on_all_function_categories() {
        let cases: &[(&str, &str)] = &[
            ("signed fn", "signed fn main() -> Word { 42 }"),
            (
                "signed yield",
                "signed yield main(_x: Word) -> Word { let _r = yield 0; 0 }",
            ),
            (
                "signed loop",
                "signed loop main(_x: Word) -> Word { let _r = yield 0; 0 }",
            ),
        ];
        for (label, src) in cases {
            let tokens = tokenize(src).unwrap_or_else(|e| panic!("{}: lex: {:?}", label, e));
            let program = parse(&tokens).unwrap_or_else(|e| panic!("{}: parse: {:?}", label, e));
            let main = program
                .functions
                .iter()
                .find(|f| f.name == "main")
                .expect("main");
            assert!(main.signed, "{}: signed not recorded", label);
        }
    }

    #[test]
    fn signed_modifier_on_helper_is_rejected_at_compile_time() {
        let src = "signed fn helper() -> Word { 0 }\nfn main() -> Word { helper() }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let err = compile(&program).expect_err("compile should reject");
        assert!(
            err.message.contains("`signed` modifier on `helper`"),
            "expected entry-only diagnostic, got: {}",
            err.message
        );
    }

    #[test]
    fn signed_entry_sets_flag_requires_signature() {
        let src = "signed fn main() -> Word { 42 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert_ne!(
            module.flags & crate::wire_format::FLAG_REQUIRES_SIGNATURE,
            0,
            "FLAG_REQUIRES_SIGNATURE must be set on signed entry"
        );
    }

    #[test]
    fn unsigned_entry_does_not_set_flag_requires_signature() {
        let src = "fn main() -> Word { 42 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        assert_eq!(
            module.flags & crate::wire_format::FLAG_REQUIRES_SIGNATURE,
            0,
            "FLAG_REQUIRES_SIGNATURE must not be set on unsigned entry"
        );
    }

    #[test]
    fn vm_new_rejects_signed_module_directly() {
        // Construct a module with the flag manually set and feed
        // it to `Vm::new`. The constructor refuses because the
        // signature info has already been stripped from the
        // Module representation; the host must use
        // `Vm::load_signed_bytes` or hot-swap instead.
        let src = "signed fn main() -> Word { 42 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let result = Vm::new(module, &arena);
        match result {
            Err(VmError::VerifyError(msg)) => assert!(
                msg.contains("FLAG_REQUIRES_SIGNATURE"),
                "expected signed-module rejection, got: {}",
                msg
            ),
            Err(other) => panic!("expected VerifyError, got: {:?}", other),
            Ok(_) => panic!("expected VerifyError, got Ok(_)"),
        }
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn signed_module_loads_through_load_signed_bytes() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[42u8; 32]);
        let verifying = signer.verifying_key();
        let src = "signed fn main() -> Word { 21 + 21 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes =
            crate::wire_format::module_to_signed_wire_bytes(&module, &signer).expect("sign");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::load_signed_bytes(&bytes, &arena, &[verifying]).expect("load+verify");
        assert_eq!(vm.verifying_keys_len(), 1);
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected Finished(42), got {:?}", other),
        }
    }

    #[cfg(all(feature = "signatures", feature = "encryption"))]
    #[test]
    fn load_encrypted_signed_bytes_executes_decrypted_module() {
        use ed25519_dalek::SigningKey;

        let signer = SigningKey::from_bytes(&[101u8; 32]);
        let verifying = signer.verifying_key();

        // Recipient X25519 keypair.
        let recipient_sk = [0xb0u8; 32];
        let recipient_pk = crate::encryption::public_key_from_private(&recipient_sk);

        let ephemeral_seed = [0xc0u8; 32];

        // Compile a simple module that returns 99.
        let src = "signed fn main() -> Word { 99 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");

        // Encrypt and sign.
        let bytes = crate::wire_format::module_to_encrypted_signed_wire_bytes(
            &module,
            &signer,
            &recipient_pk,
            &ephemeral_seed,
        )
        .expect("encrypt+sign");

        // Load through the VM. End-to-end verifies the signature,
        // decrypts the body, parses the plaintext, runs structural
        // verification, and constructs the VM.
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::load_encrypted_signed_bytes(&bytes, &arena, &[verifying], &recipient_sk)
            .expect("load+decrypt+verify");

        match vm.call(&[]).expect("execute") {
            VmState::Finished(Value::Int(99)) => (),
            other => panic!("expected Finished(99), got {:?}", other),
        }
    }

    #[cfg(all(feature = "signatures", feature = "encryption"))]
    #[test]
    fn load_encrypted_signed_bytes_rejects_wrong_decryption_key() {
        use ed25519_dalek::SigningKey;

        let signer = SigningKey::from_bytes(&[102u8; 32]);
        let verifying = signer.verifying_key();

        let alice_sk = [0xd1u8; 32];
        let alice_pk = crate::encryption::public_key_from_private(&alice_sk);
        let bob_sk = [0xd2u8; 32];

        let ephemeral_seed = [0xc1u8; 32];

        let src = "signed fn main() -> Word { 7 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");

        // Encrypt to Alice.
        let bytes = crate::wire_format::module_to_encrypted_signed_wire_bytes(
            &module,
            &signer,
            &alice_pk,
            &ephemeral_seed,
        )
        .expect("encrypt+sign");

        // Bob tries to load. Should fail at recipient_key_id check.
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let result = Vm::load_encrypted_signed_bytes(&bytes, &arena, &[verifying], &bob_sk);
        assert!(result.is_err(), "expected wrong-recipient rejection");
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn load_signed_bytes_rejects_wrong_key() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[42u8; 32]);
        let wrong = SigningKey::from_bytes(&[43u8; 32]).verifying_key();
        let src = "signed fn main() -> Word { 0 }";
        let tokens = tokenize(src).expect("lex");
        let program = parse(&tokens).expect("parse");
        let module = compile(&program).expect("compile");
        let bytes =
            crate::wire_format::module_to_signed_wire_bytes(&module, &signer).expect("sign");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let result = Vm::load_signed_bytes(&bytes, &arena, &[wrong]);
        match result {
            Err(VmError::LoadError(msg)) => assert!(
                msg.contains("signature did not verify") || msg.contains("InvalidSignature"),
                "expected InvalidSignature, got: {}",
                msg
            ),
            Err(other) => panic!("expected LoadError, got: {:?}", other),
            Ok(_) => panic!("expected LoadError, got Ok(_)"),
        }
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn load_signed_bytes_rejects_unsigned_when_trust_matrix_is_nonempty() {
        // Finding 9 regression (V0.2.1 audit). A host that supplies verifying
        // keys requires signed execution, so an unsigned module -- which an
        // adversary forges from a signed one by clearing FLAG_REQUIRES_SIGNATURE
        // and recomputing the CRC -- must be rejected, not loaded. Enforcement
        // is host policy, not the artefact's self-asserted flag bit.
        use ed25519_dalek::SigningKey;
        let verifying = SigningKey::from_bytes(&[7u8; 32]).verifying_key();
        let src = "fn main() -> Word { 42 }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes = module.to_bytes().expect("encode unsigned");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        match Vm::load_signed_bytes(&bytes, &arena, &[verifying]) {
            Err(VmError::LoadError(msg)) => assert!(
                msg.contains("signature did not verify") || msg.contains("InvalidSignature"),
                "expected a signature rejection for unsigned-with-keys, got: {}",
                msg
            ),
            Err(other) => panic!("expected LoadError, got: {:?}", other),
            Ok(_) => panic!("unsigned module with a non-empty trust matrix must be rejected"),
        }
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn load_signed_bytes_loads_unsigned_when_trust_matrix_is_empty() {
        // The permissive contract is preserved: with no enrolled keys, an
        // unsigned module loads like `load_bytes`.
        let src = "fn main() -> Word { 5 }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes = module.to_bytes().expect("encode unsigned");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm =
            Vm::load_signed_bytes(&bytes, &arena, &[]).expect("unsigned + empty matrix loads");
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(5)),
            other => panic!("expected Finished(5), got {:?}", other),
        }
    }

    // -- No-verify signed-load path (audit finding 22). The `*_unchecked`
    //    variants skip the WCMU resource-bounds check but still verify the
    //    Ed25519 signature under the same host policy as the checked variants.

    #[cfg(feature = "signatures")]
    #[test]
    fn load_signed_bytes_unchecked_verifies_signature_and_executes() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[42u8; 32]);
        let verifying = signer.verifying_key();
        let src = "signed fn main() -> Word { 21 + 21 }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes =
            crate::wire_format::module_to_signed_wire_bytes(&module, &signer).expect("sign");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // SAFETY: test-only; the unchecked path skips the WCMU bound while
        // keeping signature verification, which is what this test exercises.
        let mut vm = unsafe { Vm::load_signed_bytes_unchecked(&bytes, &arena, &[verifying]) }
            .expect("load+verify");
        assert_eq!(vm.verifying_keys_len(), 1);
        match vm.call(&[]).unwrap() {
            VmState::Finished(v) => assert_eq!(v, Value::Int(42)),
            other => panic!("expected Finished(42), got {:?}", other),
        }
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn load_signed_bytes_unchecked_rejects_wrong_key() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[42u8; 32]);
        let wrong = SigningKey::from_bytes(&[43u8; 32]).verifying_key();
        let src = "signed fn main() -> Word { 0 }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes =
            crate::wire_format::module_to_signed_wire_bytes(&module, &signer).expect("sign");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // SAFETY: test-only.
        match unsafe { Vm::load_signed_bytes_unchecked(&bytes, &arena, &[wrong]) } {
            Err(VmError::LoadError(msg)) => assert!(
                msg.contains("signature did not verify") || msg.contains("InvalidSignature"),
                "expected InvalidSignature, got: {}",
                msg
            ),
            Err(other) => panic!("expected LoadError, got: {:?}", other),
            Ok(_) => panic!("expected LoadError, got Ok(_)"),
        }
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn load_signed_bytes_unchecked_rejects_unsigned_when_trust_matrix_is_nonempty() {
        // Finding 9 must hold on the no-verify path too: an unsigned module with a
        // non-empty trust matrix is rejected, not loaded.
        use ed25519_dalek::SigningKey;
        let verifying = SigningKey::from_bytes(&[7u8; 32]).verifying_key();
        let src = "fn main() -> Word { 42 }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes = module.to_bytes().expect("encode unsigned");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // SAFETY: test-only.
        match unsafe { Vm::load_signed_bytes_unchecked(&bytes, &arena, &[verifying]) } {
            Err(VmError::LoadError(msg)) => assert!(
                msg.contains("signature did not verify") || msg.contains("InvalidSignature"),
                "expected a signature rejection for unsigned-with-keys, got: {}",
                msg
            ),
            Err(other) => panic!("expected LoadError, got: {:?}", other),
            Ok(_) => panic!("unsigned module with a non-empty trust matrix must be rejected"),
        }
    }

    #[cfg(all(feature = "signatures", feature = "encryption"))]
    #[test]
    fn load_encrypted_signed_bytes_unchecked_verifies_and_decrypts() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[101u8; 32]);
        let verifying = signer.verifying_key();
        let recipient_sk = [0xb0u8; 32];
        let recipient_pk = crate::encryption::public_key_from_private(&recipient_sk);
        let ephemeral_seed = [0xc0u8; 32];
        let src = "signed fn main() -> Word { 99 }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes = crate::wire_format::module_to_encrypted_signed_wire_bytes(
            &module,
            &signer,
            &recipient_pk,
            &ephemeral_seed,
        )
        .expect("encrypt+sign");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // SAFETY: test-only; the unchecked path skips the WCMU bound while
        // keeping signature verification and decryption.
        let mut vm = unsafe {
            Vm::load_encrypted_signed_bytes_unchecked(&bytes, &arena, &[verifying], &recipient_sk)
        }
        .expect("load+decrypt+verify");
        match vm.call(&[]).expect("execute") {
            VmState::Finished(Value::Int(99)) => (),
            other => panic!("expected Finished(99), got {:?}", other),
        }
    }

    #[cfg(all(feature = "signatures", feature = "encryption"))]
    #[test]
    fn load_encrypted_signed_bytes_unchecked_rejects_wrong_recipient() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[102u8; 32]);
        let verifying = signer.verifying_key();
        let alice_sk = [0xd1u8; 32];
        let alice_pk = crate::encryption::public_key_from_private(&alice_sk);
        let bob_sk = [0xd2u8; 32];
        let ephemeral_seed = [0xc1u8; 32];
        let src = "signed fn main() -> Word { 7 }";
        let module =
            compile(&parse(&tokenize(src).expect("lex")).expect("parse")).expect("compile");
        let bytes = crate::wire_format::module_to_encrypted_signed_wire_bytes(
            &module,
            &signer,
            &alice_pk,
            &ephemeral_seed,
        )
        .expect("encrypt+sign");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        // SAFETY: test-only.
        let result = unsafe {
            Vm::load_encrypted_signed_bytes_unchecked(&bytes, &arena, &[verifying], &bob_sk)
        };
        assert!(result.is_err(), "expected wrong-recipient rejection");
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn replace_module_from_bytes_rejects_unsigned_when_keys_registered() {
        // Finding 9 regression for the hot-swap path. A registered trust matrix
        // requires signed swaps; an unsigned module is rejected.
        use ed25519_dalek::SigningKey;
        let verifying = SigningKey::from_bytes(&[9u8; 32]).verifying_key();
        let module =
            compile(&parse(&tokenize("fn main() -> Word { 1 }").expect("lex")).expect("parse"))
                .expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("construct");
        vm.register_verifying_key(verifying);
        let swap =
            compile(&parse(&tokenize("fn main() -> Word { 2 }").expect("lex")).expect("parse"))
                .expect("compile");
        let swap_bytes = swap.to_bytes().expect("encode unsigned");
        match vm.replace_module_from_bytes(&swap_bytes, alloc::vec::Vec::new()) {
            Err(VmError::LoadError(msg)) => assert!(
                msg.contains("signature did not verify") || msg.contains("InvalidSignature"),
                "expected a signature rejection for unsigned hot-swap, got: {}",
                msg
            ),
            Err(other) => panic!("expected LoadError, got: {:?}", other),
            Ok(()) => panic!("unsigned hot-swap with registered keys must be rejected"),
        }
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn rejected_hot_swap_leaves_the_running_module_intact() {
        // Finding 5: the hot swap is transactional. The fallible decode steps
        // now run before the old private slots are dropped, so a rejected swap
        // leaves the current module fully usable rather than corrupting VM
        // state (the original bug left `private_slot_count` stale after an
        // early drop, double-dropping on the next `Drop`). Here the swap is
        // rejected by the signing policy; the original module must still run.
        // The exact original trigger -- a `to_bytes`/`decode_all_ops` failure
        // after the drop -- is not reachable on a valid module, so this checks
        // the observable property the reorder guarantees.
        use ed25519_dalek::SigningKey;
        let verifying = SigningKey::from_bytes(&[11u8; 32]).verifying_key();
        let module =
            compile(&parse(&tokenize("fn main() -> Word { 1 }").expect("lex")).expect("parse"))
                .expect("compile");
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).expect("construct");
        vm.register_verifying_key(verifying);
        let swap =
            compile(&parse(&tokenize("fn main() -> Word { 2 }").expect("lex")).expect("parse"))
                .expect("compile");
        let swap_bytes = swap.to_bytes().expect("encode");
        assert!(
            vm.replace_module_from_bytes(&swap_bytes, alloc::vec::Vec::new())
                .is_err(),
            "the unsigned swap should be rejected"
        );
        // The original module is intact and still runs after the rejected swap.
        match vm.call(&[]).expect("run after rejected swap") {
            VmState::Finished(v) => assert_eq!(v, Value::Int(1)),
            other => panic!(
                "expected Finished(1) after a rejected swap, got {:?}",
                other
            ),
        }
    }

    /// `Vm::load_bytes` must refuse signed input ahead of every
    /// other check. The minimum-viable signed-looking buffer is
    /// 16 bytes with `KELE` magic and the
    /// `FLAG_REQUIRES_SIGNATURE` bit set in the flags byte;
    /// `header_requires_signature` returns true on that and the
    /// load path short-circuits before any framing or CRC
    /// validation runs. The test fires in both feature
    /// configurations and asserts the error message names the
    /// signature contract.
    #[test]
    fn load_bytes_short_circuits_on_signed_flag() {
        let mut bytes = [0u8; 16];
        bytes[0..4].copy_from_slice(b"KELE");
        bytes[15] = crate::wire_format::FLAG_REQUIRES_SIGNATURE;
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let result = Vm::load_bytes(&bytes, &arena);
        match result {
            Err(VmError::LoadError(msg)) => {
                // Without `signatures`: the message names the
                // unsupported feature. With `signatures` on: the
                // message redirects the caller to
                // `Vm::load_signed_bytes`. Both contain
                // "signatures" or "signed"; the assertion is
                // permissive but pins the contract.
                assert!(
                    msg.contains("signatures")
                        || msg.contains("Vm::load_signed_bytes")
                        || msg.contains("signed"),
                    "expected signed-module rejection, got: {}",
                    msg
                );
            }
            Err(other) => panic!("expected LoadError, got: {:?}", other),
            Ok(_) => panic!("expected error, got Ok(_)"),
        }
    }

    /// In a build without the `signatures` feature, the same
    /// path returns the dedicated
    /// `LoadError::SignaturesUnsupported` variant rather than a
    /// `Codec` redirect. The two cases produce distinguishable
    /// error messages so operators can tell whether the
    /// build supports verification or the call site is just
    /// using the wrong API.
    #[cfg(not(feature = "signatures"))]
    #[test]
    fn load_bytes_rejects_signed_with_signatures_unsupported() {
        let mut bytes = [0u8; 16];
        bytes[0..4].copy_from_slice(b"KELE");
        bytes[15] = crate::wire_format::FLAG_REQUIRES_SIGNATURE;
        let arena = keleusma_arena::Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let result = Vm::load_bytes(&bytes, &arena);
        match result {
            Err(VmError::LoadError(msg)) => assert!(
                msg.contains("does not include the `signatures` feature"),
                "expected SignaturesUnsupported message, got: {}",
                msg
            ),
            Err(other) => panic!("expected LoadError, got: {:?}", other),
            Ok(_) => panic!("expected error, got Ok(_)"),
        }
    }
}