aver-cert 0.1.2

Independent artifact certificate engine and verifier for Aver WebAssembly
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
// ---- rendering -----------------------------------------------------------

/// Write the artifact-specific `cert/` package. `model_files` are the
/// `(path, content)` pairs from the reused `aver proof` Lean emission. The
/// checker-owned wall and build configuration are resolved from `wall_id`.
/// Any existing `cert/` directory is removed first so a reused output path
/// cannot retain files from an older package format.
///
/// PRECONDITION: `model_files` must be the SAME emission `analysis` was
/// derived from. The renderers cite each certified export's model by the
/// qualified Lean name resolved from these files, and `analyze` already
/// declined every export whose name it could not resolve — so a mismatched
/// pair would leave a renderer with a citation the gate never approved. This
/// is checked here rather than assumed: a mismatch returns an error and no
/// package is written.
pub fn write_project(
    out_dir: &Path,
    wasm_name: &str,
    wasm_bytes: &[u8],
    analysis: &Analysis,
    model_files: &[(String, String)],
) -> Result<(), String> {
    // Enforce the model-file precondition BEFORE touching the output
    // directory, so a mismatched call leaves any existing package intact.
    let model_info = ModelInfo::from_files(model_files);
    for c in &analysis.certs {
        model_citation_gate(c, &model_info).map_err(|reason| {
            format!(
                "model files passed to write_project do not match the analysis: {reason}"
            )
        })?;
    }

    let cert_dir = out_dir.join("cert");
    match std::fs::remove_dir_all(&cert_dir) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => return Err(format!("replace cert dir: {error}")),
    }
    std::fs::create_dir_all(&cert_dir).map_err(|e| format!("create cert dir: {e}"))?;

    // Copy the model files (AverCommon + <Module>.lean) verbatim.
    let mut model_roots: Vec<String> = Vec::new();
    for (path, content) in model_files {
        if path == "lakefile.lean" || path == "lean-toolchain" {
            continue;
        }
        write(&cert_dir, path, &sanitize_model_for_cert(content))?;
        if let Some(stem) = path.strip_suffix(".lean") {
            model_roots.push(model_root_from_stem(stem)?);
        }
    }

    let sha = {
        let mut h = Sha256::new();
        h.update(wasm_bytes);
        hex(&h.finalize())
    };

    write(&cert_dir, "Contracts.lean", &render_contracts(analysis))?;
    write(
        &cert_dir,
        "Module.lean",
        &render_module(analysis, wasm_name, &sha),
    )?;
    // Checker-owned Lean sources are identified by `format.wall_id` and are
    // materialized by the verifier. They are not duplicated in the package.
    // Byte-derived host-role table for source-plan encoding. One module-wide
    // value: every sym-plan encode example and artifact claim consumes it, so
    // plan-supplied indices can never enter the encoder.
    let host_table_lean = byte_derived_frag_host_table_lean(wasm_bytes)?;
    // Struct-binding table for field projections: one module-wide value,
    // unioned from the per-export (source plan, encoded plan) pairs the
    // byte-exact gate already pinned. Like the host-role table, plan-supplied
    // indices can never enter the encoder.
    let struct_table_lean = emit_frag_struct_table_lean(analysis)?;

    write(
        &cert_dir,
        "Plans.lean",
        &render_expr_fragment_plans(analysis, &model_info, &host_table_lean, &struct_table_lean),
    )?;
    write(
        &cert_dir,
        "Manifest.lean",
        &render_manifest_lean(analysis, &model_roots, &model_info, &sha),
    )?;
    write(
        &cert_dir,
        "Certificate.lean",
        &render_certificate(analysis, &model_roots, &model_info),
    )?;
    write(
        &cert_dir,
        "Final.lean",
        &render_final(),
    )?;
    // Per-role arith host-table leaves, in their own compilation unit so their
    // `decide +kernel` reductions do not stack onto `Artifact.lean`'s peak.
    // Emitted only for a carriered module (the only kind with a table to split);
    // `render_artifact` adds the matching `import ArtifactHostRoles` and the
    // recombining proof when it is present.
    if analysis.frag_host_table.box_idx.is_some() {
        write(
            &cert_dir,
            "ArtifactHostRoles.lean",
            &render_artifact_host_roles(analysis),
        )?;
    }
    write(
        &cert_dir,
        "Artifact.lean",
        &render_artifact(analysis, &model_info, &host_table_lean, &struct_table_lean),
    )?;
    write(
        &cert_dir,
        "ArtifactCertificate.lean",
        &render_artifact_certificate(),
    )?;
    write(
        &cert_dir,
        "ArtifactSoundness.lean",
        &render_artifact_soundness(),
    )?;
    std::fs::write(
        cert_dir.join("cert-manifest.json"),
        render_manifest(analysis, &model_info, wasm_name, &sha),
    )
    .map_err(|e| format!("write manifest: {e}"))?;
    Ok(())
}

/// The Lean module name a model file is imported by. A module declared as
/// `Data.Fibonacci` transpiles to the file `Data/Fibonacci.lean`; the import
/// lines in `Manifest.lean` and `Certificate.lean` need the dotted form back
/// (`import Data/Fibonacci` is not Lean syntax). Every path segment must be a
/// plain identifier so a model path can never smuggle stray syntax into an
/// interpolated import line.
fn model_root_from_stem(stem: &str) -> Result<String, String> {
    let segments: Vec<&str> = stem.split('/').collect();
    let valid = segments.iter().all(|segment| {
        let mut chars = segment.chars();
        matches!(chars.next(), Some(first) if first.is_ascii_alphabetic())
            && chars.all(|character| character.is_ascii_alphanumeric() || character == '_')
    });
    if valid {
        Ok(segments.join("."))
    } else {
        Err(format!(
            "model file stem `{stem}` is not a Lean module path (each segment must match ^[A-Za-z][A-Za-z0-9_]*$)"
        ))
    }
}

/// The module-wide struct table rendered at emit time: the consistent union of
/// every projection cert's byte-pinned entries.
fn emit_frag_struct_table_lean(analysis: &Analysis) -> Result<String, String> {
    let mut entries: Vec<(String, u32)> = Vec::new();
    for c in &analysis.certs {
        if let Cert::ExprFragment {
            source_plan: Some(source_plan),
            plan,
            ..
        } = c.inner()
        {
            let plan_entries =
                expr_fragment_struct_table_entries(source_plan, plan).ok_or_else(|| {
                    format!("inconsistent struct bindings in `{}` fragment plan", c.name())
                })?;
            entries.extend(plan_entries);
        }
    }
    frag_struct_table_lean_from_entries(entries.iter())
}

fn render_expr_fragment_plans(
    analysis: &Analysis,
    model_info: &ModelInfo,
    host_table_lean: &str,
    struct_table_lean: &str,
) -> String {
    let mut s = String::new();
    s.push_str(
        "-- Compiler-emitted source/fragment plans as Lean data.\n\
         -- This is the package's sole authoritative plan representation. The\n\
         -- checker-owned wall validates and lowers it against the actual artifact.\n\
         import Schema\n\
         import PlanCheck\n\n\
         import PlanLower\n\
         import PlanBytes\n\
         import WasmSlice\n\
         import ExprFragmentAccepted\n\
         import ArtifactBytes\n\
         import Module\n\
         import DeclaredEnvelopeAcceptTransport\n\n\
         set_option maxRecDepth 200000\n\n\
         namespace AverCert.Plans\n\
         open AverCert.Schema\n\n",
    );
    let mut any = false;
    for c in &analysis.certs {
        let Cert::ExprFragment {
            name,
            carrier,
            self_idx,
            type_idx,
            source_plan,
            plan,
            ..
        } = c.inner()
        else {
            continue;
        };
        let code_entry_bytes = lower_expr_fragment_plan_code_entry_bytes(plan, *carrier)
            .expect("certified expr-fragment plan lowers to code-entry bytes");
        let code_entry_bytes = render_byte_list(&code_entry_bytes);
        let lowered_body = lower_expr_fragment_plan(plan, *carrier)
            .map(|ops| render_ops_value(&ops))
            .expect("certified expr-fragment plan lowers to WInstr body");
        let export_name_bytes = render_byte_list(name.as_bytes());
        let func_binding = format!(
            "({{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry_bytes} }} : AverCert.WasmSlice.FuncBinding)"
        );
        let sym_plan = expr_fragment_source_plan(source_plan, plan)
            .map(|sym| {
                format!(
                    "/-- Source-level `SymPlan` projection for `{name}`. Artifact-level\n\
                     acceptance prefers this claim when the fragment has a direct\n\
                     Aver-level meaning; the encoder below still binds it to `{name}Plan`. -/\n\
                     def {name}SymPlan : SymRawPlan := {sym_plan}\n\n\
                     /-- The audited Lean-side source-plan checker accepts `{name}`'s `SymPlan`. -/\n\
                     example : AverCert.PlanCheck.checkSymRawPlan {name}SymPlan = true := rfl\n\n\
                     /-- The audited Lean-side source encoder maps `{name}`'s `SymPlan`,\n\
                         under the byte-derived host-role and struct tables, to the\n\
                         representation plan that is bound to bytes below. -/\n\
                     example : AverCert.PlanCheck.encodeSymRawPlanToExprFragmentRawPlan {host_table_lean} {struct_table_lean} {name}SymPlan =\n  \
                       some {name}Plan := rfl\n\n",
                    sym_plan = sym_plan_lean_value(&sym)
                )
            })
            .unwrap_or_else(|| {
                format!(
                    "-- `{name}` has no source-level `SymPlan` projection yet;\n\
                     -- its current fragment uses representation-only nodes.\n\n"
                )
            });
        any = true;
        s.push_str(&format!(
            "/-- Raw `expr-fragment-v1` plan for `{name}`. -/\n\
             def {name}Plan : ExprFragmentRawPlan := {plan_value}\n\n\
             {sym_plan}\
             /-- The audited Lean-side structural checker accepts `{name}`'s raw plan. -/\n\
             example : AverCert.PlanCheck.checkExprFragmentRawPlan {name}Plan = true := rfl\n\n\
             /-- The audited Lean-side canonical lowerer maps `{name}`'s raw plan\n\
                 to the same instruction body emitted in `Module.lean`. -/\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerExprFragmentBody {carrier} {name}Plan := rfl\n\n\
             /-- The audited Lean-side byte lowerer maps `{name}`'s raw plan\n\
                 to the exact canonical code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerExprFragmentCodeEntry {carrier} {name}Plan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The audited Lean-side Wasm slicer binds `{name}` to its function\n\
                 index, type index and exact expected code-entry bytes. -/\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes} =\n  \
               some {func_binding} := rfl\n\n\
             /-- The audited Lean-side expr-fragment acceptance predicate aggregates\n\
                 plan checking, semantic lowering, byte lowering and byte-origin binding. -/\n\
             example : AverCert.ExprFragmentAccepted.accepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen\n  \
               {export_name_bytes} {carrier} {name}Plan\n  \
               {lowered_body}\n  \
               {code_entry_bytes}\n  \
               {func_binding} := by dsimp [AverCert.ExprFragmentAccepted.accepted]; exact ⟨rfl, rfl, rfl, rfl⟩\n\n",
            plan_value = expr_fragment_plan_lean_value(plan),
            sym_plan = sym_plan,
        ));
        // Stage-1 record scalar field read: the record's ordered scalar-leaf
        // declaration as `Plans` data. The wall re-derives the same layout from
        // the bytes and pins it by equality inside the checked record face; the
        // obligation and face both read these defs, and the recognizer pin below
        // documents that the encoded plan fires the record recognizer.
        if let (Some(face), Some((_struct_idx, leaves))) =
            (c.record_param_face(), c.record_decl())
        {
            s.push_str(&format!(
                "/-- The Plan record declaration for `{name}` as ordered scalar leaves. -/\n\
                 def {name}RecordFields : List TypeDecl := {fields_value}\n\n\
                 def {name}RecordDecl : TypeDecl := .record {struct_idx} {name}RecordFields\n\n\
                 /-- The shared record-projection recognizer fires on `{name}`'s encoded plan. -/\n\
                 example : AverCert.WasmSlice.exprRecordProjFace? {name}Plan = some ({struct_idx}, {field}) := rfl\n\n",
                fields_value = record_leaves_lean_value(leaves),
                struct_idx = face.struct_idx,
                field = face.field_idx,
            ));
        }
    }
    for c in &analysis.certs {
        let Cert::FieldProjection {
            name,
            self_idx,
            type_idx,
            carrier,
            struct_idx,
            field_count,
            ..
        } = c.inner()
        else {
            continue;
        };
        let Some((plan, result_ty)) = field_projection_plan_from_cert(c) else {
            continue;
        };
        let code_entry = lower_field_projection_code_entry(
            &plan,
            *carrier,
            *struct_idx,
            result_ty,
        );
        let code_entry = render_byte_list(&code_entry);
        let result_ty_lean = field_projection_result_ty_lean_value(result_ty);
        let export_name_bytes = render_byte_list(name.as_bytes());
        let binding = format!(
            "({{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry} }} : AverCert.WasmSlice.FuncBinding)"
        );
        any = true;
        s.push_str(&format!(
            "/-- Byte-origin plan for bare tuple/record projection `{name}`. -/\n\
             def {name}FieldProjectionPlan : FieldProjectionRawPlan := {plan_value}\n\n\
             example : AverCert.PlanCheck.checkFieldProjectionRawPlan {field_count} {name}FieldProjectionPlan = true := rfl\n\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerFieldProjectionBody {struct_idx} {field_count} {name}FieldProjectionPlan := rfl\n\n\
             example : AverCert.PlanBytes.lowerFieldProjectionCodeEntry {carrier} {struct_idx} {field_count} {result_ty_lean} {name}FieldProjectionPlan =\n  \
               some {code_entry} := rfl\n\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} =\n  \
               some {binding} := rfl\n\n\
             example : AverCert.WasmSlice.projectionStructTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {struct_idx} {field_count} {field_idx} {result_ty_lean} = true := rfl\n\n\
             example : AverCert.WasmSlice.projectionFuncTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {type_idx} {struct_idx} {result_ty_lean} = true := rfl\n\n",
            plan_value = field_projection_plan_lean_value(&plan),
            field_idx = plan.field_idx,
        ));
    }
    for c in &analysis.certs {
        let Cert::AdtConstructor {
            name,
            self_idx,
            type_idx,
            carrier,
            struct_idx,
            elem_ty,
            ..
        } = c.inner()
        else {
            continue;
        };
        let Some(sym_plan) = adt_constructor_sym_plan_from_cert(c, model_info) else {
            continue;
        };
        let Some(construct_plan) = construct_plan_from_cert(c) else {
            continue;
        };
        let Ok(code_entry_bytes) =
            lower_construct_plan_code_entry_bytes(&construct_plan, *carrier, *struct_idx)
        else {
            continue;
        };
        let lowered_body = lower_construct_plan(&construct_plan, *struct_idx)
            .map(|ops| render_ops_value(&ops))
            .expect("checked construct plan lowers to WInstr body");
        let code_entry_bytes = render_byte_list(&code_entry_bytes);
        let export_name_bytes = render_byte_list(name.as_bytes());
        let elem_ty = construct_val_type_lean_value(*elem_ty)
            .expect("certified constructor has a supported byte-level element type");
        let type_match_pins = if sym_plan_is_list_construct(&sym_plan) {
            format!(
                "/-- The byte-derived list struct binds `{name}`'s element representation. -/\n\
                 theorem {name}ConstructStructTypeMatches :\n  \
                   AverCert.WasmSlice.listConstructStructTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {struct_idx} ({elem_ty}) = true := rfl\n\n\
                 /-- The byte-derived exported signature binds `{name}`'s element representation. -/\n\
                 theorem {name}ConstructFuncTypeMatches :\n  \
                   AverCert.WasmSlice.listConstructFuncTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {type_idx} {name}ConstructPlan.arity {struct_idx} ({elem_ty}) = true := rfl\n\n"
            )
        } else {
            String::new()
        };
        let func_binding = format!(
            "({{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry_bytes} }} : AverCert.WasmSlice.FuncBinding)"
        );
        any = true;
        s.push_str(&format!(
            "/-- Source-level constructor `SymPlan` for legacy ADT constructor `{name}`.\n\
                This says what source value is being constructed; the target-bound\n\
                `ConstructRawPlan` below pins the wasm-gc `struct.new` layout. -/\n\
             def {name}ConstructSymPlan : SymRawPlan := {sym_plan_value}\n\n\
             /-- Target-bound constructor witness for `{name}`. -/\n\
             def {name}ConstructPlan : ConstructRawPlan := {construct_plan_value}\n\n\
             /-- The audited Lean-side source-plan checker accepts `{name}`'s constructor plan. -/\n\
             example : AverCert.PlanCheck.checkSymRawPlan {name}ConstructSymPlan = true := rfl\n\n\
             /-- The audited Lean-side structural checker accepts `{name}`'s target constructor plan. -/\n\
             example : AverCert.PlanCheck.checkConstructRawPlan {name}ConstructPlan = true := rfl\n\n\
             /-- The audited Lean-side source/target matcher confirms that `{name}`'s\n\
                 source constructor plan explains the byte-bound constructor witness. -/\n\
             example : AverCert.PlanCheck.constructPlanMatchesSymRawPlan\n  \
               {name}ConstructSymPlan {name}ConstructPlan = true := rfl\n\n\
             /-- `construct` is not yet part of the v1 source-to-fragment encoder. -/\n\
             example : AverCert.PlanCheck.encodeSymRawPlanToExprFragmentRawPlan {host_table_lean} {struct_table_lean} {name}ConstructSymPlan = none := rfl\n\n\
             /-- The audited Lean-side canonical lowerer maps `{name}`'s constructor plan\n\
                 to the exact instruction body. -/\n\
             example : AverCert.PlanLower.lowerConstructBody {struct_idx} {name}ConstructPlan =\n  \
               some {lowered_body} := rfl\n\n\
             /-- The audited Lean-side canonical lowerer maps `{name}`'s constructor plan\n\
                 to the same instruction body emitted in `Module.lean`. -/\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerConstructBody {struct_idx} {name}ConstructPlan := rfl\n\n\
             /-- The audited Lean-side byte lowerer maps `{name}`'s constructor plan\n\
                 to the exact canonical code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerConstructCodeEntry {carrier} {struct_idx} {name}ConstructPlan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The audited Lean-side Wasm slicer binds `{name}` to its function\n\
                 index, type index and exact expected code-entry bytes. -/\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes} =\n  \
               some {func_binding} := rfl\n\n\
             {type_match_pins}",
            sym_plan_value = sym_plan_lean_value(&sym_plan),
            construct_plan_value = construct_plan_lean_value(&construct_plan),
            lowered_body = lowered_body,
        ));
    }
    for c in &analysis.certs {
        let Cert::StringConcatVerbatimMatch {
            name,
            self_idx,
            type_idx,
            carrier,
            string_concat_idx,
            container_ty,
            result_ty,
            ..
        } = c.inner()
        else {
            continue;
        };
        let plan = string_concat_plan_from_cert(c)
            .expect("certified String.concat should project to a source plan");
        let sym_plan = string_concat_sym_plan_from_plan(&plan);
        let code_entry_bytes = lower_string_concat_plan_code_entry_bytes(
            &plan,
            *carrier,
            *result_ty,
            *container_ty,
            *string_concat_idx,
        )
        .expect("certified String.concat plan lowers to code-entry bytes");
        let code_entry_bytes = render_byte_list(&code_entry_bytes);
        let export_name_bytes = render_byte_list(name.as_bytes());
        let func_binding = format!(
            "({{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry_bytes} }} : AverCert.WasmSlice.FuncBinding)"
        );
        any = true;
        s.push_str(&format!(
            "/-- Source-level `SymPlan` view of `{name}`'s string concatenation. -/\n\
             def {name}StringConcatSymPlan : SymRawPlan := {sym_plan_value}\n\n\
             /-- Target-bound `string-concat-v1` encoder witness for `{name}`. -/\n\
             def {name}StringConcatPlan : StringConcatRawPlan := {plan_value}\n\n\
             /-- The audited Lean-side source-plan checker accepts `{name}`'s string `SymPlan`. -/\n\
             example : AverCert.PlanCheck.checkSymRawPlan {name}StringConcatSymPlan = true := rfl\n\n\
             /-- The audited Lean-side source/target matcher confirms that `{name}`'s\n\
                 string `SymPlan` explains the byte-bound String.concat plan below. -/\n\
             example : AverCert.PlanCheck.stringConcatPlanMatchesSymRawPlan\n  \
               {name}StringConcatSymPlan {name}StringConcatPlan = true := rfl\n\n\
             /-- The audited Lean-side structural checker accepts `{name}`'s String.concat plan. -/\n\
             example : AverCert.PlanCheck.checkStringConcatRawPlan {name}StringConcatPlan = true := rfl\n\n\
             /-- The audited Lean-side canonical lowerer maps `{name}`'s String.concat plan\n\
                 to the same instruction body emitted in `Module.lean`. -/\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerStringConcatBody {result_ty} {container_ty} {string_concat_idx} {name}StringConcatPlan := rfl\n\n\
             /-- The audited Lean-side byte lowerer maps `{name}`'s String.concat plan\n\
                 to the exact canonical code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerStringConcatCodeEntry {carrier_state} {result_ty} {container_ty} {string_concat_idx} {name}StringConcatPlan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The audited Lean-side Wasm slicer binds `{name}` to its function\n\
                 index, type index and exact expected code-entry bytes. -/\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes} =\n  \
               some {func_binding} := rfl\n\n\
             \n",
            sym_plan_value = sym_plan_lean_value(&sym_plan),
            plan_value = string_concat_plan_lean_value(&plan),
            carrier_state = render_carrier_state(*carrier),
        ));
    }
    // The carrier state is a property of the MODULE, not of an export, so its
    // audit line is emitted once for the whole package rather than repeated
    // identically per concatenation. Acceptance pins it per claim anyway
    // (`stringConcatPlanAccepted`); this is the readable restatement.
    if let Some(carrier) = analysis
        .certs
        .iter()
        .find_map(|c| match c.inner() {
            Cert::StringConcatVerbatimMatch { carrier, .. } => Some(*carrier),
            _ => None,
        })
    {
        s.push_str(&format!(
            "/-- The module's byte-derived carrier state: the value that selects the\n\
                 locals prelude of every `string-concat-v1` code entry above.\n\
                 Recomputed from the artifact bytes, so no claim can declare a\n\
                 prelude the type section does not license. -/\n\
             example : CertDecode.carrierState AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen =\n  \
               some {carrier_state} := rfl\n\n",
            carrier_state = render_carrier_state(carrier),
        ));
    }
    for c in &analysis.certs {
        let Cert::StringEqVerbatimMatch {
            name,
            self_idx,
            type_idx,
            carrier,
            string_eq_idx,
            ..
        } = c.inner()
        else {
            continue;
        };
        let plan = string_eq_plan_from_cert(c)
            .expect("certified String.eq should project to a source plan");
        let sym_plan = string_eq_sym_plan_from_plan(&plan);
        let string_ty =
            string_eq_string_ty_from_cert(c).expect("certified String.eq should use string arrays");
        let code_entry_bytes =
            lower_string_eq_plan_code_entry_bytes(&plan, *carrier, string_ty, *string_eq_idx)
                .expect("certified String.eq plan lowers to code-entry bytes");
        let code_entry_bytes = render_byte_list(&code_entry_bytes);
        let export_name_bytes = render_byte_list(name.as_bytes());
        let func_binding = format!(
            "({{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry_bytes} }} : AverCert.WasmSlice.FuncBinding)"
        );
        any = true;
        s.push_str(&format!(
            "/-- Source-level `SymPlan` view of `{name}`'s String.eq dispatch. -/\n\
             def {name}StringEqSymPlan : SymRawPlan := {sym_plan_value}\n\n\
             /-- Target-bound `string-eq-v1` encoder witness for `{name}`. -/\n\
             def {name}StringEqPlan : StringEqRawPlan := {plan_value}\n\n\
             /-- The audited Lean-side source-plan checker accepts `{name}`'s String.eq `SymPlan`. -/\n\
             example : AverCert.PlanCheck.checkSymRawPlan {name}StringEqSymPlan = true := rfl\n\n\
             /-- The audited Lean-side source/target matcher confirms that `{name}`'s\n\
                 string `SymPlan` explains the byte-bound String.eq plan below. -/\n\
             example : AverCert.PlanCheck.stringEqPlanMatchesSymRawPlan\n  \
               {name}StringEqSymPlan {name}StringEqPlan = true := rfl\n\n\
             /-- The audited Lean-side structural checker accepts `{name}`'s String.eq plan. -/\n\
             example : AverCert.PlanCheck.checkStringEqRawPlan {name}StringEqPlan = true := rfl\n\n\
             /-- The audited Lean-side canonical lowerer maps `{name}`'s String.eq plan\n\
                 to the same instruction body emitted in `Module.lean`. -/\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerStringEqBody {string_ty} {string_eq_idx} {name}StringEqPlan := rfl\n\n\
             /-- The audited Lean-side byte lowerer maps `{name}`'s String.eq plan\n\
                 to the exact canonical code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerStringEqCodeEntry {carrier} {string_ty} {string_eq_idx} {name}StringEqPlan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The audited Lean-side Wasm slicer binds `{name}` to its function\n\
                 index, type index and exact expected code-entry bytes. -/\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes} =\n  \
               some {func_binding} := rfl\n\n\
             \n",
            sym_plan_value = sym_plan_lean_value(&sym_plan),
            plan_value = string_eq_plan_lean_value(&plan),
        ));
    }
    for c in &analysis.certs {
        let (name, self_idx, type_idx, carrier) = match c.inner() {
            Cert::Recursive {
                name,
                self_idx,
                type_idx,
                carrier,
                ..
            }
            | Cert::AccumulatorRecursive {
                name,
                self_idx,
                type_idx,
                carrier,
                ..
            } => (name, *self_idx, *type_idx, *carrier),
            _ => continue,
        };
        let Some(plan) = recursion_plan_from_cert(c) else {
            continue;
        };
        let code_entry_bytes = lower_expr_fragment_plan_code_entry_bytes(&plan, carrier)
            .expect("certified recursion plan lowers to code-entry bytes");
        let code_entry_bytes = render_byte_list(&code_entry_bytes);
        let export_name_bytes = render_byte_list(name.as_bytes());
        let func_binding = format!(
            "({{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry_bytes} }} : AverCert.WasmSlice.FuncBinding)"
        );
        let host_table = recursion_host_table_lean_value(c);
        let totality_role = c.totality_role_lean_value();
        let wrong_totality_role = if c.requires_mul_totality() {
            ".addSub"
        } else {
            ".mul"
        };
        let arity = plan.params.len();
        any = true;
        s.push_str(&format!(
            "/-- Byte-derived `recursion-plan-v1` plan for `{name}` (fuel-recursive). -/\n\
             def {name}RecursionPlan : RecursionRawPlan := {plan_value}\n\n\
             /-- The audited recursion-plan checker accepts `{name}`'s byte-derived plan. -/\n\
             example : AverCert.PlanCheck.checkRecursionRawPlan {name}RecursionPlan = true := rfl\n\n\
             /-- The context-sensitive recursion grammar accepts `{name}`'s plan: the\n\
                 self-call targets the export's own byte-derived function index and every\n\
                 host call cites the byte-derived role table. -/\n\
             example : AverCert.PlanCheck.checkRecursionPlanShape {self_idx} {host_table} {totality_role} {name}RecursionPlan = true := rfl\n\n\
             /-- The opposite totality role is rejected by the same byte-pinned grammar. -/\n\
             example : AverCert.PlanCheck.checkRecursionPlanShape {self_idx} {host_table} {wrong_totality_role} {name}RecursionPlan = false := rfl\n\n\
             /-- The declared function type of `{name}` is the canonical certified\n\
                 signature over the Int carrier. -/\n\
             example : AverCert.WasmSlice.funcTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {type_idx} {arity} {carrier} = true := rfl\n\n\
             /-- The audited recursion lowerer maps `{name}`'s plan to the exact `Module.lean` body. -/\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerRecursionBody {carrier} {name}RecursionPlan := rfl\n\n\
             /-- The audited recursion byte lowerer reproduces `{name}`'s exact code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerRecursionCodeEntry {carrier} {name}RecursionPlan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The Wasm slicer finds `{name}`'s exact code-entry bytes by export name. -/\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes} =\n  \
               some {func_binding} := rfl\n\n",
            plan_value = recursion_plan_lean_value(&plan),
        ));
    }
    for c in &analysis.certs {
        let Cert::MutualRecursion {
            name,
            self_idx,
            carrier,
            box_idx,
            sub_idx,
            position,
            scc,
        } = c.inner()
        else {
            continue;
        };
        let Some(plan) = mutual_plan_from_cert(c) else {
            continue;
        };
        let member = &scc[*position];
        let type_idx = member.type_idx;
        let primary = &scc[0].name;
        let code_entry_bytes = lower_expr_fragment_plan_code_entry_bytes(&plan, *carrier)
            .expect("certified mutual member plan lowers to code-entry bytes");
        let code_entry_bytes = render_byte_list(&code_entry_bytes);
        let export_name_bytes = render_byte_list(name.as_bytes());
        let func_binding = format!(
            "({{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry_bytes} }} : AverCert.WasmSlice.FuncBinding)"
        );
        let host_table = mutual_host_table_lean_value(*box_idx, *sub_idx);
        let member_set = mutual_member_set_lean_value(scc);
        any = true;
        s.push_str(&format!(
            "/-- Byte-derived `mutual-plan-v1` plan for `{name}` (one member of the\n\
                 mutually-recursive SCC whose shared code table `{primary}Code` emits). -/\n\
             def {name}MutualPlan : MutualRawPlan := {plan_value}\n\n\
             /-- The audited mutual-plan checker accepts `{name}`'s byte-derived plan. -/\n\
             example : AverCert.PlanCheck.checkMutualRawPlan {name}MutualPlan = true := rfl\n\n\
             /-- The context-sensitive mutual grammar accepts `{name}`'s plan: the\n\
                 member-call targets an index in the byte-derived SCC member set and every\n\
                 host call cites the byte-derived box/sub role table. -/\n\
             example : AverCert.PlanCheck.checkMutualPlanShape {member_set} {host_table} {name}MutualPlan = true := rfl\n\n\
             /-- The declared function type of `{name}` is the canonical certified\n\
                 signature over the Int carrier. -/\n\
             example : AverCert.WasmSlice.funcTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {type_idx} 1 {carrier} = true := rfl\n\n\
             /-- The audited mutual lowerer maps `{name}`'s plan to its arm of the shared\n\
                 `{primary}Code` table (the exact `Module.lean` body). -/\n\
             example : (CertModule.{primary}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerMutualBody {carrier} {name}MutualPlan := rfl\n\n\
             /-- The audited mutual byte lowerer reproduces `{name}`'s exact code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerMutualCodeEntry {carrier} {name}MutualPlan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The Wasm slicer finds `{name}`'s exact code-entry bytes by export name. -/\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes} =\n  \
               some {func_binding} := rfl\n\n",
            plan_value = mutual_plan_lean_value(&plan),
        ));
    }
    for c in &analysis.certs {
        let (name, self_idx, carrier) = match c.inner() {
            Cert::VerbatimWidenedMatch {
                name,
                self_idx,
                carrier,
                ..
            }
            | Cert::VerbatimVariantDispatch {
                name,
                self_idx,
                carrier,
                ..
            } => (name, *self_idx, *carrier),
            _ => continue,
        };
        let Some(plan) = verbatim_plan_from_cert(c) else {
            continue;
        };
        let code_entry_bytes = render_byte_list(&lower_verbatim_code_entry(&plan, carrier));
        let export_name_bytes = render_byte_list(name.as_bytes());
        let nlocals = if verbatim_dispatch_has_projection(&plan.body) {
            3
        } else {
            2
        };
        any = true;
        s.push_str(&format!(
            "/-- Byte-derived `verbatim-plan-v1` plan for `{name}` (a `Cod := WVal`\n\
                 verbatim `ref.test`-dispatch match; no host, no representation). -/\n\
             def {name}VerbatimPlan : VerbatimRawPlan := {plan_value}\n\n\
             /-- The audited verbatim-plan admission checker accepts `{name}`'s\n\
                 byte-derived plan with its canonical local count. -/\n\
             example : AverCert.PlanCheck.checkVerbatimPlan {nlocals} {name}VerbatimPlan = true := rfl\n\n\
             /-- The audited verbatim lowerer maps `{name}`'s plan to the exact `Module.lean` body. -/\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               some (AverCert.PlanLower.lowerVerbatimBody {name}VerbatimPlan) := rfl\n\n\
             /-- The audited verbatim byte lowerer reproduces `{name}`'s exact code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerVerbatimCodeEntry {carrier} {name}VerbatimPlan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The Wasm slicer finds `{name}`'s export binding with the exact code-entry bytes. -/\n\
             example : (AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes}).isSome = true := rfl\n\n",
            plan_value = verbatim_plan_lean_value(&plan),
        ));
    }
    for c in &analysis.certs {
        let (name, self_idx, carrier) = match c.inner() {
            Cert::VariantDispatch {
                name,
                self_idx,
                carrier,
                ..
            }
            | Cert::WidenedIntMatch {
                name,
                self_idx,
                carrier,
                ..
            } => (name, *self_idx, *carrier),
            _ => continue,
        };
        let Some(plan) = int_dispatch_plan_from_cert(c, analysis.frag_host_table) else {
            continue;
        };
        let hosts = int_dispatch_host_table_from_cert(c)
            .expect("Int-face dispatch cert carries its host table");
        let code_entry_bytes = render_byte_list(
            &lower_int_dispatch_code_entry(&plan, carrier, &hosts)
                .expect("certified Int-face dispatch plan lowers to code-entry bytes"),
        );
        let export_name_bytes = render_byte_list(name.as_bytes());
        let host_table = int_dispatch_host_table_lean_value(&hosts);
        any = true;
        s.push_str(&format!(
            "/-- Byte-derived `int-dispatch-v1` plan for `{name}` (a `Cod := Int`\n\
                 ADT-match; host helpers are cited by ROLE — the byte-derived role\n\
                 table below parameterizes the lowerers, so the plan carries no\n\
                 function index). -/\n\
             def {name}IntDispatchPlan : IntDispatchRawPlan := {plan_value}\n\n\
             /-- The audited int-dispatch checker accepts `{name}`'s byte-derived plan. -/\n\
             example : AverCert.PlanCheck.checkIntDispatchRawPlan {name}IntDispatchPlan = true := rfl\n\n\
             /-- The byte-derived role table maps roles to pairwise distinct indices\n\
                 (so the byte-equality gate distinguishes an arm's role). -/\n\
             example : AverCert.PlanCheck.hostTableIndicesDistinct {host_table} = true := rfl\n\n\
             /-- The audited int-dispatch lowerer maps `{name}`'s plan to the exact `Module.lean` body. -/\n\
             example : (CertModule.{name}Code {self_idx}).map (fun c => c.body) =\n  \
               AverCert.PlanLower.lowerIntDispatchBody {host_table} {name}IntDispatchPlan := rfl\n\n\
             /-- The audited int-dispatch byte lowerer reproduces `{name}`'s exact code-entry bytes. -/\n\
             example : AverCert.PlanBytes.lowerIntDispatchCodeEntry {carrier} {host_table} {name}IntDispatchPlan =\n  \
               some {code_entry_bytes} := rfl\n\n\
             /-- The Wasm slicer finds `{name}`'s export binding with the exact code-entry bytes. -/\n\
             example : (AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry_bytes}).isSome = true := rfl\n\n",
            plan_value = int_dispatch_plan_lean_value(&plan),
        ));
    }
    for (entry, plan) in composition_member_plans(analysis) {
        let Cert::Composition { carrier, closure, .. } = analysis
            .certs
            .iter()
            .find(|cert| match cert.inner() {
                Cert::Composition { closure, .. } => {
                    closure.iter().any(|candidate| candidate.name == entry.name)
                }
                _ => false,
            })
            .expect("composition member belongs to a composition cert")
            .inner()
        else {
            unreachable!()
        };
        let add_idx = analysis
            .frag_host_table
            .add_idx
            .expect("plan-backed composition has strict add host");
        let funcs = composition_func_table(closure);
        let lowered = lower_composition_plan(&plan, add_idx, &funcs)
            .expect("composition member plan lowers");
        let code_entry = composition_code_entry_bytes(&plan, *carrier, add_idx, &funcs)
            .expect("composition member plan byte-lowers");
        let host_table = composition_host_table_lean_value(add_idx);
        let func_table = composition_func_table_lean_value(closure);
        let export_name_bytes = render_byte_list(entry.name.as_bytes());
        let binding = format!(
            "({{ funcIdx := {}, typeIdx := {}, codeEntry := {} }} : AverCert.WasmSlice.FuncBinding)",
            entry.self_idx,
            entry.type_idx,
            render_byte_list(&code_entry),
        );
        any = true;
        s.push_str(&format!(
            "/-- Byte-derived composition shape for `{name}`. Callees are named;\n\
                 numeric indices come from the byte-derived function table. -/\n\
             def {name}CompositionPlan : CompositionRawPlan := {plan_value}\n\n\
             example : AverCert.PlanCheck.checkCompositionRawPlan {name}CompositionPlan = true := rfl\n\n\
             example : AverCert.PlanLower.lowerCompositionBody {host_table} {func_table} {name}CompositionPlan =\n  \
               some {body} := rfl\n\n\
             example : AverCert.PlanBytes.lowerCompositionCodeEntry {carrier} {host_table} {func_table} {name}CompositionPlan =\n  \
               some {code_entry} := rfl\n\n\
             example : AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} =\n  \
               some {binding} := rfl\n\n",
            name = entry.name,
            plan_value = composition_plan_lean_value(&plan),
            body = render_ops_value(&lowered),
            code_entry = render_byte_list(&code_entry),
            binding = binding,
        ));
    }
    for c in &analysis.certs {
        let Some(envelope) = declared_envelope_for_cert(c, model_info, analysis) else {
            continue;
        };
        any = true;
        s.push_str(&format!(
            "/-- Declared ADT envelope for `{name}`: root, carrier and every constructor's\n\
                 flattened type index, shape and payload target. The wall confirms the whole\n\
                 declaration against the module bytes with one type-section walk-match\n\
                 traversal (`DeclaredIndexEnvelope.dWalkPinned`). -/\n\
             def {name}DeclaredEnvelope : AverCert.DeclaredIndexEnvelope.DIdxEnvelope :=\n  \
             {env}\n\n\
             /-- Opaque declared type-section bytes before `{name}`'s constructor entries. -/\n\
             def {name}TypePrefix : List Nat :=\n  \
             {prefix}\n\n",
            name = c.name(),
            env = envelope.lean_env(),
            prefix = envelope.lean_prefix(),
        ));
    }
    if analysis.certs.iter().any(|c| {
        declared_envelope_for_cert(c, model_info, analysis).is_some()
            || matches!(c.inner(), Cert::StringConcatVerbatimMatch { .. })
    }) {
        any = true;
        s.push_str(
            "/-- Located type-section entry cursor: the section payload found by\n\
                 `modulePayload 1`, advanced past the vector-count LEB. A framing\n\
                 locate only — no type entry is parsed. -/\n\
             def declaredTypeCur : Nat × Nat :=\n  \
             (AverCert.DeclaredIndexEnvelope.typeSectionCursor AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen).getD (0, 0)\n\n",
        );
    }
    if !any {
        s.push_str("-- This artifact contains no source/fragment plans.\n\n");
    }
    s.push_str("end AverCert.Plans\n");
    s
}

/// The declared envelope backing a user-ADT claim, when the certificate must
/// carry one: Int-face dispatch (keyed by the first tested variant) and
/// model-bearing named-ADT constructors (keyed by the constructed variant).
/// Analysis keeps only certs whose envelope is extractable, so a `None` here
/// means the cert simply carries no envelope.
fn declared_envelope_for_cert<'a>(
    c: &Cert,
    model_info: &ModelInfo,
    analysis: &'a Analysis,
) -> Option<&'a DeclaredEnvelope> {
    match c.inner() {
        Cert::VariantDispatch { .. } | Cert::WidenedIntMatch { .. } => {
            let plan = int_dispatch_plan_from_cert(c, analysis.frag_host_table)?;
            let first = int_dispatch_test_tags(&plan.body).first().copied()?;
            analysis.declared_envelopes.for_ctor(first)
        }
        Cert::AdtConstructor { struct_idx, .. }
            if adt_constructor_uses_model(c, model_info) =>
        {
            analysis.declared_envelopes.for_ctor(*struct_idx)
        }
        _ => None,
    }
}

struct RenderedArtifactClaims {
    sym_claims: String,
    string_eq_claims: String,
    string_claims: String,
    construct_claims: String,
    recursion_claims: String,
    mutual_claims: String,
    verbatim_claims: String,
    int_dispatch_claims: String,
    field_projection_claims: String,
    composition_members: String,
    composition_claims: String,
    claim_proof_bundles: String,
    obligation_proof: String,
    sym_proof: String,
    string_eq_proof: String,
    string_proof: String,
    construct_proof: String,
    recursion_proof: String,
    mutual_proof: String,
    verbatim_proof: String,
    int_dispatch_proof: String,
    field_projection_proof: String,
    composition_proof: String,
    string_concat_face_proof: String,
    construct_face_proof: String,
    int_dispatch_face_proof: String,
    /// Aggregate proof of the `sym` family's `symFragmentMatches` face slot. Only
    /// meaningful when `sym_faces_have_record` is set; otherwise the slot keeps
    /// its inline `repeat' constructor` and this stays empty.
    sym_face_proof: String,
    /// Whether any `sym` claim carries a record-parameter face, so the face slot
    /// must route through `sym_face_proof` instead of `repeat' constructor`.
    sym_faces_have_record: bool,
}

/// Render one opaque declared-envelope face theorem per claim plus the
/// aggregate spine `standardFacesChecked` consumes for the family slot.
/// `None` elements are known-face claims closed inline by `repeat' constructor`.
fn render_face_bundles(
    family: &str,
    face_def: &str,
    claims_def: &str,
    extra_unfolds: &str,
    host_table_conj: bool,
    elements: &[Option<(String, String)>],
) -> (String, String) {
    let mut theorems = String::new();
    let mut parts = Vec::with_capacity(elements.len());
    for (index, element) in elements.iter().enumerate() {
        match element {
            Some((plan_ref, proof)) => {
                let theorem = format!("{family}Claim{index}Face");
                theorems.push_str(&format!(
                    "theorem {theorem} :\n  \
                     AverCert.StandardFace.{face_def} AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen ({claims_def}.get ⟨{index}, by decide⟩) {plan_ref} := by\n  \
                     dsimp [{claims_def}, AverCert.StandardFace.{face_def}{extra_unfolds}]\n  \
                     exact {proof}\n\n"
                ));
                if host_table_conj {
                    parts.push(format!("⟨rfl, {theorem}⟩"));
                } else {
                    parts.push(theorem);
                }
            }
            None => parts.push("(by repeat' constructor)".to_string()),
        }
    }
    let aggregate = parts
        .into_iter()
        .rev()
        .fold("trivial".to_string(), |rest, part| {
            format!("⟨{part}, {rest}⟩")
        });
    (theorems, aggregate)
}

/// Render, per claim, the SPLIT acceptance proof: `per_claim(index)` supplies
/// the already-numbered witness `def`s and per-conjunct leaf theorems as one
/// text block plus the aggregate proof term that combines those constants. The
/// aggregate `{family}Claim{index}Accepted` theorem is stated exactly like the
/// opaque tuple it replaces — it indexes the same family
/// list and `dsimp`s the same predicate — but
/// its `exact` references the leaf constants instead of inlining one monolithic
/// witness tuple.
///
/// This is the mechanism the expr-fragment beachhead established generalized to
/// the other data-carrying families: emitting the heavy `WInstr` body, the
/// code-entry bytes, and the function binding as their OWN top-level `def`s (so
/// no large literal is duplicated into the aggregate term) and each acceptance
/// conjunct that walks the module bytes as its OWN leaf theorem means every
/// `addDecl` completes and frees before the next is elaborated. The per-claim
/// kernel peak becomes the largest single leaf (a `modBytes` type-section walk)
/// rather than the whole witness tuple held live at once. The leaf conjuncts are
/// stated over the encoded plan `def` the aggregate reduces to, so the
/// aggregate re-runs no byte-decode or lowering work.
fn render_split_bundles(
    family: &str,
    predicate: &str,
    claims_def: &str,
    unfolds: &str,
    count: usize,
    per_claim: impl Fn(usize) -> (String, String),
) -> (String, String) {
    let mut theorems = String::new();
    let mut names = Vec::with_capacity(count);
    for index in 0..count {
        let (declarations, aggregate_proof) = per_claim(index);
        let accepted = format!("{family}Claim{index}Accepted");
        theorems.push_str(&declarations);
        theorems.push_str(&format!(
            "theorem {accepted} :\n  {predicate} ({claims_def}.get ⟨{index}, by decide⟩) := by\n  dsimp [{claims_def}, {unfolds}]\n  exact {aggregate_proof}\n\n"
        ));
        names.push(accepted);
    }
    let aggregate = names
        .into_iter()
        .rev()
        .fold("trivial".to_string(), |rest, theorem| {
            format!("⟨{theorem}, {rest}⟩")
        });
    (theorems, aggregate)
}

/// Structured inputs for one expr-fragment (`sym`) claim's split acceptance
/// proof. The heavy witness data (lowered body, code-entry bytes, function
/// binding) and each acceptance conjunct are emitted as their OWN top-level
/// declarations by `render_sym_claim_bundles`.
struct SymClaimParts {
    name: String,
    lowered_body: String,
    code_entry_bytes: String,
    export_name_bytes: String,
    self_idx: u32,
    type_idx: u32,
    carrier: u32,
}

/// Render, per `sym` claim, named data `def`s + per-conjunct leaf theorems +
/// the aggregate `symFragmentClaim{i}Accepted` theorem that combines the
/// already-checked constants.
///
/// The former shape emitted ONE theorem per claim whose proof was
/// `dsimp [...]; exact ⟨…giant nested tuple…⟩`. A `theorem` submits its entire
/// proof term to the kernel in a single `addDecl`, so the whole witness tuple
/// (the large `WInstr` body list, the code-entry bytes, the binding record, and
/// every conjunct's `isDefEq`) was held live at once — the affine verify peaked
/// at ~6.7 GB there. Splitting the data into `def`s and each conjunct into its
/// own `theorem` means every `addDecl` completes and frees before the next is
/// elaborated, so the per-claim peak becomes the largest single leaf (the
/// `modBytes` decode / type-section walks, each measured ≤ ~1.24 GB) rather
/// than the whole tuple. The aggregate then only references the constants, so
/// its own `exact` re-runs no heavy reduction: the encoded plan the conjuncts
/// are stated over is `AverCert.Plans.{name}Plan`, definitionally the value the
/// aggregate's `dsimp` computes, so unifying them is a structural plan compare,
/// not a byte-carrier walk.
///
/// Every data-carrying claim family is split this way; this sym builder and the
/// generic `render_split_bundles` below share the same leaf-plus-aggregate shape.
fn render_sym_claim_bundles(parts: &[SymClaimParts], host_table_lean: &str) -> (String, String) {
    let mut theorems = String::new();
    let mut names = Vec::with_capacity(parts.len());
    for (index, part) in parts.iter().enumerate() {
        let SymClaimParts {
            name,
            lowered_body,
            code_entry_bytes,
            export_name_bytes,
            self_idx,
            type_idx,
            carrier,
        } = part;
        let body = format!("symFragmentClaim{index}Body");
        let code_entry = format!("symFragmentClaim{index}CodeEntry");
        let binding = format!("symFragmentClaim{index}Binding");
        let carrier_bound = format!("symFragmentClaim{index}CarrierBound");
        let host_types = format!("symFragmentClaim{index}HostTableFuncTypes");
        let check_plan = format!("symFragmentClaim{index}CheckPlan");
        let lower_body = format!("symFragmentClaim{index}LowerBody");
        let lower_code = format!("symFragmentClaim{index}LowerCodeEntry");
        let func_binding = format!("symFragmentClaim{index}FuncBinding");
        let func_type = format!("symFragmentClaim{index}FuncTypeMatches");
        let nominal = format!("symFragmentClaim{index}NominalTypes");
        let accepted = format!("symFragmentClaim{index}Accepted");
        let plan = format!("AverCert.Plans.{name}Plan");
        theorems.push_str(&format!(
            "-- Witness data for `{name}` as named constants so no large literal is\n\
             -- duplicated across the leaf statements or baked into the aggregate term.\n\
             def {body} : List CertPrelude.WInstr := {lowered_body}\n\n\
             def {code_entry} : AverCert.WasmSlice.ByteSeq := {code_entry_bytes}\n\n\
             def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
               {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry} }}\n\n\
             -- One leaf theorem per acceptance conjunct. Each is checked and freed in\n\
             -- its own `addDecl`; the heavy ones are the `modBytes` type-section walks\n\
             -- and the function-binding decode.\n\
             theorem {carrier_bound} :\n  \
               AverCert.AcceptedArtifact.symFragmentCarrierBound AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {carrier} {host_table_lean} {plan} = true := by\n  \
               rfl\n\n\
             theorem {host_types} :\n  \
               AverCert.WasmSlice.hostTableFuncTypesMatch AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {carrier} {host_table_lean} = true := by\n  \
               rfl\n\n\
             theorem {check_plan} :\n  \
               AverCert.PlanCheck.checkExprFragmentRawPlan {plan} = true := by\n  \
               rfl\n\n\
             theorem {lower_body} :\n  \
               AverCert.PlanLower.lowerExprFragmentBody {carrier} {plan} = some {body} := by\n  \
               rfl\n\n\
             theorem {lower_code} :\n  \
               AverCert.PlanBytes.lowerExprFragmentCodeEntry {carrier} {plan} = some {code_entry} := by\n  \
               rfl\n\n\
             theorem {func_binding} :\n  \
               AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
               rfl\n\n\
             theorem {func_type} :\n  \
               AverCert.WasmSlice.exprFragmentFuncTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding}.typeIdx {carrier} {plan}.params {plan}.result = true := by\n  \
               rfl\n\n\
             theorem {nominal} :\n  \
               AverCert.WasmSlice.exprFragmentNominalTypesMatch AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding}.typeIdx {carrier} {plan} = true := by\n  \
               rfl\n\n\
             -- Aggregate: combine the already-checked leaf constants. `dsimp` only\n\
             -- prepares the goal shape; the `exact` holds no heavy reduction.\n\
             theorem {accepted} :\n  \
               AverCert.AcceptedArtifact.symFragmentClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen (symFragmentClaims.get ⟨{index}, by decide⟩) := by\n  \
               dsimp [symFragmentClaims, AverCert.AcceptedArtifact.symFragmentClaimAccepted, AverCert.AcceptedArtifact.symFragmentPlanAccepted, AverCert.AcceptedArtifact.exprFragmentPlanAccepted, AverCert.ExprFragmentAccepted.accepted]\n  \
               exact ⟨{carrier_bound}, {host_types}, rfl, rfl, ⟨{body}, {code_entry}, {binding}, ⟨⟨{check_plan}, {lower_body}, {lower_code}, {func_binding}⟩, {func_type}, {nominal}, rfl, rfl⟩⟩⟩\n\n"
        ));
        names.push(accepted);
    }
    let aggregate = names
        .into_iter()
        .rev()
        .fold("trivial".to_string(), |rest, theorem| {
            format!("⟨{theorem}, {rest}⟩")
        });
    (theorems, aggregate)
}

/// Structured inputs for one fuel-recursion claim's split acceptance proof.
struct RecursionParts {
    name: String,
    lowered_body: String,
    code_entry_bytes: String,
    export_name_bytes: String,
    host_table: String,
    self_idx: u32,
    type_idx: u32,
    carrier: u32,
}

/// Split the fuel-recursion family exactly as `render_sym_claim_bundles` splits
/// the expr-fragment family: the lowered body, code-entry bytes and function
/// binding become named `def`s, each byte-walking conjunct of
/// `recursionPlanAccepted` becomes its own leaf theorem over
/// `AverCert.Plans.{name}RecursionPlan`, and the aggregate combines them.
fn render_recursion_claim_bundles(parts: &[RecursionParts]) -> (String, String) {
    render_split_bundles(
        "recursion",
        "AverCert.AcceptedArtifact.recursionClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "recursionClaims",
        "AverCert.AcceptedArtifact.recursionClaimAccepted, AverCert.AcceptedArtifact.recursionPlanForExport, AverCert.AcceptedArtifact.recursionPlanAccepted",
        parts.len(),
        |index| {
            let RecursionParts {
                name,
                lowered_body,
                code_entry_bytes,
                export_name_bytes,
                host_table,
                self_idx,
                type_idx,
                carrier,
            } = &parts[index];
            let body = format!("recursionClaim{index}Body");
            let code_entry = format!("recursionClaim{index}CodeEntry");
            let binding = format!("recursionClaim{index}Binding");
            let check_plan = format!("recursionClaim{index}CheckPlan");
            let lower_body = format!("recursionClaim{index}LowerBody");
            let lower_code = format!("recursionClaim{index}LowerCode");
            let func_binding = format!("recursionClaim{index}FuncBinding");
            let check_shape = format!("recursionClaim{index}CheckShape");
            let func_type = format!("recursionClaim{index}FuncType");
            let host_types = format!("recursionClaim{index}HostTypes");
            let plan = format!("AverCert.Plans.{name}RecursionPlan");
            let obligation = format!("AverCert.{name}Ob");
            let declarations = format!(
                "-- Witness data for `{name}` as named constants so no large literal is\n\
                 -- duplicated across the leaf statements or baked into the aggregate term.\n\
                 def {body} : List CertPrelude.WInstr := {lowered_body}\n\n\
                 def {code_entry} : AverCert.WasmSlice.ByteSeq := {code_entry_bytes}\n\n\
                 def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
                   {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry} }}\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy ones are the\n\
                 -- `modBytes` binding decode and type-section walks.\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkRecursionRawPlan {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_body} :\n  \
                   AverCert.PlanLower.lowerRecursionBody {carrier} {plan} = some {body} := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerRecursionCodeEntry {carrier} {plan} = some {code_entry} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
                   rfl\n\n\
                 theorem {check_shape} :\n  \
                   AverCert.PlanCheck.checkRecursionPlanShape {binding}.funcIdx {host_table} {obligation}.totalityRole {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {func_type} :\n  \
                   AverCert.WasmSlice.funcTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding}.typeIdx {plan}.params.length {carrier} = true := by\n  \
                   rfl\n\n\
                 theorem {host_types} :\n  \
                   AverCert.WasmSlice.hostTableFuncTypesMatch AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {carrier} {host_table} = true := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, rfl, {check_plan}, rfl, ⟨{body}, {code_entry}, {binding}, ⟨{lower_body}, {lower_code}, {func_binding}, rfl, {check_shape}, {func_type}, {host_types}, rfl⟩⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// Structured inputs for one mutual-recursion member claim's split proof.
struct MutualParts {
    name: String,
    lowered_body: String,
    code_entry_bytes: String,
    export_name_bytes: String,
    host_table: String,
    member_set: String,
    self_idx: u32,
    type_idx: u32,
    carrier: u32,
}

/// Split the mutual-recursion family the same way as the fuel-recursion family.
fn render_mutual_claim_bundles(parts: &[MutualParts]) -> (String, String) {
    render_split_bundles(
        "mutual",
        "AverCert.AcceptedArtifact.mutualRecursionClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "mutualRecursionClaims",
        "AverCert.AcceptedArtifact.mutualRecursionClaimAccepted, AverCert.AcceptedArtifact.mutualPlanForExport, AverCert.AcceptedArtifact.mutualPlanAccepted",
        parts.len(),
        |index| {
            let MutualParts {
                name,
                lowered_body,
                code_entry_bytes,
                export_name_bytes,
                host_table,
                member_set,
                self_idx,
                type_idx,
                carrier,
            } = &parts[index];
            let body = format!("mutualClaim{index}Body");
            let code_entry = format!("mutualClaim{index}CodeEntry");
            let binding = format!("mutualClaim{index}Binding");
            let check_plan = format!("mutualClaim{index}CheckPlan");
            let lower_body = format!("mutualClaim{index}LowerBody");
            let lower_code = format!("mutualClaim{index}LowerCode");
            let func_binding = format!("mutualClaim{index}FuncBinding");
            let check_shape = format!("mutualClaim{index}CheckShape");
            let func_type = format!("mutualClaim{index}FuncType");
            let host_types = format!("mutualClaim{index}HostTypes");
            let plan = format!("AverCert.Plans.{name}MutualPlan");
            let declarations = format!(
                "-- Witness data for `{name}` as named constants so no large literal is\n\
                 -- duplicated across the leaf statements or baked into the aggregate term.\n\
                 def {body} : List CertPrelude.WInstr := {lowered_body}\n\n\
                 def {code_entry} : AverCert.WasmSlice.ByteSeq := {code_entry_bytes}\n\n\
                 def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
                   {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry} }}\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy ones are the\n\
                 -- `modBytes` binding decode and type-section walks.\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkMutualRawPlan {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_body} :\n  \
                   AverCert.PlanLower.lowerMutualBody {carrier} {plan} = some {body} := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerMutualCodeEntry {carrier} {plan} = some {code_entry} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
                   rfl\n\n\
                 theorem {check_shape} :\n  \
                   AverCert.PlanCheck.checkMutualPlanShape {member_set} {host_table} {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {func_type} :\n  \
                   AverCert.WasmSlice.funcTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding}.typeIdx {plan}.params.length {carrier} = true := by\n  \
                   rfl\n\n\
                 theorem {host_types} :\n  \
                   AverCert.WasmSlice.hostTableFuncTypesMatch AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {carrier} {host_table} = true := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, rfl, rfl, {check_plan}, rfl, ⟨{body}, {code_entry}, {binding}, ⟨{lower_body}, {lower_code}, {func_binding}, rfl, {check_shape}, {func_type}, {host_types}, rfl⟩⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// Structured inputs for one String.concat claim's split acceptance proof.
struct StringConcatParts {
    name: String,
    lowered_body: String,
    code_entry_bytes: String,
    export_name_bytes: String,
    carrier_state: String,
    result_ty: u32,
    container_ty: u32,
    concat_func_idx: u32,
    self_idx: u32,
    type_idx: u32,
}

/// Split the String.concat family. Beyond the shared body/code-entry/binding
/// data, the heavy conjuncts are the carrier-state decode and the function
/// binding decode, both `modBytes` walks; the plan/sym checks and the two
/// lowerings are leaves stated over `Plans.{name}StringConcat{Sym}Plan`.
fn render_string_concat_claim_bundles(parts: &[StringConcatParts]) -> (String, String) {
    render_split_bundles(
        "stringConcat",
        "AverCert.AcceptedArtifact.stringConcatClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "stringConcatClaims",
        "AverCert.AcceptedArtifact.stringConcatClaimAccepted, AverCert.AcceptedArtifact.stringConcatPlanForExport, AverCert.AcceptedArtifact.stringConcatPlanAccepted, AverCert.AcceptedArtifact.stringConcatCanonicalHost",
        parts.len(),
        |index| {
            let StringConcatParts {
                name,
                lowered_body,
                code_entry_bytes,
                export_name_bytes,
                carrier_state,
                result_ty,
                container_ty,
                concat_func_idx,
                self_idx,
                type_idx,
            } = &parts[index];
            let body = format!("stringConcatClaim{index}Body");
            let code_entry = format!("stringConcatClaim{index}CodeEntry");
            let binding = format!("stringConcatClaim{index}Binding");
            let carrier_dec = format!("stringConcatClaim{index}CarrierState");
            let check_sym = format!("stringConcatClaim{index}CheckSym");
            let match_sym = format!("stringConcatClaim{index}MatchSym");
            let check_plan = format!("stringConcatClaim{index}CheckPlan");
            let lower_body = format!("stringConcatClaim{index}LowerBody");
            let lower_code = format!("stringConcatClaim{index}LowerCode");
            let func_binding = format!("stringConcatClaim{index}FuncBinding");
            let sym_plan = format!("AverCert.Plans.{name}StringConcatSymPlan");
            let plan = format!("AverCert.Plans.{name}StringConcatPlan");
            let declarations = format!(
                "-- Witness data for `{name}` as named constants so no large literal is\n\
                 -- duplicated across the leaf statements or baked into the aggregate term.\n\
                 def {body} : List CertPrelude.WInstr := {lowered_body}\n\n\
                 def {code_entry} : AverCert.WasmSlice.ByteSeq := {code_entry_bytes}\n\n\
                 def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
                   {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry} }}\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy ones are the\n\
                 -- `modBytes` carrier-state decode and the binding decode.\n\
                 theorem {carrier_dec} :\n  \
                   CertDecode.carrierState AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen = some {carrier_state} := by\n  \
                   rfl\n\n\
                 theorem {check_sym} :\n  \
                   AverCert.PlanCheck.checkSymRawPlan {sym_plan} = true := by\n  \
                   rfl\n\n\
                 theorem {match_sym} :\n  \
                   AverCert.PlanCheck.stringConcatPlanMatchesSymRawPlan {sym_plan} {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkStringConcatRawPlan {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_body} :\n  \
                   AverCert.PlanLower.lowerStringConcatBody {result_ty} {container_ty} {concat_func_idx} {plan} = some {body} := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerStringConcatCodeEntry {carrier_state} {result_ty} {container_ty} {concat_func_idx} {plan} = some {code_entry} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, {carrier_dec}, rfl, rfl, rfl, ⟨{body}, {code_entry}, {binding}, ⟨{check_sym}, {match_sym}, {check_plan}, {lower_body}, {lower_code}, {func_binding}, rfl, rfl⟩⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// Structured inputs for one String.eq claim's split acceptance proof.
struct StringEqParts {
    name: String,
    lowered_body: String,
    code_entry_bytes: String,
    export_name_bytes: String,
    string_ty: u32,
    string_eq_idx: u32,
    self_idx: u32,
    type_idx: u32,
    carrier: u32,
}

/// Split the String.eq family. The only `modBytes` walk is the function binding
/// decode; the sym/plan checks and the two lowerings are leaves stated over
/// `Plans.{name}StringEq{Sym}Plan`.
fn render_string_eq_claim_bundles(parts: &[StringEqParts]) -> (String, String) {
    render_split_bundles(
        "stringEq",
        "AverCert.AcceptedArtifact.stringEqClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "stringEqClaims",
        "AverCert.AcceptedArtifact.stringEqClaimAccepted, AverCert.AcceptedArtifact.stringEqPlanForExport, AverCert.AcceptedArtifact.stringEqPlanAccepted, AverCert.AcceptedArtifact.stringEqCanonicalHost",
        parts.len(),
        |index| {
            let StringEqParts {
                name,
                lowered_body,
                code_entry_bytes,
                export_name_bytes,
                string_ty,
                string_eq_idx,
                self_idx,
                type_idx,
                carrier,
            } = &parts[index];
            let body = format!("stringEqClaim{index}Body");
            let code_entry = format!("stringEqClaim{index}CodeEntry");
            let binding = format!("stringEqClaim{index}Binding");
            let check_sym = format!("stringEqClaim{index}CheckSym");
            let match_sym = format!("stringEqClaim{index}MatchSym");
            let check_plan = format!("stringEqClaim{index}CheckPlan");
            let lower_body = format!("stringEqClaim{index}LowerBody");
            let lower_code = format!("stringEqClaim{index}LowerCode");
            let func_binding = format!("stringEqClaim{index}FuncBinding");
            let sym_plan = format!("AverCert.Plans.{name}StringEqSymPlan");
            let plan = format!("AverCert.Plans.{name}StringEqPlan");
            let declarations = format!(
                "-- Witness data for `{name}` as named constants so no large literal is\n\
                 -- duplicated across the leaf statements or baked into the aggregate term.\n\
                 def {body} : List CertPrelude.WInstr := {lowered_body}\n\n\
                 def {code_entry} : AverCert.WasmSlice.ByteSeq := {code_entry_bytes}\n\n\
                 def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
                   {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry} }}\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy one is the\n\
                 -- `modBytes` binding decode.\n\
                 theorem {check_sym} :\n  \
                   AverCert.PlanCheck.checkSymRawPlan {sym_plan} = true := by\n  \
                   rfl\n\n\
                 theorem {match_sym} :\n  \
                   AverCert.PlanCheck.stringEqPlanMatchesSymRawPlan {sym_plan} {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkStringEqRawPlan {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_body} :\n  \
                   AverCert.PlanLower.lowerStringEqBody {string_ty} {string_eq_idx} {plan} = some {body} := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerStringEqCodeEntry {carrier} {string_ty} {string_eq_idx} {plan} = some {code_entry} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, rfl, rfl, rfl, {check_sym}, {match_sym}, {check_plan}, ⟨{body}, {code_entry}, {binding}, ⟨{lower_body}, {lower_code}, {func_binding}, rfl, rfl⟩⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// Structured inputs for one ADT-constructor claim's split acceptance proof.
struct ConstructParts {
    name: String,
    lowered_body: String,
    code_entry_bytes: String,
    export_name_bytes: String,
    struct_type_proof: String,
    func_type_proof: String,
    struct_idx: u32,
    self_idx: u32,
    type_idx: u32,
    carrier: u32,
}

/// Split the ADT-constructor family. The sym/plan checks and the two lowerings
/// are leaves over `Plans.{name}Construct{Sym}Plan`, and the function binding
/// decode is the `modBytes` walk. The list-constructor struct/func-type
/// conjuncts already reference the hoisted `Plans.{name}Construct…Matches`
/// lemmas, so they stay as-is (constants, not re-run literals).
fn render_construct_claim_bundles(parts: &[ConstructParts]) -> (String, String) {
    render_split_bundles(
        "construct",
        "AverCert.AcceptedArtifact.constructClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "constructClaims",
        "AverCert.AcceptedArtifact.constructClaimAccepted, AverCert.AcceptedArtifact.constructPlanForExport, AverCert.AcceptedArtifact.constructPlanAccepted",
        parts.len(),
        |index| {
            let ConstructParts {
                name,
                lowered_body,
                code_entry_bytes,
                export_name_bytes,
                struct_type_proof,
                func_type_proof,
                struct_idx,
                self_idx,
                type_idx,
                carrier,
            } = &parts[index];
            let body = format!("constructClaim{index}Body");
            let code_entry = format!("constructClaim{index}CodeEntry");
            let binding = format!("constructClaim{index}Binding");
            let check_sym = format!("constructClaim{index}CheckSym");
            let match_sym = format!("constructClaim{index}MatchSym");
            let check_plan = format!("constructClaim{index}CheckPlan");
            let lower_body = format!("constructClaim{index}LowerBody");
            let lower_code = format!("constructClaim{index}LowerCode");
            let func_binding = format!("constructClaim{index}FuncBinding");
            let sym_plan = format!("AverCert.Plans.{name}ConstructSymPlan");
            let plan = format!("AverCert.Plans.{name}ConstructPlan");
            let declarations = format!(
                "-- Witness data for `{name}` as named constants so no large literal is\n\
                 -- duplicated across the leaf statements or baked into the aggregate term.\n\
                 def {body} : List CertPrelude.WInstr := {lowered_body}\n\n\
                 def {code_entry} : AverCert.WasmSlice.ByteSeq := {code_entry_bytes}\n\n\
                 def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
                   {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_entry} }}\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy one is the\n\
                 -- `modBytes` binding decode.\n\
                 theorem {check_sym} :\n  \
                   AverCert.PlanCheck.checkSymRawPlan {sym_plan} = true := by\n  \
                   rfl\n\n\
                 theorem {match_sym} :\n  \
                   AverCert.PlanCheck.constructPlanMatchesSymRawPlan {sym_plan} {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkConstructRawPlan {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_body} :\n  \
                   AverCert.PlanLower.lowerConstructBody {struct_idx} {plan} = some {body} := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerConstructCodeEntry {carrier} {struct_idx} {plan} = some {code_entry} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, rfl, {check_sym}, {match_sym}, {check_plan}, rfl, ⟨{body}, {code_entry}, {binding}, ⟨{lower_body}, {lower_code}, {func_binding}, rfl, {struct_type_proof}, {func_type_proof}, rfl⟩⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// One composition member's witness data for the split proof.
struct CompositionMemberData {
    export_name_bytes: String,
    body: String,
    code_entry: String,
    self_idx: u32,
    type_idx: u32,
}

/// Structured inputs for one composition-root claim's split acceptance proof.
struct CompositionParts {
    carrier: u32,
    host_table: String,
    members: Vec<CompositionMemberData>,
}

/// Split the cross-function composition family. Each member's lowered body and
/// code-entry bytes become named `def`s, and the member `modBytes` walks (the
/// binding decode and the declared-function-type pin) plus the claim-level
/// host-table type pin become their own leaf theorems. The member lowerings and
/// the closure/root conjuncts stay inline: they read the byte-derived
/// `funcTable`, which the aggregate must reduce to enter the `some` branch in
/// any case, so isolating them would not remove that one walk.
fn render_composition_claim_bundles(parts: &[CompositionParts]) -> (String, String) {
    render_split_bundles(
        "composition",
        "AverCert.AcceptedArtifact.compositionClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen compositionMembers",
        "compositionClaims",
        "AverCert.AcceptedArtifact.compositionClaimAccepted, AverCert.AcceptedArtifact.compositionFuncTable, AverCert.AcceptedArtifact.compositionMemberBinding, AverCert.AcceptedArtifact.compositionNamedMembersAccepted, AverCert.AcceptedArtifact.compositionMemberPlanAccepted, AverCert.AcceptedArtifact.compositionMemberForName, AverCert.AcceptedArtifact.compositionClosureBound, AverCert.AcceptedArtifact.compositionEdges, AverCert.AcceptedArtifact.compositionPlanCallees, AverCert.AcceptedArtifact.compositionEdgesDescend, AverCert.AcceptedArtifact.compositionReachClosure, AverCert.AcceptedArtifact.compositionReachStep, AverCert.AcceptedArtifact.stringListNodup, AverCert.AcceptedArtifact.stringListSetEq",
        parts.len(),
        |index| {
            let CompositionParts {
                carrier,
                host_table,
                members,
            } = &parts[index];
            let host_types = format!("compositionClaim{index}HostTypes");
            // Shared host-table type pin: the same statement is the claim-level
            // conjunct and every member's host-type conjunct, so one leaf serves
            // both and no member re-runs the walk.
            let mut declarations = format!(
                "-- Claim-level host-table declared-function-type pin (a `modBytes`\n\
                 -- type-section walk), shared by the claim and every member.\n\
                 theorem {host_types} :\n  \
                   AverCert.WasmSlice.hostTableFuncTypesMatch AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {carrier} {host_table} = true := by\n  \
                   rfl\n\n"
            );
            let mut named_proof = "trivial".to_string();
            for (member_index, member) in members.iter().enumerate().rev() {
                let CompositionMemberData {
                    export_name_bytes,
                    body,
                    code_entry,
                    self_idx,
                    type_idx,
                } = member;
                let body_def = format!("compositionClaim{index}Member{member_index}Body");
                let code_def = format!("compositionClaim{index}Member{member_index}CodeEntry");
                let binding_def = format!("compositionClaim{index}Member{member_index}Binding");
                let func_binding = format!("compositionClaim{index}Member{member_index}FuncBinding");
                let func_type = format!("compositionClaim{index}Member{member_index}FuncType");
                declarations = format!(
                    "-- Member `{member_index}` witness data as named constants.\n\
                     def {body_def} : List CertPrelude.WInstr := {body}\n\n\
                     def {code_def} : AverCert.WasmSlice.ByteSeq := {code_entry}\n\n\
                     def {binding_def} : AverCert.WasmSlice.FuncBinding :=\n  \
                       {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_def} }}\n\n\
                     theorem {func_binding} :\n  \
                       AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_def} = some {binding_def} := by\n  \
                       rfl\n\n\
                     theorem {func_type} :\n  \
                       AverCert.WasmSlice.funcTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding_def}.typeIdx 1 {carrier} = true := by\n  \
                       rfl\n\n{declarations}"
                );
                let member_proof = format!(
                    "⟨rfl, ⟨{body_def}, {code_def}, {binding_def}, rfl, rfl, {func_binding}, {func_type}, {host_types}, rfl⟩⟩"
                );
                named_proof = format!("⟨{member_proof}, {named_proof}⟩");
            }
            let aggregate_proof = format!(
                "⟨rfl, ⟨rfl, ⟨rfl, ⟨{host_types}, ⟨rfl, ⟨rfl, ⟨rfl, {named_proof}⟩⟩⟩⟩⟩⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// Structured inputs for one field-projection claim's split acceptance proof.
struct FieldProjectionParts {
    name: String,
    body: String,
    code_entry: String,
    export_name_bytes: String,
    result_ty: String,
    struct_idx: u32,
    field_count: u32,
    self_idx: u32,
    type_idx: u32,
    carrier: u32,
}

/// Split the field-projection family. The former proof left the body,
/// code-entry and binding as `_`; elaboration solves them to the same large
/// literals the byte lowerers produce, so they still bloated the single proof
/// term. Emit them as named `def`s (the `Cert` already carries the exact bytes
/// and ops the wall lowerers reproduce) and each byte-walking conjunct as its
/// own leaf theorem over `Plans.{name}FieldProjectionPlan`.
fn render_field_projection_claim_bundles(parts: &[FieldProjectionParts]) -> (String, String) {
    render_split_bundles(
        "fieldProjection",
        "AverCert.AcceptedArtifact.fieldProjectionClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "fieldProjectionClaims",
        "AverCert.AcceptedArtifact.fieldProjectionClaimAccepted, AverCert.AcceptedArtifact.fieldProjectionPlanForExport, AverCert.AcceptedArtifact.fieldProjectionPlanAccepted",
        parts.len(),
        |index| {
            let FieldProjectionParts {
                name,
                body,
                code_entry,
                export_name_bytes,
                result_ty,
                struct_idx,
                field_count,
                self_idx,
                type_idx,
                carrier,
            } = &parts[index];
            let body_def = format!("fieldProjectionClaim{index}Body");
            let code_def = format!("fieldProjectionClaim{index}CodeEntry");
            let binding_def = format!("fieldProjectionClaim{index}Binding");
            let check_plan = format!("fieldProjectionClaim{index}CheckPlan");
            let lower_body = format!("fieldProjectionClaim{index}LowerBody");
            let lower_code = format!("fieldProjectionClaim{index}LowerCode");
            let func_binding = format!("fieldProjectionClaim{index}FuncBinding");
            let struct_type = format!("fieldProjectionClaim{index}StructType");
            let func_type = format!("fieldProjectionClaim{index}FuncType");
            let plan = format!("AverCert.Plans.{name}FieldProjectionPlan");
            let declarations = format!(
                "-- Witness data for `{name}` as named constants so the byte lowerings\n\
                 -- are not solved into large literals inside one proof term.\n\
                 def {body_def} : List CertPrelude.WInstr := {body}\n\n\
                 def {code_def} : AverCert.WasmSlice.ByteSeq := {code_entry}\n\n\
                 def {binding_def} : AverCert.WasmSlice.FuncBinding :=\n  \
                   {{ funcIdx := {self_idx}, typeIdx := {type_idx}, codeEntry := {code_def} }}\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy ones are the\n\
                 -- `modBytes` binding decode and type-section walks.\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkFieldProjectionRawPlan {field_count} {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_body} :\n  \
                   AverCert.PlanLower.lowerFieldProjectionBody {struct_idx} {field_count} {plan} = some {body_def} := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerFieldProjectionCodeEntry {carrier} {struct_idx} {field_count} {result_ty} {plan} = some {code_def} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_def} = some {binding_def} := by\n  \
                   rfl\n\n\
                 theorem {struct_type} :\n  \
                   AverCert.WasmSlice.projectionStructTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {struct_idx} {field_count} {plan}.fieldIdx {result_ty} = true := by\n  \
                   rfl\n\n\
                 theorem {func_type} :\n  \
                   AverCert.WasmSlice.projectionFuncTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding_def}.typeIdx {struct_idx} {result_ty} = true := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, rfl, {check_plan}, ⟨{body_def}, {code_def}, {binding_def}, {lower_body}, {lower_code}, {func_binding}, {struct_type}, {func_type}, rfl, rfl⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// Structured inputs for one verbatim `ref.test`-dispatch claim's split proof.
struct VerbatimParts {
    name: String,
    export_name_bytes: String,
    carrier: u32,
}

/// Split the verbatim family. Its `Cert` carries no code/type index (the binding
/// is recovered from the module by name), so rather than rendering literals the
/// witnesses are named `def`s whose VALUE is the wall lowerer / byte decoder
/// applied to the encoded plan. The stored definition body is small, so the
/// theorems that reference it hold no large literal; each byte walk is
/// materialized transiently inside its own leaf `addDecl` and freed.
fn render_verbatim_claim_bundles(parts: &[VerbatimParts]) -> (String, String) {
    render_split_bundles(
        "verbatim",
        "AverCert.AcceptedArtifact.verbatimClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "verbatimClaims",
        "AverCert.AcceptedArtifact.verbatimClaimAccepted, AverCert.AcceptedArtifact.verbatimPlanForExport, AverCert.AcceptedArtifact.verbatimPlanAccepted",
        parts.len(),
        |index| {
            let VerbatimParts {
                name,
                export_name_bytes,
                carrier,
            } = &parts[index];
            let code_entry = format!("verbatimClaim{index}CodeEntry");
            let binding = format!("verbatimClaim{index}Binding");
            let check_plan = format!("verbatimClaim{index}CheckPlan");
            let lower_code = format!("verbatimClaim{index}LowerCode");
            let func_binding = format!("verbatimClaim{index}FuncBinding");
            let func_type = format!("verbatimClaim{index}FuncType");
            let payloads = format!("verbatimClaim{index}Payloads");
            let plan = format!("AverCert.Plans.{name}VerbatimPlan");
            let declarations = format!(
                "-- Witness data for `{name}` as named `def`s computed by the wall\n\
                 -- lowerer / decoder, so no large literal is baked into the aggregate.\n\
                 def {code_entry} : AverCert.WasmSlice.ByteSeq :=\n  \
                   (AverCert.PlanBytes.lowerVerbatimCodeEntry {carrier} {plan}).getD []\n\n\
                 def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
                   (AverCert.WasmSlice.funcBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes}).getD ⟨0, 0, []⟩\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy ones are the\n\
                 -- `modBytes` binding decode and type-section walk.\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkVerbatimPlan (AverCert.AcceptedArtifact.verbatimNLocals {plan}) {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerVerbatimCodeEntry {carrier} {plan} = some {code_entry} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
                   rfl\n\n\
                 theorem {func_type} :\n  \
                   AverCert.WasmSlice.verbatimFuncTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding}.typeIdx {plan}.resultSig = true := by\n  \
                   rfl\n\n\
                 theorem {payloads} :\n  \
                   AverCert.AcceptedArtifact.verbatimPayloadsBound AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {plan}.body = true := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, rfl, {check_plan}, ⟨{code_entry}, {binding}, {lower_code}, {func_binding}, rfl, {func_type}, {payloads}, rfl⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

/// Structured inputs for one Int-face `ref.test`-dispatch claim's split proof.
struct IntDispatchParts {
    name: String,
    export_name_bytes: String,
    host_table: String,
    carrier: u32,
}

/// Split the Int-face dispatch family the same way as the verbatim family: the
/// body, code entry and binding — formerly inferred `_` witnesses solved into
/// large literals — become named `def`s computed by the wall lowerers and byte
/// decoder, and each byte-walking conjunct becomes its own leaf theorem.
fn render_int_dispatch_claim_bundles(parts: &[IntDispatchParts]) -> (String, String) {
    render_split_bundles(
        "intDispatch",
        "AverCert.AcceptedArtifact.intDispatchClaimAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen AverCert.manifest",
        "intDispatchClaims",
        "AverCert.AcceptedArtifact.intDispatchClaimAccepted, AverCert.AcceptedArtifact.intDispatchPlanForExport, AverCert.AcceptedArtifact.intDispatchPlanAccepted",
        parts.len(),
        |index| {
            let IntDispatchParts {
                name,
                export_name_bytes,
                host_table,
                carrier,
            } = &parts[index];
            let body = format!("intDispatchClaim{index}Body");
            let code_entry = format!("intDispatchClaim{index}CodeEntry");
            let binding = format!("intDispatchClaim{index}Binding");
            let check_plan = format!("intDispatchClaim{index}CheckPlan");
            let host_types = format!("intDispatchClaim{index}HostTypes");
            let lower_body = format!("intDispatchClaim{index}LowerBody");
            let lower_code = format!("intDispatchClaim{index}LowerCode");
            let func_binding = format!("intDispatchClaim{index}FuncBinding");
            let func_type = format!("intDispatchClaim{index}FuncType");
            let plan = format!("AverCert.Plans.{name}IntDispatchPlan");
            let declarations = format!(
                "-- Witness data for `{name}` as named `def`s computed by the wall\n\
                 -- lowerers / decoder, so no large literal is baked into the aggregate.\n\
                 def {body} : List CertPrelude.WInstr :=\n  \
                   (AverCert.PlanLower.lowerIntDispatchBody {host_table} {plan}).getD []\n\n\
                 def {code_entry} : AverCert.WasmSlice.ByteSeq :=\n  \
                   (AverCert.PlanBytes.lowerIntDispatchCodeEntry {carrier} {host_table} {plan}).getD []\n\n\
                 def {binding} : AverCert.WasmSlice.FuncBinding :=\n  \
                   (AverCert.WasmSlice.funcBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes}).getD ⟨0, 0, []⟩\n\n\
                 -- One leaf theorem per acceptance conjunct; the heavy ones are the\n\
                 -- `modBytes` binding decode and type-section walks.\n\
                 theorem {check_plan} :\n  \
                   AverCert.PlanCheck.checkIntDispatchRawPlan {plan} = true := by\n  \
                   rfl\n\n\
                 theorem {host_types} :\n  \
                   AverCert.WasmSlice.hostTableFuncTypesMatch AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {carrier} {host_table} = true := by\n  \
                   rfl\n\n\
                 theorem {lower_body} :\n  \
                   AverCert.PlanLower.lowerIntDispatchBody {host_table} {plan} = some {body} := by\n  \
                   rfl\n\n\
                 theorem {lower_code} :\n  \
                   AverCert.PlanBytes.lowerIntDispatchCodeEntry {carrier} {host_table} {plan} = some {code_entry} := by\n  \
                   rfl\n\n\
                 theorem {func_binding} :\n  \
                   AverCert.WasmSlice.exactFuncBindingForExport AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {export_name_bytes} {code_entry} = some {binding} := by\n  \
                   rfl\n\n\
                 theorem {func_type} :\n  \
                   AverCert.WasmSlice.verbatimFuncTypeMatches AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen {binding}.typeIdx (.refNull {carrier}) = true := by\n  \
                   rfl\n\n"
            );
            let aggregate_proof = format!(
                "⟨rfl, rfl, {check_plan}, rfl, {host_types}, rfl, ⟨{body}, {code_entry}, {binding}, {lower_body}, {lower_code}, {func_binding}, rfl, {func_type}, rfl⟩⟩"
            );
            (declarations, aggregate_proof)
        },
    )
}

fn render_artifact_expr_fragment_claims(
    analysis: &Analysis,
    model_info: &ModelInfo,
    host_table_lean: &str,
    struct_table_lean: &str,
) -> RenderedArtifactClaims {
    let mut sym_claims = Vec::new();
    let mut string_eq_claims = Vec::new();
    let mut string_claims = Vec::new();
    let mut construct_claims = Vec::new();
    let mut recursion_claims = Vec::new();
    let mut mutual_claims = Vec::new();
    let mut verbatim_claims = Vec::new();
    let mut int_dispatch_claims = Vec::new();
    let mut field_projection_claims = Vec::new();
    let mut composition_claims = Vec::new();
    let mut sym_parts: Vec<SymClaimParts> = Vec::new();
    let mut string_eq_parts: Vec<StringEqParts> = Vec::new();
    let mut string_parts: Vec<StringConcatParts> = Vec::new();
    let mut construct_parts: Vec<ConstructParts> = Vec::new();
    let mut recursion_parts: Vec<RecursionParts> = Vec::new();
    let mut mutual_parts: Vec<MutualParts> = Vec::new();
    let mut verbatim_parts: Vec<VerbatimParts> = Vec::new();
    let mut int_dispatch_parts: Vec<IntDispatchParts> = Vec::new();
    let mut field_projection_parts: Vec<FieldProjectionParts> = Vec::new();
    let mut composition_parts: Vec<CompositionParts> = Vec::new();
    let mut string_concat_faces: Vec<Option<(String, String)>> = Vec::new();
    let mut construct_faces: Vec<Option<(String, String)>> = Vec::new();
    let mut int_dispatch_faces: Vec<Option<(String, String)>> = Vec::new();
    // One entry per `sym` claim, in `symFragmentClaims` order: `Some` carries a
    // record-parameter face witness, `None` is a known-face claim closed inline
    // by `repeat' constructor`.
    let mut sym_faces: Vec<Option<(String, String)>> = Vec::new();
    for c in &analysis.certs {
        match c.inner() {
            Cert::ExprFragment {
                name,
                carrier,
                self_idx,
                type_idx,
                source_plan,
                plan,
                ..
            } => {
                let code_entry_bytes = lower_expr_fragment_plan_code_entry_bytes(plan, *carrier)
                    .expect("certified expr-fragment plan lowers to code-entry bytes");
                let code_entry_bytes = render_byte_list(&code_entry_bytes);
                let lowered_body = lower_expr_fragment_plan(plan, *carrier)
                    .map(|ops| render_ops_value(&ops))
                    .expect("certified expr-fragment plan lowers to WInstr body");
                let export_name_bytes = render_byte_list(name.as_bytes());
                if expr_fragment_source_plan(source_plan, plan).is_some() {
                    sym_claims.push(format!(
                        "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier}, hostTable := {host_table_lean}, structTable := {struct_table_lean}, plan := AverCert.Plans.{name}SymPlan, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.SymFragmentClaim)",
                        export_name = lean_str(name),
                    ));
                    // Structured inputs for this claim's SPLIT acceptance proof:
                    // the witness data and every conjunct become their own
                    // top-level declarations (see `render_sym_claim_bundles`), so
                    // the kernel checks and frees each in a separate `addDecl`
                    // instead of holding one monolithic witness tuple live.
                    sym_parts.push(SymClaimParts {
                        name: name.clone(),
                        lowered_body,
                        code_entry_bytes,
                        export_name_bytes,
                        self_idx: *self_idx,
                        type_idx: *type_idx,
                        carrier: *carrier,
                    });
                    // A stage-1 record scalar field read routes through the
                    // wall's record-parameter face: `symFragmentFace` yields
                    // `none` on the recognized record plan (proved once and for
                    // all by `symFragmentFace_none_of_recordProj`), so this arm
                    // is the record shape's only route. The witness pins the
                    // Plan declaration, the equality pin against the decoded
                    // type entry, the export's parameter binding, and the `HEq`
                    // meaning fields — the exact structure of the hand-checked
                    // `PersonBeachhead.isMemberFace`.
                    sym_faces.push(c.record_param_face().map(|face| {
                        // The three byte pins (carrier state, type-section
                        // equality, parameter binding) discharge by kernel `rfl`,
                        // never `native_decide`: the checker-owned witness admits
                        // only `[propext, Classical.choice, Quot.sound]`, so a
                        // compiled-reduction axiom would be rejected. The
                        // accepted-conjunction's byte scans reduce by `rfl` the
                        // same way.
                        let witness = format!(
                            "⟨rfl, rfl, rfl, AverCert.Plans.{name}RecordDecl, {si}, {fi}, \
                             AverCert.Plans.{name}RecordFields, by decide, rfl, rfl, rfl, rfl, \
                             fun _ => by rfl, by rfl, by rfl, \
                             HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl⟩",
                            si = face.struct_idx,
                            fi = face.field_idx,
                        );
                        (format!("AverCert.Plans.{name}Plan"), witness)
                    }));
                }
            }
            Cert::StringConcatVerbatimMatch {
                name,
                self_idx,
                type_idx,
                carrier,
                string_concat_idx,
                container_ty,
                result_ty,
                ..
            } => {
                let plan = string_concat_plan_from_cert(c)
                    .expect("certified String.concat should project to a source plan");
                let code_entry_bytes = lower_string_concat_plan_code_entry_bytes(
                    &plan,
                    *carrier,
                    *result_ty,
                    *container_ty,
                    *string_concat_idx,
                )
                .expect("certified String.concat plan lowers to code-entry bytes");
                let code_entry_bytes = render_byte_list(&code_entry_bytes);
                let lowered_body = lower_string_concat_plan(
                    &plan,
                    *result_ty,
                    *container_ty,
                    *string_concat_idx,
                )
                .map(|ops| render_ops_value(&ops))
                .expect("certified String.concat plan lowers to WInstr body");
                let export_name_bytes = render_byte_list(name.as_bytes());
                let carrier_state = render_carrier_state(*carrier);
                // The obligation declares what `decodedCarrierIndex` forces:
                // the real carrier index, or the reserved `0` in a module that
                // provably has no Int carrier struct.
                let obligation_carrier = carrier.unwrap_or(0);
                string_claims.push(format!(
                    "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier_state}, resultTy := {result_ty}, containerTy := {container_ty}, concatFuncIdx := {string_concat_idx}, symPlan := AverCert.Plans.{name}StringConcatSymPlan, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.StringConcatClaim)",
                    export_name = lean_str(name),
                ));
                // Split acceptance proof; see `render_string_concat_claim_bundles`.
                string_parts.push(StringConcatParts {
                    name: name.clone(),
                    lowered_body,
                    code_entry_bytes,
                    export_name_bytes,
                    carrier_state,
                    result_ty: *result_ty,
                    container_ty: *container_ty,
                    concat_func_idx: *string_concat_idx,
                    self_idx: *self_idx,
                    type_idx: *type_idx,
                });
                string_concat_faces.push(Some((
                    format!("AverCert.Plans.{name}StringConcatPlan"),
                    format!(
                        "⟨rfl, rfl, ([] : List Nat), (⟨0, {obligation_carrier}, []⟩ : AverCert.DeclaredIndexEnvelope.DIdxEnvelope), \
                         ⟨AverCert.Plans.declaredTypeCur, rfl, Nat.zero_le _, rfl⟩, rfl, rfl, \
                         HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl⟩"
                    ),
                )));
            }
            Cert::StringEqVerbatimMatch {
                name,
                self_idx,
                type_idx,
                carrier,
                string_eq_idx,
                ..
            } => {
                let plan = string_eq_plan_from_cert(c)
                    .expect("certified String.eq should project to a source plan");
                let string_ty = string_eq_string_ty_from_cert(c)
                    .expect("certified String.eq should use string arrays");
                let code_entry_bytes =
                    lower_string_eq_plan_code_entry_bytes(&plan, *carrier, string_ty, *string_eq_idx)
                        .expect("certified String.eq plan lowers to code-entry bytes");
                let code_entry_bytes = render_byte_list(&code_entry_bytes);
                let lowered_body = lower_string_eq_plan(&plan, string_ty, *string_eq_idx)
                    .map(|ops| render_ops_value(&ops))
                    .expect("certified String.eq plan lowers to WInstr body");
                let export_name_bytes = render_byte_list(name.as_bytes());
                string_eq_claims.push(format!(
                    "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier}, stringTy := {string_ty}, stringEqFuncIdx := {string_eq_idx}, symPlan := AverCert.Plans.{name}StringEqSymPlan, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.StringEqClaim)",
                    export_name = lean_str(name),
                ));
                // Split acceptance proof; see `render_string_eq_claim_bundles`.
                string_eq_parts.push(StringEqParts {
                    name: name.clone(),
                    lowered_body,
                    code_entry_bytes,
                    export_name_bytes,
                    string_ty,
                    string_eq_idx: *string_eq_idx,
                    self_idx: *self_idx,
                    type_idx: *type_idx,
                    carrier: *carrier,
                });
            }
            Cert::AdtConstructor {
                name,
                self_idx,
                type_idx,
                carrier,
                struct_idx,
                field_count,
                elem_ty,
                ..
            } => {
                let Some(sym_plan) = adt_constructor_sym_plan_from_cert(c, model_info) else {
                    continue;
                };
                let Some(plan) = construct_plan_from_cert(c) else {
                    continue;
                };
                let code_entry_bytes =
                    lower_construct_plan_code_entry_bytes(&plan, *carrier, *struct_idx)
                    .expect("certified constructor plan lowers to code-entry bytes");
                let code_entry_bytes = render_byte_list(&code_entry_bytes);
                let lowered_body = lower_construct_plan(&plan, *struct_idx)
                    .map(|ops| render_ops_value(&ops))
                    .expect("certified constructor plan lowers to WInstr body");
                let export_name_bytes = render_byte_list(name.as_bytes());
                let elem_ty = construct_val_type_lean_value(*elem_ty)
                    .expect("certified constructor has a supported byte-level element type");
                let (struct_type_proof, func_type_proof) =
                    if sym_plan_is_list_construct(&sym_plan) {
                        (
                            format!("Or.inr AverCert.Plans.{name}ConstructStructTypeMatches"),
                            format!("Or.inr AverCert.Plans.{name}ConstructFuncTypeMatches"),
                        )
                    } else {
                        ("Or.inl rfl".to_string(), "Or.inl rfl".to_string())
                    };
                construct_claims.push(format!(
                    "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier}, structIdx := {struct_idx}, fieldCount := {field_count}, elemTy := {elem_ty}, symPlan := AverCert.Plans.{name}ConstructSymPlan, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.ConstructClaim)",
                    export_name = lean_str(name),
                ));
                // Split acceptance proof; see `render_construct_claim_bundles`.
                construct_parts.push(ConstructParts {
                    name: name.clone(),
                    lowered_body,
                    code_entry_bytes,
                    export_name_bytes,
                    struct_type_proof,
                    func_type_proof,
                    struct_idx: *struct_idx,
                    self_idx: *self_idx,
                    type_idx: *type_idx,
                    carrier: *carrier,
                });
                if adt_constructor_uses_model(c, model_info) {
                    construct_faces.push(Some((
                        format!("AverCert.Plans.{name}ConstructPlan"),
                        "⟨rfl, rfl, rfl, AverCert.Plans.{name}TypePrefix, AverCert.Plans.{name}DeclaredEnvelope, \
                         by decide, by decide, rfl, rfl, \
                         ⟨AverCert.Plans.declaredTypeCur, rfl, by decide +kernel⟩, \
                         rfl, rfl, HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl⟩"
                            .replace("{name}", name),
                    )));
                } else {
                    construct_faces.push(None);
                }
            }
            Cert::Recursive {
                name,
                self_idx,
                type_idx,
                carrier,
                ..
            }
            | Cert::AccumulatorRecursive {
                name,
                self_idx,
                type_idx,
                carrier,
                ..
            } => {
                // Analysis declines a normalized body whose canonical plan
                // cannot reproduce its exact bytes. Keep this guard as a
                // fail-closed invariant.
                let Some(plan) = recursion_plan_from_cert(c) else {
                    continue;
                };
                let code_entry_bytes = lower_expr_fragment_plan_code_entry_bytes(&plan, *carrier)
                    .expect("certified recursion plan lowers to code-entry bytes");
                let code_entry_bytes = render_byte_list(&code_entry_bytes);
                let lowered_body = lower_expr_fragment_plan(&plan, *carrier)
                    .map(|ops| render_ops_value(&ops))
                    .expect("certified recursion plan lowers to WInstr body");
                let export_name_bytes = render_byte_list(name.as_bytes());
                let host_table = recursion_host_table_lean_value(c);
                recursion_claims.push(format!(
                    "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier}, hostTable := {host_table}, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.RecursionClaim)",
                    export_name = lean_str(name),
                ));
                // Split acceptance proof: the witness data and every byte-walking
                // conjunct become their own top-level declarations (see
                // `render_recursion_claim_bundles`) so the kernel checks and frees
                // each separately instead of holding one monolithic witness tuple.
                recursion_parts.push(RecursionParts {
                    name: name.clone(),
                    lowered_body,
                    code_entry_bytes,
                    export_name_bytes,
                    host_table,
                    self_idx: *self_idx,
                    type_idx: *type_idx,
                    carrier: *carrier,
                });
            }
            Cert::MutualRecursion {
                name,
                self_idx,
                carrier,
                box_idx,
                sub_idx,
                position,
                scc,
            } => {
                // Analysis declines any member whose canonical plan cannot
                // reproduce its exact bytes. Keep this guard as a fail-closed
                // invariant.
                let Some(plan) = mutual_plan_from_cert(c) else {
                    continue;
                };
                let member = &scc[*position];
                let code_entry_bytes = lower_expr_fragment_plan_code_entry_bytes(&plan, *carrier)
                    .expect("certified mutual member plan lowers to code-entry bytes");
                let code_entry_bytes = render_byte_list(&code_entry_bytes);
                let lowered_body = lower_expr_fragment_plan(&plan, *carrier)
                    .map(|ops| render_ops_value(&ops))
                    .expect("certified mutual member plan lowers to WInstr body");
                let export_name_bytes = render_byte_list(name.as_bytes());
                let host_table = mutual_host_table_lean_value(*box_idx, *sub_idx);
                let member_set = mutual_member_set_lean_value(scc);
                mutual_claims.push(format!(
                    "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier}, memberSet := {member_set}, hostTable := {host_table}, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.MutualRecursionClaim)",
                    export_name = lean_str(name),
                ));
                // Split acceptance proof; see `render_mutual_claim_bundles`.
                mutual_parts.push(MutualParts {
                    name: name.clone(),
                    lowered_body,
                    code_entry_bytes,
                    export_name_bytes,
                    host_table,
                    member_set,
                    self_idx: *self_idx,
                    type_idx: member.type_idx,
                    carrier: *carrier,
                });
            }
            Cert::VerbatimWidenedMatch {
                name, carrier, ..
            }
            | Cert::VerbatimVariantDispatch {
                name, carrier, ..
            } => {
                // Analysis declines a body whose canonical verbatim plan cannot
                // reproduce its exact bytes. Keep this guard as a fail-closed
                // invariant.
                if verbatim_plan_from_cert(c).is_none() {
                    continue;
                }
                let export_name_bytes = render_byte_list(name.as_bytes());
                verbatim_claims.push(format!(
                    "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier}, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.VerbatimClaim)",
                    export_name = lean_str(name),
                ));
                // Split acceptance proof; see `render_verbatim_claim_bundles`.
                verbatim_parts.push(VerbatimParts {
                    name: name.clone(),
                    export_name_bytes,
                    carrier: *carrier,
                });
            }
            Cert::VariantDispatch { name, carrier, .. }
            | Cert::WidenedIntMatch { name, carrier, .. } => {
                // Analysis declines a body whose canonical Int-face plan cannot
                // reproduce its exact bytes. Keep this guard as a fail-closed
                // invariant.
                if int_dispatch_plan_from_cert(c, analysis.frag_host_table).is_none() {
                    continue;
                }
                let hosts = int_dispatch_host_table_from_cert(c)
                    .expect("Int-face dispatch cert carries its host table");
                let host_table = int_dispatch_host_table_lean_value(&hosts);
                let export_name_bytes = render_byte_list(name.as_bytes());
                int_dispatch_claims.push(format!(
                    "({{ exportNameBytes := {export_name_bytes}, exportName := {export_name}, carrier := {carrier}, hostTable := {host_table}, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.IntDispatchClaim)",
                    export_name = lean_str(name),
                ));
                // Split acceptance proof; see `render_int_dispatch_claim_bundles`.
                int_dispatch_parts.push(IntDispatchParts {
                    name: name.clone(),
                    export_name_bytes,
                    host_table,
                    carrier: *carrier,
                });
                int_dispatch_faces.push(Some((
                    format!("AverCert.Plans.{name}IntDispatchPlan"),
                    "⟨rfl, rfl, AverCert.Plans.{name}TypePrefix, AverCert.Plans.{name}DeclaredEnvelope, \
                     by decide, by decide, \
                     ⟨AverCert.Plans.declaredTypeCur, rfl, by decide +kernel⟩, \
                     rfl, HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl, HEq.rfl⟩"
                        .replace("{name}", name),
                )));
            }
            Cert::FieldProjection {
                name,
                self_idx,
                type_idx,
                carrier,
                struct_idx,
                field_count,
                code_entry_bytes,
                ops,
                ..
            } => {
                let Some((_plan, result_ty)) = field_projection_plan_from_cert(c) else {
                    continue;
                };
                let result_ty = field_projection_result_ty_lean_value(result_ty);
                field_projection_claims.push(format!(
                    "({{ exportNameBytes := {bytes}, exportName := {export_name}, carrier := {carrier}, structIdx := {struct_idx}, fieldCount := {field_count}, resultTy := {result_ty}, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.FieldProjectionClaim)",
                    bytes = render_byte_list(name.as_bytes()),
                    export_name = lean_str(name),
                ));
                // Split acceptance proof; the `Cert` already carries the exact
                // ops and code-entry bytes the wall lowerers reproduce, so no `_`
                // witness is solved into a large literal. See
                // `render_field_projection_claim_bundles`.
                field_projection_parts.push(FieldProjectionParts {
                    name: name.clone(),
                    body: render_ops_value(ops),
                    code_entry: render_byte_list(code_entry_bytes),
                    export_name_bytes: render_byte_list(name.as_bytes()),
                    result_ty,
                    struct_idx: *struct_idx,
                    field_count: *field_count,
                    self_idx: *self_idx,
                    type_idx: *type_idx,
                    carrier: *carrier,
                });
            }
            _ => {}
        }
    }
    let composition_members_data = composition_member_plans(analysis);
    let composition_members = composition_members_data
        .iter()
        .map(|(entry, _)| {
            format!(
                "({{ exportNameBytes := {bytes}, exportName := {name}, plan := AverCert.Plans.{ident}CompositionPlan }} : AverCert.AcceptedArtifact.CompositionMemberClaim)",
                bytes = render_byte_list(entry.name.as_bytes()),
                name = lean_str(&entry.name),
                ident = entry.name,
            )
        })
        .collect::<Vec<_>>();
    let global_func_table = composition_members_data
        .iter()
        .map(|(entry, _)| (entry.name.clone(), entry.self_idx))
        .collect::<std::collections::HashMap<_, _>>();
    for cert in &analysis.certs {
        let Cert::Composition {
            name,
            self_idx,
            carrier,
            closure,
            ..
        } = cert.inner()
        else {
            continue;
        };
        let Some(plans) = composition_plans_from_cert(cert, analysis.frag_host_table) else {
            continue;
        };
        let add_idx = analysis
            .frag_host_table
            .add_idx
            .expect("plan-backed composition has strict add host");
        let host_table = composition_host_table_lean_value(add_idx);
        let member_names = format!(
            "[{}]",
            closure
                .iter()
                .map(|entry| lean_str(&entry.name))
                .collect::<Vec<_>>()
                .join(", ")
        );
        composition_claims.push(format!(
            "({{ exportName := {export_name}, carrier := {carrier}, hostTable := {host_table}, memberNames := {member_names}, obligation := AverCert.{name}Ob }} : AverCert.AcceptedArtifact.CompositionClaim)",
            export_name = lean_str(name),
        ));
        // Collect each member's witness data for the split acceptance proof;
        // see `render_composition_claim_bundles`.
        let members = plans
            .iter()
            .map(|(entry, plan)| {
                let body = render_ops_value(
                    &lower_composition_plan(plan, add_idx, &global_func_table)
                        .expect("composition member lowers against global byte table"),
                );
                let code_entry = render_byte_list(
                    &composition_code_entry_bytes(plan, *carrier, add_idx, &global_func_table)
                        .expect("composition member byte-lowers against global byte table"),
                );
                CompositionMemberData {
                    export_name_bytes: render_byte_list(entry.name.as_bytes()),
                    body,
                    code_entry,
                    self_idx: entry.self_idx,
                    type_idx: entry.type_idx,
                }
            })
            .collect::<Vec<_>>();
        let _ = self_idx;
        composition_parts.push(CompositionParts {
            carrier: *carrier,
            host_table,
            members,
        });
    }
    let sym_claims = if sym_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", sym_claims.join(",\n  "))
    };
    let string_claims = if string_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", string_claims.join(",\n  "))
    };
    let string_eq_claims = if string_eq_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", string_eq_claims.join(",\n  "))
    };
    let construct_claims = if construct_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", construct_claims.join(",\n  "))
    };
    let recursion_claims = if recursion_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", recursion_claims.join(",\n  "))
    };
    let mutual_claims = if mutual_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", mutual_claims.join(",\n  "))
    };
    let verbatim_claims = if verbatim_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", verbatim_claims.join(",\n  "))
    };
    let int_dispatch_claims = if int_dispatch_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", int_dispatch_claims.join(",\n  "))
    };
    let field_projection_claims = if field_projection_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", field_projection_claims.join(",\n  "))
    };
    let composition_members = if composition_members.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", composition_members.join(",\n  "))
    };
    let composition_claims = if composition_claims.is_empty() {
        "[]".to_string()
    } else {
        format!("[\n  {}\n]", composition_claims.join(",\n  "))
    };
    let obligation_proof_count = sym_parts.len()
        + string_eq_parts.len()
        + string_parts.len()
        + construct_parts.len()
        + recursion_parts.len()
        + mutual_parts.len()
        + verbatim_parts.len()
        + int_dispatch_parts.len()
        + field_projection_parts.len()
        + composition_parts.len();
    let obligation_proof = (0..obligation_proof_count).fold("trivial".to_string(), |acc, _| {
        format!("⟨rfl, {acc}⟩")
    });
    // The expr-fragment (`sym`) family emits a SPLIT proof: witness data as
    // named `def`s and each acceptance conjunct as its own leaf theorem, with
    // the aggregate combining the already-checked constants. This keeps the
    // per-claim kernel peak at the largest single leaf instead of the whole
    // witness tuple. The other nine families still emit one opaque theorem.
    let (sym_bundles, sym_proof) = render_sym_claim_bundles(&sym_parts, host_table_lean);
    let (string_bundles, string_proof) = render_string_concat_claim_bundles(&string_parts);
    let (string_eq_bundles, string_eq_proof) = render_string_eq_claim_bundles(&string_eq_parts);
    let construct_claim_count = construct_parts.len();
    let (construct_bundles, construct_claims_proof) = render_construct_claim_bundles(&construct_parts);
    // `acceptedConstructFragments` conjoins per-claim acceptance with unique
    // export-name coverage. Build the `Nodup` proof one list cell at a time so
    // Lean never runs a whole-list decision procedure inside the already deep
    // artifact acceptance term.
    let construct_nodup_proof = (0..construct_claim_count).fold(
        "List.nodup_nil".to_string(),
        |acc, _| format!("List.nodup_cons.mpr ⟨by decide, {acc}⟩"),
    );
    let construct_proof = format!("⟨{construct_claims_proof}, {construct_nodup_proof}⟩");
    let (recursion_bundles, recursion_proof) = render_recursion_claim_bundles(&recursion_parts);
    let (mutual_bundles, mutual_proof) = render_mutual_claim_bundles(&mutual_parts);
    let (verbatim_bundles, verbatim_proof) = render_verbatim_claim_bundles(&verbatim_parts);
    let (int_dispatch_bundles, int_dispatch_proof) =
        render_int_dispatch_claim_bundles(&int_dispatch_parts);
    let (field_projection_bundles, field_projection_proof) =
        render_field_projection_claim_bundles(&field_projection_parts);
    let (composition_bundles, composition_claims_proof) =
        render_composition_claim_bundles(&composition_parts);
    // `acceptedCompositionFragments` conjoins the per-claim acceptance with the
    // artifact-wide member coverage, manifest-obligation coverage, and unique
    // obligation-export bounds. Each is a decidable `Bool = true` over concrete
    // artifact literals, closed by `rfl`.
    let composition_proof = format!("⟨{composition_claims_proof}, rfl, rfl, rfl⟩");
    let (string_concat_face_bundles, string_concat_face_proof) = render_face_bundles(
        "stringConcat",
        "stringConcatDeclaredFace",
        "stringConcatClaims",
        ", AverCert.AcceptedArtifact.stringConcatCanonicalHost",
        false,
        &string_concat_faces,
    );
    let (construct_face_bundles, construct_face_proof) = render_face_bundles(
        "construct",
        "constructNamedFace",
        "constructClaims",
        ", AverCert.StandardFace.emptyHost",
        false,
        &construct_faces,
    );
    let (int_dispatch_face_bundles, int_dispatch_face_proof) = render_face_bundles(
        "intDispatch",
        "intDispatchDeclaredFace",
        "intDispatchClaims",
        ", AverCert.AcceptedArtifact.intDispatchCanonicalHost, AverCert.AcceptedArtifact.intDispatchCanonicalSlots",
        true,
        &int_dispatch_faces,
    );
    // The `sym` family's face slot (`symFragmentMatches`). Every known-face
    // claim closes inline by `repeat' constructor` (a `None` element); a
    // record-parameter claim carries an explicit `recordParamDeclaredFace`
    // witness, routed exactly like the declared-index envelope faces. The slot
    // only switches away from the inline `repeat' constructor` when at least one
    // record claim is present, so non-record modules render byte-for-byte as
    // before.
    let sym_faces_have_record = sym_faces.iter().any(Option::is_some);
    let (sym_face_bundles, sym_face_proof) = if sym_faces_have_record {
        render_face_bundles(
            "symFragment",
            "recordParamDeclaredFace",
            "symFragmentClaims",
            "",
            true,
            &sym_faces,
        )
    } else {
        (String::new(), String::new())
    };
    let claim_proof_bundles = [
        sym_bundles,
        string_eq_bundles,
        string_bundles,
        construct_bundles,
        recursion_bundles,
        mutual_bundles,
        verbatim_bundles,
        int_dispatch_bundles,
        field_projection_bundles,
        composition_bundles,
        string_concat_face_bundles,
        construct_face_bundles,
        int_dispatch_face_bundles,
        sym_face_bundles,
    ]
    .concat();
    RenderedArtifactClaims {
        sym_claims,
        string_eq_claims,
        string_claims,
        construct_claims,
        recursion_claims,
        mutual_claims,
        verbatim_claims,
        int_dispatch_claims,
        field_projection_claims,
        composition_members,
        composition_claims,
        claim_proof_bundles,
        obligation_proof,
        sym_proof,
        string_eq_proof,
        string_proof,
        construct_proof,
        recursion_proof,
        mutual_proof,
        verbatim_proof,
        int_dispatch_proof,
        field_projection_proof,
        composition_proof,
        string_concat_face_proof,
        construct_face_proof,
        int_dispatch_face_proof,
        sym_face_proof,
        sym_faces_have_record,
    }
}

fn render_artifact(
    analysis: &Analysis,
    model_info: &ModelInfo,
    host_table_lean: &str,
    struct_table_lean: &str,
) -> String {
    let claims = render_artifact_expr_fragment_claims(
        analysis,
        model_info,
        host_table_lean,
        struct_table_lean,
    );
    let nat_list = |values: &[u32]| {
        format!(
            "[{}]",
            values
                .iter()
                .map(u32::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        )
    };
    let closure_claim = format!(
        "({{ roots := {}, helpers := {}, admitted := {} }} : AverCert.AcceptedArtifact.ClosureClaim)",
        nat_list(&analysis.module_envelope.closure.roots),
        nat_list(&analysis.module_envelope.closure.helpers),
        nat_list(&analysis.module_envelope.closure.admitted),
    );
    // Shared source-side rendering for the few cross-family reductions. Each
    // proof family below gets its own opaque theorem instead of contributing
    // an inline branch to one enormous `acceptedWithFinal` proof term. The
    // expansion deliberately contains no Lean `macro`: Artifact.lean is data
    // from the verifier's perspective and must pass the elaboration-code wall.
    let artifact_dsimp = concat!(
            "  dsimp [data, closureClaim, symFragmentClaims, stringEqClaims, stringConcatClaims, constructClaims, recursionClaims, mutualRecursionClaims, verbatimClaims, intDispatchClaims, fieldProjectionClaims, compositionMembers, compositionClaims, AverCert.AcceptedArtifact.accepted,\n",
            "    AverCert.AcceptedArtifact.subjectMatchesArtifactRoot,\n",
            "    AverCert.AcceptedArtifact.expectedArtifactRoot,\n",
            "    AverCert.AcceptedArtifact.fragmentClaimObligationsInManifest,\n",
            "    AverCert.AcceptedArtifact.claimObligations,\n",
            "    AverCert.AcceptedArtifact.claimObligationsInManifest,\n",
            "    AverCert.AcceptedArtifact.claimObligationExports,\n",
            "    AverCert.AcceptedArtifact.claimsMatchManifest,\n",
            "    AverCert.AcceptedArtifact.decodedNonExprFacts,\n",
            "    AverCert.AcceptedArtifact.decodedNonExprClaimFacts,\n",
            "    AverCert.AcceptedArtifact.decodedStringHostRoles,\n",
            "    AverCert.AcceptedArtifact.stringEqCanonicalHost,\n",
            "    AverCert.AcceptedArtifact.stringConcatCanonicalHost,\n",
            "    AverCert.AcceptedArtifact.decodedClaims,\n",
            "    AverCert.AcceptedArtifact.decodedObligationFacts,\n",
            "    AverCert.AcceptedArtifact.decodedCodeAtAll,\n",
            "    AverCert.AcceptedArtifact.decodedCodeAt,\n",
            "    AverCert.AcceptedArtifact.decodedConstructStructFields,\n",
            "    AverCert.AcceptedArtifact.decodedProjectionStructFields,\n",
            "    AverCert.AcceptedArtifact.decodedCompositionClaims,\n",
            "    AverCert.AcceptedArtifact.decodedCompositionNames,\n",
            "    AverCert.AcceptedArtifact.symFragmentClaimPlanPairs,\n",
            "    AverCert.AcceptedArtifact.symFragmentClaimEncodedPlanPairs,\n",
            "    AverCert.AcceptedArtifact.symFragmentClaimEncodedPlanPair?,\n",
            "    AverCert.AcceptedArtifact.stringEqClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.stringEqManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.stringEqClaimSymPlanPairs,\n",
            "    AverCert.AcceptedArtifact.stringConcatClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.stringConcatManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.stringConcatClaimSymPlanPairs,\n",
            "    AverCert.AcceptedArtifact.constructClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.constructManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.constructClaimSymPlanPairs,\n",
            "    AverCert.AcceptedArtifact.recursionClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.recursionManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.mutualRecursionClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.mutualManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.verbatimClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.verbatimManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.intDispatchClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.intDispatchManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.fieldProjectionClaimExportNames,\n",
            "    AverCert.AcceptedArtifact.fieldProjectionManifestPlanNames,\n",
            "    AverCert.AcceptedArtifact.compositionMemberPlanPairs,\n",
            "    AverCert.AcceptedArtifact.acceptedFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedSymFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedStringEqFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedStringConcatFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedConstructFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedRecursionFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedMutualRecursionFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedVerbatimFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedIntDispatchFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedFieldProjectionFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedCompositionFragments,\n",
            "    AverCert.AcceptedArtifact.acceptedWholeModule,\n",
            "    AverCert.AcceptedArtifact.allClaims,\n",
            "    AverCert.AcceptedArtifact.symFragmentClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.symFragmentClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.symFragmentPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.stringEqClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.stringEqClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.stringEqPlanForExport,\n",
            "    AverCert.AcceptedArtifact.stringEqPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.stringConcatClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.stringConcatClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.stringConcatPlanForExport,\n",
            "    AverCert.AcceptedArtifact.stringConcatPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.constructClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.constructClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.constructPlanForExport,\n",
            "    AverCert.AcceptedArtifact.constructPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.recursionClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.recursionClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.recursionPlanForExport,\n",
            "    AverCert.AcceptedArtifact.recursionPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.mutualRecursionClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.mutualRecursionClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.mutualPlanForExport,\n",
            "    AverCert.AcceptedArtifact.mutualPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.verbatimClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.verbatimClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.verbatimPlanForExport,\n",
            "    AverCert.AcceptedArtifact.verbatimPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.intDispatchClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.intDispatchClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.intDispatchPlanForExport,\n",
            "    AverCert.AcceptedArtifact.intDispatchPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.fieldProjectionClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.fieldProjectionClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.fieldProjectionPlanForExport,\n",
            "    AverCert.AcceptedArtifact.fieldProjectionPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.compositionClaimsAccepted,\n",
            "    AverCert.AcceptedArtifact.compositionClaimAccepted,\n",
            "    AverCert.AcceptedArtifact.compositionFuncTable,\n",
            "    AverCert.AcceptedArtifact.compositionMemberBinding,\n",
            "    AverCert.AcceptedArtifact.compositionNamedMembersAccepted,\n",
            "    AverCert.AcceptedArtifact.compositionMemberPlanAccepted,\n",
            "    AverCert.AcceptedArtifact.compositionMemberForName,\n",
            "    AverCert.AcceptedArtifact.compositionClosureBound,\n",
            "    AverCert.AcceptedArtifact.compositionEdges,\n",
            "    AverCert.AcceptedArtifact.compositionPlanCallees,\n",
            "    AverCert.AcceptedArtifact.compositionEdgesDescend,\n",
            "    AverCert.AcceptedArtifact.compositionReachClosure,\n",
            "    AverCert.AcceptedArtifact.compositionReachStep,\n",
            "    AverCert.AcceptedArtifact.stringListNodup,\n",
            "    AverCert.AcceptedArtifact.stringListSetEq,\n",
            "    AverCert.AcceptedArtifact.manifestObligationsClaimed,\n",
            "    AverCert.AcceptedArtifact.manifestObligationExportsUnique,\n",
            "    AverCert.AcceptedArtifact.intDispatchCanonicalHost,\n",
            "    AverCert.AcceptedArtifact.intDispatchCanonicalSlots,\n",
            "    AverCert.AcceptedArtifact.exprFragmentPlanAccepted,\n",
            "    AverCert.ExprFragmentAccepted.accepted]\n"
    );
    let face_dsimp = concat!(
        "  dsimp [AverCert.StandardFace.checkedFaces,\n",
        "    AverCert.Schema.Subject.hostRoles,\n",
        "    AverCert.StandardFace.claimExportsUnique,\n",
        "    AverCert.StandardFace.hostTableBound,\n",
        "    AverCert.StandardFace.decodedRoleIdx,\n",
        "    AverCert.StandardFace.symFragmentMatches,\n",
        "    AverCert.StandardFace.symFragmentFace,\n",
        "    AverCert.StandardFace.stringEqMatches,\n",
        "    AverCert.StandardFace.stringConcatMatches,\n",
        "    AverCert.StandardFace.constructMatches,\n",
        "    AverCert.StandardFace.recursionMatches,\n",
        "    AverCert.StandardFace.mutualMatches,\n",
        "    AverCert.StandardFace.verbatimMatches,\n",
        "    AverCert.StandardFace.intDispatchMatches,\n",
        "    AverCert.StandardFace.fieldProjectionMatches,\n",
        "    AverCert.StandardFace.compositionMatches,\n",
        "    AverCert.StandardFace.StandardFace.Matches,\n",
        "    AverCert.AcceptedArtifact.claimObligationExports,\n",
        "    AverCert.AcceptedArtifact.allClaims,\n",
        "    AverCert.AcceptedArtifact.namedPlanForExport,\n",
        "    AverCert.AcceptedArtifact.stringEqPlanForExport,\n",
        "    AverCert.AcceptedArtifact.stringConcatPlanForExport,\n",
        "    AverCert.AcceptedArtifact.constructPlanForExport,\n",
        "    AverCert.AcceptedArtifact.recursionPlanForExport,\n",
        "    AverCert.AcceptedArtifact.mutualPlanForExport,\n",
        "    AverCert.AcceptedArtifact.verbatimPlanForExport,\n",
        "    AverCert.AcceptedArtifact.intDispatchPlanForExport,\n",
        "    AverCert.AcceptedArtifact.fieldProjectionPlanForExport,\n",
        "    AverCert.AcceptedArtifact.compositionMemberForName,\n",
        "    data, symFragmentClaims, stringEqClaims, stringConcatClaims,\n",
        "    constructClaims, recursionClaims, mutualRecursionClaims,\n",
        "    verbatimClaims, intDispatchClaims, fieldProjectionClaims,\n",
        "    compositionMembers, compositionClaims]\n"
    );
    // `dsimp` closes a reduced `True` goal immediately.  Do not emit a
    // trailing `exact trivial` for an empty family: Lean correctly reports a
    // tactic after goal closure as an error.
    let family_exact = |proof: &str| {
        if proof == "trivial" {
            String::new()
        } else {
            format!("  exact {proof}\n")
        }
    };
    let proof_bundles = format!(
        concat!(
            "theorem claimObligationsBound : AverCert.AcceptedArtifact.fragmentClaimObligationsInManifest data := by\n",
            "{artifact_dsimp}",
            "{obligation_proof_step}\n",
            "theorem claimsMatchManifest : AverCert.AcceptedArtifact.claimsMatchManifest data := by\n",
            "{artifact_dsimp}",
            "  exact ⟨rfl, ⟨rfl, ⟨rfl, ⟨rfl, ⟨rfl, ⟨rfl, ⟨rfl, ⟨rfl, ⟨rfl, ⟨rfl, rfl⟩⟩⟩⟩⟩⟩⟩⟩⟩⟩\n\n",
            "theorem standardFacesChecked : AverCert.StandardFace.checkedFaces data := by\n",
            "{face_dsimp}",
            "  refine ⟨rfl, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩\n",
            "{sym_face_step}",
            "  · repeat' constructor\n",
            "  · exact {string_concat_face_proof}\n",
            "  · exact {construct_face_proof}\n",
            "  · repeat' constructor\n",
            "  · repeat' constructor\n",
            "  · repeat' constructor\n",
            "  · exact {int_dispatch_face_proof}\n",
            "  · repeat' constructor\n",
            "  · repeat' constructor\n\n",
            "theorem claimAxesChecked : AverCert.ClaimAxes.checked data = true := rfl\n\n",
            "theorem decodedNonExprClaimFacts : AverCert.AcceptedArtifact.decodedNonExprClaimFacts data := by\n",
            "{artifact_dsimp}",
            "  repeat' constructor\n\n",
            "theorem decodedNonExprFacts : AverCert.AcceptedArtifact.decodedNonExprFacts data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.decodedNonExprFacts]\n",
            "  exact ⟨decodedHostRoles, decodedStringHostRoles, decodedNonExprClaimFacts⟩\n\n",
            "theorem symFragmentsAccepted : AverCert.AcceptedArtifact.acceptedSymFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedSymFragments, AverCert.AcceptedArtifact.symFragmentClaimsAccepted, AverCert.AcceptedArtifact.allClaims, data, symFragmentClaims]\n",
            "{sym_proof_step}\n",
            "theorem stringEqFragmentsAccepted : AverCert.AcceptedArtifact.acceptedStringEqFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedStringEqFragments, AverCert.AcceptedArtifact.stringEqClaimsAccepted, AverCert.AcceptedArtifact.allClaims, data, stringEqClaims]\n",
            "{string_eq_proof_step}\n",
            "theorem stringConcatFragmentsAccepted : AverCert.AcceptedArtifact.acceptedStringConcatFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedStringConcatFragments, AverCert.AcceptedArtifact.stringConcatClaimsAccepted, AverCert.AcceptedArtifact.allClaims, data, stringConcatClaims]\n",
            "{string_proof_step}\n",
            "theorem constructFragmentsAccepted : AverCert.AcceptedArtifact.acceptedConstructFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedConstructFragments, AverCert.AcceptedArtifact.constructClaimsAccepted, AverCert.AcceptedArtifact.allClaims, AverCert.AcceptedArtifact.constructClaimExportNames, data, constructClaims]\n",
            "  exact {construct_proof}\n\n",
            "theorem recursionFragmentsAccepted : AverCert.AcceptedArtifact.acceptedRecursionFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedRecursionFragments, AverCert.AcceptedArtifact.recursionClaimsAccepted, AverCert.AcceptedArtifact.allClaims, data, recursionClaims]\n",
            "{recursion_proof_step}\n",
            "theorem mutualFragmentsAccepted : AverCert.AcceptedArtifact.acceptedMutualRecursionFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedMutualRecursionFragments, AverCert.AcceptedArtifact.mutualRecursionClaimsAccepted, AverCert.AcceptedArtifact.allClaims, AverCert.AcceptedArtifact.mutualClaimsFormClosedSccs, AverCert.AcceptedArtifact.mutualClaimEdges, AverCert.AcceptedArtifact.mutualClaimEdge, AverCert.AcceptedArtifact.mutualPlanForExport, AverCert.AcceptedArtifact.mutualPlanTarget, AverCert.AcceptedArtifact.mutualMembersFormClosedSccs, AverCert.AcceptedArtifact.followSccCycle, AverCert.AcceptedArtifact.natEdgeLookup, AverCert.AcceptedArtifact.natListNodup, AverCert.AcceptedArtifact.natListSetEq, data, mutualRecursionClaims]\n",
            "  exact ⟨{mutual_proof}, rfl⟩\n\n",
            "theorem verbatimFragmentsAccepted : AverCert.AcceptedArtifact.acceptedVerbatimFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedVerbatimFragments, AverCert.AcceptedArtifact.verbatimClaimsAccepted, AverCert.AcceptedArtifact.allClaims, data, verbatimClaims]\n",
            "{verbatim_proof_step}\n",
            "theorem intDispatchFragmentsAccepted : AverCert.AcceptedArtifact.acceptedIntDispatchFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedIntDispatchFragments, AverCert.AcceptedArtifact.intDispatchClaimsAccepted, AverCert.AcceptedArtifact.allClaims, data, intDispatchClaims]\n",
            "{int_dispatch_proof_step}\n",
            "theorem fieldProjectionFragmentsAccepted : AverCert.AcceptedArtifact.acceptedFieldProjectionFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedFieldProjectionFragments, AverCert.AcceptedArtifact.fieldProjectionClaimsAccepted, AverCert.AcceptedArtifact.allClaims, data, fieldProjectionClaims]\n",
            "{field_projection_proof_step}\n",
            "theorem compositionFragmentsAccepted : AverCert.AcceptedArtifact.acceptedCompositionFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedCompositionFragments, AverCert.AcceptedArtifact.compositionClaimsAccepted, AverCert.AcceptedArtifact.allClaims, AverCert.AcceptedArtifact.compositionMembersCovered, AverCert.AcceptedArtifact.compositionClaimedNames, AverCert.AcceptedArtifact.manifestObligationsClaimed, AverCert.AcceptedArtifact.claimObligationExports, AverCert.AcceptedArtifact.manifestObligationExportsUnique, AverCert.AcceptedArtifact.stringListNodup, data, compositionMembers, compositionClaims]\n",
            "  exact {composition_proof}\n\n",
            "theorem wholeModuleAccepted : AverCert.AcceptedArtifact.acceptedWholeModule data := by\n",
            "{artifact_dsimp}",
            "  exact ⟨rfl, rfl, rfl, rfl, rfl⟩\n\n",
            "theorem fragmentsAccepted : AverCert.AcceptedArtifact.acceptedFragments data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.acceptedFragments]\n",
            "  exact ⟨symFragmentsAccepted, stringEqFragmentsAccepted, stringConcatFragmentsAccepted, constructFragmentsAccepted, recursionFragmentsAccepted, mutualFragmentsAccepted, verbatimFragmentsAccepted, intDispatchFragmentsAccepted, fieldProjectionFragmentsAccepted, compositionFragmentsAccepted, wholeModuleAccepted⟩\n\n",
            "theorem acceptedWithFinal\n",
            "    (finalCert : AverCert.Schema.Holds AverCert.manifest) :\n",
            "    AverCert.AcceptedArtifact.accepted data := by\n",
            "  dsimp [AverCert.AcceptedArtifact.accepted, AverCert.AcceptedArtifact.subjectMatchesArtifactRoot, AverCert.AcceptedArtifact.expectedArtifactRoot]\n",
            "  exact ⟨finalCert, rfl, claimObligationsBound, claimsMatchManifest, standardFacesChecked, claimAxesChecked, decodedNonExprFacts, fragmentsAccepted⟩\n"
        ),
        obligation_proof_step = family_exact(&claims.obligation_proof),
        sym_proof_step = family_exact(&claims.sym_proof),
        string_eq_proof_step = family_exact(&claims.string_eq_proof),
        string_proof_step = family_exact(&claims.string_proof),
        construct_proof = claims.construct_proof,
        recursion_proof_step = family_exact(&claims.recursion_proof),
        mutual_proof = claims.mutual_proof,
        verbatim_proof_step = family_exact(&claims.verbatim_proof),
        int_dispatch_proof_step = family_exact(&claims.int_dispatch_proof),
        field_projection_proof_step = family_exact(&claims.field_projection_proof),
        composition_proof = claims.composition_proof,
        artifact_dsimp = artifact_dsimp,
        face_dsimp = face_dsimp,
        string_concat_face_proof = claims.string_concat_face_proof,
        construct_face_proof = claims.construct_face_proof,
        int_dispatch_face_proof = claims.int_dispatch_face_proof,
        sym_face_step = if claims.sym_faces_have_record {
            format!("  · exact {}\n", claims.sym_face_proof)
        } else {
            "  · repeat' constructor\n".to_string()
        },
    );
    // The whole-module arith host-role pin (`decodedHostRoleTable`) is the one
    // per-module conjunct whose `decide +kernel` reduction sits well above the
    // import floor: it materialises five decoded function bodies and five
    // synthesised helper bodies in a single kernel term. A carriered module
    // proves each role in its own freed leaf theorem in a SEPARATE compilation
    // unit (`ArtifactHostRoles.lean`) and recombines them here with a cheap
    // rewrite, so neither the leaf peak nor this module's other theorems pay
    // for the monolith. A carrierless module has no table to split — its
    // `arithTableCheck` is the floor-cost `carrierHelperAbsent` scan — so it
    // keeps the single-tactic proof and emits no leaf file.
    let (host_roles_import, decoded_host_roles_proof) = render_decoded_host_roles(analysis);
    format!(
         "-- Artifact-carried acceptance root.\n\
         -- This file is useful metadata, not verifier authority: `aver cert verify`\n\
         -- pins its bytes and manifest to checker-owned inputs and\n\
         -- audits `AverCert.Artifact.certificate` through the Lean axiom collector.\n\
         import AcceptedArtifact\n\
         import ArtifactBytes\n\
         import Certificate\n\
         import Manifest\n\
         import Plans\n\
         {host_roles_import}\
         import AcceptanceSoundness\n\n\
         -- The whole-module big-Nat closure fold is kernel reduction. This\n\
         -- explicit depth budget affects kernel reduction limits only, not soundness or axioms.\n\
         set_option maxRecDepth 200000\n\
         -- Companion budget for the elaborator, matching the one Certificate.lean\n\
         -- already carries. Precautionary rather than a fix for an observed\n\
         -- failure: this proof is one fixed shape repeated per claim, so its\n\
         -- elaboration cost grows with the size of the artifact, and the stock\n\
         -- allowance is the only thing here that was never stated explicitly.\n\
         -- Like the depth budget above it moves a resource limit only: no axiom,\n\
         -- no trusted hypothesis, no change to what the kernel must accept.\n\
         set_option maxHeartbeats 1600000\n\
         set_option linter.unusedSimpArgs false\n\n\
         namespace AverCert.Artifact\n\n\
         def symFragmentClaims : List AverCert.AcceptedArtifact.SymFragmentClaim := {sym_claims_list}\n\n\
         def stringEqClaims : List AverCert.AcceptedArtifact.StringEqClaim := {string_eq_claims_list}\n\n\
         def stringConcatClaims : List AverCert.AcceptedArtifact.StringConcatClaim := {string_claims_list}\n\n\
         def constructClaims : List AverCert.AcceptedArtifact.ConstructClaim := {construct_claims_list}\n\n\
         def recursionClaims : List AverCert.AcceptedArtifact.RecursionClaim := {recursion_claims_list}\n\n\
         def mutualRecursionClaims : List AverCert.AcceptedArtifact.MutualRecursionClaim := {mutual_claims_list}\n\n\
         def verbatimClaims : List AverCert.AcceptedArtifact.VerbatimClaim := {verbatim_claims_list}\n\n\
         def intDispatchClaims : List AverCert.AcceptedArtifact.IntDispatchClaim := {int_dispatch_claims_list}\n\n\
         def fieldProjectionClaims : List AverCert.AcceptedArtifact.FieldProjectionClaim := {field_projection_claims_list}\n\n\
         def compositionMembers : List AverCert.AcceptedArtifact.CompositionMemberClaim := {composition_members_list}\n\n\
         def compositionClaims : List AverCert.AcceptedArtifact.CompositionClaim := {composition_claims_list}\n\n\
         def closureClaim : AverCert.AcceptedArtifact.ClosureClaim := {closure_claim}\n\n\
         {mutual_scc_closure_pins}\
         def data : AverCert.AcceptedArtifact.ArtifactData :=\n  \
           ({{ modBytes := AverCert.ArtifactBytes.modBytes, modLen := AverCert.ArtifactBytes.modLen, manifest := AverCert.manifest, symFragmentClaims := symFragmentClaims, stringEqClaims := stringEqClaims, stringConcatClaims := stringConcatClaims, constructClaims := constructClaims, recursionClaims := recursionClaims, mutualRecursionClaims := mutualRecursionClaims, verbatimClaims := verbatimClaims, intDispatchClaims := intDispatchClaims, fieldProjectionClaims := fieldProjectionClaims, compositionMembers := compositionMembers, compositionClaims := compositionClaims, closureFuel := {closure_fuel}, closureClaim := closureClaim }} : AverCert.AcceptedArtifact.ArtifactData)\n\n\
         {decoded_host_roles_proof}\n\n\
         theorem decodedStringHostRoles : CertDecode.StringHost.roleTable AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen = some AverCert.manifest.subject.stringHostRoles := by change AverCert.AcceptedArtifact.decodedStringHostRoles data; dsimp [AverCert.AcceptedArtifact.decodedStringHostRoles, data]; rfl\n\n\
         {claim_proof_bundles}\
         {proof_bundles}\n\n\
         {side_conditions}\n\
         end AverCert.Artifact\n",
        sym_claims_list = claims.sym_claims,
        string_eq_claims_list = claims.string_eq_claims,
        string_claims_list = claims.string_claims,
        construct_claims_list = claims.construct_claims,
        recursion_claims_list = claims.recursion_claims,
        mutual_claims_list = claims.mutual_claims,
        verbatim_claims_list = claims.verbatim_claims,
        int_dispatch_claims_list = claims.int_dispatch_claims,
        field_projection_claims_list = claims.field_projection_claims,
        composition_members_list = claims.composition_members,
        composition_claims_list = claims.composition_claims,
        closure_claim = closure_claim,
        closure_fuel = analysis.module_envelope.closure_fuel,
        mutual_scc_closure_pins = render_mutual_scc_closure_pins(analysis),
        claim_proof_bundles = claims.claim_proof_bundles,
        proof_bundles = proof_bundles,
        side_conditions = render_discharge_side_conditions(analysis, model_info),
        host_roles_import = host_roles_import,
        decoded_host_roles_proof = decoded_host_roles_proof,
    )
}

/// The `import` line for the per-role leaf module and the proof of the
/// whole-module `decodedHostRoles` theorem.
///
/// * Carriered module — the leaf theorems live in `ArtifactHostRoles.lean`
///   (emitted by `render_project`); the aggregate rewrites the manifest
///   projections to their literals, unfolds `arithTableCheck`, and rewrites the
///   seven `arithRoleCheck` subterms to `true` from the imported leaves, leaving
///   only the floor-cost carrier/index conjuncts for a final `decide +kernel`.
///   The statement is byte-identical to the monolith; only the proof changes.
/// * Carrierless module — no table, no leaf file, and the original single
///   `decide +kernel` (its `arithTableCheck` is the floor-cost
///   `carrierHelperAbsent` scan).
fn render_decoded_host_roles(analysis: &Analysis) -> (String, String) {
    let carriered = analysis.frag_host_table.box_idx.is_some();
    if !carriered {
        return (
            String::new(),
            "theorem decodedHostRoles : AverCert.AcceptedArtifact.decodedHostRoleTable data := \
             by dsimp [AverCert.AcceptedArtifact.decodedHostRoleTable, data]; decide +kernel"
                .to_string(),
        );
    }
    let roles_literal = analysis.frag_host_table.roles_lean_value();
    let params_literal = analysis
        .frag_host_table
        .arith_params_record_lean_value(analysis.carrier)
        .expect("a carriered module declares arith params");
    let proof = format!(
        "theorem decodedHostRoles : AverCert.AcceptedArtifact.decodedHostRoleTable data := by\n  \
         dsimp only [AverCert.AcceptedArtifact.decodedHostRoleTable, data]\n  \
         rw [show AverCert.manifest.subject.hostRoleTable = some {roles_literal} from rfl,\n      \
         show AverCert.manifest.subject.arithParams = some {params_literal} from rfl]\n  \
         simp only [AverCert.AcceptedArtifact.arithTableCheck, decodedHostRole_box, \
         decodedHostRole_toIndex, decodedHostRole_add, decodedHostRole_sub, decodedHostRole_mul, \
         decodedHostRole_cmp, decodedHostRole_eq, \
         Bool.and_true, Bool.true_and]\n  \
         decide +kernel"
    );
    ("import ArtifactHostRoles\n".to_string(), proof)
}

/// The separate compilation unit that proves each declared arith host role in
/// its own freed `decide +kernel` leaf theorem. Isolating them from the rest of
/// `Artifact.lean` keeps the module peak at the shared import/whole-module-fold
/// shelf instead of stacking the per-role reductions on top of it. Emitted only
/// for a carriered module; the aggregate in `Artifact.lean` recombines these.
fn render_artifact_host_roles(analysis: &Analysis) -> String {
    let params_literal = analysis
        .frag_host_table
        .arith_params_record_lean_value(analysis.carrier)
        .expect("a carriered module declares arith params");
    let table = &analysis.frag_host_table;
    let leaf = |name: &str, role: &str, idx: Option<u32>| {
        let idx = idx.map_or_else(|| "none".to_string(), |idx| format!("(some {idx})"));
        format!(
            "theorem decodedHostRole_{name} : \
             AverCert.AcceptedArtifact.arithRoleCheck AverCert.ArtifactBytes.modBytes \
             AverCert.ArtifactBytes.modLen ArithTemplateDerisk.ArithRole.{role} {idx} \
             {params_literal} = true := by decide +kernel"
        )
    };
    let leaves = [
        leaf("box", "box", table.box_idx),
        leaf("toIndex", "toIndex", table.to_index_idx),
        leaf("add", "add", table.add_idx),
        leaf("sub", "sub", table.sub_idx),
        leaf("mul", "mul", table.mul_idx),
        leaf("cmp", "cmp", table.cmp_idx),
        leaf("eq", "eq", table.eq_idx),
    ]
    .join("\n\n");
    format!(
        "-- Per-role arith host-table leaves for `Artifact.decodedHostRoles`.\n\
         -- Each role's template equality is checked and freed in its own\n\
         -- `decide +kernel` declaration, in this separate compilation unit, so\n\
         -- the whole-module proof never materialises all seven at once.\n\
         import AcceptedArtifact\n\
         import ArtifactBytes\n\n\
         set_option maxRecDepth 200000\n\n\
         namespace AverCert.Artifact\n\n\
         {leaves}\n\n\
         end AverCert.Artifact\n"
    )
}

/// Final acceptance wrapper kept separate from artifact data so `Final.lean`
/// can consume the byte/plan acceptance facts without an import cycle.
fn render_artifact_certificate() -> String {
    r#"import Artifact
import Final

namespace AverCert.Artifact

theorem certificate : AverCert.AcceptedArtifact.accepted data :=
  acceptedWithFinal AverCert.Final.cert

#print axioms AverCert.Artifact.certificate

end AverCert.Artifact
"#
    .to_string()
}

/// Per-artifact glue from the hash-parametric audited wall to the real schema.
/// This module deliberately remains outside the sha-pinned wall because its
/// conclusion mentions the generated `CertModule.wasmSha256` through
/// `AverCert.Schema.Holds`.
fn render_artifact_soundness() -> String {
    r#"import Artifact
import AcceptanceSoundness

namespace AverCert.ArtifactSoundness

/-- Instantiate the artifact-independent acceptance wall at this artifact's real
wasm hash.  The remaining semantic bridge assumptions are still explicit. -/
theorem accept_sound_holds
    (hSide : AcceptanceSoundness.dischargeSideConditions AverCert.Artifact.data) :
    AverCert.Schema.Holds AverCert.Artifact.data.manifest := by
  exact AcceptanceSoundness.accept_sound CertModule.wasmSha256 AverCert.Artifact.data rfl
    AverCert.Artifact.claimObligationsBound
    AverCert.Artifact.standardFacesChecked
    AverCert.Artifact.fragmentsAccepted hSide

end AverCert.ArtifactSoundness
"#
    .to_string()
}

/// One redundant-but-honest closure pin per mutual-recursion SCC (emitted for the
/// primary member so each SCC appears once): the byte-derived
/// `(self, cross-target, memberSet)` triples the artifact's claims carry,
/// asserted to form a single closed cycle by the audited
/// `mutualMembersFormClosedSccs`. The artifact's `acceptedWithFinal` proof
/// already binds this closure over the real claims; this concrete pin documents
/// the byte-derived SCC group and gives the checker a self-contained surface
/// that fails closed if the group is not one closed cycle (a member's declared
/// set diverging, an extra/omitted/duplicate member, or a broken cross-edge).
fn render_mutual_scc_closure_pins(analysis: &Analysis) -> String {
    let mut out = String::new();
    for c in &analysis.certs {
        let Cert::MutualRecursion {
            position, scc, name, ..
        } = c.inner()
        else {
            continue;
        };
        if *position != 0 {
            continue;
        }
        if mutual_plan_from_cert(c).is_none() {
            continue;
        }
        let member_set = mutual_member_set_lean_value(scc);
        let members = scc
            .iter()
            .map(|m| format!("({}, {}, {member_set})", m.self_idx, m.cross_idx))
            .collect::<Vec<_>>()
            .join(", ");
        out.push_str(&format!(
            "/-- The byte-derived `{name}` SCC forms one closed mutual-recursion cycle. -/\n\
             example : AverCert.AcceptedArtifact.mutualMembersFormClosedSccs [{members}] = true := rfl\n\n",
        ));
    }
    out
}

/// Render a module carrier state as a Lean `Option Nat` literal. `none` is the
/// byte-proved carrierless state, not a missing value.
fn render_carrier_state(carrier: Option<u32>) -> String {
    match carrier {
        Some(idx) => format!("(some {idx})"),
        None => "none".to_string(),
    }
}

fn render_byte_list(bytes: &[u8]) -> String {
    let parts = bytes
        .iter()
        .map(|b| b.to_string())
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{parts}]")
}

pub fn render_artifact_bytes_lean(wasm_bytes: &[u8]) -> String {
    format!(
        "-- Exact Wasm module as a little-endian Lean Nat plus byte length.\n\
         -- `aver cert verify` regenerates this file from the artifact it reads;\n\
         -- a cert-supplied file with this name is ignored.\n\
         import WasmSlice\n\n\
         set_option maxRecDepth 200000\n\n\
         namespace AverCert.ArtifactBytes\n\n\
         def modBytes : Nat := {}\n\n\
         def modLen : Nat := {}\n\n\
         end AverCert.ArtifactBytes\n",
        render_byte_nat(wasm_bytes),
        wasm_bytes.len()
    )
}

fn render_byte_nat(bytes: &[u8]) -> String {
    if bytes.is_empty() {
        return "0".to_string();
    }
    let mut numeral = String::with_capacity(2 + bytes.len() * 2);
    numeral.push_str("0x");
    for byte in bytes.iter().rev() {
        numeral.push_str(&format!("{byte:02x}"));
    }
    numeral
}

/// Write one file of the certificate project.
///
/// `name` may be a nested path: a module declared as `Data.Fibonacci` transpiles
/// to `Data/Fibonacci.lean`. The certificate directory is cleared and recreated
/// at the start of rendering, so intermediate directories never survive from a
/// previous run and have to be made here — without this, every project with a
/// dotted module dependency failed to emit a certificate at all.
fn write(dir: &Path, name: &str, content: &str) -> Result<(), String> {
    let path = dir.join(name);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("create directory for {name}: {e}"))?;
    }
    std::fs::write(path, content).map_err(|e| format!("write {name}: {e}"))
}

fn sanitize_model_for_cert(content: &str) -> String {
    let mut out = String::with_capacity(content.len());
    for line in content.lines() {
        if line.trim_start().starts_with("deriving ") {
            continue;
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

fn hex(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

fn render_contracts(analysis: &Analysis) -> String {
    let mut s = String::new();
    s.push_str(
        "/-\n  Named runtime-layer contracts consumed by the certificates in this project.\n\n\
         Each is threaded as an explicit HYPOTHESIS of the certificate theorems (the\n\
         `hadd` / `hAdd` / `hSub` / `boxRef` faces in `Certificate.lean`), never as a\n\
         Lean `axiom`, so `#print axioms` on every certificate theorem stays on the\n\
         core whitelist `[propext, Classical.choice, Quot.sound]`. The obligations\n\
         below are the \"prove once per toolchain release\" runtime layer; the\n\
         machine-readable list is `cert-manifest.json`.\n\n",
    );
    if analysis.contracts.is_empty() {
        s.push_str("  (no user function was certified — no runtime contracts consumed)\n");
    } else {
        for c in &analysis.contracts {
            s.push_str(&format!("  * {c}\n"));
        }
    }
    s.push_str("-/\n");
    s
}

fn render_module(analysis: &Analysis, wasm_name: &str, sha: &str) -> String {
    let mut s = String::new();
    s.push_str(&format!(
        "-- Emitted user-function bodies as `CertPrelude.WInstr` data, plus the\n\
         -- sha256 of the final `{wasm_name}.wasm` bytes (pinned).\n\
         import CertPrelude\n\nnamespace CertModule\nopen CertPrelude\n\n",
    ));
    s.push_str(&format!(
        "/-- sha256 of the certified `{wasm_name}.wasm` module bytes. -/\n\
         def wasmSha256 : String := \"{sha}\"\n\n",
    ));
    for c in &analysis.certs {
        s.push_str(&render_code_def(c));
        s.push('\n');
        s.push_str(&render_host_def(c));
        s.push('\n');
    }
    s.push_str("end CertModule\n");
    s
}

/// The runtime host-contract wiring for a certified body, as data in
/// `CertModule` so both the certificate proofs and the manifest reference the
/// one definition.
fn render_host_def(c: &Cert) -> String {
    // Host-call expr fragments with the integer-add face wire the byte-derived
    // box/add indices directly.
    if let Some(face) = c.int_add_face() {
        return format!(
            "/-- Runtime host wiring for `{name}` (box + add contracts). -/\n\
             def {name}Host (add : List WVal → Option WVal) : HostTbl := fun fn =>\n  \
             if fn = {box_idx} then some (1, boxRef {carrier})\n  \
             else if fn = {add_idx} then some (2, add)\n  else none\n",
            name = c.name(),
            box_idx = face.box_idx,
            add_idx = face.add_idx,
            carrier = c.carrier(),
        );
    }
    match c.inner() {
        Cert::Recursive {
            name,
            carrier,
            box_idx,
            add_idx,
            sub_idx,
            combinator,
            ..
        } => {
            let cp = combinator.param();
            format!(
                "/-- Runtime host wiring for `{name}` (box + {cp} + sub contracts). -/\n\
                 def {name}Host ({cp} sub : List WVal → Option WVal) : HostTbl := fun fn =>\n  \
                 if fn = {box_idx} then some (1, boxRef {carrier})\n  \
                 else if fn = {add_idx} then some (2, {cp})\n  \
                 else if fn = {sub_idx} then some (2, sub)\n  else none\n",
            )
        }
        Cert::AccumulatorRecursive {
            name,
            carrier,
            box_idx,
            add_idx,
            sub_idx,
            ..
        } => format!(
            "/-- Runtime host wiring for `{name}` (box + add + sub contracts). -/\n\
             def {name}Host (add sub : List WVal → Option WVal) : HostTbl := fun fn =>\n  \
             if fn = {box_idx} then some (1, boxRef {carrier})\n  \
             else if fn = {add_idx} then some (2, add)\n  \
             else if fn = {sub_idx} then some (2, sub)\n  else none\n",
        ),
        Cert::AdtConstructor { name, .. }
        | Cert::FieldProjection { name, .. }
        | Cert::VerbatimWidenedMatch { name, .. }
        | Cert::VerbatimVariantDispatch { name, .. }
        | Cert::ExprFragment { name, .. } => format!(
            "/-- Runtime host wiring for `{name}` (no host calls). -/\n\
             def {name}Host : HostTbl := fun _ => none\n",
        ),
        Cert::StringEqVerbatimMatch {
            name,
            string_eq_idx,
            ..
        } => format!(
            "/-- Runtime host wiring for `{name}` (String.eq contract). -/\n\
             def {name}Host (stringEq : List WVal → Option WVal) : HostTbl := fun fn =>\n  \
             if fn = {string_eq_idx} then some (2, stringEq)\n  else none\n",
        ),
        Cert::StringConcatVerbatimMatch {
            name,
            string_concat_idx,
            result_ty,
            ..
        } => format!(
            "/-- Runtime host wiring for `{name}` (String.concat contract). -/\n\
             def {name}Host (stringConcat : Nat → List WVal → Option WVal) : HostTbl := fun fn =>\n  \
             if fn = {string_concat_idx} then some (1, stringConcat {result_ty})\n  else none\n",
        ),
        Cert::WidenedIntMatch {
            name,
            carrier,
            box_idx,
            ..
        } => format!(
            "/-- Runtime host wiring for `{name}` (box contract for the default `0`). -/\n\
             def {name}Host : HostTbl := fun fn =>\n  \
             if fn = {box_idx} then some (1, boxRef {carrier})\n  else none\n",
        ),
        Cert::VariantDispatch {
            name,
            carrier,
            box_idx,
            add_idx,
            sub_idx,
            ..
        } => {
            let a = if add_idx.is_some() { "add" } else { "_add" };
            let s = if sub_idx.is_some() { "sub" } else { "_sub" };
            let mut chain = format!("if fn = {box_idx} then some (1, boxRef {carrier})");
            if let Some(i) = add_idx {
                chain.push_str(&format!("\n  else if fn = {i} then some (2, add)"));
            }
            if let Some(i) = sub_idx {
                chain.push_str(&format!("\n  else if fn = {i} then some (2, sub)"));
            }
            format!(
                "/-- Runtime host wiring for `{name}` (box + contracted arithmetic). -/\n\
                 def {name}Host ({a} {s} : List WVal → Option WVal) : HostTbl := fun fn =>\n  \
                 {chain}\n  else none\n",
            )
        }
        Cert::Composition { name, closure, .. } => format!(
            "/-- Runtime host wiring for `{name}`'s call closure (add contract). -/\n\
             def {name}Host (add _sub : List WVal → Option WVal) : HostTbl := fun fn =>\n    {}\n",
            compose_host_arms(closure),
        ),
        // The whole SCC shares ONE host, emitted once by the primary member.
        Cert::MutualRecursion {
            scc,
            position,
            carrier,
            box_idx,
            sub_idx,
            ..
        } => {
            if *position != 0 {
                String::new()
            } else {
                let primary = &scc[0].name;
                format!(
                    "/-- Runtime host wiring for the mutual-recursive SCC `{primary}` (box + sub). -/\n\
                     def {primary}Host (sub : List WVal → Option WVal) : HostTbl := fun fn =>\n  \
                     if fn = {box_idx} then some (1, boxRef {carrier})\n  \
                     else if fn = {sub_idx} then some (2, sub)\n  else none\n",
                )
            }
        }
        Cert::NonRecursive { .. } => unreachable!(),
    }
}

fn render_code_def(c: &Cert) -> String {
    // The SCC shares ONE code table (all members' arms), named after the primary
    // (lowest-`self_idx`) member and emitted once by it.
    if let Cert::MutualRecursion { scc, position, .. } = c.inner() {
        if *position != 0 {
            return String::new();
        }
        let primary = &scc[0].name;
        return format!(
            "/-- Verbatim shared code table for the mutual-recursive SCC `{primary}` \
             (one arm per member). -/\n\
             def {primary}Code : CodeTbl := {value}\n",
            value = render_code_value(c),
        );
    }
    let doc = match c.inner() {
        Cert::Recursive { .. } => "self-recursive",
        Cert::AccumulatorRecursive { .. } => "accumulator self-recursive",
        Cert::AdtConstructor { .. } => "ADT constructor",
        Cert::FieldProjection { .. } => "field projection",
        Cert::WidenedIntMatch { .. } => "widened Int variant match",
        Cert::VerbatimWidenedMatch { .. } => "verbatim widened variant match",
        Cert::VerbatimVariantDispatch { .. } => "verbatim variant dispatch",
        Cert::StringEqVerbatimMatch { .. } => "verbatim String equality match",
        Cert::StringConcatVerbatimMatch { .. } => "verbatim String concatenation match",
        Cert::ExprFragment { .. } => "expr-fragment-v1",
        Cert::VariantDispatch { .. } => "general variant dispatch",
        Cert::Composition { .. } => "cross-function composition, whole call closure",
        Cert::MutualRecursion { .. } => "mutual-recursive SCC",
        Cert::NonRecursive { .. } => unreachable!(),
    };
    format!(
        "/-- Verbatim emitted body of `{name}` ({doc}). -/\n\
         def {name}Code : CodeTbl := {value}\n",
        name = c.name(),
        value = render_code_value(c),
    )
}

// Code-value helpers live in render_code.rs.

#[cfg(test)]
mod render_project_tests {
    use super::model_root_from_stem;

    #[test]
    fn model_roots_become_dotted_lean_module_names() {
        assert_eq!(model_root_from_stem("AverCommon").unwrap(), "AverCommon");
        assert_eq!(
            model_root_from_stem("Apps/Notepad/Store").unwrap(),
            "Apps.Notepad.Store"
        );
        assert!(model_root_from_stem("Apps/../Store").is_err());
        assert!(model_root_from_stem("Apps/Bad Name").is_err());
        assert!(model_root_from_stem("").is_err());
    }
}