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
//! V0.2.0 wire format types and codec.
//!
//! This module ships the wire-format types specified in
//! [`docs/architecture/WIRE_FORMAT.md`](../../docs/architecture/WIRE_FORMAT.md):
//! the sixty-four-byte framing header, the fixed-size four-byte
//! opcode records with their parity bit, and the eight-byte
//! operand pool entries that carry compound operands referenced
//! from the opcode stream.
//!
//! V0.2.0 Phase 7a publishes the types and the per-op codec; the
//! execution loop, [`crate::bytecode::Module::to_bytes`], and
//! [`crate::bytecode::Module::from_bytes`] continue to round-trip
//! through rkyv until Phase 7b cuts the producer and consumer over
//! to the section-partitioned body. The phased cutover preserves
//! the existing test surface while the new format gains coverage
//! through the round-trip tests in this module.
//!
//! The encoder and decoder operate on individual `Op` values. A
//! producer that wants a full module wire-format buffer assembles
//! the opcode records and operand pool entries side by side, then
//! frames them with the sixty-four-byte header and the CRC-32
//! trailer. The full module producer is the load-bearing piece of
//! Phase 7b.

extern crate alloc;

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;

use rkyv::{Archive, Deserialize, Serialize};

use crate::bytecode::{
    BYTECODE_MAGIC, BYTECODE_VERSION, BlockType, Chunk, ConstValue, DataLayout, LoadError, Module,
    Op, StructTemplate, TypeTag, crc32,
};

/// Error surfaced by the wire-format decoder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WireFormatError {
    /// The record's parity bit did not match the parity of its
    /// payload. Detected single-bit corruption of the four-byte
    /// record.
    OpcodeRecordParityMismatch,
    /// The opcode identifier in the record did not match any
    /// known [`Op`] variant. The runtime treats this as a
    /// corrupted record rather than a valid opcode whose
    /// dispatch is not implemented.
    UnknownOpcodeId(u8),
    /// The pool index encoded in the opcode record exceeded the
    /// supplied pool length. The record references an entry that
    /// does not exist.
    OperandPoolIndexOutOfBounds(usize),
    /// The operand pool entry's parity byte did not match the
    /// parity of its payload. Detected single-bit corruption of
    /// the eight-byte entry.
    OperandPoolParityMismatch,
    /// The operand pool entry's type tag did not match the
    /// expected tag for the consuming opcode. Either the
    /// producer assembled the pool incorrectly or the entry was
    /// corrupted.
    OperandPoolTagMismatch {
        /// Tag observed in the pool entry.
        observed: u8,
        /// Tag the consuming opcode requires.
        expected: u8,
    },
    /// The operand pool index did not fit in the three inline
    /// bytes of the opcode record. The pool exceeds 16,777,216
    /// entries which is well beyond any observed program; the
    /// producer rejects such modules at encode time.
    OperandPoolIndexOverflow,
    /// The scalar-kind tag in a baked flat-composite access operand
    /// (`Op::GetTupleField` or `Op::GetIndex`) did not map to a known
    /// [`crate::value_layout::ScalarKind`]. Either the producer
    /// assembled the operand incorrectly or the record was corrupted.
    /// The boxed sentinel (`255`) is handled separately and is not
    /// reported here.
    TupleFieldKindUnknown(u8),
}

/// Opcode identifier as it appears in the seven low bits of byte
/// zero of a [`OpcodeRecord`]. The mapping is fixed at version 1
/// of the wire format. Adding a new opcode appends to the table;
/// removing an opcode keeps the identifier vacant rather than
/// shifting later identifiers, preserving wire-format stability
/// for unaffected opcodes.
///
/// V0.2.0 ISA uses identifiers in the range `[0, 68]`; the upper
/// bound is one less than the number of variants. The seven-bit
/// field admits up to `128` identifiers before the version field
/// would need to bump.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpcodeId(pub u8);

/// Pool entry type tag for the `(u16, u16)` shape. Used by
/// `Op::GetDataIndexed`, `Op::SetDataIndexed`, and
/// `Op::IsEnum`.
pub const POOL_TAG_U16_U16: u8 = 0x01;

/// Pool entry type tag for the `(u16, u16, u8)` shape. Used by
/// `Op::NewComposite` (boxed form).
pub const POOL_TAG_U16_U16_U8: u8 = 0x02;

/// Pool entry type tag for the `(u16, u16, u16)` shape. Used by
/// `Op::IsEnum` (enum-name, variant-name, discriminant-value constant
/// indices); the three `u16`s occupy bytes two through seven (B28 P2).
pub const POOL_TAG_U16_U16_U16: u8 = 0x03;

/// Byte-three sentinel in a baked `Op::GetTupleField` record marking
/// the boxed (positional-index) form. Distinguished from a flat
/// scalar-kind tag because [`crate::value_layout::ScalarKind::to_tag`]
/// returns values in `0..=7`, well below `255`. For the flat form
/// byte three holds the scalar-kind tag and bytes one and two hold
/// the little-endian offset; for the boxed form byte one holds the
/// index.
pub const TUPLE_FIELD_BOXED_SENTINEL: u8 = 0xFF;

/// Byte-three sentinel base marking the `FlatNested` form of a baked
/// composite-access record (B28 P2 nested inlining). The low two bits
/// carry the [`crate::value_layout::CompositeKind`] tag, so the four
/// concrete sentinels are `0xF0..=0xF3`. Distinguished from a flat
/// scalar-kind tag (`0..=7`) and from the boxed sentinel (`0xFF`).
///
/// Unlike the inline scalar form, a nested access cannot fit its
/// `(offset, size)` in the remaining two operand bytes, so it spills to
/// an operand-pool entry (the existing `from_u16_u16` shape). Bytes one
/// and two hold the pool index (little-endian `u16`); byte three is this
/// sentinel with the variant tag. The pool entry holds `(offset, size)`
/// for the field forms (`GetField`/`GetTupleField`/`GetEnumField`) and
/// `(size, 0)` for `GetIndex` (a homogeneous array has no per-element
/// offset; the element offset is `index * size`). A module whose nested
/// access would reference a pool index beyond `u16::MAX` is rejected at
/// encode time, which the `no_std` target's small modules never reach.
pub const FLAT_NESTED_SENTINEL_BASE: u8 = 0xF0;

/// Largest field count carried inline in a flat [`crate::bytecode::Op::NewComposite`]
/// record (B28 P4). The count occupies the low six bits of byte three, and
/// `0x3F` is reserved as the pool sentinel, so the inline maximum is `62`.
pub const NEW_COMPOSITE_INLINE_MAX_COUNT: u16 = 0x3E;

/// Low-six-bit sentinel in a [`crate::bytecode::Op::NewComposite`] record's
/// byte three marking the pool form (a field count that does not fit inline,
/// or the boxed form) (B28 P4). Byte three's high two bits carry the
/// composite kind in both forms.
pub const NEW_COMPOSITE_POOL_SENTINEL: u8 = 0x3F;

/// Mask selecting the [`FLAT_NESTED_SENTINEL_BASE`] marker bits (the
/// high six bits); the low two bits carry the composite-kind tag.
pub const FLAT_NESTED_SENTINEL_MASK: u8 = 0xFC;

/// Width of an opcode record in bytes.
pub const OPCODE_RECORD_BYTES: usize = 4;

/// Width of an operand pool entry in bytes.
pub const OPERAND_POOL_ENTRY_BYTES: usize = 8;

/// Width of the framing header in bytes for unsigned modules.
/// Signed modules grow the header by a signature-extension block;
/// the decoder reads the actual header length from bytes 6..8.
pub const WIRE_FORMAT_HEADER_BYTES: usize = 64;

/// Width of the signature-extension metadata block that follows
/// the base header on signed modules. Bytes are laid out as:
///
/// - byte 0: `scheme_id` (u8). `0` is reserved-invalid; `1` is
///   Ed25519. Other values are reserved for future schemes.
/// - byte 1: reserved (must be `0`).
/// - bytes 2..4: `signature_length` (u16 little-endian).
/// - bytes 4..8: reserved (must be `0`).
pub const SIGNATURE_METADATA_BYTES: usize = 8;

/// Bit in the framing header's `flags: u8` byte (offset 15) that
/// signals "this module must be loaded only after a successful
/// signature verification." The flag is set by the compiler when
/// the entry function carries the `signed` modifier and is
/// enforced by the load-time runtime against the host-supplied
/// trust matrix.
pub const FLAG_REQUIRES_SIGNATURE: u8 = 0x02;

/// Bit in the framing header's `flags: u8` byte (offset 15) that
/// signals "this module's body is encrypted." The flag is set by
/// the compiler when producing an encrypted artefact and is
/// enforced by the load-time runtime which decrypts the body
/// before structural verification. Encrypted modules are also
/// signed because the signature covers the encrypted body and is
/// what authenticates the artefact's origin against tampering on
/// the delivery channel.
pub const FLAG_ENCRYPTED: u8 = 0x04;

/// Signature scheme identifier for the Ed25519 algorithm. The
/// only scheme V0.2.0 implements; the byte exists to make the
/// wire format scheme-agnostic so future migrations do not
/// require an ABI break.
pub const SIGNATURE_SCHEME_ED25519: u8 = 0x01;

/// Length of an Ed25519 signature in bytes.
pub const ED25519_SIGNATURE_BYTES: usize = 64;

/// Length of an Ed25519 verifying key in bytes.
pub const ED25519_VERIFYING_KEY_BYTES: usize = 32;

/// Width of the encryption-metadata block appended after the
/// signature extension on encrypted modules. The layout is
/// documented in [`crate::encryption::EncryptionMetadata`] and in
/// `tmp/encrypted_signed_modules.md`. Always 88 bytes for the
/// V0.2.1 X25519+AES-256-GCM scheme; future schemes may use the
/// same constant or extend it through a scheme-specific
/// negotiation.
pub const ENCRYPTION_METADATA_BYTES: usize = 88;

/// Maximum operand pool size addressable by the twenty-four-bit
/// inline pool index. `16_777_216`.
pub const MAX_POOL_ENTRIES: usize = 1 << 24;

/// A four-byte opcode record. Byte zero carries the parity bit
/// (high) and the opcode identifier (low seven bits). Bytes one
/// through three carry either the inline operand or the
/// little-endian operand-pool index.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpcodeRecord(pub [u8; OPCODE_RECORD_BYTES]);

/// An eight-byte operand pool entry. Byte zero carries the type
/// tag; byte one carries the parity byte; bytes two through seven
/// carry the payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperandPoolEntry(pub [u8; OPERAND_POOL_ENTRY_BYTES]);

impl OpcodeRecord {
    /// Construct a record from its raw four bytes. The caller is
    /// responsible for the parity bit; see [`Self::from_id_and_operand`]
    /// for the parity-computing constructor used by the encoder.
    pub fn from_raw(bytes: [u8; OPCODE_RECORD_BYTES]) -> Self {
        OpcodeRecord(bytes)
    }

    /// Construct a record from an opcode identifier and three
    /// inline operand bytes. Computes the parity bit and writes
    /// it to the high bit of byte zero.
    pub fn from_id_and_operand(id: OpcodeId, operand: [u8; 3]) -> Self {
        let raw = [id.0 & 0x7F, operand[0], operand[1], operand[2]];
        let parity = compute_parity(&raw);
        let mut bytes = raw;
        bytes[0] |= parity << 7;
        OpcodeRecord(bytes)
    }

    /// Extract the opcode identifier from byte zero, ignoring the
    /// parity bit.
    pub fn opcode_id(&self) -> OpcodeId {
        OpcodeId(self.0[0] & 0x7F)
    }

    /// Extract the three inline operand bytes (bytes one through
    /// three).
    pub fn operand_bytes(&self) -> [u8; 3] {
        [self.0[1], self.0[2], self.0[3]]
    }

    /// Verify that the parity bit matches the parity of the rest
    /// of the record. Returns `Ok` on match, `Err` on mismatch.
    pub fn check_parity(&self) -> Result<(), WireFormatError> {
        let masked = [self.0[0] & 0x7F, self.0[1], self.0[2], self.0[3]];
        let expected = (self.0[0] >> 7) & 1;
        if compute_parity(&masked) == expected {
            Ok(())
        } else {
            Err(WireFormatError::OpcodeRecordParityMismatch)
        }
    }

    /// Decode the inline operand as a little-endian `u8` in byte
    /// one. Bytes two and three are not consulted.
    pub fn operand_u8(&self) -> u8 {
        self.0[1]
    }

    /// Decode the inline operand as a little-endian `u16` from
    /// bytes one through two.
    pub fn operand_u16(&self) -> u16 {
        u16::from_le_bytes([self.0[1], self.0[2]])
    }

    /// Decode the inline operand as `(u16, u8)` where the `u16`
    /// is little-endian in bytes one through two and the `u8` is
    /// byte three.
    pub fn operand_u16_u8(&self) -> (u16, u8) {
        (u16::from_le_bytes([self.0[1], self.0[2]]), self.0[3])
    }

    /// Decode the inline operand as a twenty-four-bit
    /// little-endian pool index. The producer guarantees the
    /// pool fits in twenty-four bits.
    pub fn operand_pool_index(&self) -> u32 {
        u32::from_le_bytes([self.0[1], self.0[2], self.0[3], 0])
    }
}

impl OperandPoolEntry {
    /// Construct a `(u16, u16)` pool entry. Computes the parity
    /// byte over the type tag and the payload.
    pub fn from_u16_u16(a: u16, b: u16) -> Self {
        let mut bytes = [0u8; OPERAND_POOL_ENTRY_BYTES];
        bytes[0] = POOL_TAG_U16_U16;
        // Byte 1 is the parity; computed below.
        bytes[2..4].copy_from_slice(&a.to_le_bytes());
        bytes[4..6].copy_from_slice(&b.to_le_bytes());
        // Bytes 6 and 7 stay zero for the `(u16, u16)` shape.
        let parity_payload = [
            bytes[0], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ];
        bytes[1] = pool_entry_parity(&parity_payload);
        OperandPoolEntry(bytes)
    }

    /// Construct a `(u16, u16, u8)` pool entry. Computes the
    /// parity byte over the type tag and the payload.
    pub fn from_u16_u16_u8(a: u16, b: u16, c: u8) -> Self {
        let mut bytes = [0u8; OPERAND_POOL_ENTRY_BYTES];
        bytes[0] = POOL_TAG_U16_U16_U8;
        bytes[2..4].copy_from_slice(&a.to_le_bytes());
        bytes[4..6].copy_from_slice(&b.to_le_bytes());
        bytes[6] = c;
        // Byte 7 stays zero (reserved).
        let parity_payload = [
            bytes[0], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ];
        bytes[1] = pool_entry_parity(&parity_payload);
        OperandPoolEntry(bytes)
    }

    /// Construct a `(u16, u16, u16)` pool entry. The three indices occupy
    /// bytes two-three, four-five, and six-seven (B28 P2).
    pub fn from_u16_u16_u16(a: u16, b: u16, c: u16) -> Self {
        let mut bytes = [0u8; OPERAND_POOL_ENTRY_BYTES];
        bytes[0] = POOL_TAG_U16_U16_U16;
        bytes[2..4].copy_from_slice(&a.to_le_bytes());
        bytes[4..6].copy_from_slice(&b.to_le_bytes());
        bytes[6..8].copy_from_slice(&c.to_le_bytes());
        let parity_payload = [
            bytes[0], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ];
        bytes[1] = pool_entry_parity(&parity_payload);
        OperandPoolEntry(bytes)
    }

    /// Verify the parity byte against the rest of the entry.
    pub fn check_parity(&self) -> Result<(), WireFormatError> {
        let parity_payload = [
            self.0[0], self.0[2], self.0[3], self.0[4], self.0[5], self.0[6], self.0[7],
        ];
        if pool_entry_parity(&parity_payload) == self.0[1] {
            Ok(())
        } else {
            Err(WireFormatError::OperandPoolParityMismatch)
        }
    }

    /// Return the type tag (byte zero).
    pub fn tag(&self) -> u8 {
        self.0[0]
    }

    /// Decode the `(u16, u16)` payload. Caller verifies the tag
    /// and parity before invoking.
    pub fn as_u16_u16(&self) -> (u16, u16) {
        (
            u16::from_le_bytes([self.0[2], self.0[3]]),
            u16::from_le_bytes([self.0[4], self.0[5]]),
        )
    }

    /// Decode the `(u16, u16, u16)` payload. Caller verifies the tag
    /// and parity before invoking.
    pub fn as_u16_u16_u16(&self) -> (u16, u16, u16) {
        let (a, b) = self.as_u16_u16();
        (a, b, u16::from_le_bytes([self.0[6], self.0[7]]))
    }

    /// Decode the `(u16, u16, u8)` payload. Caller verifies the
    /// tag and parity before invoking.
    pub fn as_u16_u16_u8(&self) -> (u16, u16, u8) {
        let (a, b) = self.as_u16_u16();
        (a, b, self.0[6])
    }
}

/// Compute the parity bit over a four-byte slice. Returns `0` or
/// `1`. The high bit of byte zero must be cleared before calling
/// when computing the parity of an opcode record.
fn compute_parity(bytes: &[u8; OPCODE_RECORD_BYTES]) -> u8 {
    let total = bytes.iter().map(|b| b.count_ones()).sum::<u32>();
    (total & 1) as u8
}

/// Compute the parity byte over a seven-byte slice covering the
/// type tag and the payload of an [`OperandPoolEntry`]. Returns
/// the XOR of the seven bytes; a consumer compares this against
/// the parity byte stored in byte one of the entry.
fn pool_entry_parity(bytes: &[u8; 7]) -> u8 {
    bytes.iter().fold(0u8, |acc, b| acc ^ b)
}

/// Canonical opcode identifier table. The mapping is fixed at
/// version 1 of the wire format. The list mirrors the
/// declaration order of the `Op` enum in `src/bytecode.rs` and is
/// part of the wire-format ABI: adding a new opcode appends to
/// the tail of the list, and removing an opcode keeps the
/// vacated identifier reserved rather than shifting later
/// identifiers.
///
/// The Phase 7a release ships the table as a `const` array
/// indexed by an internal discriminator computed by [`opcode_id_of`].
/// Phase 7b transitions to a derived mapping that the compile-
/// pipeline runs once at module load.
const OPCODE_ID_TABLE: &[(&str, u8)] = &[
    ("Const", 0),
    ("GetLocal", 1),
    ("SetLocal", 2),
    ("GetData", 3),
    ("SetData", 4),
    ("GetDataIndexed", 5),
    ("SetDataIndexed", 6),
    ("BoundsCheck", 7),
    ("Add", 8),
    ("Sub", 9),
    ("Mul", 10),
    ("Div", 11),
    ("Mod", 12),
    ("Neg", 13),
    ("CmpEq", 14),
    ("CmpNe", 15),
    ("CmpLt", 16),
    ("CmpGt", 17),
    ("CmpLe", 18),
    ("CmpGe", 19),
    ("Not", 20),
    ("If", 21),
    ("Else", 22),
    ("EndIf", 23),
    ("Loop", 24),
    ("EndLoop", 25),
    ("Break", 26),
    ("BreakIf", 27),
    ("Stream", 28),
    ("Reset", 29),
    ("Call", 30),
    ("Return", 31),
    ("Yield", 32),
    ("Dup", 33),
    ("GetField", 38),
    ("GetIndex", 39),
    ("GetTupleField", 40),
    ("GetEnumField", 41),
    ("Len", 42),
    ("IsEnum", 43),
    ("IsStruct", 44),
    ("IntToFloat", 45),
    ("FloatToInt", 46),
    ("WordToByte", 47),
    ("ByteToWord", 48),
    ("WordToFixed", 49),
    ("FixedToWord", 50),
    ("FixedMul", 51),
    ("FixedDiv", 52),
    ("Trap", 53),
    ("CheckedAdd", 54),
    ("CheckedSub", 55),
    ("CheckedMul", 56),
    ("CheckedNeg", 57),
    ("CheckedDiv", 58),
    ("CheckedMod", 59),
    ("PushImmediate", 60),
    ("PopN", 61),
    ("BitAnd", 62),
    ("BitOr", 63),
    ("BitXor", 64),
    ("Shl", 65),
    ("Shr", 66),
    ("CallVerifiedNative", 67),
    ("CallExternalNative", 68),
    ("NewComposite", 69),
];

/// Return the wire-format identifier for an `Op` variant.
pub fn opcode_id_of(op: &Op) -> OpcodeId {
    let id = match op {
        Op::Const(_) => 0,
        Op::GetLocal(_) => 1,
        Op::SetLocal(_) => 2,
        Op::GetData(_) => 3,
        Op::SetData(_) => 4,
        Op::GetDataIndexed(_, _) => 5,
        Op::SetDataIndexed(_, _) => 6,
        Op::BoundsCheck(_) => 7,
        Op::Add => 8,
        Op::Sub => 9,
        Op::Mul => 10,
        Op::Div => 11,
        Op::Mod => 12,
        Op::Neg => 13,
        Op::CmpEq => 14,
        Op::CmpNe => 15,
        Op::CmpLt => 16,
        Op::CmpGt => 17,
        Op::CmpLe => 18,
        Op::CmpGe => 19,
        Op::Not => 20,
        Op::If(_) => 21,
        Op::Else(_) => 22,
        Op::EndIf => 23,
        Op::Loop(_) => 24,
        Op::EndLoop(_) => 25,
        Op::Break(_) => 26,
        Op::BreakIf(_) => 27,
        Op::Stream => 28,
        Op::Reset => 29,
        Op::Call(_, _) => 30,
        Op::Return => 31,
        Op::Yield => 32,
        Op::Dup => 33,
        Op::GetField(_) => 38,
        Op::GetIndex(_) => 39,
        Op::GetTupleField(_) => 40,
        Op::GetEnumField(_) => 41,
        Op::Len => 42,
        Op::IsEnum(_, _, _) => 43,
        Op::IsStruct(_) => 44,
        Op::IntToFloat => 45,
        Op::FloatToInt => 46,
        Op::WordToByte => 47,
        Op::ByteToWord => 48,
        Op::WordToFixed(_) => 49,
        Op::FixedToWord(_) => 50,
        Op::FixedMul(_) => 51,
        Op::FixedDiv(_) => 52,
        Op::Trap(_) => 53,
        Op::CheckedAdd => 54,
        Op::CheckedSub => 55,
        Op::CheckedMul(_) => 56,
        Op::CheckedNeg => 57,
        Op::CheckedDiv(_) => 58,
        Op::CheckedMod => 59,
        Op::PushImmediate(_) => 60,
        Op::PopN(_) => 61,
        Op::BitAnd => 62,
        Op::BitOr => 63,
        Op::BitXor => 64,
        Op::Shl => 65,
        Op::Shr => 66,
        Op::CallVerifiedNative(_, _) => 67,
        Op::CallExternalNative(_, _) => 68,
        Op::NewComposite(_) => 69,
    };
    OpcodeId(id)
}

/// Look up the variant name for an opcode identifier. Used by
/// the decoder's error path to surface readable diagnostics.
fn opcode_name_for_id(id: u8) -> Option<&'static str> {
    OPCODE_ID_TABLE
        .iter()
        .find_map(|(name, code)| if *code == id { Some(*name) } else { None })
}

/// Append a `from_u16_u16(a, b)` pool entry for a nested composite
/// access and return the inline operand record `[idx_lo, idx_hi,
/// sentinel | variant]` (B28 P2). The pool index must fit a `u16`
/// because the nested record reserves byte three for the variant
/// sentinel; a larger index is rejected with `OperandPoolIndexOverflow`.
fn encode_nested(
    pool: &mut Vec<OperandPoolEntry>,
    a: u16,
    b: u16,
    variant: crate::value_layout::CompositeKind,
) -> Result<[u8; 3], WireFormatError> {
    let idx = pool.len();
    if idx >= MAX_POOL_ENTRIES || idx > u16::MAX as usize {
        return Err(WireFormatError::OperandPoolIndexOverflow);
    }
    pool.push(OperandPoolEntry::from_u16_u16(a, b));
    let idx_bytes = (idx as u16).to_le_bytes();
    Ok([
        idx_bytes[0],
        idx_bytes[1],
        FLAT_NESTED_SENTINEL_BASE | variant.to_tag(),
    ])
}

/// Encode an [`Op`] into an [`OpcodeRecord`], appending an entry
/// to `pool` for the compound-operand opcodes (`GetDataIndexed`,
/// `SetDataIndexed`, `IsEnum`, `NewEnum`, and the `FlatNested` form of
/// the composite-access opcodes).
///
/// The pool index of an appended entry is the entry's position
/// in `pool` before the append. The encoder rejects modules
/// whose pool exceeds [`MAX_POOL_ENTRIES`] entries with
/// `WireFormatError::OperandPoolIndexOverflow`.
pub fn encode_op(
    op: &Op,
    pool: &mut Vec<OperandPoolEntry>,
) -> Result<OpcodeRecord, WireFormatError> {
    let id = opcode_id_of(op);
    let operand = match op {
        // No operand. All three operand bytes are zero.
        Op::Add
        | Op::Sub
        | Op::Mul
        | Op::Div
        | Op::Mod
        | Op::Neg
        | Op::CmpEq
        | Op::CmpNe
        | Op::CmpLt
        | Op::CmpGt
        | Op::CmpLe
        | Op::CmpGe
        | Op::Not
        | Op::EndIf
        | Op::Stream
        | Op::Reset
        | Op::Return
        | Op::Yield
        | Op::Dup
        | Op::Len
        | Op::IntToFloat
        | Op::FloatToInt
        | Op::WordToByte
        | Op::ByteToWord
        | Op::CheckedAdd
        | Op::CheckedSub
        | Op::CheckedNeg
        | Op::CheckedMod
        | Op::BitAnd
        | Op::BitOr
        | Op::BitXor
        | Op::Shl
        | Op::Shr => [0, 0, 0],

        // Baked enum-payload access (B28 P2). Same inline layout as the
        // struct/tuple field forms: the flat form stores the offset
        // little-endian in bytes one and two and the scalar-kind tag in
        // byte three; the boxed form stores the index in byte one and the
        // boxed sentinel in byte three.
        Op::GetEnumField(crate::bytecode::EnumField::Flat { offset, kind }) => {
            let b = offset.to_le_bytes();
            [b[0], b[1], kind.to_tag()]
        }
        Op::GetEnumField(crate::bytecode::EnumField::FlatNested {
            offset,
            size,
            variant,
        }) => encode_nested(pool, *offset, *size, *variant)?,
        Op::GetEnumField(crate::bytecode::EnumField::Boxed { index }) => {
            [*index, 0, TUPLE_FIELD_BOXED_SENTINEL]
        }

        // `u8` operand carried inline in byte one.
        Op::WordToFixed(n)
        | Op::FixedToWord(n)
        | Op::FixedMul(n)
        | Op::FixedDiv(n)
        | Op::CheckedMul(n)
        | Op::CheckedDiv(n)
        | Op::PushImmediate(n)
        | Op::PopN(n) => [*n, 0, 0],

        // `u16` operand carried little-endian in bytes one and two.
        Op::Const(v)
        | Op::GetLocal(v)
        | Op::SetLocal(v)
        | Op::GetData(v)
        | Op::SetData(v)
        | Op::BoundsCheck(v)
        | Op::If(v)
        | Op::Else(v)
        | Op::Loop(v)
        | Op::EndLoop(v)
        | Op::Break(v)
        | Op::BreakIf(v)
        | Op::IsStruct(v)
        | Op::Trap(v) => {
            let b = v.to_le_bytes();
            [b[0], b[1], 0]
        }

        // `(u16, u8)` operand carried inline: u16 little-endian in
        // bytes one and two, u8 in byte three.
        Op::Call(c, n) | Op::CallVerifiedNative(c, n) | Op::CallExternalNative(c, n) => {
            let b = c.to_le_bytes();
            [b[0], b[1], *n]
        }

        // Baked tuple-field access (B28 P2). The flat form stores the
        // little-endian offset in bytes one and two and the scalar-kind
        // tag in byte three. The boxed form stores the index in byte
        // one and the boxed sentinel in byte three.
        Op::GetTupleField(crate::bytecode::TupleField::Flat { offset, kind }) => {
            let b = offset.to_le_bytes();
            [b[0], b[1], kind.to_tag()]
        }
        Op::GetTupleField(crate::bytecode::TupleField::FlatNested {
            offset,
            size,
            variant,
        }) => encode_nested(pool, *offset, *size, *variant)?,
        Op::GetTupleField(crate::bytecode::TupleField::Boxed { index }) => {
            [*index, 0, TUPLE_FIELD_BOXED_SENTINEL]
        }

        // Baked struct-field access (B28 P2). Both forms carry a u16 in
        // bytes one and two; byte three discriminates: a scalar-kind tag
        // for the flat read, or the boxed sentinel for the by-name lookup.
        Op::GetField(crate::bytecode::StructField::Flat { offset, kind }) => {
            let b = offset.to_le_bytes();
            [b[0], b[1], kind.to_tag()]
        }
        Op::GetField(crate::bytecode::StructField::FlatNested {
            offset,
            size,
            variant,
        }) => encode_nested(pool, *offset, *size, *variant)?,
        Op::GetField(crate::bytecode::StructField::Boxed { name_const }) => {
            let b = name_const.to_le_bytes();
            [b[0], b[1], TUPLE_FIELD_BOXED_SENTINEL]
        }

        // Baked array element access (B28 P2). The flat form stores the
        // element scalar-kind tag in byte one; the runtime derives the
        // element size and the offset from the index. The boxed form
        // stores the boxed sentinel in byte one.
        Op::GetIndex(crate::bytecode::ArrayElem::Flat { kind }) => [kind.to_tag(), 0, 0],
        // A nested array element carries no per-element offset (the offset
        // is `index * size`, computed at run time), so the pool entry holds
        // `(size, 0)`.
        Op::GetIndex(crate::bytecode::ArrayElem::FlatNested { size, variant }) => {
            encode_nested(pool, *size, 0, *variant)?
        }
        Op::GetIndex(crate::bytecode::ArrayElem::Boxed) => [TUPLE_FIELD_BOXED_SENTINEL, 0, 0],

        // Pool-using shapes. Append the entry and store the index
        // in the inline operand bytes.
        Op::GetDataIndexed(a, b) | Op::SetDataIndexed(a, b) => {
            let idx = pool.len();
            if idx >= MAX_POOL_ENTRIES {
                return Err(WireFormatError::OperandPoolIndexOverflow);
            }
            pool.push(OperandPoolEntry::from_u16_u16(*a, *b));
            let idx_bytes = (idx as u32).to_le_bytes();
            [idx_bytes[0], idx_bytes[1], idx_bytes[2]]
        }
        Op::IsEnum(a, b, d) => {
            let idx = pool.len();
            if idx >= MAX_POOL_ENTRIES {
                return Err(WireFormatError::OperandPoolIndexOverflow);
            }
            pool.push(OperandPoolEntry::from_u16_u16_u16(*a, *b, *d));
            let idx_bytes = (idx as u32).to_le_bytes();
            [idx_bytes[0], idx_bytes[1], idx_bytes[2]]
        }
        // NewComposite (B28 P4). The common flat form with a small field
        // count rides inline: bytes one and two hold the allocation byte
        // size, byte three packs the composite kind in its high two bits and
        // the field count (0..=62) in its low six. A field count that does
        // not fit, or the boxed form, spills to a `from_u16_u16_u8` pool
        // entry `(count, byte_size_or_meta, boxed_flag)` referenced by a
        // sixteen-bit index in bytes one and two, with byte three carrying
        // the kind and the low-six sentinel `0x3F`.
        Op::NewComposite(operand) => {
            let (kind, count, b_field, boxed_flag) = match operand {
                crate::bytecode::NewCompositeOperand::Flat {
                    kind,
                    count,
                    byte_size,
                } => (*kind, *count, *byte_size, 0u8),
                crate::bytecode::NewCompositeOperand::Boxed { kind, count, meta } => {
                    (*kind, *count, *meta, 1u8)
                }
            };
            let ktag = kind.to_tag();
            if boxed_flag == 0 && count <= NEW_COMPOSITE_INLINE_MAX_COUNT {
                let b = b_field.to_le_bytes();
                [b[0], b[1], (ktag << 6) | (count as u8)]
            } else {
                let idx = pool.len();
                if idx >= MAX_POOL_ENTRIES || idx > u16::MAX as usize {
                    return Err(WireFormatError::OperandPoolIndexOverflow);
                }
                pool.push(OperandPoolEntry::from_u16_u16_u8(
                    count, b_field, boxed_flag,
                ));
                let ib = (idx as u16).to_le_bytes();
                [ib[0], ib[1], (ktag << 6) | NEW_COMPOSITE_POOL_SENTINEL]
            }
        }
    };
    Ok(OpcodeRecord::from_id_and_operand(id, operand))
}

/// Decode the byte-three sentinel of a composite-access record into a
/// nested composite kind, or `None` when the byte is not a nested
/// sentinel (B28 P2 nested inlining). The high six bits select the
/// nested marker; the low two carry the
/// [`crate::value_layout::CompositeKind`] tag.
fn decode_nested_variant(tag: u8) -> Option<crate::value_layout::CompositeKind> {
    if tag & FLAT_NESTED_SENTINEL_MASK == FLAT_NESTED_SENTINEL_BASE {
        crate::value_layout::CompositeKind::from_tag(tag & !FLAT_NESTED_SENTINEL_MASK)
    } else {
        None
    }
}

/// Decode an [`OpcodeRecord`] into an [`Op`], consulting the
/// supplied operand pool for the four compound-operand opcodes.
///
/// Verifies the record's parity before dispatching. Pool-using
/// opcodes additionally verify the pool entry's parity and type
/// tag.
pub fn decode_op(record: OpcodeRecord, pool: &[OperandPoolEntry]) -> Result<Op, WireFormatError> {
    record.check_parity()?;
    let id = record.opcode_id().0;
    let op = match id {
        0 => Op::Const(record.operand_u16()),
        1 => Op::GetLocal(record.operand_u16()),
        2 => Op::SetLocal(record.operand_u16()),
        3 => Op::GetData(record.operand_u16()),
        4 => Op::SetData(record.operand_u16()),
        5 => {
            let (a, b) = decode_pool_u16_u16(record, pool)?;
            Op::GetDataIndexed(a, b)
        }
        6 => {
            let (a, b) = decode_pool_u16_u16(record, pool)?;
            Op::SetDataIndexed(a, b)
        }
        7 => Op::BoundsCheck(record.operand_u16()),
        8 => Op::Add,
        9 => Op::Sub,
        10 => Op::Mul,
        11 => Op::Div,
        12 => Op::Mod,
        13 => Op::Neg,
        14 => Op::CmpEq,
        15 => Op::CmpNe,
        16 => Op::CmpLt,
        17 => Op::CmpGt,
        18 => Op::CmpLe,
        19 => Op::CmpGe,
        20 => Op::Not,
        21 => Op::If(record.operand_u16()),
        22 => Op::Else(record.operand_u16()),
        23 => Op::EndIf,
        24 => Op::Loop(record.operand_u16()),
        25 => Op::EndLoop(record.operand_u16()),
        26 => Op::Break(record.operand_u16()),
        27 => Op::BreakIf(record.operand_u16()),
        28 => Op::Stream,
        29 => Op::Reset,
        30 => {
            let (c, n) = record.operand_u16_u8();
            Op::Call(c, n)
        }
        31 => Op::Return,
        32 => Op::Yield,
        33 => Op::Dup,
        38 => {
            let bytes = record.operand_bytes();
            if bytes[2] == TUPLE_FIELD_BOXED_SENTINEL {
                let name_const = u16::from_le_bytes([bytes[0], bytes[1]]);
                Op::GetField(crate::bytecode::StructField::Boxed { name_const })
            } else if let Some(variant) = decode_nested_variant(bytes[2]) {
                let (offset, size) = decode_nested_pool(record, pool)?;
                Op::GetField(crate::bytecode::StructField::FlatNested {
                    offset,
                    size,
                    variant,
                })
            } else {
                let offset = u16::from_le_bytes([bytes[0], bytes[1]]);
                let kind = crate::value_layout::ScalarKind::from_tag(bytes[2])
                    .ok_or(WireFormatError::TupleFieldKindUnknown(bytes[2]))?;
                Op::GetField(crate::bytecode::StructField::Flat { offset, kind })
            }
        }
        39 => {
            let bytes = record.operand_bytes();
            if bytes[2] == 0 && bytes[0] == TUPLE_FIELD_BOXED_SENTINEL {
                Op::GetIndex(crate::bytecode::ArrayElem::Boxed)
            } else if let Some(variant) = decode_nested_variant(bytes[2]) {
                let (size, _) = decode_nested_pool(record, pool)?;
                Op::GetIndex(crate::bytecode::ArrayElem::FlatNested { size, variant })
            } else {
                let kind = crate::value_layout::ScalarKind::from_tag(bytes[0])
                    .ok_or(WireFormatError::TupleFieldKindUnknown(bytes[0]))?;
                Op::GetIndex(crate::bytecode::ArrayElem::Flat { kind })
            }
        }
        40 => {
            let bytes = record.operand_bytes();
            if bytes[2] == TUPLE_FIELD_BOXED_SENTINEL {
                Op::GetTupleField(crate::bytecode::TupleField::Boxed { index: bytes[0] })
            } else if let Some(variant) = decode_nested_variant(bytes[2]) {
                let (offset, size) = decode_nested_pool(record, pool)?;
                Op::GetTupleField(crate::bytecode::TupleField::FlatNested {
                    offset,
                    size,
                    variant,
                })
            } else {
                let offset = u16::from_le_bytes([bytes[0], bytes[1]]);
                let kind = crate::value_layout::ScalarKind::from_tag(bytes[2])
                    .ok_or(WireFormatError::TupleFieldKindUnknown(bytes[2]))?;
                Op::GetTupleField(crate::bytecode::TupleField::Flat { offset, kind })
            }
        }
        41 => {
            let bytes = record.operand_bytes();
            if bytes[2] == TUPLE_FIELD_BOXED_SENTINEL {
                Op::GetEnumField(crate::bytecode::EnumField::Boxed { index: bytes[0] })
            } else if let Some(variant) = decode_nested_variant(bytes[2]) {
                let (offset, size) = decode_nested_pool(record, pool)?;
                Op::GetEnumField(crate::bytecode::EnumField::FlatNested {
                    offset,
                    size,
                    variant,
                })
            } else {
                let offset = u16::from_le_bytes([bytes[0], bytes[1]]);
                let kind = crate::value_layout::ScalarKind::from_tag(bytes[2])
                    .ok_or(WireFormatError::TupleFieldKindUnknown(bytes[2]))?;
                Op::GetEnumField(crate::bytecode::EnumField::Flat { offset, kind })
            }
        }
        42 => Op::Len,
        43 => {
            let (a, b, d) = decode_pool_u16_u16_u16(record, pool)?;
            Op::IsEnum(a, b, d)
        }
        44 => Op::IsStruct(record.operand_u16()),
        45 => Op::IntToFloat,
        46 => Op::FloatToInt,
        47 => Op::WordToByte,
        48 => Op::ByteToWord,
        49 => Op::WordToFixed(record.operand_u8()),
        50 => Op::FixedToWord(record.operand_u8()),
        51 => Op::FixedMul(record.operand_u8()),
        52 => Op::FixedDiv(record.operand_u8()),
        53 => Op::Trap(record.operand_u16()),
        54 => Op::CheckedAdd,
        55 => Op::CheckedSub,
        56 => Op::CheckedMul(record.operand_u8()),
        57 => Op::CheckedNeg,
        58 => Op::CheckedDiv(record.operand_u8()),
        59 => Op::CheckedMod,
        60 => Op::PushImmediate(record.operand_u8()),
        61 => Op::PopN(record.operand_u8()),
        62 => Op::BitAnd,
        63 => Op::BitOr,
        64 => Op::BitXor,
        65 => Op::Shl,
        66 => Op::Shr,
        67 => {
            let (c, n) = record.operand_u16_u8();
            Op::CallVerifiedNative(c, n)
        }
        68 => {
            let (c, n) = record.operand_u16_u8();
            Op::CallExternalNative(c, n)
        }
        69 => {
            let bytes = record.operand_bytes();
            let kind = crate::value_layout::CompositeKind::from_tag(bytes[2] >> 6)
                .ok_or(WireFormatError::TupleFieldKindUnknown(bytes[2]))?;
            let low = bytes[2] & 0x3F;
            if low == NEW_COMPOSITE_POOL_SENTINEL {
                // Pool form: index in bytes one and two.
                let idx = u16::from_le_bytes([bytes[0], bytes[1]]) as usize;
                let entry = pool
                    .get(idx)
                    .copied()
                    .ok_or(WireFormatError::OperandPoolIndexOutOfBounds(idx))?;
                entry.check_parity()?;
                if entry.tag() != POOL_TAG_U16_U16_U8 {
                    return Err(WireFormatError::OperandPoolTagMismatch {
                        observed: entry.tag(),
                        expected: POOL_TAG_U16_U16_U8,
                    });
                }
                let (count, b_field, boxed_flag) = entry.as_u16_u16_u8();
                if boxed_flag == 1 {
                    Op::NewComposite(crate::bytecode::NewCompositeOperand::Boxed {
                        kind,
                        count,
                        meta: b_field,
                    })
                } else {
                    Op::NewComposite(crate::bytecode::NewCompositeOperand::Flat {
                        kind,
                        count,
                        byte_size: b_field,
                    })
                }
            } else {
                // Inline flat: byte size in bytes one and two, count in the
                // low six bits of byte three.
                Op::NewComposite(crate::bytecode::NewCompositeOperand::Flat {
                    kind,
                    count: low as u16,
                    byte_size: u16::from_le_bytes([bytes[0], bytes[1]]),
                })
            }
        }
        other => return Err(WireFormatError::UnknownOpcodeId(other)),
    };
    let _ = opcode_name_for_id(id);
    Ok(op)
}

/// Helper: fetch a `(u16, u16)` operand pool entry, validating
/// the index, the parity, and the type tag.
fn decode_pool_u16_u16(
    record: OpcodeRecord,
    pool: &[OperandPoolEntry],
) -> Result<(u16, u16), WireFormatError> {
    let idx = record.operand_pool_index() as usize;
    let entry = pool
        .get(idx)
        .copied()
        .ok_or(WireFormatError::OperandPoolIndexOutOfBounds(idx))?;
    entry.check_parity()?;
    if entry.tag() != POOL_TAG_U16_U16 {
        return Err(WireFormatError::OperandPoolTagMismatch {
            observed: entry.tag(),
            expected: POOL_TAG_U16_U16,
        });
    }
    Ok(entry.as_u16_u16())
}

/// Helper: fetch the `(offset, size)` of a nested composite access from
/// a `from_u16_u16` pool entry, reading the pool index from operand bytes
/// one and two (byte three holds the variant sentinel) (B28 P2).
fn decode_nested_pool(
    record: OpcodeRecord,
    pool: &[OperandPoolEntry],
) -> Result<(u16, u16), WireFormatError> {
    let bytes = record.operand_bytes();
    let idx = u16::from_le_bytes([bytes[0], bytes[1]]) as usize;
    let entry = pool
        .get(idx)
        .copied()
        .ok_or(WireFormatError::OperandPoolIndexOutOfBounds(idx))?;
    entry.check_parity()?;
    if entry.tag() != POOL_TAG_U16_U16 {
        return Err(WireFormatError::OperandPoolTagMismatch {
            observed: entry.tag(),
            expected: POOL_TAG_U16_U16,
        });
    }
    Ok(entry.as_u16_u16())
}

/// Helper: fetch a `(u16, u16, u16)` operand pool entry, validating the
/// index, the parity, and the type tag.
fn decode_pool_u16_u16_u16(
    record: OpcodeRecord,
    pool: &[OperandPoolEntry],
) -> Result<(u16, u16, u16), WireFormatError> {
    let idx = record.operand_pool_index() as usize;
    let entry = pool
        .get(idx)
        .copied()
        .ok_or(WireFormatError::OperandPoolIndexOutOfBounds(idx))?;
    entry.check_parity()?;
    if entry.tag() != POOL_TAG_U16_U16_U16 {
        return Err(WireFormatError::OperandPoolTagMismatch {
            observed: entry.tag(),
            expected: POOL_TAG_U16_U16_U16,
        });
    }
    Ok(entry.as_u16_u16_u16())
}

/// Footer length: the trailing CRC-32 over the entire framed
/// bytecode.
pub const WIRE_FORMAT_FOOTER_BYTES: usize = 4;

/// Information about a module's signature, extracted from the
/// framing header's signature-extension block. Used both by the
/// decoder (to validate framing) and by the signature-verification
/// path (to locate the signature bytes and construct the message
/// view).
#[derive(Debug, Clone, Copy)]
pub struct SignatureInfo {
    /// Scheme identifier at byte 64 of the header. The only V0.2.0
    /// scheme is `SIGNATURE_SCHEME_ED25519 = 1`.
    pub scheme_id: u8,
    /// Byte offset within the framed buffer where the raw
    /// signature bytes begin. Always `WIRE_FORMAT_HEADER_BYTES +
    /// SIGNATURE_METADATA_BYTES = 72` for the V0.2.0 layout.
    pub signature_offset: usize,
    /// Length of the signature in bytes. For Ed25519: 64.
    pub signature_length: usize,
}

/// Compute the framing header length for a signed module given
/// the chosen signature scheme. Pads to an 8-byte boundary so the
/// body that follows starts aligned.
pub const fn signed_header_length(signature_length: usize) -> usize {
    let unpadded = WIRE_FORMAT_HEADER_BYTES + SIGNATURE_METADATA_BYTES + signature_length;
    // Round up to multiple of 8 for body alignment.
    (unpadded + 7) & !7
}

/// Parse the optional signature-extension metadata block at the
/// tail of the framing header. Returns `Ok(None)` for an unsigned
/// module (header_length exactly `WIRE_FORMAT_HEADER_BYTES`).
/// Returns `Ok(Some(info))` for a well-formed signed module.
/// Returns `Err` if the extension is malformed, claims an unknown
/// scheme, or carries an unexpected signature length.
///
/// `bytes` must point at the start of the framed buffer (after
/// any shebang strip). `header_length` must already be validated
/// to fall within the buffer.
pub fn parse_signature_metadata(
    bytes: &[u8],
    header_length: usize,
) -> Result<Option<SignatureInfo>, LoadError> {
    if header_length == WIRE_FORMAT_HEADER_BYTES {
        return Ok(None);
    }
    if header_length < WIRE_FORMAT_HEADER_BYTES + SIGNATURE_METADATA_BYTES {
        return Err(LoadError::Codec(format!(
            "header_length {} is less than the minimum {} required for a signature extension",
            header_length,
            WIRE_FORMAT_HEADER_BYTES + SIGNATURE_METADATA_BYTES,
        )));
    }
    let scheme_id = bytes[64];
    let reserved_byte = bytes[65];
    let signature_length = u16::from_le_bytes([bytes[66], bytes[67]]) as usize;
    let reserved_word = u32::from_le_bytes([bytes[68], bytes[69], bytes[70], bytes[71]]);
    if reserved_byte != 0 || reserved_word != 0 {
        return Err(LoadError::Codec(String::from(
            "signature metadata reserved fields must be zero",
        )));
    }
    if scheme_id == 0 {
        return Err(LoadError::Codec(String::from(
            "signature metadata scheme_id 0 is reserved; signed modules must use scheme_id >= 1",
        )));
    }
    if scheme_id != SIGNATURE_SCHEME_ED25519 {
        return Err(LoadError::Codec(format!(
            "signature scheme_id {} is not supported in this build (only Ed25519 = {} is implemented in V0.2.0)",
            scheme_id, SIGNATURE_SCHEME_ED25519,
        )));
    }
    if signature_length != ED25519_SIGNATURE_BYTES {
        return Err(LoadError::Codec(format!(
            "Ed25519 signature_length must be {}; got {}",
            ED25519_SIGNATURE_BYTES, signature_length,
        )));
    }
    let expected_header_length = signed_header_length(signature_length);
    let expected_encrypted_header_length = expected_header_length + ENCRYPTION_METADATA_BYTES;
    let encrypted = bytes[15] & FLAG_ENCRYPTED != 0;
    let acceptable = if encrypted {
        header_length == expected_encrypted_header_length
    } else {
        header_length == expected_header_length
    };
    if !acceptable {
        let expected = if encrypted {
            expected_encrypted_header_length
        } else {
            expected_header_length
        };
        return Err(LoadError::Codec(format!(
            "header_length {} does not match expected {} (sig metadata {} + sig {}{} + padding to 8-byte multiple)",
            header_length,
            expected,
            SIGNATURE_METADATA_BYTES,
            signature_length,
            if encrypted {
                " + encryption metadata"
            } else {
                ""
            },
        )));
    }
    Ok(Some(SignatureInfo {
        scheme_id,
        signature_offset: WIRE_FORMAT_HEADER_BYTES + SIGNATURE_METADATA_BYTES,
        signature_length,
    }))
}

/// Reflected polynomial residue produced after concatenating any
/// byte sequence with the little-endian encoding of its CRC-32.
/// The wire-format reader verifies the bytecode through this
/// residue equality.
const WIRE_FORMAT_CRC32_RESIDUE: u32 = 0x2144DF1C;

/// Wire-format chunk metadata. Mirrors [`Chunk`] but moves the
/// `ops` vector out of the rkyv-archived body and into the
/// opcode stream section. Carries the byte offset and record
/// count needed to recover the chunk's opcode sequence from the
/// section-partitioned body.
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct WireChunk {
    /// Function name; matches `Chunk::name`.
    pub name: String,
    /// Constant pool; matches `Chunk::constants`.
    pub constants: Vec<ConstValue>,
    /// Struct templates; matches `Chunk::struct_templates`.
    pub struct_templates: Vec<StructTemplate>,
    /// Total local variable slots; matches `Chunk::local_count`.
    pub local_count: u16,
    /// Number of parameters; matches `Chunk::param_count`.
    pub param_count: u8,
    /// Block type classification; matches `Chunk::block_type`.
    pub block_type: BlockType,
    /// Parameter type tags; matches `Chunk::param_types`.
    pub param_types: Vec<TypeTag>,
    /// Byte offset into the opcode stream section where this
    /// chunk's opcode records start. Always a multiple of
    /// [`OPCODE_RECORD_BYTES`].
    pub op_byte_offset: u32,
    /// Number of opcode records that compose this chunk's body.
    /// The chunk's total byte span in the opcode stream is
    /// `op_record_count * OPCODE_RECORD_BYTES`.
    pub op_record_count: u32,
    /// Optional strippable debug metadata (B29), carried as the
    /// canonical bytes produced by
    /// [`crate::debug_meta::DebugPool::encode`]. `None` for a release
    /// build or a stripped artefact. Held as opaque bytes so the
    /// section is parseable by external tooling without rkyv and so
    /// dropping it (strip) is a single `None` assignment. The debug
    /// metadata lives only here in the auxiliary body, never in the
    /// opcode stream, which keeps the opcode stream byte-identical
    /// between debug and release builds.
    pub debug_pool_bytes: Option<Vec<u8>>,
}

/// Wire-format auxiliary body. Mirrors [`Module`] but carries
/// [`WireChunk`] metadata (ops live in the opcode stream
/// section).
#[derive(Debug, Clone, Archive, Serialize, Deserialize)]
pub struct WireAuxBody {
    /// Chunk metadata for the module's chunks.
    pub chunks: Vec<WireChunk>,
    /// Native function names referenced by the module.
    pub native_names: Vec<String>,
    /// Entry-point chunk index, if the module declares one.
    pub entry_point: Option<usize>,
    /// Data-segment layout, if the module declares any data fields.
    pub data_layout: Option<DataLayout>,
    /// Runtime word width declared by the module, encoded as the
    /// base-2 logarithm of the bit width.
    pub word_bits_log2: u8,
    /// Runtime address width declared by the module, log2 form.
    pub addr_bits_log2: u8,
    /// Runtime float width declared by the module, log2 form.
    pub float_bits_log2: u8,
    /// Declared WCET in pipelined cycles per Stream-to-Reset slice.
    /// `0` means auto; `u32::MAX` means overflow.
    pub wcet_cycles: u32,
    /// Declared WCMU in bytes per Stream-to-Reset slice. `0` means
    /// auto; `u32::MAX` means overflow.
    pub wcmu_bytes: u32,
    /// Header flag byte (e.g. `FLAG_EPHEMERAL`, `FLAG_REQUIRES_SIGNATURE`).
    pub flags: u8,
    /// Verifier-populated byte count for the shared partition of
    /// the data segment.
    pub shared_data_bytes: u32,
    /// Verifier-populated byte count for the private partition of
    /// the data segment.
    pub private_data_bytes: u32,
    /// CRC-32 of the canonical serialisation of
    /// `(slot_name, visibility)` per slot in declaration order.
    /// Used by `Vm::replace_module` to reject schema-incompatible
    /// hot swaps.
    pub schema_hash: u32,
    /// Per-enum-type layout descriptors; mirrors `Module::enum_layouts`
    /// (B37). Rkyv-archived in the auxiliary body alongside the chunk
    /// metadata.
    pub enum_layouts: Vec<crate::bytecode::EnumLayout>,
    /// Per-chunk signature descriptors for the typed operand-stack verifier
    /// pass (A.2.1 Phase 2b); mirrors `Module::signatures`. Additive in the
    /// auxiliary body alongside `enum_layouts`; empty for a module compiled
    /// without the descriptors, which the pass treats as all-`Top`.
    pub signatures: Vec<crate::bytecode::ChunkSignature>,
    /// Native return-value flat shapes; mirrors `Module::native_return_shapes`,
    /// parallel to `native_names`. Additive in the auxiliary body; empty for a
    /// module compiled without the descriptors.
    pub native_return_shapes: Vec<crate::bytecode::WireShape>,
}

/// Strip a `#!` shebang prefix from a byte slice. Wire-format
/// bytes that begin with `#!` are produced when a host appends
/// the bytecode after an executable shebang; the strip returns
/// the slice past the first `\n`. Bytes without the prefix pass
/// through unchanged.
pub(crate) fn strip_shebang_prefix(bytes: &[u8]) -> &[u8] {
    if bytes.starts_with(b"#!") {
        if let Some(newline_pos) = bytes.iter().position(|&b| b == b'\n') {
            &bytes[newline_pos + 1..]
        } else {
            bytes
        }
    } else {
        bytes
    }
}

/// Borrowed view of the three body sections inside a framed
/// V0.2.0 wire-format buffer. Callers obtain this through
/// [`parse_wire_sections`] after framing-level validation has
/// run.
#[derive(Debug, Clone, Copy)]
pub struct WireSections<'a> {
    /// Bytes of the opcode stream section. Length is a multiple
    /// of [`OPCODE_RECORD_BYTES`].
    pub opcode_stream: &'a [u8],
    /// Bytes of the operand pool section. Length is a multiple
    /// of [`OPERAND_POOL_ENTRY_BYTES`].
    pub operand_pool: &'a [u8],
    /// Bytes of the rkyv-archived auxiliary body.
    pub aux_body: &'a [u8],
}

/// Header-mirrored fields exposed by [`read_header_fields`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeaderFields {
    /// Declared word width, encoded as the base-2 logarithm of the
    /// bit width.
    pub word_bits_log2: u8,
    /// Declared address width, log2 form.
    pub addr_bits_log2: u8,
    /// Declared float width, log2 form.
    pub float_bits_log2: u8,
    /// Header flag byte.
    pub flags: u8,
    /// Declared WCET in pipelined cycles. `0` means auto;
    /// `u32::MAX` means overflow.
    pub wcet_cycles: u32,
    /// Declared WCMU in bytes. Same convention as `wcet_cycles`.
    pub wcmu_bytes: u32,
    /// Verifier-populated byte count for the shared data partition.
    pub shared_data_bytes: u32,
    /// Verifier-populated byte count for the private data partition.
    pub private_data_bytes: u32,
}

/// Parse a framed V0.2.0 wire-format buffer and return slices
/// for the three body sections. Validates the framing header
/// (magic, version, header length, total length), the CRC-32
/// residue, and the section bounds. Does not deserialize the
/// auxiliary body; callers feed `aux_body` to
/// `rkyv::access::<ArchivedWireAuxBody, _>` or to
/// `rkyv::from_bytes::<WireAuxBody, _>`.
///
/// The returned slices borrow from the input. Used by both
/// [`module_from_wire_bytes`] and the VM's zero-copy view path.
pub fn parse_wire_sections(bytes: &[u8]) -> Result<WireSections<'_>, LoadError> {
    let bytes = strip_shebang_prefix(bytes);
    if bytes.len() < WIRE_FORMAT_HEADER_BYTES + WIRE_FORMAT_FOOTER_BYTES {
        return Err(LoadError::Truncated);
    }
    if bytes[0..4] != BYTECODE_MAGIC {
        return Err(LoadError::BadMagic);
    }
    let version = u16::from_le_bytes([bytes[4], bytes[5]]);
    if version != BYTECODE_VERSION {
        return Err(LoadError::UnsupportedVersion {
            got: version,
            expected: BYTECODE_VERSION,
        });
    }
    let header_length = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
    if header_length < WIRE_FORMAT_HEADER_BYTES {
        return Err(LoadError::Codec(format!(
            "wire format header_length {} is below the minimum {}",
            header_length, WIRE_FORMAT_HEADER_BYTES
        )));
    }
    if header_length > bytes.len() {
        return Err(LoadError::Truncated);
    }
    let total_length = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
    if total_length < header_length + WIRE_FORMAT_FOOTER_BYTES || total_length > bytes.len() {
        return Err(LoadError::Truncated);
    }
    let bytes = &bytes[..total_length];
    if crc32(bytes) != WIRE_FORMAT_CRC32_RESIDUE {
        return Err(LoadError::BadChecksum);
    }
    // Signature-extension consistency. If the flag is set, the
    // header must carry a signature metadata block; if the flag
    // is unset, the header must be exactly the base size.
    let flags = bytes[15];
    let signed = (flags & FLAG_REQUIRES_SIGNATURE) != 0;
    let sig_info = parse_signature_metadata(bytes, header_length)?;
    match (signed, sig_info) {
        (true, None) => {
            return Err(LoadError::Codec(String::from(
                "FLAG_REQUIRES_SIGNATURE is set but the header carries no signature extension",
            )));
        }
        (false, Some(_)) => {
            return Err(LoadError::Codec(String::from(
                "header carries a signature extension but FLAG_REQUIRES_SIGNATURE is not set; V0.2.0 does not admit audit-only signatures",
            )));
        }
        _ => {}
    }
    let opcode_stream_offset =
        u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]) as usize;
    let opcode_stream_length =
        u32::from_le_bytes([bytes[36], bytes[37], bytes[38], bytes[39]]) as usize;
    let operand_pool_offset =
        u32::from_le_bytes([bytes[40], bytes[41], bytes[42], bytes[43]]) as usize;
    let operand_pool_length =
        u32::from_le_bytes([bytes[44], bytes[45], bytes[46], bytes[47]]) as usize;
    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 body_end = total_length - WIRE_FORMAT_FOOTER_BYTES;
    let in_body = |off: usize, len: usize| -> bool {
        off >= header_length && off.checked_add(len).is_some_and(|end| end <= body_end)
    };
    if !in_body(opcode_stream_offset, opcode_stream_length)
        || !in_body(operand_pool_offset, operand_pool_length)
        || !in_body(aux_body_offset, aux_body_length)
    {
        return Err(LoadError::Truncated);
    }
    if !opcode_stream_length.is_multiple_of(OPCODE_RECORD_BYTES) {
        return Err(LoadError::Codec(format!(
            "opcode stream length {} is not a multiple of the record size {}",
            opcode_stream_length, OPCODE_RECORD_BYTES,
        )));
    }
    if !operand_pool_length.is_multiple_of(OPERAND_POOL_ENTRY_BYTES) {
        return Err(LoadError::Codec(format!(
            "operand pool length {} is not a multiple of the entry size {}",
            operand_pool_length, OPERAND_POOL_ENTRY_BYTES,
        )));
    }
    Ok(WireSections {
        opcode_stream: &bytes[opcode_stream_offset..opcode_stream_offset + opcode_stream_length],
        operand_pool: &bytes[operand_pool_offset..operand_pool_offset + operand_pool_length],
        aux_body: &bytes[aux_body_offset..aux_body_offset + aux_body_length],
    })
}

/// Read header-mirrored target widths and declared WCET / WCMU
/// fields from a framed V0.2.0 wire-format buffer. Used by
/// [`crate::bytecode::Module::access_bytes`] (and the VM's
/// zero-copy path) to surface the fast-path metadata without
/// deserializing the auxiliary body.
pub fn read_header_fields(bytes: &[u8]) -> Result<HeaderFields, LoadError> {
    // The parse_wire_sections call validates framing and CRC;
    // reuse it so the header read participates in the same
    // validation pass.
    let _ = parse_wire_sections(bytes)?;
    let bytes = strip_shebang_prefix(bytes);
    Ok(HeaderFields {
        word_bits_log2: bytes[12],
        addr_bits_log2: bytes[13],
        float_bits_log2: bytes[14],
        flags: bytes[15],
        wcet_cycles: u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]),
        wcmu_bytes: u32::from_le_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]),
        shared_data_bytes: u32::from_le_bytes([bytes[24], bytes[25], bytes[26], bytes[27]]),
        private_data_bytes: u32::from_le_bytes([bytes[28], bytes[29], bytes[30], bytes[31]]),
    })
}

/// Decode every opcode record in `opcode_stream` against
/// `operand_pool` and return the resulting `Vec<Op>`. Used by
/// the VM at construction time to populate `decoded_ops` from
/// the wire-format sections.
pub fn decode_op_stream(
    opcode_stream: &[u8],
    operand_pool_bytes: &[u8],
) -> Result<Vec<Op>, LoadError> {
    if !opcode_stream.len().is_multiple_of(OPCODE_RECORD_BYTES) {
        return Err(LoadError::Codec(format!(
            "opcode stream length {} is not a multiple of {}",
            opcode_stream.len(),
            OPCODE_RECORD_BYTES,
        )));
    }
    if !operand_pool_bytes
        .len()
        .is_multiple_of(OPERAND_POOL_ENTRY_BYTES)
    {
        return Err(LoadError::Codec(format!(
            "operand pool length {} is not a multiple of {}",
            operand_pool_bytes.len(),
            OPERAND_POOL_ENTRY_BYTES,
        )));
    }
    let mut pool: Vec<OperandPoolEntry> =
        Vec::with_capacity(operand_pool_bytes.len() / OPERAND_POOL_ENTRY_BYTES);
    for chunk_off in (0..operand_pool_bytes.len()).step_by(OPERAND_POOL_ENTRY_BYTES) {
        let mut entry = [0u8; OPERAND_POOL_ENTRY_BYTES];
        entry.copy_from_slice(&operand_pool_bytes[chunk_off..chunk_off + OPERAND_POOL_ENTRY_BYTES]);
        let entry = OperandPoolEntry(entry);
        entry
            .check_parity()
            .map_err(|e| LoadError::Codec(format!("operand pool entry corruption: {:?}", e)))?;
        pool.push(entry);
    }
    let mut ops: Vec<Op> = Vec::with_capacity(opcode_stream.len() / OPCODE_RECORD_BYTES);
    for off in (0..opcode_stream.len()).step_by(OPCODE_RECORD_BYTES) {
        let mut rec = [0u8; OPCODE_RECORD_BYTES];
        rec.copy_from_slice(&opcode_stream[off..off + OPCODE_RECORD_BYTES]);
        let op = decode_op(OpcodeRecord(rec), &pool)
            .map_err(|e| LoadError::Codec(format!("opcode decode failed: {:?}", e)))?;
        ops.push(op);
    }
    Ok(ops)
}

/// Encode a [`Module`] into the V0.2.0 wire format: 64-byte
/// framing header, opcode stream, operand pool, rkyv-archived
/// auxiliary body, 4-byte CRC-32 trailer.
///
/// The opcode stream packs every chunk's opcodes as 4-byte
/// records in chunk declaration order. The auxiliary body's
/// [`WireChunk`] entries point into the opcode stream through
/// `op_byte_offset` and `op_record_count`. Compound operands
/// (`(u16, u16)` for `Op::GetDataIndexed` / `Op::SetDataIndexed`
/// / `Op::IsEnum` and `(u16, u16, u8)` for `Op::NewEnum`) flow
/// into the operand pool as 8-byte entries indexed by the
/// inline 24-bit pool index in the opcode record.
pub fn module_to_wire_bytes(module: &Module) -> Result<Vec<u8>, LoadError> {
    // Build the opcode stream and operand pool. Track per-chunk
    // byte offsets and record counts for the WireChunk metadata.
    let mut opcode_stream: Vec<u8> = Vec::new();
    let mut operand_pool: Vec<OperandPoolEntry> = Vec::new();
    let mut wire_chunks: Vec<WireChunk> = Vec::with_capacity(module.chunks.len());
    for chunk in &module.chunks {
        let op_byte_offset = opcode_stream.len() as u32;
        let op_record_count = chunk.ops.len() as u32;
        for op in &chunk.ops {
            let record = encode_op(op, &mut operand_pool)
                .map_err(|e| LoadError::Codec(format!("opcode encode failed: {:?}", e)))?;
            opcode_stream.extend_from_slice(&record.0);
        }
        wire_chunks.push(WireChunk {
            name: chunk.name.clone(),
            constants: chunk.constants.clone(),
            struct_templates: chunk.struct_templates.clone(),
            local_count: chunk.local_count,
            param_count: chunk.param_count,
            block_type: chunk.block_type,
            param_types: chunk.param_types.clone(),
            op_byte_offset,
            op_record_count,
            debug_pool_bytes: chunk.debug_pool.as_ref().map(|p| p.encode()),
        });
    }
    let aux = WireAuxBody {
        chunks: wire_chunks,
        enum_layouts: module.enum_layouts.clone(),
        signatures: module.signatures.clone(),
        native_return_shapes: module.native_return_shapes.clone(),
        native_names: module.native_names.clone(),
        entry_point: module.entry_point,
        data_layout: module.data_layout.clone(),
        word_bits_log2: module.word_bits_log2,
        addr_bits_log2: module.addr_bits_log2,
        float_bits_log2: module.float_bits_log2,
        wcet_cycles: module.wcet_cycles,
        wcmu_bytes: module.wcmu_bytes,
        flags: module.flags,
        shared_data_bytes: module.shared_data_bytes,
        private_data_bytes: module.private_data_bytes,
        schema_hash: module.schema_hash,
    };
    let aux_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&aux)
        .map_err(|e| LoadError::Codec(format!("aux body encode failed: {}", e)))?;

    // Flatten operand pool to bytes.
    let mut operand_pool_bytes: Vec<u8> =
        Vec::with_capacity(operand_pool.len() * OPERAND_POOL_ENTRY_BYTES);
    for entry in &operand_pool {
        operand_pool_bytes.extend_from_slice(&entry.0);
    }

    assemble_wire_bytes(
        module,
        &opcode_stream,
        &operand_pool_bytes,
        &aux_bytes,
        None,
    )
}

/// Shared buffer assembly for both signed and unsigned encoder
/// paths. The `signature` parameter encodes whether the output
/// should include a signature-extension block:
///
/// - `None`: produces an unsigned buffer with a 64-byte framing
///   header. The buffer is fully framed including the CRC trailer.
/// - `Some(scheme_id)`: produces a signed buffer with an extended
///   header that holds the signature metadata and a *zeroed*
///   signature payload. The CRC trailer is also zeroed. The
///   caller (`module_to_signed_wire_bytes`) is responsible for
///   computing the signature over the zeroed buffer, patching the
///   real signature bytes into the header, and finally computing
///   and patching the real CRC.
fn assemble_wire_bytes(
    module: &Module,
    opcode_stream: &[u8],
    operand_pool_bytes: &[u8],
    aux_bytes: &[u8],
    signature: Option<u8>,
) -> Result<Vec<u8>, LoadError> {
    // Determine header_length and the flag state of the module.
    let (header_length, effective_flags) = match signature {
        None => (WIRE_FORMAT_HEADER_BYTES, module.flags),
        Some(SIGNATURE_SCHEME_ED25519) => (
            signed_header_length(ED25519_SIGNATURE_BYTES),
            module.flags | FLAG_REQUIRES_SIGNATURE,
        ),
        Some(other) => {
            return Err(LoadError::Codec(format!(
                "unsupported signature scheme_id {} (only Ed25519 = {} ships in V0.2.0)",
                other, SIGNATURE_SCHEME_ED25519
            )));
        }
    };
    // Compute section offsets. The opcode stream begins
    // immediately after the framing header. Each section is then
    // padded to an 8-byte boundary so the next section starts
    // aligned. The aux body is rkyv-archived and requires 8-byte
    // alignment for in-place access.
    let opcode_stream_offset = header_length as u32;
    let opcode_stream_length = opcode_stream.len() as u32;
    let mut after_opcodes = opcode_stream_offset + opcode_stream_length;
    let opcode_padding = ((8 - (after_opcodes as usize % 8)) % 8) as u32;
    after_opcodes += opcode_padding;
    let operand_pool_offset = after_opcodes;
    let operand_pool_length = operand_pool_bytes.len() as u32;
    let mut after_pool = operand_pool_offset + operand_pool_length;
    let pool_padding = ((8 - (after_pool as usize % 8)) % 8) as u32;
    after_pool += pool_padding;
    let aux_body_offset = after_pool;
    let aux_body_length = aux_bytes.len() as u32;
    let after_aux = aux_body_offset + aux_body_length;
    let total_length = after_aux + WIRE_FORMAT_FOOTER_BYTES as u32;

    // Assemble the buffer.
    let mut buf: Vec<u8> = Vec::with_capacity(total_length as usize);
    // Framing header (base 64 bytes).
    buf.extend_from_slice(&BYTECODE_MAGIC);
    buf.extend_from_slice(&BYTECODE_VERSION.to_le_bytes());
    buf.extend_from_slice(&(header_length as u16).to_le_bytes());
    buf.extend_from_slice(&total_length.to_le_bytes());
    buf.push(module.word_bits_log2);
    buf.push(module.addr_bits_log2);
    buf.push(module.float_bits_log2);
    buf.push(effective_flags);
    buf.extend_from_slice(&module.wcet_cycles.to_le_bytes());
    buf.extend_from_slice(&module.wcmu_bytes.to_le_bytes());
    buf.extend_from_slice(&module.shared_data_bytes.to_le_bytes());
    buf.extend_from_slice(&module.private_data_bytes.to_le_bytes());
    buf.extend_from_slice(&opcode_stream_offset.to_le_bytes());
    buf.extend_from_slice(&opcode_stream_length.to_le_bytes());
    buf.extend_from_slice(&operand_pool_offset.to_le_bytes());
    buf.extend_from_slice(&operand_pool_length.to_le_bytes());
    buf.extend_from_slice(&aux_body_offset.to_le_bytes());
    buf.extend_from_slice(&aux_body_length.to_le_bytes());
    // Runtime ephemeral tracking-list pre-size figure (B28 P3 item 5,
    // Phase C). Occupies the formerly-reserved word at offset 56; a `0`
    // value leaves the bytes identical to the prior reserved zero-fill.
    buf.extend_from_slice(&module.aux_arena_bytes.to_le_bytes()); // offsets 56..60
    // Persistent flat-composite body pool size for private `.data` slots
    // (B28 P3 item 5, item 3a). Occupies the formerly-reserved word at offset
    // 60; a `0` value leaves the bytes identical to the prior reserved
    // zero-fill, so a module with no private composite slots is byte-unchanged.
    buf.extend_from_slice(&module.persistent_composite_bytes.to_le_bytes()); // offsets 60..64
    debug_assert_eq!(buf.len(), WIRE_FORMAT_HEADER_BYTES);

    // Signature extension. The signature payload is zero-filled
    // here; the caller patches the real signature in after signing
    // the zero-filled buffer.
    if let Some(scheme_id) = signature {
        // 8-byte signature metadata block.
        buf.push(scheme_id);
        buf.push(0); // reserved
        let signature_length = match scheme_id {
            SIGNATURE_SCHEME_ED25519 => ED25519_SIGNATURE_BYTES,
            _ => unreachable!("validated above"),
        };
        buf.extend_from_slice(&(signature_length as u16).to_le_bytes());
        buf.extend_from_slice(&[0u8; 4]); // reserved
        // Signature payload (zero placeholder).
        buf.resize(buf.len() + signature_length, 0);
        // Pad to 8-byte boundary so the body starts aligned.
        while buf.len() < header_length {
            buf.push(0);
        }
        debug_assert_eq!(buf.len(), header_length);
    }

    // Opcode stream + alignment padding.
    buf.extend_from_slice(opcode_stream);
    buf.resize(buf.len() + opcode_padding as usize, 0);

    // Operand pool + alignment padding.
    buf.extend_from_slice(operand_pool_bytes);
    buf.resize(buf.len() + pool_padding as usize, 0);

    // Auxiliary body.
    buf.extend_from_slice(aux_bytes);

    // CRC trailer. Compute over the buffer so far (signed and
    // unsigned paths both produce a valid CRC at this point).
    let crc = crc32(&buf);
    buf.extend_from_slice(&crc.to_le_bytes());
    debug_assert_eq!(buf.len(), total_length as usize);
    Ok(buf)
}

/// Encode a [`Module`] into the V0.2.0 wire format with an
/// Ed25519 signature appended to the framing header. Sets
/// `FLAG_REQUIRES_SIGNATURE` in the header's flags byte.
///
/// The signature is computed over the entire framed buffer with
/// the signature payload bytes and the CRC trailer bytes zeroed.
/// The verifier reconstructs the same view by copying the
/// received buffer and zeroing those two regions before calling
/// [`verify_module_signature`].
///
/// Requires the `signatures` cargo feature. Without it, the
/// `signed` surface keyword still parses (for source-file
/// portability) but no host can produce signed bytecode.
#[cfg(feature = "signatures")]
pub fn module_to_signed_wire_bytes(
    module: &Module,
    signing_key: &ed25519_dalek::SigningKey,
) -> Result<Vec<u8>, LoadError> {
    use ed25519_dalek::Signer;

    // Re-run the per-chunk encoding so we have the opcode stream,
    // operand pool, and aux body bytes to hand to the shared
    // assembler. This is a small duplication of `module_to_wire_bytes`
    // but keeps the signed and unsigned encode paths uniform.
    let mut opcode_stream: Vec<u8> = Vec::new();
    let mut operand_pool: Vec<OperandPoolEntry> = Vec::new();
    let mut wire_chunks: Vec<WireChunk> = Vec::with_capacity(module.chunks.len());
    for chunk in &module.chunks {
        let op_byte_offset = opcode_stream.len() as u32;
        let op_record_count = chunk.ops.len() as u32;
        for op in &chunk.ops {
            let record = encode_op(op, &mut operand_pool)
                .map_err(|e| LoadError::Codec(format!("opcode encode failed: {:?}", e)))?;
            opcode_stream.extend_from_slice(&record.0);
        }
        wire_chunks.push(WireChunk {
            name: chunk.name.clone(),
            constants: chunk.constants.clone(),
            struct_templates: chunk.struct_templates.clone(),
            local_count: chunk.local_count,
            param_count: chunk.param_count,
            block_type: chunk.block_type,
            param_types: chunk.param_types.clone(),
            op_byte_offset,
            op_record_count,
            debug_pool_bytes: chunk.debug_pool.as_ref().map(|p| p.encode()),
        });
    }
    let aux = WireAuxBody {
        chunks: wire_chunks,
        enum_layouts: module.enum_layouts.clone(),
        signatures: module.signatures.clone(),
        native_return_shapes: module.native_return_shapes.clone(),
        native_names: module.native_names.clone(),
        entry_point: module.entry_point,
        data_layout: module.data_layout.clone(),
        word_bits_log2: module.word_bits_log2,
        addr_bits_log2: module.addr_bits_log2,
        float_bits_log2: module.float_bits_log2,
        wcet_cycles: module.wcet_cycles,
        wcmu_bytes: module.wcmu_bytes,
        flags: module.flags | FLAG_REQUIRES_SIGNATURE,
        shared_data_bytes: module.shared_data_bytes,
        private_data_bytes: module.private_data_bytes,
        schema_hash: module.schema_hash,
    };
    let aux_bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&aux)
        .map_err(|e| LoadError::Codec(format!("aux body encode failed: {}", e)))?;
    let mut operand_pool_bytes: Vec<u8> =
        Vec::with_capacity(operand_pool.len() * OPERAND_POOL_ENTRY_BYTES);
    for entry in &operand_pool {
        operand_pool_bytes.extend_from_slice(&entry.0);
    }

    // Assemble with a zeroed signature payload.
    let mut buf = assemble_wire_bytes(
        module,
        &opcode_stream,
        &operand_pool_bytes,
        &aux_bytes,
        Some(SIGNATURE_SCHEME_ED25519),
    )?;
    let total_length = buf.len();

    // Zero the CRC trailer for the signing pass.
    let footer_start = total_length - WIRE_FORMAT_FOOTER_BYTES;
    for byte in &mut buf[footer_start..] {
        *byte = 0;
    }

    // Sign over (header + zeroed signature + body + zeroed CRC).
    let signature = signing_key.sign(&buf);
    let sig_bytes = signature.to_bytes();

    // Patch the real signature into the header.
    let sig_offset = WIRE_FORMAT_HEADER_BYTES + SIGNATURE_METADATA_BYTES;
    buf[sig_offset..sig_offset + ED25519_SIGNATURE_BYTES].copy_from_slice(&sig_bytes);

    // Recompute and write the real CRC trailer.
    let crc = crc32(&buf[..footer_start]);
    buf[footer_start..].copy_from_slice(&crc.to_le_bytes());

    Ok(buf)
}

/// Verify that the bytecode at `bytes` carries a signature
/// matching at least one of the supplied verifying keys. Returns
/// `Ok(())` on a successful match; `Err(LoadError::InvalidSignature)`
/// if no key matches; other `LoadError` variants if the framing
/// or signature metadata is malformed.
///
/// The verification message is the bytecode buffer with the
/// signature payload bytes and the CRC trailer bytes zeroed. This
/// matches the signing convention in
/// [`module_to_signed_wire_bytes`].
///
/// Requires the `signatures` cargo feature.
#[cfg(feature = "signatures")]
pub fn verify_module_signature(
    bytes: &[u8],
    keys: &[ed25519_dalek::VerifyingKey],
) -> Result<(), LoadError> {
    let bytes = strip_shebang_prefix(bytes);
    if bytes.len() < WIRE_FORMAT_HEADER_BYTES + WIRE_FORMAT_FOOTER_BYTES {
        return Err(LoadError::Truncated);
    }
    if bytes[0..4] != BYTECODE_MAGIC {
        return Err(LoadError::BadMagic);
    }
    let header_length = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
    let total_length = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
    if total_length > bytes.len() {
        return Err(LoadError::Truncated);
    }
    let bytes = &bytes[..total_length];
    let sig_info = parse_signature_metadata(bytes, header_length)?
        .ok_or_else(|| LoadError::Codec(String::from("module is not signed")))?;

    // Build the verification message: the entire framed buffer
    // with the signature payload and CRC trailer zeroed.
    let mut message: Vec<u8> = bytes.to_vec();
    let sig_start = sig_info.signature_offset;
    let sig_end = sig_start + sig_info.signature_length;
    for byte in &mut message[sig_start..sig_end] {
        *byte = 0;
    }
    let footer_start = total_length - WIRE_FORMAT_FOOTER_BYTES;
    for byte in &mut message[footer_start..] {
        *byte = 0;
    }

    // Extract the signature.
    let mut signature_bytes = [0u8; ED25519_SIGNATURE_BYTES];
    signature_bytes.copy_from_slice(&bytes[sig_start..sig_end]);
    let signature = ed25519_dalek::Signature::from_bytes(&signature_bytes);

    // Try each key. The first match wins; an empty key set
    // produces `InvalidSignature` (no host trust matrix → reject).
    // `verify_strict` rejects the malleable forms `verify` admits (a
    // non-canonical scalar `S`, or an `R`/`A` with a small-order
    // component), so a signed module has a single canonical signature
    // and a third party cannot mint a distinct one that still verifies
    // (audit finding 23).
    for key in keys {
        if key.verify_strict(&message, &signature).is_ok() {
            return Ok(());
        }
    }
    Err(LoadError::InvalidSignature)
}

/// Returns `true` if the framing header carries the signature-
/// requirement flag. Used by load-time paths that may not have
/// the `signatures` feature compiled in: such builds reject the
/// module with `LoadError::SignaturesUnsupported` rather than
/// silently admitting an unverified signed module.
pub fn header_requires_signature(bytes: &[u8]) -> bool {
    let bytes = strip_shebang_prefix(bytes);
    bytes.len() > 15 && (bytes[15] & FLAG_REQUIRES_SIGNATURE) != 0
}

/// Returns `true` if the framing header carries the encryption
/// flag. Used by load-time paths that may not have the
/// `encryption` feature compiled in: such builds reject the
/// module with `LoadError::EncryptionUnsupported` rather than
/// silently admitting an encrypted module that the runtime
/// cannot decrypt.
pub fn header_requires_encryption(bytes: &[u8]) -> bool {
    let bytes = strip_shebang_prefix(bytes);
    bytes.len() > 15 && (bytes[15] & FLAG_ENCRYPTED) != 0
}

/// Compute the framing header length for a signed-and-encrypted
/// module using the Ed25519+X25519+AES-256-GCM scheme. The header
/// extends the signed header by an 88-byte encryption-metadata
/// block. The result is the offset at which the encrypted body
/// (ciphertext + AES-GCM tag) begins.
pub const fn encrypted_signed_header_length() -> usize {
    let signed_part = signed_header_length(ED25519_SIGNATURE_BYTES);
    // 88 bytes is already 8-byte aligned; no extra padding needed.
    signed_part + ENCRYPTION_METADATA_BYTES
}

/// Encode a [`Module`] into the V0.2.1 wire format with both an
/// Ed25519 signature and X25519+AES-256-GCM body encryption. Sets
/// both `FLAG_REQUIRES_SIGNATURE` and `FLAG_ENCRYPTED` in the
/// header's flags byte.
///
/// The body bytes (opcode stream + operand pool + aux body, with
/// alignment padding) are encrypted with a per-module AES-256
/// key derived from an X25519 Diffie-Hellman against the
/// destination runtime's public key. The encryption metadata
/// block (ephemeral public key, recipient_key_id, AES-GCM nonce)
/// is appended to the framing header.
///
/// The signature covers the entire on-disk framed buffer with
/// the signature payload bytes and the CRC trailer bytes zeroed.
/// This means the signature authenticates both the encryption
/// metadata and the ciphertext, so an adversary cannot strip the
/// encryption layer and substitute cleartext bytecode while
/// preserving signature validity.
///
/// Requires both the `signatures` and `encryption` cargo features.
///
/// # Parameters
///
/// - `module`: the compiled module to encrypt and sign.
/// - `signing_key`: the Ed25519 signing key (typically the head
///   office's release key). Held by the compiler.
/// - `recipient_public_key`: the destination runtime's X25519
///   public key. Encryption is against this key; only the
///   matching private key on the destination runtime can decrypt.
/// - `ephemeral_seed`: 32 bytes of cryptographic randomness for
///   the per-module ephemeral X25519 key. The caller is
///   responsible for sourcing this from the OS RNG.
#[cfg(all(feature = "signatures", feature = "encryption"))]
pub fn module_to_encrypted_signed_wire_bytes(
    module: &Module,
    signing_key: &ed25519_dalek::SigningKey,
    recipient_public_key: &[u8; crate::encryption::X25519_PUBLIC_KEY_LEN],
    ephemeral_seed: &[u8; crate::encryption::X25519_PRIVATE_KEY_LEN],
) -> Result<Vec<u8>, LoadError> {
    use crate::encryption::{AES_GCM_TAG_LEN, encrypt_to_recipient};
    use ed25519_dalek::Signer;

    // Reuse the signed-encode flow to produce the "virtual"
    // unencrypted-signed wire bytes. Then encrypt the body in
    // place and patch the header to advertise the encryption.

    // Step 1. Build the signed (but unencrypted) wire bytes.
    let signed_bytes = module_to_signed_wire_bytes(module, signing_key)?;

    // The body in the signed_bytes occupies the range
    // [signed_header_length, signed_bytes.len() - WIRE_FORMAT_FOOTER_BYTES).
    let signed_header_len = signed_header_length(ED25519_SIGNATURE_BYTES);
    let plaintext_body_start = signed_header_len;
    let plaintext_body_end = signed_bytes.len() - WIRE_FORMAT_FOOTER_BYTES;
    let plaintext_body = &signed_bytes[plaintext_body_start..plaintext_body_end];

    // Step 2. Encrypt the body. The ciphertext returned by AES-GCM
    // is the encrypted bytes plus a 16-byte authentication tag.
    let (encryption_metadata, ciphertext_with_tag) =
        encrypt_to_recipient(plaintext_body, recipient_public_key, ephemeral_seed)
            .map_err(|e| LoadError::Codec(format!("encryption failed: {}", e)))?;
    debug_assert_eq!(
        ciphertext_with_tag.len(),
        plaintext_body.len() + AES_GCM_TAG_LEN
    );

    // Step 3. Assemble the encrypted-signed buffer.
    //
    // Layout:
    // - bytes 0..64:                     base framing header
    // - bytes 64..72:                    signature metadata block
    // - bytes 72..136:                   Ed25519 signature (placeholder zero for now)
    // - bytes 136..224:                  encryption metadata block (88 bytes)
    // - bytes 224..(224+ciphertext_len): ciphertext + AES-GCM tag
    // - last 4 bytes:                    CRC trailer
    let encrypted_header_len = encrypted_signed_header_length();
    let on_disk_total = encrypted_header_len + ciphertext_with_tag.len() + WIRE_FORMAT_FOOTER_BYTES;

    let mut buf: Vec<u8> = Vec::with_capacity(on_disk_total);

    // Copy the base header from the signed buffer, then patch the
    // flags, header_length, total_length, and section offsets.
    buf.extend_from_slice(&signed_bytes[..WIRE_FORMAT_HEADER_BYTES]);

    // Patch flags to include FLAG_ENCRYPTED.
    buf[15] |= FLAG_ENCRYPTED;

    // Patch header_length to the encrypted-signed value.
    buf[6..8].copy_from_slice(&(encrypted_header_len as u16).to_le_bytes());

    // Patch total_length to the on-disk file size.
    buf[8..12].copy_from_slice(&(on_disk_total as u32).to_le_bytes());

    // Patch section offsets to point at the locations where the
    // sections will live in the reconstructed plaintext view after
    // decryption. Each section offset in the original signed
    // buffer pointed at signed_header_len + section_offset_within_body.
    // In the reconstructed plaintext buffer the same sections will
    // be at encrypted_header_len + section_offset_within_body.
    // So shift each offset by (encrypted_header_len - signed_header_len) = 88.
    let shift = encrypted_header_len - signed_header_len;
    patch_section_offsets(&mut buf, shift);

    // Copy the signature metadata block and the signature.
    buf.extend_from_slice(&signed_bytes[WIRE_FORMAT_HEADER_BYTES..signed_header_len]);

    // Append the encryption metadata block.
    buf.extend_from_slice(&encryption_metadata.to_bytes());
    debug_assert_eq!(buf.len(), encrypted_header_len);

    // Append ciphertext + tag.
    buf.extend_from_slice(&ciphertext_with_tag);

    // Append zeroed CRC trailer placeholder.
    buf.extend_from_slice(&[0u8; WIRE_FORMAT_FOOTER_BYTES]);
    debug_assert_eq!(buf.len(), on_disk_total);

    // Re-sign over the new buffer (with signature payload and CRC
    // zeroed; both already zero in the assembled buffer at this
    // point because the signature was copied from the original
    // signed buffer and then the encryption metadata + ciphertext
    // + tag were appended, changing what the signature should
    // cover. Zero out the signature payload before re-signing.)
    let sig_offset = WIRE_FORMAT_HEADER_BYTES + SIGNATURE_METADATA_BYTES;
    for byte in &mut buf[sig_offset..sig_offset + ED25519_SIGNATURE_BYTES] {
        *byte = 0;
    }
    let signature = signing_key.sign(&buf);
    let sig_bytes = signature.to_bytes();
    buf[sig_offset..sig_offset + ED25519_SIGNATURE_BYTES].copy_from_slice(&sig_bytes);

    // Compute and patch the real CRC.
    let crc_offset = on_disk_total - WIRE_FORMAT_FOOTER_BYTES;
    let crc = crc32(&buf[..crc_offset]);
    buf[crc_offset..].copy_from_slice(&crc.to_le_bytes());

    Ok(buf)
}

/// Patch the section-offset fields in the framing header by adding
/// `shift` to each. Used by the encryption assembler to shift
/// section offsets from "signed header" positions (header_length =
/// 136) to "encrypted-signed header" positions (header_length =
/// 224). The body sections move 88 bytes forward in the file.
///
/// Header field offsets being patched:
/// - bytes 32..36: opcode_stream_offset (u32 LE)
/// - bytes 40..44: operand_pool_offset (u32 LE)
/// - bytes 48..52: aux_body_offset (u32 LE)
#[cfg(all(feature = "signatures", feature = "encryption"))]
fn patch_section_offsets(buf: &mut [u8], shift: usize) {
    let shift = shift as u32;
    for offset in [32, 40, 48] {
        let mut bytes = [0u8; 4];
        bytes.copy_from_slice(&buf[offset..offset + 4]);
        let old = u32::from_le_bytes(bytes);
        let new = old + shift;
        buf[offset..offset + 4].copy_from_slice(&new.to_le_bytes());
    }
}

/// Decrypt an encrypted-signed module and reconstruct a buffer
/// equivalent to an unencrypted-signed module of the same content.
/// The reconstructed buffer has the same shape an `unencrypted
/// signed` wire-format buffer would have, so the existing
/// signature-verifying load path can process it without further
/// modification.
///
/// Verifies the signature over the encrypted form FIRST (to
/// authenticate origin before doing any decryption work), then
/// decrypts the body, then constructs the plaintext view with
/// FLAG_ENCRYPTED cleared and section offsets adjusted.
///
/// Requires both the `signatures` and `encryption` cargo features.
///
/// # Parameters
///
/// - `bytes`: the on-disk encrypted-signed bytecode buffer.
/// - `verifying_keys`: the host's trust matrix for signature
///   verification. The signature must validate against at least
///   one of these.
/// - `local_private_key`: the host's X25519 private key. Used to
///   decrypt the body. The corresponding public key must match
///   the `recipient_key_id` in the encryption metadata.
#[cfg(all(feature = "signatures", feature = "encryption"))]
pub fn decrypt_encrypted_signed_to_signed_bytes(
    bytes: &[u8],
    verifying_keys: &[ed25519_dalek::VerifyingKey],
    local_private_key: &[u8; crate::encryption::X25519_PRIVATE_KEY_LEN],
) -> Result<Vec<u8>, LoadError> {
    use crate::encryption::{AES_GCM_TAG_LEN, EncryptionMetadata, decrypt_from_metadata};

    let bytes = strip_shebang_prefix(bytes);

    // Step 1. Basic framing validation.
    if bytes.len() < encrypted_signed_header_length() + WIRE_FORMAT_FOOTER_BYTES {
        return Err(LoadError::Truncated);
    }
    if bytes[0..4] != BYTECODE_MAGIC[..] {
        return Err(LoadError::BadMagic);
    }
    let flags = bytes[15];
    if flags & FLAG_ENCRYPTED == 0 {
        return Err(LoadError::Codec(String::from(
            "decrypt_encrypted_signed_to_signed_bytes called on bytes without FLAG_ENCRYPTED",
        )));
    }
    if flags & FLAG_REQUIRES_SIGNATURE == 0 {
        return Err(LoadError::Codec(String::from(
            "FLAG_ENCRYPTED requires FLAG_REQUIRES_SIGNATURE; encrypted modules must be signed",
        )));
    }

    // Step 2. Verify the signature against the encrypted form.
    // This authenticates origin before any decryption work runs,
    // and ensures the encryption metadata has not been tampered
    // with.
    verify_module_signature(bytes, verifying_keys)?;

    // Step 3. Parse the encryption metadata.
    let encrypted_header_len = encrypted_signed_header_length();
    let signed_header_len = signed_header_length(ED25519_SIGNATURE_BYTES);
    let metadata_offset = signed_header_len;
    let metadata_bytes = &bytes[metadata_offset..metadata_offset + ENCRYPTION_METADATA_BYTES];
    let metadata = EncryptionMetadata::from_bytes(metadata_bytes).ok_or_else(|| {
        LoadError::Codec(String::from(
            "encryption metadata malformed or scheme unsupported",
        ))
    })?;

    // Step 4. Extract ciphertext + tag from the body region.
    let body_start = encrypted_header_len;
    let body_end = bytes.len() - WIRE_FORMAT_FOOTER_BYTES;
    if body_end <= body_start || body_end - body_start < AES_GCM_TAG_LEN {
        return Err(LoadError::Truncated);
    }
    let ciphertext_with_tag = &bytes[body_start..body_end];

    // Step 5. Decrypt.
    let plaintext = decrypt_from_metadata(&metadata, ciphertext_with_tag, local_private_key)
        .map_err(|e| LoadError::Codec(format!("decryption failed: {}", e)))?;

    // Step 6. Reconstruct an equivalent unencrypted-signed buffer.
    // Layout:
    // - bytes 0..64:                  base header (modified)
    // - bytes 64..72:                 signature metadata (copied)
    // - bytes 72..136:                signature (copied)
    // - bytes 136..(136+plaintext):   plaintext body
    // - last 4 bytes:                 fresh CRC
    let reconstructed_total = signed_header_len + plaintext.len() + WIRE_FORMAT_FOOTER_BYTES;
    let mut buf: Vec<u8> = Vec::with_capacity(reconstructed_total);

    // Copy base header from the encrypted form, then patch.
    buf.extend_from_slice(&bytes[..WIRE_FORMAT_HEADER_BYTES]);

    // Clear FLAG_ENCRYPTED.
    buf[15] &= !FLAG_ENCRYPTED;

    // Patch header_length back to signed-only value.
    buf[6..8].copy_from_slice(&(signed_header_len as u16).to_le_bytes());

    // Patch total_length to the reconstructed size.
    buf[8..12].copy_from_slice(&(reconstructed_total as u32).to_le_bytes());

    // Shift section offsets back by 88 (encryption_metadata block
    // is gone in the reconstructed form).
    let shift = encrypted_header_len - signed_header_len;
    patch_section_offsets_subtract(&mut buf, shift);

    // Copy signature metadata and signature bytes.
    buf.extend_from_slice(&bytes[WIRE_FORMAT_HEADER_BYTES..signed_header_len]);

    // Append plaintext body.
    buf.extend_from_slice(&plaintext);

    // Compute and append fresh CRC. The CRC range excludes the
    // last 4 bytes (the CRC itself).
    let crc_offset = reconstructed_total - WIRE_FORMAT_FOOTER_BYTES;
    let crc = crc32(&buf[..crc_offset]);
    buf.extend_from_slice(&crc.to_le_bytes());
    debug_assert_eq!(buf.len(), reconstructed_total);

    // The signature in the reconstructed buffer was valid for the
    // encrypted form, but is no longer valid for the reconstructed
    // (decrypted) form. Callers must not re-verify the signature
    // on the reconstructed buffer; they should verify against the
    // original encrypted bytes (already done in step 2 above).
    //
    // The reconstructed buffer is intended to be passed directly to
    // a deserializer that does NOT re-verify the signature. The
    // simplest way to communicate this is by having the runtime
    // route this through a different entry point that skips the
    // signature check.
    Ok(buf)
}

/// Patch the section-offset fields in the framing header by
/// subtracting `shift` from each. Inverse of [`patch_section_offsets`].
#[cfg(all(feature = "signatures", feature = "encryption"))]
fn patch_section_offsets_subtract(buf: &mut [u8], shift: usize) {
    let shift = shift as u32;
    for offset in [32, 40, 48] {
        let mut bytes = [0u8; 4];
        bytes.copy_from_slice(&buf[offset..offset + 4]);
        let old = u32::from_le_bytes(bytes);
        let new = old.saturating_sub(shift);
        buf[offset..offset + 4].copy_from_slice(&new.to_le_bytes());
    }
}

/// Decode the V0.2.0 wire format produced by
/// [`module_to_wire_bytes`] back into a [`Module`].
///
/// Validates the framing header, the CRC residue, and the
/// declared section offsets/lengths. Reads the opcode stream
/// and operand pool, deserializes the rkyv-archived auxiliary
/// body, and reconstructs each chunk's `ops` from its byte
/// offset and record count.
///
/// V0.2.0 Phase 7b ships this function as a parallel route to
/// [`Module::from_bytes`]; the cutover is Phase 7c.
pub fn module_from_wire_bytes(bytes: &[u8]) -> Result<Module, LoadError> {
    let bytes = strip_shebang_prefix(bytes);
    if bytes.len() < WIRE_FORMAT_HEADER_BYTES + WIRE_FORMAT_FOOTER_BYTES {
        return Err(LoadError::Truncated);
    }
    if bytes[0..4] != BYTECODE_MAGIC {
        return Err(LoadError::BadMagic);
    }
    let version = u16::from_le_bytes([bytes[4], bytes[5]]);
    if version != BYTECODE_VERSION {
        return Err(LoadError::UnsupportedVersion {
            got: version,
            expected: BYTECODE_VERSION,
        });
    }
    let header_length = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
    if header_length < WIRE_FORMAT_HEADER_BYTES {
        return Err(LoadError::Codec(format!(
            "wire format header_length {} is below the minimum {}",
            header_length, WIRE_FORMAT_HEADER_BYTES
        )));
    }
    if header_length > bytes.len() {
        return Err(LoadError::Truncated);
    }
    let total_length = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
    if total_length < header_length + WIRE_FORMAT_FOOTER_BYTES || total_length > bytes.len() {
        return Err(LoadError::Truncated);
    }
    let bytes = &bytes[..total_length];
    if crc32(bytes) != WIRE_FORMAT_CRC32_RESIDUE {
        return Err(LoadError::BadChecksum);
    }
    let word_bits_log2 = bytes[12];
    let addr_bits_log2 = bytes[13];
    let float_bits_log2 = bytes[14];
    let flags = bytes[15];
    let wcet_cycles = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
    let wcmu_bytes = u32::from_le_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
    let shared_data_bytes = u32::from_le_bytes([bytes[24], bytes[25], bytes[26], bytes[27]]);
    let private_data_bytes = u32::from_le_bytes([bytes[28], bytes[29], bytes[30], bytes[31]]);
    let opcode_stream_offset =
        u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]) as usize;
    let opcode_stream_length =
        u32::from_le_bytes([bytes[36], bytes[37], bytes[38], bytes[39]]) as usize;
    let operand_pool_offset =
        u32::from_le_bytes([bytes[40], bytes[41], bytes[42], bytes[43]]) as usize;
    let operand_pool_length =
        u32::from_le_bytes([bytes[44], bytes[45], bytes[46], bytes[47]]) as usize;
    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;
    // Offsets 56..60 carry the runtime ephemeral tracking-list pre-size
    // figure (B28 P3 item 5, Phase C); offsets 60..64 carry the persistent
    // flat-composite body pool size for private `.data` slots (item 3a). A
    // module without private composite slots leaves offset 60 at zero, matching
    // the prior reserved zero-fill.
    let aux_arena_bytes = u32::from_le_bytes([bytes[56], bytes[57], bytes[58], bytes[59]]);
    let persistent_composite_bytes =
        u32::from_le_bytes([bytes[60], bytes[61], bytes[62], bytes[63]]);
    // Signature-extension consistency. Reuse `parse_wire_sections`'
    // logic by inlining the same check.
    let signed = (flags & FLAG_REQUIRES_SIGNATURE) != 0;
    let sig_info = parse_signature_metadata(bytes, header_length)?;
    match (signed, sig_info) {
        (true, None) => {
            return Err(LoadError::Codec(String::from(
                "FLAG_REQUIRES_SIGNATURE is set but the header carries no signature extension",
            )));
        }
        (false, Some(_)) => {
            return Err(LoadError::Codec(String::from(
                "header carries a signature extension but FLAG_REQUIRES_SIGNATURE is not set; V0.2.0 does not admit audit-only signatures",
            )));
        }
        _ => {}
    }
    // Section bounds sanity. Each section fits entirely within
    // the frame (after the header, before the CRC trailer).
    let body_end = total_length - WIRE_FORMAT_FOOTER_BYTES;
    let in_body = |off: usize, len: usize| -> bool {
        off >= header_length && off.checked_add(len).is_some_and(|end| end <= body_end)
    };
    if !in_body(opcode_stream_offset, opcode_stream_length)
        || !in_body(operand_pool_offset, operand_pool_length)
        || !in_body(aux_body_offset, aux_body_length)
    {
        return Err(LoadError::Truncated);
    }
    if !opcode_stream_length.is_multiple_of(OPCODE_RECORD_BYTES) {
        return Err(LoadError::Codec(format!(
            "opcode stream length {} is not a multiple of the record size {}",
            opcode_stream_length, OPCODE_RECORD_BYTES,
        )));
    }
    if !operand_pool_length.is_multiple_of(OPERAND_POOL_ENTRY_BYTES) {
        return Err(LoadError::Codec(format!(
            "operand pool length {} is not a multiple of the entry size {}",
            operand_pool_length, OPERAND_POOL_ENTRY_BYTES,
        )));
    }

    // Slice the sections.
    let opcode_stream = &bytes[opcode_stream_offset..opcode_stream_offset + opcode_stream_length];
    let operand_pool_bytes = &bytes[operand_pool_offset..operand_pool_offset + operand_pool_length];
    let aux_body_bytes = &bytes[aux_body_offset..aux_body_offset + aux_body_length];

    // Decode the operand pool. Each entry's parity is validated
    // here so a corruption error surfaces before the chunks are
    // walked.
    let mut operand_pool: Vec<OperandPoolEntry> = Vec::with_capacity(operand_pool_bytes.len() / 8);
    for chunk_offset in (0..operand_pool_bytes.len()).step_by(OPERAND_POOL_ENTRY_BYTES) {
        let mut entry_bytes = [0u8; OPERAND_POOL_ENTRY_BYTES];
        entry_bytes.copy_from_slice(
            &operand_pool_bytes[chunk_offset..chunk_offset + OPERAND_POOL_ENTRY_BYTES],
        );
        let entry = OperandPoolEntry(entry_bytes);
        entry
            .check_parity()
            .map_err(|e| LoadError::Codec(format!("operand pool entry corruption: {:?}", e)))?;
        operand_pool.push(entry);
    }

    // Validate target widths against the runtime maxima before
    // touching the auxiliary body so the most specific error
    // surfaces. A header field that exceeds the runtime maximum
    // is reported as the matching SizeMismatch variant rather
    // than as a header-versus-aux mismatch.
    if word_bits_log2 > crate::bytecode::RUNTIME_WORD_BITS_LOG2 {
        return Err(LoadError::WordSizeMismatch {
            got: word_bits_log2,
            max_supported: crate::bytecode::RUNTIME_WORD_BITS_LOG2,
        });
    }
    if addr_bits_log2 > crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2 {
        return Err(LoadError::AddressSizeMismatch {
            got: addr_bits_log2,
            max_supported: crate::bytecode::RUNTIME_ADDRESS_BITS_LOG2,
        });
    }
    if float_bits_log2 > crate::bytecode::RUNTIME_FLOAT_BITS_LOG2 {
        return Err(LoadError::FloatSizeMismatch {
            got: float_bits_log2,
            max_supported: crate::bytecode::RUNTIME_FLOAT_BITS_LOG2,
        });
    }

    // Deserialize the auxiliary body. `rkyv::from_bytes` calls
    // `rkyv::access` internally which validates the archive in
    // place; the validation requires the buffer to be aligned to
    // `align_of::<ArchivedWireAuxBody>()` (8 bytes). The
    // `aux_body_bytes` subslice inherits the input buffer's
    // alignment, which is not guaranteed for `include_bytes!`
    // payloads, file reads, or arbitrary host-supplied byte
    // sources. Copy into an 8-byte-aligned scratch buffer so the
    // archive validation observes the required alignment on every
    // target architecture. The legacy `Module::from_bytes` path
    // (pre V0.2.0 Phase 7c) used the same pattern; the cutover
    // dropped the copy step, which produced an unaligned decode
    // on 32-bit targets where the input buffer happens to land at
    // a 4-byte boundary.
    let mut aligned: rkyv::util::AlignedVec<8> =
        rkyv::util::AlignedVec::with_capacity(aux_body_bytes.len());
    aligned.extend_from_slice(aux_body_bytes);
    let aux = rkyv::from_bytes::<WireAuxBody, rkyv::rancor::Error>(&aligned)
        .map_err(|e| LoadError::Codec(format!("aux body decode failed: {}", e)))?;

    // Cross-check header-mirrored fields against the auxiliary
    // body. The header is the fast-path view; the aux body is
    // the authoritative copy. Disagreement signals a malformed
    // producer or a corrupted artefact.
    if aux.word_bits_log2 != word_bits_log2
        || aux.addr_bits_log2 != addr_bits_log2
        || aux.float_bits_log2 != float_bits_log2
        || aux.flags != flags
        || aux.wcet_cycles != wcet_cycles
        || aux.wcmu_bytes != wcmu_bytes
        || aux.shared_data_bytes != shared_data_bytes
        || aux.private_data_bytes != private_data_bytes
    {
        return Err(LoadError::Codec(String::from(
            "wire-format header fields disagree with the auxiliary body",
        )));
    }

    // Decode chunks. Each WireChunk identifies its opcode span
    // by (op_byte_offset, op_record_count). The records and any
    // pool entries they reference are read from the previously-
    // decoded `operand_pool`.
    let mut chunks: Vec<Chunk> = Vec::with_capacity(aux.chunks.len());
    for wc in &aux.chunks {
        let start = wc.op_byte_offset as usize;
        let record_count = wc.op_record_count as usize;
        let byte_span = record_count
            .checked_mul(OPCODE_RECORD_BYTES)
            .ok_or_else(|| LoadError::Codec(String::from("opcode span overflow")))?;
        let end = start
            .checked_add(byte_span)
            .ok_or_else(|| LoadError::Codec(String::from("opcode span overflow")))?;
        if end > opcode_stream.len() {
            return Err(LoadError::Codec(format!(
                "chunk `{}` opcode span [{}..{}) exceeds opcode stream length {}",
                wc.name,
                start,
                end,
                opcode_stream.len(),
            )));
        }
        let mut ops: Vec<Op> = Vec::with_capacity(record_count);
        let chunk_bytes = &opcode_stream[start..end];
        for offset in (0..byte_span).step_by(OPCODE_RECORD_BYTES) {
            let mut rec = [0u8; OPCODE_RECORD_BYTES];
            rec.copy_from_slice(&chunk_bytes[offset..offset + OPCODE_RECORD_BYTES]);
            let op = decode_op(OpcodeRecord(rec), &operand_pool)
                .map_err(|e| LoadError::Codec(format!("opcode decode failed: {:?}", e)))?;
            ops.push(op);
        }
        let debug_pool = match &wc.debug_pool_bytes {
            Some(bytes) => Some(
                crate::debug_meta::DebugPool::decode(bytes)
                    .map_err(|e| LoadError::Codec(format!("debug pool decode failed: {:?}", e)))?,
            ),
            None => None,
        };
        chunks.push(Chunk {
            name: wc.name.clone(),
            ops,
            constants: wc.constants.clone(),
            struct_templates: wc.struct_templates.clone(),
            local_count: wc.local_count,
            param_count: wc.param_count,
            block_type: wc.block_type,
            param_types: wc.param_types.clone(),
            debug_pool,
        });
    }

    Ok(Module {
        chunks,
        enum_layouts: aux.enum_layouts,
        signatures: aux.signatures,
        native_return_shapes: aux.native_return_shapes,
        native_names: aux.native_names,
        entry_point: aux.entry_point,
        data_layout: aux.data_layout,
        word_bits_log2: aux.word_bits_log2,
        addr_bits_log2: aux.addr_bits_log2,
        float_bits_log2: aux.float_bits_log2,
        wcet_cycles: aux.wcet_cycles,
        wcmu_bytes: aux.wcmu_bytes,
        // Carried only in the framing header (CRC-covered) at offset 56,
        // not mirrored in the auxiliary body (B28 P3 item 5, Phase C).
        aux_arena_bytes,
        // Carried in the framing header at offset 60 (B28 P3 item 5, item 3a).
        persistent_composite_bytes,
        flags: aux.flags,
        shared_data_bytes: aux.shared_data_bytes,
        private_data_bytes: aux.private_data_bytes,
        schema_hash: aux.schema_hash,
    })
}

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

    fn roundtrip(op: Op) {
        let mut pool: Vec<OperandPoolEntry> = Vec::new();
        let record = encode_op(&op, &mut pool).expect("encode");
        record.check_parity().expect("parity");
        let decoded = decode_op(record, &pool).expect("decode");
        assert_eq!(op, decoded);
    }

    #[test]
    fn opcode_id_table_is_dense_and_unique() {
        // Every identifier in the table is in range and the
        // mapping is a bijection. The table is part of the wire-
        // format ABI; a regression here is a wire-format break.
        let mut seen: alloc::collections::BTreeSet<u8> = alloc::collections::BTreeSet::new();
        for (_, id) in OPCODE_ID_TABLE.iter() {
            assert!(*id < 128, "opcode id {} does not fit in seven bits", id);
            assert!(seen.insert(*id), "duplicate opcode id {}", id);
        }
        assert_eq!(seen.len(), OPCODE_ID_TABLE.len());
    }

    #[test]
    fn opcode_id_of_matches_table() {
        // For each variant in the canonical table, build the
        // representative `Op` value and confirm `opcode_id_of`
        // returns the same identifier.
        let cases: &[(Op, u8)] = &[
            (Op::Const(0), 0),
            (Op::GetLocal(0), 1),
            (Op::SetLocal(0), 2),
            (Op::GetData(0), 3),
            (Op::SetData(0), 4),
            (Op::GetDataIndexed(0, 0), 5),
            (Op::SetDataIndexed(0, 0), 6),
            (Op::BoundsCheck(0), 7),
            (Op::Add, 8),
            (Op::Sub, 9),
            (Op::Mul, 10),
            (Op::Div, 11),
            (Op::Mod, 12),
            (Op::Neg, 13),
            (Op::CmpEq, 14),
            (Op::CmpNe, 15),
            (Op::CmpLt, 16),
            (Op::CmpGt, 17),
            (Op::CmpLe, 18),
            (Op::CmpGe, 19),
            (Op::Not, 20),
            (Op::If(0), 21),
            (Op::Else(0), 22),
            (Op::EndIf, 23),
            (Op::Loop(0), 24),
            (Op::EndLoop(0), 25),
            (Op::Break(0), 26),
            (Op::BreakIf(0), 27),
            (Op::Stream, 28),
            (Op::Reset, 29),
            (Op::Call(0, 0), 30),
            (Op::Return, 31),
            (Op::Yield, 32),
            (Op::Dup, 33),
            (
                Op::GetField(crate::bytecode::StructField::Boxed { name_const: 0 }),
                38,
            ),
            (Op::GetIndex(crate::bytecode::ArrayElem::Boxed), 39),
            (
                Op::GetTupleField(crate::bytecode::TupleField::Boxed { index: 0 }),
                40,
            ),
            (
                Op::GetEnumField(crate::bytecode::EnumField::Boxed { index: 0 }),
                41,
            ),
            (Op::Len, 42),
            (Op::IsEnum(0, 0, 0), 43),
            (Op::IsStruct(0), 44),
            (Op::IntToFloat, 45),
            (Op::FloatToInt, 46),
            (Op::WordToByte, 47),
            (Op::ByteToWord, 48),
            (Op::WordToFixed(0), 49),
            (Op::FixedToWord(0), 50),
            (Op::FixedMul(0), 51),
            (Op::FixedDiv(0), 52),
            (Op::Trap(0), 53),
            (Op::CheckedAdd, 54),
            (Op::CheckedSub, 55),
            (Op::CheckedMul(0), 56),
            (Op::CheckedNeg, 57),
            (Op::CheckedDiv(0), 58),
            (Op::CheckedMod, 59),
            (Op::PushImmediate(0), 60),
            (Op::PopN(0), 61),
            (Op::BitAnd, 62),
            (Op::BitOr, 63),
            (Op::BitXor, 64),
            (Op::Shl, 65),
            (Op::Shr, 66),
            (Op::CallVerifiedNative(0, 0), 67),
            (Op::CallExternalNative(0, 0), 68),
            (
                Op::NewComposite(crate::bytecode::NewCompositeOperand::Flat {
                    kind: crate::value_layout::CompositeKind::Tuple,
                    count: 0,
                    byte_size: 0,
                }),
                69,
            ),
        ];
        for (op, expected) in cases {
            assert_eq!(
                opcode_id_of(op).0,
                *expected,
                "wrong opcode id for {:?}",
                op,
            );
        }
        assert_eq!(cases.len(), OPCODE_ID_TABLE.len());
    }

    #[test]
    fn new_composite_roundtrips_all_forms() {
        use crate::bytecode::NewCompositeOperand as NCO;
        use crate::value_layout::CompositeKind as CK;
        let cases = [
            // Inline flat: small count, kind in the high bits.
            NCO::Flat {
                kind: CK::Struct,
                count: 3,
                byte_size: 24,
            },
            NCO::Flat {
                kind: CK::Enum,
                count: 62,
                byte_size: 65535,
            },
            // Pool flat: count beyond the inline maximum.
            NCO::Flat {
                kind: CK::Array,
                count: 1000,
                byte_size: 8000,
            },
            // Boxed: metadata index, no byte size.
            NCO::Boxed {
                kind: CK::Struct,
                count: 2,
                meta: 7,
            },
            NCO::Boxed {
                kind: CK::Tuple,
                count: 4,
                meta: 0,
            },
        ];
        for operand in cases {
            let mut pool = Vec::new();
            let record = encode_op(&Op::NewComposite(operand), &mut pool).unwrap();
            let decoded = decode_op(record, &pool).unwrap();
            assert_eq!(decoded, Op::NewComposite(operand), "round-trip mismatch");
        }
    }

    #[test]
    fn opcode_record_roundtrip_no_operand() {
        for op in [
            Op::Add,
            Op::Sub,
            Op::Mul,
            Op::Div,
            Op::Mod,
            Op::Neg,
            Op::CmpEq,
            Op::CmpNe,
            Op::CmpLt,
            Op::CmpGt,
            Op::CmpLe,
            Op::CmpGe,
            Op::Not,
            Op::EndIf,
            Op::Stream,
            Op::Reset,
            Op::Return,
            Op::Yield,
            Op::Dup,
            Op::Len,
            Op::IntToFloat,
            Op::FloatToInt,
            Op::WordToByte,
            Op::ByteToWord,
            Op::CheckedAdd,
            Op::CheckedSub,
            Op::CheckedNeg,
            Op::CheckedMod,
            Op::BitAnd,
            Op::BitOr,
            Op::BitXor,
            Op::Shl,
            Op::Shr,
        ] {
            roundtrip(op);
        }
    }

    #[test]
    fn opcode_record_roundtrip_u8_operand() {
        for op in [
            Op::GetEnumField(crate::bytecode::EnumField::Boxed { index: 3 }),
            Op::WordToFixed(32),
            Op::FixedToWord(16),
            Op::FixedMul(8),
            Op::FixedDiv(4),
            Op::CheckedMul(0),
            Op::CheckedMul(8),
            Op::CheckedDiv(0),
            Op::CheckedDiv(4),
            Op::PushImmediate(5),
            Op::PopN(2),
        ] {
            roundtrip(op);
        }
    }

    #[test]
    fn opcode_record_roundtrip_tuple_field() {
        use crate::bytecode::TupleField;
        use crate::value_layout::ScalarKind;
        for op in [
            Op::GetTupleField(TupleField::Boxed { index: 0 }),
            Op::GetTupleField(TupleField::Boxed { index: 255 }),
            Op::GetTupleField(TupleField::Flat {
                offset: 0,
                kind: ScalarKind::Bool,
            }),
            Op::GetTupleField(TupleField::Flat {
                offset: 9,
                kind: ScalarKind::Int,
            }),
            Op::GetTupleField(TupleField::Flat {
                offset: 65535,
                kind: ScalarKind::Byte,
            }),
            Op::GetTupleField(TupleField::Flat {
                offset: 16,
                kind: ScalarKind::Fixed,
            }),
            Op::GetIndex(crate::bytecode::ArrayElem::Boxed),
            Op::GetIndex(crate::bytecode::ArrayElem::Flat {
                kind: ScalarKind::Int,
            }),
            Op::GetIndex(crate::bytecode::ArrayElem::Flat {
                kind: ScalarKind::Byte,
            }),
        ] {
            roundtrip(op);
        }
    }

    #[test]
    fn tuple_field_unknown_kind_tag_rejected() {
        // Byte three carries a kind tag of 9, which maps to no
        // ScalarKind and is not the boxed sentinel, so the decoder
        // reports a corrupted operand rather than fabricating a kind.
        let record = OpcodeRecord::from_id_and_operand(OpcodeId(40), [0, 0, 9]);
        let result = decode_op(record, &[]);
        assert_eq!(result, Err(WireFormatError::TupleFieldKindUnknown(9)));
    }

    #[test]
    fn opcode_record_roundtrip_u16_operand() {
        for op in [
            Op::Const(0),
            Op::Const(65535),
            Op::GetLocal(12),
            Op::SetLocal(34),
            Op::GetData(56),
            Op::SetData(78),
            Op::BoundsCheck(100),
            Op::If(200),
            Op::Else(300),
            Op::Loop(400),
            Op::EndLoop(500),
            Op::Break(600),
            Op::BreakIf(700),
            Op::GetField(crate::bytecode::StructField::Boxed { name_const: 1000 }),
            Op::IsStruct(1100),
            Op::Trap(1200),
        ] {
            roundtrip(op);
        }
    }

    #[test]
    fn opcode_record_roundtrip_u16_u8_operand() {
        for op in [
            Op::Call(0, 0),
            Op::Call(65535, 255),
            Op::CallVerifiedNative(42, 3),
            Op::CallExternalNative(43, 1),
        ] {
            roundtrip(op);
        }
    }

    #[test]
    fn opcode_record_roundtrip_pool_u16_u16() {
        for op in [
            Op::GetDataIndexed(0, 0),
            Op::GetDataIndexed(65535, 65535),
            Op::SetDataIndexed(100, 200),
            Op::IsEnum(7, 13, 21),
        ] {
            roundtrip(op);
        }
    }

    #[test]
    fn parity_detects_bit_flip_in_opcode_record() {
        let mut pool: Vec<OperandPoolEntry> = Vec::new();
        let record = encode_op(&Op::Const(42), &mut pool).expect("encode");
        // Flip one bit in byte one.
        let mut corrupted = record.0;
        corrupted[1] ^= 0x01;
        let result = OpcodeRecord(corrupted).check_parity();
        assert_eq!(result, Err(WireFormatError::OpcodeRecordParityMismatch));
    }

    #[test]
    fn parity_detects_bit_flip_in_opcode_id() {
        let mut pool: Vec<OperandPoolEntry> = Vec::new();
        let record = encode_op(&Op::Add, &mut pool).expect("encode");
        let mut corrupted = record.0;
        // Flip a bit in the opcode id (not the parity bit).
        corrupted[0] ^= 0x01;
        let result = OpcodeRecord(corrupted).check_parity();
        assert_eq!(result, Err(WireFormatError::OpcodeRecordParityMismatch));
    }

    #[test]
    fn parity_detects_bit_flip_in_pool_entry() {
        let entry = OperandPoolEntry::from_u16_u16(1234, 5678);
        let mut corrupted = entry.0;
        // Flip a bit in the payload.
        corrupted[3] ^= 0x80;
        let result = OperandPoolEntry(corrupted).check_parity();
        assert_eq!(result, Err(WireFormatError::OperandPoolParityMismatch));
    }

    #[test]
    fn pool_tag_mismatch_surfaces_error() {
        // A pool entry tagged for (u16, u16) cannot satisfy an
        // opcode that wants (u16, u16, u8). Hand-craft the
        // mismatch and confirm the decoder rejects.
        let mut pool: Vec<OperandPoolEntry> = Vec::new();
        // First, encode something that uses the (u16, u16) shape.
        let _record = encode_op(&Op::GetDataIndexed(1, 2), &mut pool).expect("encode");
        // Manufacture a NewEnum record that references the same
        // (mismatched) entry.
        let id = opcode_id_of(&Op::NewComposite(
            crate::bytecode::NewCompositeOperand::Boxed {
                kind: crate::value_layout::CompositeKind::Struct,
                count: 0,
                meta: 0,
            },
        ));
        // Pool index 0, kind in the high bits, pool sentinel in the low six.
        let byte2 = (crate::value_layout::CompositeKind::Struct.to_tag() << 6)
            | NEW_COMPOSITE_POOL_SENTINEL;
        let bad_record = OpcodeRecord::from_id_and_operand(id, [0, 0, byte2]);
        let result = decode_op(bad_record, &pool);
        assert_eq!(
            result,
            Err(WireFormatError::OperandPoolTagMismatch {
                observed: POOL_TAG_U16_U16,
                expected: POOL_TAG_U16_U16_U8,
            }),
        );
    }

    #[test]
    fn pool_index_out_of_bounds_surfaces_error() {
        let pool: Vec<OperandPoolEntry> = Vec::new();
        let id = opcode_id_of(&Op::GetDataIndexed(0, 0));
        let idx_bytes = (5u32).to_le_bytes();
        let record =
            OpcodeRecord::from_id_and_operand(id, [idx_bytes[0], idx_bytes[1], idx_bytes[2]]);
        let result = decode_op(record, &pool);
        assert_eq!(result, Err(WireFormatError::OperandPoolIndexOutOfBounds(5)));
    }

    #[test]
    fn unknown_opcode_id_surfaces_error() {
        // Identifier 100 is unassigned in V0.2.0. The decoder
        // surfaces `UnknownOpcodeId` rather than panicking.
        let record = OpcodeRecord::from_id_and_operand(OpcodeId(100), [0, 0, 0]);
        let pool: Vec<OperandPoolEntry> = Vec::new();
        let result = decode_op(record, &pool);
        assert_eq!(result, Err(WireFormatError::UnknownOpcodeId(100)));
    }

    fn module_roundtrip_through_wire_format(module: Module) {
        let bytes = module_to_wire_bytes(&module).expect("encode");
        // Header sanity: magic and version.
        assert_eq!(&bytes[0..4], &BYTECODE_MAGIC);
        assert_eq!(u16::from_le_bytes([bytes[4], bytes[5]]), BYTECODE_VERSION,);
        assert_eq!(
            u16::from_le_bytes([bytes[6], bytes[7]]),
            WIRE_FORMAT_HEADER_BYTES as u16,
        );
        let decoded = module_from_wire_bytes(&bytes).expect("decode");
        // Compare structurally. The Module derives `Debug + Clone`
        // but not `PartialEq`; compare through serialized bytes.
        let re_encoded = module_to_wire_bytes(&decoded).expect("re-encode");
        assert_eq!(bytes, re_encoded, "wire-format round trip differs");
    }

    // A.2.1 Phase 2b: the typed-verifier signature table is carried additively
    // in the auxiliary body and survives a serialize/deserialize round trip
    // (Option A). A populated table must decode with the same shapes.
    #[test]
    fn signature_table_survives_wire_round_trip() {
        use crate::bytecode::{ChunkSignature, WireShape};
        let mut module = make_minimal_module();
        module.signatures = alloc::vec![ChunkSignature {
            params: alloc::vec![WireShape::Flat { kind: 2, size: 16 }],
            ret: WireShape::Scalar { kind: 3 },
            resume: WireShape::Top,
        }];
        module.native_return_shapes =
            alloc::vec![WireShape::Flat { kind: 2, size: 24 }, WireShape::Top];
        // Byte-stable round trip (re-encoding the decode matches).
        module_roundtrip_through_wire_format(module.clone());
        // And the decoded shapes are exactly the encoded ones.
        let bytes = module_to_wire_bytes(&module).expect("encode");
        let decoded = module_from_wire_bytes(&bytes).expect("decode");
        assert_eq!(decoded.signatures.len(), 1);
        let s = &decoded.signatures[0];
        assert_eq!(s.params.len(), 1);
        assert!(matches!(s.params[0], WireShape::Flat { kind: 2, size: 16 }));
        assert!(matches!(s.ret, WireShape::Scalar { kind: 3 }));
        assert!(matches!(s.resume, WireShape::Top));
        assert_eq!(decoded.native_return_shapes.len(), 2);
        assert!(matches!(
            decoded.native_return_shapes[0],
            WireShape::Flat { kind: 2, size: 24 }
        ));
        assert!(matches!(decoded.native_return_shapes[1], WireShape::Top));
    }

    fn make_minimal_module() -> Module {
        // Hand-crafted chunk: PushImmediate(1) then Return.
        let chunk = Chunk {
            name: alloc::string::String::from("main"),
            ops: alloc::vec![Op::PushImmediate(5), Op::Return],
            constants: alloc::vec::Vec::new(),
            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,
        };
        Module {
            chunks: alloc::vec![chunk],
            native_names: alloc::vec::Vec::new(),
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            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,
            schema_hash: 0,
        }
    }

    #[test]
    fn module_roundtrip_preserves_aux_arena_bytes() {
        // The runtime ephemeral tracking-list pre-size figure occupies the
        // framing-header word at offset 56 (B28 P3 item 5, Phase C); it must
        // be written there and survive a wire round trip.
        let mut module = make_minimal_module();
        module.aux_arena_bytes = 4096;
        let bytes = module_to_wire_bytes(&module).expect("encode");
        assert_eq!(
            u32::from_le_bytes([bytes[56], bytes[57], bytes[58], bytes[59]]),
            4096,
            "aux_arena_bytes must occupy header offset 56"
        );
        let decoded = module_from_wire_bytes(&bytes).expect("decode");
        assert_eq!(decoded.aux_arena_bytes, 4096);
        // A zero value must leave the formerly-reserved word zero-filled.
        let zero = make_minimal_module();
        let zbytes = module_to_wire_bytes(&zero).expect("encode");
        assert_eq!(&zbytes[56..64], &[0u8; 8], "zero aux + reserved stays zero");
        module_roundtrip_through_wire_format(module);
    }

    #[test]
    fn module_roundtrip_empty_chunks() {
        // Zero chunks: opcode stream and operand pool both empty.
        // Verifies the section-offset math and the rkyv encoding
        // of an empty `WireAuxBody::chunks`.
        let module = Module {
            chunks: alloc::vec::Vec::new(),
            native_names: alloc::vec::Vec::new(),
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            entry_point: None,
            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,
            schema_hash: 0,
        };
        module_roundtrip_through_wire_format(module);
    }

    #[test]
    fn module_roundtrip_minimal_program() {
        module_roundtrip_through_wire_format(make_minimal_module());
    }

    fn sample_debug_pool() -> crate::debug_meta::DebugPool {
        use crate::debug_meta::{DebugPool, DebugRecord, DebugRecordKind};
        DebugPool {
            string_pool: alloc::vec![alloc::string::String::from("main.kel")],
            span_pool: alloc::vec![(0, 0, 2)],
            type_pool: alloc::vec::Vec::new(),
            records: alloc::vec![
                DebugRecord {
                    op_index: 0,
                    kind: DebugRecordKind::SourceSpan,
                    operands: alloc::vec![0],
                },
                DebugRecord {
                    op_index: 1,
                    kind: DebugRecordKind::CallSite,
                    operands: alloc::vec![0],
                },
            ],
        }
    }

    #[test]
    fn module_roundtrip_preserves_debug_pool() {
        let mut module = make_minimal_module();
        let pool = sample_debug_pool();
        module.chunks[0].debug_pool = Some(pool.clone());
        let bytes = module_to_wire_bytes(&module).expect("encode");
        let decoded = module_from_wire_bytes(&bytes).expect("decode");
        let decoded_pool = decoded.chunks[0]
            .debug_pool
            .as_ref()
            .expect("debug pool survives round trip");
        // Compare canonically; `encode` is record-order independent.
        assert_eq!(decoded_pool.encode(), pool.encode());
        // Decode then re-encode is byte-stable.
        let re = module_to_wire_bytes(&decoded).expect("re-encode");
        assert_eq!(bytes, re);
    }

    #[test]
    fn debug_pool_does_not_alter_opcode_stream() {
        // B29 invariant 4: debug metadata lives only in the auxiliary
        // body, so the opcode stream section is byte-identical whether
        // or not a chunk carries a debug pool.
        let without = make_minimal_module();
        let mut with = make_minimal_module();
        with.chunks[0].debug_pool = Some(sample_debug_pool());

        let bytes_without = module_to_wire_bytes(&without).expect("encode");
        let bytes_with = module_to_wire_bytes(&with).expect("encode");

        let s_without = parse_wire_sections(&bytes_without).expect("sections");
        let s_with = parse_wire_sections(&bytes_with).expect("sections");
        assert_eq!(
            s_without.opcode_stream, s_with.opcode_stream,
            "debug metadata must not change the opcode stream"
        );
    }

    #[test]
    fn stripping_debug_pool_reproduces_release_bytes() {
        // B29 invariant 5 at the wire level: encoding a module whose
        // debug pool has been dropped yields bytes identical to a module
        // that never carried one.
        let release = make_minimal_module();
        let release_bytes = module_to_wire_bytes(&release).expect("encode");

        let mut debug = make_minimal_module();
        debug.chunks[0].debug_pool = Some(sample_debug_pool());
        // Strip: drop the section.
        debug.chunks[0].debug_pool = None;
        let stripped_bytes = module_to_wire_bytes(&debug).expect("encode");

        assert_eq!(
            release_bytes, stripped_bytes,
            "stripped bytecode must be byte-identical to a release build"
        );
    }

    #[test]
    fn module_roundtrip_branchy_program() {
        // Exercise If/Else/EndIf and a loop with a BreakIf.
        let body_chunk = Chunk {
            name: alloc::string::String::from("loop_body"),
            ops: alloc::vec![
                Op::Loop(7),
                Op::PushImmediate(2),
                Op::PushImmediate(2),
                Op::CmpEq,
                Op::BreakIf(7),
                Op::EndLoop(1),
                Op::PushImmediate(0),
                Op::Return,
            ],
            constants: alloc::vec::Vec::new(),
            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 if_chunk = Chunk {
            name: alloc::string::String::from("if_chain"),
            ops: alloc::vec![
                Op::PushImmediate(1),
                Op::If(4),
                Op::PushImmediate(5),
                Op::Else(5),
                Op::PushImmediate(6),
                Op::EndIf,
                Op::Return,
            ],
            constants: alloc::vec::Vec::new(),
            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 {
            chunks: alloc::vec![body_chunk, if_chunk],
            native_names: alloc::vec::Vec::new(),
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            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,
            schema_hash: 0,
        };
        module_roundtrip_through_wire_format(module);
    }

    #[test]
    fn module_roundtrip_pool_using_program() {
        // Exercise the operand pool. NewEnum uses the
        // `(u16, u16, u8)` shape; IsEnum and GetDataIndexed use
        // `(u16, u16)`. All four pool-using opcodes appear at
        // least once.
        let chunk = Chunk {
            name: alloc::string::String::from("pool_user"),
            ops: alloc::vec![
                Op::NewComposite(crate::bytecode::NewCompositeOperand::Boxed {
                    kind: crate::value_layout::CompositeKind::Enum,
                    count: 1,
                    meta: 4,
                }),
                Op::NewComposite(crate::bytecode::NewCompositeOperand::Boxed {
                    kind: crate::value_layout::CompositeKind::Struct,
                    count: 0,
                    meta: 0,
                }),
                Op::IsEnum(3, 4, 5),
                Op::GetDataIndexed(7, 8),
                Op::SetDataIndexed(7, 8),
                Op::Return,
            ],
            constants: alloc::vec::Vec::new(),
            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 {
            chunks: alloc::vec![chunk],
            native_names: alloc::vec::Vec::new(),
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            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,
            schema_hash: 0,
        };
        module_roundtrip_through_wire_format(module);
    }

    #[test]
    fn module_roundtrip_stream_chunk() {
        // Stream chunks have distinct structural constraints
        // (Op::Stream, Op::Yield, Op::Reset). Round-trip a
        // minimal Stream chunk to confirm block-type preservation
        // and full opcode stream coverage.
        let chunk = Chunk {
            name: alloc::string::String::from("tick"),
            ops: alloc::vec![
                Op::Stream,
                Op::PushImmediate(7),
                Op::Yield,
                Op::PopN(1),
                Op::Reset,
            ],
            constants: alloc::vec::Vec::new(),
            struct_templates: alloc::vec::Vec::new(),
            local_count: 0,
            param_count: 0,
            block_type: BlockType::Stream,
            param_types: alloc::vec::Vec::new(),
            debug_pool: None,
        };
        let module = Module {
            chunks: alloc::vec![chunk],
            native_names: alloc::vec::Vec::new(),
            enum_layouts: alloc::vec::Vec::new(),
            signatures: alloc::vec::Vec::new(),
            native_return_shapes: alloc::vec::Vec::new(),
            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,
            schema_hash: 0,
        };
        module_roundtrip_through_wire_format(module);
    }

    #[test]
    fn module_roundtrip_bad_magic_rejected() {
        let module = make_minimal_module();
        let mut bytes = module_to_wire_bytes(&module).expect("encode");
        bytes[0] = b'X';
        let err = module_from_wire_bytes(&bytes).unwrap_err();
        assert!(matches!(err, LoadError::BadMagic));
    }

    #[test]
    fn module_roundtrip_bad_crc_rejected() {
        let module = make_minimal_module();
        let mut bytes = module_to_wire_bytes(&module).expect("encode");
        let len = bytes.len();
        bytes[len - 1] ^= 0x01;
        let err = module_from_wire_bytes(&bytes).unwrap_err();
        assert!(matches!(err, LoadError::BadChecksum));
    }

    #[test]
    fn module_roundtrip_truncated_rejected() {
        let module = make_minimal_module();
        let bytes = module_to_wire_bytes(&module).expect("encode");
        let err = module_from_wire_bytes(&bytes[..32]).unwrap_err();
        assert!(matches!(err, LoadError::Truncated));
    }

    #[test]
    fn module_roundtrip_shebang_stripped() {
        let module = make_minimal_module();
        let bytes = module_to_wire_bytes(&module).expect("encode");
        let mut with_shebang: alloc::vec::Vec<u8> =
            alloc::vec::Vec::from(b"#!/usr/bin/env keleusma\n".as_slice());
        with_shebang.extend_from_slice(&bytes);
        let decoded = module_from_wire_bytes(&with_shebang).expect("decode");
        // Confirm the decoded chunk preserves the ops.
        assert_eq!(decoded.chunks.len(), 1);
        assert_eq!(decoded.chunks[0].ops.len(), 2);
    }

    #[test]
    fn unsigned_module_header_length_is_64() {
        let bytes = module_to_wire_bytes(&make_minimal_module()).expect("encode");
        let header_length = u16::from_le_bytes([bytes[6], bytes[7]]);
        assert_eq!(header_length, WIRE_FORMAT_HEADER_BYTES as u16);
        // Flags byte has FLAG_REQUIRES_SIGNATURE clear.
        assert_eq!(bytes[15] & FLAG_REQUIRES_SIGNATURE, 0);
    }

    #[test]
    fn flag_requires_signature_without_extension_rejected() {
        // Construct an otherwise-valid file but flip the signed
        // bit without adding a signature extension. The decoder
        // must reject as malformed (header_length still 64).
        let mut bytes = module_to_wire_bytes(&make_minimal_module()).expect("encode");
        bytes[15] |= FLAG_REQUIRES_SIGNATURE;
        // Repair the CRC trailer so we exercise the flag/extension
        // consistency check rather than the CRC check.
        let footer_start = bytes.len() - WIRE_FORMAT_FOOTER_BYTES;
        let crc = crc32(&bytes[..footer_start]);
        bytes[footer_start..].copy_from_slice(&crc.to_le_bytes());
        let err = module_from_wire_bytes(&bytes).unwrap_err();
        match err {
            LoadError::Codec(msg) => assert!(
                msg.contains("FLAG_REQUIRES_SIGNATURE is set"),
                "expected flag/extension consistency error, got: {}",
                msg
            ),
            other => panic!("unexpected error: {:?}", other),
        }
    }

    #[test]
    fn parse_signature_metadata_rejects_unsupported_scheme() {
        // Hand-craft a buffer with a fake signature extension
        // claiming scheme_id = 99 (not Ed25519).
        let mut bytes = alloc::vec![0u8; 144];
        bytes[64] = 99; // scheme_id
        bytes[66] = 64; // signature_length (lo)
        let err = parse_signature_metadata(&bytes, 144).unwrap_err();
        match err {
            LoadError::Codec(msg) => assert!(
                msg.contains("scheme_id 99 is not supported"),
                "expected scheme rejection, got: {}",
                msg
            ),
            other => panic!("unexpected error: {:?}", other),
        }
    }

    #[test]
    fn parse_signature_metadata_rejects_scheme_id_zero() {
        let bytes = alloc::vec![0u8; 144];
        let err = parse_signature_metadata(&bytes, 144).unwrap_err();
        match err {
            LoadError::Codec(msg) => assert!(
                msg.contains("scheme_id 0 is reserved"),
                "expected zero-scheme rejection, got: {}",
                msg
            ),
            other => panic!("unexpected error: {:?}", other),
        }
    }

    #[test]
    fn signed_header_length_for_ed25519() {
        assert_eq!(signed_header_length(ED25519_SIGNATURE_BYTES), 136);
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn ed25519_round_trip_verifies() {
        use ed25519_dalek::SigningKey;
        // Deterministic 32-byte seed so the test is reproducible.
        let seed = [7u8; 32];
        let signing_key = SigningKey::from_bytes(&seed);
        let verifying_key = signing_key.verifying_key();

        let module = make_minimal_module();
        let signed_bytes = module_to_signed_wire_bytes(&module, &signing_key).expect("sign+encode");
        // Header reflects the signed extension.
        assert_eq!(
            u16::from_le_bytes([signed_bytes[6], signed_bytes[7]]),
            signed_header_length(ED25519_SIGNATURE_BYTES) as u16,
        );
        assert_ne!(signed_bytes[15] & FLAG_REQUIRES_SIGNATURE, 0);
        assert_eq!(signed_bytes[64], SIGNATURE_SCHEME_ED25519);
        assert_eq!(
            u16::from_le_bytes([signed_bytes[66], signed_bytes[67]]),
            ED25519_SIGNATURE_BYTES as u16,
        );

        // Verification matches.
        verify_module_signature(&signed_bytes, &[verifying_key]).expect("verify");

        // The decoded module preserves the entry point and op
        // count from the original.
        let decoded = module_from_wire_bytes(&signed_bytes).expect("decode");
        assert_eq!(decoded.entry_point, module.entry_point);
        assert_eq!(decoded.chunks.len(), module.chunks.len());
        assert_eq!(decoded.chunks[0].ops.len(), module.chunks[0].ops.len());
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn ed25519_verify_rejects_wrong_key() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[7u8; 32]);
        let wrong = SigningKey::from_bytes(&[8u8; 32]).verifying_key();
        let signed = module_to_signed_wire_bytes(&make_minimal_module(), &signer).expect("sign");
        let err = verify_module_signature(&signed, &[wrong]).unwrap_err();
        assert!(
            matches!(err, LoadError::InvalidSignature),
            "expected InvalidSignature, got: {:?}",
            err
        );
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn ed25519_verify_rejects_empty_key_set() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[7u8; 32]);
        let signed = module_to_signed_wire_bytes(&make_minimal_module(), &signer).expect("sign");
        let err = verify_module_signature(&signed, &[]).unwrap_err();
        assert!(
            matches!(err, LoadError::InvalidSignature),
            "expected InvalidSignature, got: {:?}",
            err
        );
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn ed25519_tamper_in_body_caught_by_crc_before_signature() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[7u8; 32]);
        let verifying = signer.verifying_key();
        let mut signed =
            module_to_signed_wire_bytes(&make_minimal_module(), &signer).expect("sign");
        // Flip a byte in the opcode stream (well past the
        // signature section). The CRC residue check inside
        // `verify_module_signature` is at the framing layer; it
        // runs before the signature math.
        let opcode_offset = signed_header_length(ED25519_SIGNATURE_BYTES);
        signed[opcode_offset] ^= 0x01;
        let err = verify_module_signature(&signed, &[verifying]).unwrap_err();
        match err {
            LoadError::BadChecksum | LoadError::Codec(_) | LoadError::InvalidSignature => {}
            other => panic!(
                "expected BadChecksum / Codec / InvalidSignature, got: {:?}",
                other
            ),
        }
    }

    #[cfg(feature = "signatures")]
    #[test]
    fn ed25519_signature_mutation_caught_after_crc_repair() {
        use ed25519_dalek::SigningKey;
        let signer = SigningKey::from_bytes(&[7u8; 32]);
        let verifying = signer.verifying_key();
        let mut signed =
            module_to_signed_wire_bytes(&make_minimal_module(), &signer).expect("sign");
        // Flip a bit inside the signature section.
        let sig_offset = WIRE_FORMAT_HEADER_BYTES + SIGNATURE_METADATA_BYTES;
        signed[sig_offset] ^= 0x01;
        // Repair the CRC trailer so the framing-level check
        // passes and only the cryptographic check rejects.
        let footer_start = signed.len() - WIRE_FORMAT_FOOTER_BYTES;
        let crc = crc32(&signed[..footer_start]);
        signed[footer_start..].copy_from_slice(&crc.to_le_bytes());
        let err = verify_module_signature(&signed, &[verifying]).unwrap_err();
        assert!(
            matches!(err, LoadError::InvalidSignature),
            "expected InvalidSignature after sig mutation, got: {:?}",
            err
        );
    }

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

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

        // Recipient X25519 keypair.
        let recipient_sk = [0xb2u8; 32];
        let recipient_pk = public_key_from_private(&recipient_sk);

        // Ephemeral seed for this module.
        let ephemeral_seed = [0xc3u8; 32];

        let module = make_minimal_module();

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

        // Header flags should advertise both signing and encryption.
        assert_ne!(encrypted[15] & FLAG_REQUIRES_SIGNATURE, 0);
        assert_ne!(encrypted[15] & FLAG_ENCRYPTED, 0);

        // header_length should equal encrypted_signed_header_length.
        let hl = u16::from_le_bytes([encrypted[6], encrypted[7]]) as usize;
        assert_eq!(hl, encrypted_signed_header_length());

        // Decrypt back to signed-only form.
        let reconstructed =
            decrypt_encrypted_signed_to_signed_bytes(&encrypted, &[verifying], &recipient_sk)
                .expect("decrypt");

        // The reconstructed buffer should NOT have FLAG_ENCRYPTED.
        assert_eq!(reconstructed[15] & FLAG_ENCRYPTED, 0);
        // But should still carry FLAG_REQUIRES_SIGNATURE.
        assert_ne!(reconstructed[15] & FLAG_REQUIRES_SIGNATURE, 0);

        // The reconstructed buffer should parse back to the same
        // module as the original. Round-trip through
        // module_from_wire_bytes gives us a Module value to compare.
        let decoded = module_from_wire_bytes(&reconstructed).expect("parse reconstructed");
        assert_eq!(decoded.chunks.len(), module.chunks.len());
        assert_eq!(decoded.chunks[0].ops, module.chunks[0].ops);
    }

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

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

        let alice_sk = [0x11u8; 32];
        let alice_pk = public_key_from_private(&alice_sk);
        let bob_sk = [0x22u8; 32];

        let ephemeral_seed = [0x33u8; 32];

        let encrypted = module_to_encrypted_signed_wire_bytes(
            &make_minimal_module(),
            &signer,
            &alice_pk,
            &ephemeral_seed,
        )
        .expect("encrypt+sign");

        let result = decrypt_encrypted_signed_to_signed_bytes(&encrypted, &[verifying], &bob_sk);
        assert!(result.is_err(), "expected error decrypting as bob");
    }

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

        let real_signer = SigningKey::from_bytes(&[0xa3; 32]);
        let other_signer = SigningKey::from_bytes(&[0xa4; 32]);
        let other_verifying = other_signer.verifying_key();

        let recipient_sk = [0x55u8; 32];
        let recipient_pk = public_key_from_private(&recipient_sk);

        let ephemeral_seed = [0x66u8; 32];

        let encrypted = module_to_encrypted_signed_wire_bytes(
            &make_minimal_module(),
            &real_signer,
            &recipient_pk,
            &ephemeral_seed,
        )
        .expect("encrypt+sign");

        // Try to verify with a different signer's key.
        let result =
            decrypt_encrypted_signed_to_signed_bytes(&encrypted, &[other_verifying], &recipient_sk);
        match result {
            Err(LoadError::InvalidSignature) => (),
            other => panic!(
                "expected InvalidSignature when verifying with wrong key, got: {:?}",
                other
            ),
        }
    }

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

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

        let recipient_sk = [0x77u8; 32];
        let recipient_pk = public_key_from_private(&recipient_sk);

        let ephemeral_seed = [0x88u8; 32];

        let mut encrypted = module_to_encrypted_signed_wire_bytes(
            &make_minimal_module(),
            &signer,
            &recipient_pk,
            &ephemeral_seed,
        )
        .expect("encrypt+sign");

        // Flip a byte in the ciphertext region. Then repair the
        // CRC so framing validation passes but the signature or
        // decryption fails as the substantive check.
        let body_start = encrypted_signed_header_length();
        encrypted[body_start + 4] ^= 0x01;
        let footer_start = encrypted.len() - WIRE_FORMAT_FOOTER_BYTES;
        let crc = crc32(&encrypted[..footer_start]);
        encrypted[footer_start..].copy_from_slice(&crc.to_le_bytes());

        let result =
            decrypt_encrypted_signed_to_signed_bytes(&encrypted, &[verifying], &recipient_sk);
        assert!(
            result.is_err(),
            "expected rejection on tampered ciphertext after CRC repair"
        );
    }

    #[test]
    fn header_requires_encryption_detects_flag() {
        let mut bytes: Vec<u8> = alloc::vec![0u8; 20];
        bytes[0..4].copy_from_slice(&BYTECODE_MAGIC[..]);
        assert!(!header_requires_encryption(&bytes));
        bytes[15] = FLAG_ENCRYPTED;
        assert!(header_requires_encryption(&bytes));
        bytes[15] = FLAG_REQUIRES_SIGNATURE | FLAG_ENCRYPTED;
        assert!(header_requires_encryption(&bytes));
        assert!(header_requires_signature(&bytes));
    }
}