aver-cert 0.1.7

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
// ---- rendering the schema-9 package -----------------------------------------

/// Target artifact whose delivered bytes are bound by a certificate package.
///
/// The certificate engine always analyzes and renders facts about a core Wasm
/// module. For raw wasm-gc the delivered artifact and that core are the same
/// bytes. For wasip2 they are deliberately distinct: the component is hashed
/// as the delivered artifact, while the wall consumes the exact core-module
/// payload declared inside that component.
pub enum CertificateArtifact<'a> {
    WasmGc {
        file_name: &'a str,
        module_bytes: &'a [u8],
    },
    Wasip2 {
        file_name: &'a str,
        component_bytes: &'a [u8],
        embedded_core_module: &'a [u8],
        envelope: crate::format::Wasip2ComponentEnvelopeDeclaration,
    },
}

impl CertificateArtifact<'_> {
    fn validate(&self) -> Result<(), String> {
        match self {
            Self::WasmGc { module_bytes, .. } => {
                if module_bytes.is_empty() {
                    return Err("cannot certify an empty wasm-gc module".to_string());
                }
            }
            Self::Wasip2 {
                component_bytes,
                embedded_core_module,
                envelope,
                ..
            } => {
                let (_, declared_core, _) = envelope.split_component(component_bytes).ok_or_else(|| {
                    "wasip2 certificate envelope does not split the delivered component by its declared lengths"
                        .to_string()
                })?;
                if declared_core != *embedded_core_module {
                    return Err(
                        "wasip2 certificate core bytes do not equal the envelope-declared component slice"
                            .to_string(),
                    );
                }
            }
        }
        Ok(())
    }

    pub fn file_name(&self) -> &str {
        match self {
            Self::WasmGc { file_name, .. } | Self::Wasip2 { file_name, .. } => file_name,
        }
    }

    fn delivered_bytes(&self) -> &[u8] {
        match self {
            Self::WasmGc { module_bytes, .. } => module_bytes,
            Self::Wasip2 {
                component_bytes, ..
            } => component_bytes,
        }
    }

    pub fn core_module_bytes(&self) -> &[u8] {
        match self {
            Self::WasmGc { module_bytes, .. } => module_bytes,
            Self::Wasip2 {
                embedded_core_module,
                ..
            } => embedded_core_module,
        }
    }

    pub fn target(&self) -> &'static str {
        match self {
            Self::WasmGc { .. } => crate::format::TARGET_WASM_GC,
            Self::Wasip2 { .. } => crate::format::TARGET_WASIP2,
        }
    }

    fn abi(&self) -> &'static str {
        match self {
            Self::WasmGc { .. } => crate::format::RUNTIME_ABI_WASM_GC,
            Self::Wasip2 { .. } => crate::format::RUNTIME_ABI_WASIP2,
        }
    }

    fn wasip2_component_envelope(
        &self,
    ) -> Option<crate::format::Wasip2ComponentEnvelopeDeclaration> {
        match self {
            Self::WasmGc { .. } => None,
            Self::Wasip2 { envelope, .. } => Some(*envelope),
        }
    }
}

/// What the producer refused to declare, by surface. Each entry is
/// `(name, reason)`; neither kind changes which exports are certified.
#[derive(Debug, Default)]
pub struct ProjectDeclines {
    pub law_claims: Vec<(String, String)>,
    pub source_bridges: Vec<(String, String)>,
}

fn lean_str(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            _ => out.push(ch),
        }
    }
    out.push('"');
    out
}

fn json_str(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            _ => out.push(ch),
        }
    }
    out.push('"');
    out
}

fn write(dir: &Path, name: &str, content: &str) -> Result<(), String> {
    let path = dir.join(name);
    std::fs::write(&path, content).map_err(|e| format!("write {}: {e}", path.display()))
}

/// A String as the Lean list of its characters. A String literal is
/// definitionally `String.ofList` of exactly this list, which the kernel
/// checks without building the String's bytes. Printable ASCII other than
/// the quote and escape characters stays a plain literal (so the checker's
/// lexical gate sees no string opener); every other character is spelled by
/// its code point.
fn lean_char_list(s: &str) -> String {
    let chars = s
        .chars()
        .map(|c| {
            if (' '..='~').contains(&c) && !matches!(c, '\'' | '\\' | '"') {
                format!("'{c}'")
            } else {
                format!("(Char.ofNat {})", c as u32)
            }
        })
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{chars}]")
}

/// A list of Strings as the Lean list of their character lists, one per
/// line after `separator`.
fn lean_char_lists(items: &[String], separator: &str) -> String {
    let lists = items
        .iter()
        .map(|item| lean_char_list(item))
        .collect::<Vec<_>>()
        .join(&format!(",{separator}"));
    format!("[{lists}]")
}

/// Pairs of Strings as the Lean list of pairs of their character lists.
fn lean_char_pairs(items: &[(String, String)]) -> String {
    let pairs = items
        .iter()
        .map(|(a, b)| format!("({}, {})", lean_char_list(a), lean_char_list(b)))
        .collect::<Vec<_>>()
        .join(",\n     ");
    format!("[{pairs}]")
}

fn plan_def_name(func_idx: u32) -> String {
    format!("fn{func_idx}")
}

fn render_plans(analysis: &Analysis) -> String {
    let mut s = String::from(
        "-- The certificate's plans: every planned function's optimized MIR body,\n\
         -- printed 1:1 into the one plan grammar, and the declared type layout.\n\
         -- Producer data: the wall lowers each plan and pins the result to the\n\
         -- function's code entry, and confirms the layout against the bytes.\n\
         import SchemaCore\n\n\
         namespace AverCert.Plans\n\
         open AverCert.Schema AverCert.Grammar\n\n",
    );
    s.push_str(&analysis.types.lean_decls("types"));
    for e in &analysis.entries {
        s.push_str(&format!(
            "/-- `{}` (function {}). -/\ndef {} : FnPlan :=\n  {}\n\n",
            e.name.replace('-', "_"),
            e.func_idx,
            plan_def_name(e.func_idx),
            e.plan.lean()
        ));
    }
    let entries = analysis
        .entries
        .iter()
        .map(|e| {
            format!(
                "⟨{}, {}, {}, {}, {}⟩",
                lean_str(&e.name),
                e.exported,
                e.func_idx,
                e.group,
                plan_def_name(e.func_idx)
            )
        })
        .collect::<Vec<_>>();
    // Compiling one list literal of a thousand entries passes Lean's default
    // recursion limit, so a long list raises it for this one definition. The
    // literal stays one term: the bridge proofs read entries of `fnPlans` by
    // `rfl`, which is several times slower through `++` of pieces.
    let depth = if entries.len() > 512 {
        "set_option maxRecDepth 100000 in\n"
    } else {
        ""
    };
    let entries = format!("[{}]", entries.join(",\n   "));
    s.push_str(&format!("{depth}def fnPlans : List FnEntry :=\n  {entries}\n\n"));
    s.push_str("end AverCert.Plans\n");
    s
}

/// The declared-uncertified exports, in the order of the wall's name keys
/// (`WasmSlice.seqKey` of the name's code points: one digit of 21 bits per
/// code point, the first the lowest), so the export accounting finds them
/// already sorted (`SortedKeys.sortedOr`) instead of sorting them in the
/// kernel. The order is a convenience only: any other order is sorted by the
/// kernel and accepted the same.
fn declared_uncertified(analysis: &Analysis) -> Vec<(String, String)> {
    let mut declared = analysis
        .module_envelope
        .declared_uncertified(analysis.certified_names(), &analysis.declined);
    declared.sort_by_cached_key(|(name, _)| name_key_order(name));
    declared
}

/// A sort key whose order is the numeric order of `WasmSlice.seqKey` over a
/// name's code points: more code points is larger (every digit is at least
/// 1), and at equal length the last code point is the most significant.
fn name_key_order(name: &str) -> (usize, Vec<u32>) {
    let mut codes: Vec<u32> = name.chars().map(u32::from).collect();
    codes.reverse();
    (codes.len(), codes)
}

/// The manifest. With a declared layout, the declared-uncertified exports are
/// written in `declared_pieces`, one piece per block of the export walk
/// (`ArtifactExports`), joined right-nested so each block's declaration reads
/// its piece by name; the list they join to is the one written without them.
fn render_manifest_lean(
    analysis: &Analysis,
    sha: &str,
    target: &str,
    abi: &str,
    declared_pieces: Option<&[Vec<(String, String)>]>,
) -> String {
    let roles = match &analysis.roles {
        Some(r) => format!("some {}", r.roles_lean_value()),
        None => "(none : Option CertDecode.AddSub.Roles)".to_string(),
    };
    let params = match analysis
        .roles
        .as_ref()
        .and_then(|r| r.arith_params_record_lean(analysis.carrier))
    {
        Some(p) => format!("some {p}"),
        None => "(none : Option ArithTemplateDerisk.ArithHostParams)".to_string(),
    };
    let strings = format!(
        "[{}]",
        analysis
            .string_roles
            .iter()
            .map(|(idx, role)| format!("({idx}, {})", role.lean_value()))
            .collect::<Vec<_>>()
            .join(", ")
    );
    let start = match analysis.module_envelope.start {
        Some(i) => format!("some {i}"),
        None => "none".to_string(),
    };
    // A big module's export lists do not fit one declaration: they are
    // written in pieces (`lean_list_in_pieces`) ahead of `subject`. The pieces
    // live under `AverCert.Plans`, not under `AverCert.subject`: the checker's
    // audit refuses a package name that extends another declared constant.
    let mut pieces = String::new();
    let string_items = |items: &[String]| items.iter().map(|x| lean_str(x)).collect::<Vec<_>>();
    let pair_items = |items: &[(String, String)]| {
        items
            .iter()
            .map(|(a, b)| format!("({}, {})", lean_str(a), lean_str(b)))
            .collect::<Vec<_>>()
    };
    let exports = lean_list_in_pieces(
        &mut pieces,
        "Plans.subject_exports",
        "String",
        &string_items(&analysis.certified_names()),
    );
    let declared = match declared_pieces {
        None => lean_list_in_pieces(
            &mut pieces,
            "Plans.subject_declaredUncertified",
            "String × String",
            &pair_items(&declared_uncertified(analysis)),
        ),
        Some(blocks) => {
            let mut names = Vec::new();
            for (b, piece) in blocks.iter().enumerate() {
                let name = format!("Plans.subject_declaredUncertified_{b}");
                pieces.push_str(&format!(
                    "def {name} : List (String × String) :=\n  [{}]\n\n",
                    pair_items(piece).join(",\n   ")
                ));
                names.push(name);
            }
            right_nested(&names)
        }
    };
    let capabilities = lean_list_in_pieces(
        &mut pieces,
        "Plans.subject_capabilities",
        "String × String",
        &pair_items(&analysis.module_envelope.capabilities),
    );
    let contracts = lean_list_in_pieces(
        &mut pieces,
        "Plans.subject_contracts",
        "String",
        &string_items(&analysis.contracts),
    );
    format!(
        "-- The certificate's manifest: the subject (artifact identity, exports,\n\
         -- helper indices and the contracts it is conditional on), the plans and\n\
         -- the obligations, which are exactly the ones the wall derives.\n\
         import SchemaCore\n\
         import AcceptedArtifactCore\n\
         import Plans\n\n\
         namespace AverCert\n\
         open AverCert.Schema\n\n\
         {pieces}\
         def subject : Subject :=\n  \
           {{ artifactHash := {sha}\n    \
             target := {target}, profile := {profile}, abi := {abi}\n    \
             artifactRoot := {root}\n    \
             exports := {exports}\n    \
             declaredUncertified := {declared}\n    \
             capabilities := {capabilities}\n    \
             start := {start}\n    \
             hostRoleTable := {roles}\n    \
             arithParams := {params}\n    \
             stringHostRoles := {strings}\n    \
             contracts := {contracts} }}\n\n\
         def manifest : Manifest :=\n  \
           {{ subject := subject, types := Plans.types, fnPlans := Plans.fnPlans,\n    \
             obligations := AverCert.AcceptedArtifact.obligationsOf subject Plans.types Plans.fnPlans }}\n\n\
         end AverCert\n",
        sha = lean_str(sha),
        target = lean_str(target),
        profile = lean_str(PROFILE_ID),
        abi = lean_str(abi),
        root = lean_str(ARTIFACT_CERTIFICATE_ROOT),
    )
}

fn render_artifact_host_roles(analysis: &Analysis, params: &str, layout: bool) -> String {
    let roles = analysis.roles.expect("a carriered module declares roles");
    // With a declared layout, each helper body is read from it (one slice)
    // instead of decoding the code section in every declaration.
    let proof = if layout {
        "by\n  rw [AverCert.DeclaredLayout.arithRoleCheck_of_layout layout_ok] <;> decide +kernel"
    } else {
        "by decide +kernel"
    };
    let leaf = |name: &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.{name} {idx} {params} = true := {proof}"
        )
    };
    let leaves = [
        leaf("box", roles.box_idx),
        leaf("toIndex", roles.to_index_idx),
        leaf("add", roles.add_idx),
        leaf("sub", roles.sub_idx),
        leaf("mul", roles.mul_idx),
        leaf("cmp", roles.cmp_idx),
        leaf("eq", roles.eq_idx),
        leaf("divmod", roles.divmod_idx),
        leaf("bitwise", roles.bitwise_idx),
    ]
    .join("\n\n");
    format!(
        "-- Per-role helper template pins, each in its own `decide +kernel`\n\
         -- declaration, in a separate compilation unit.\n\
         import AcceptedArtifact\n\
         import ArtifactBytes\n\
         {layout_import}\n\
         set_option maxRecDepth 200000\n\n\
         namespace AverCert.Artifact\n\n\
         {leaves}\n\n\
         end AverCert.Artifact\n",
        layout_import = if layout {
            format!("import {}\n", layout_facts_module(analysis))
        } else {
            String::new()
        },
    )
}

/// Plans a package may have before its byte facts are spread over several
/// modules (`splits_artifact_modules`).
const PLAN_CHUNK: usize = 32;

/// Plans checked per module of a split package: one declaration each.
const PLANS_PER_MODULE: usize = 100;

/// The per-plan checks. With a declared layout each plan is its own
/// `decide +kernel` declaration (`ScaleLayout.planOne`): its lowering packed
/// and compared with the chunk window of its declared code entry, its
/// typing, calls and function type, its export entry read on a window at its
/// declared position, and its role bits. Each declaration names its plan
/// entry, declaration and role bits as the literals the lists hold, so no
/// check indexes into a list. The declarations are joined along the lists
/// (`plansFrom_cons`, `plansFrom_block`) and turned into every plan's
/// `entryAccepted` and role bits by `ScaleLayout.entries_of_packed`. A split
/// package puts `PLANS_PER_MODULE` plans in each module, so a parallel Lake
/// checks them at once. Without a layout (a package with no plans) the
/// check over every plan is decided directly.
fn render_artifact_plans(
    analysis: &Analysis,
    decls: &[String],
    sites: &[String],
    layout: bool,
) -> Vec<(String, String)> {
    let n = analysis.entries.len();
    let header = "set_option maxRecDepth 200000\n\
         set_option maxHeartbeats 1600000\n\n\
         namespace AverCert.Artifact\n\
         open AverCert AverCert.Schema AverCert.AcceptedArtifact AverCert.TypeTable\n\n";
    let plan_ok = "/-- One plan's acceptance check against the staged artifact bytes. -/\n\
         noncomputable abbrev planOk : FnEntry → Bool :=\n  \
           entryAccepted AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen\n    \
           (mctxOf AverCert.manifest.subject AverCert.manifest.types AverCert.manifest.fnPlans)\n    \
           AverCert.manifest.fnPlans\n\n";
    if !layout {
        return vec![(
            "ArtifactPlans.lean".to_string(),
            format!(
                "-- The per-plan acceptance checks.\n\
                 import AcceptedArtifact\nimport ArtifactBytes\nimport Manifest\n\n\
                 {header}{plan_ok}\
                 theorem plans_all : AverCert.manifest.fnPlans.all planOk = true := by\n  \
                 decide +kernel\n\n\
                 end AverCert.Artifact\n"
            ),
        )];
    }
    let split = splits_artifact_modules(analysis);
    let check = format!(
        "{plan_ok}\
         /-- The lowering context of every plan check. -/\n\
         abbrev planM : AverCert.Grammar.MCtx :=\n  \
           mctxOf AverCert.manifest.subject AverCert.manifest.types AverCert.manifest.fnPlans\n\n\
         /-- One plan entry's check (`ScaleLayout.planOne`). -/\n\
         noncomputable abbrev planCheck :\n    \
           FnEntry → AverCert.DeclaredLayout.FnDecl → Nat → Nat × Nat → Bool :=\n  \
           AverCert.ScaleLayout.planOne AverCert.ArtifactBytes.chunks layout fnTypes planM\n    \
           AverCert.manifest.fnPlans exportStart exportStarts\n\n\
         /-- The plan checks along the lists (`ScaleLayout.plansFrom`). -/\n\
         noncomputable abbrev plansOf : List FnEntry → List AverCert.DeclaredLayout.FnDecl →\n    \
           List Nat → List (Nat × Nat) → Bool :=\n  \
           AverCert.ScaleLayout.plansFrom AverCert.ArtifactBytes.chunks layout fnTypes planM\n    \
           AverCert.manifest.fnPlans exportStart exportStarts\n\n\
         theorem types_ok : AverCert.DeclaredLayout.fnTypesConfirmed AverCert.ArtifactBytes.modBytes\n    \
           AverCert.ArtifactBytes.modLen fnTypes = true := by\n  \
           rw [AverCert.DeclaredLayout.fnTypesConfirmed, types_at]; decide +kernel\n\n"
    );
    // The plan entries' names against the declared ones, by `rfl`: in a split
    // package a module of its own, beside the plan modules.
    let names = "theorem names_eq : AverCert.manifest.fnPlans.map (·.name) =\n    \
           fnDecls.map (fun d => String.ofList d.name) := rfl\n\n";
    let plan = |i: usize| {
        let e = &analysis.entries[i];
        format!(
            "theorem plan_{i} : planCheck\n    ⟨{}, {}, {}, {}, AverCert.Plans.{}⟩\n    {}\n    {} {} = true := by\n  \
             decide +kernel\n\n",
            lean_str(&e.name),
            e.exported,
            e.func_idx,
            e.group,
            plan_def_name(e.func_idx),
            decls[i],
            analysis.role_bits[i],
            sites[i]
        )
    };
    // The plans `k, …, k + m - 1` from their own declarations.
    let block = |k: usize, m: usize| {
        let mut term = "AverCert.ScaleLayout.plansFrom_nil _ _ _ _ _ _ _".to_string();
        for i in (k..k + m).rev() {
            term = format!("AverCert.ScaleLayout.plansFrom_cons plan_{i}\n    ({term})");
        }
        format!(
            "theorem plans_block_{k} : plansOf ((AverCert.manifest.fnPlans.drop {k}).take {m})\n    \
             ((fnDecls.drop {k}).take {m}) ((callBits.drop {k}).take {m})\n    \
             ((exportSites.drop {k}).take {m}) = true :=\n  \
             {term}\n\n"
        )
    };
    let per_module = if split { PLANS_PER_MODULE } else { n.max(1) };
    let starts: Vec<usize> = (0..n).step_by(per_module).collect();
    let mut joined = format!(
        "(AverCert.ScaleLayout.plansFrom_nil _ _ _ _ _ _ _ :\n      \
         plansOf (AverCert.manifest.fnPlans.drop {n}) (fnDecls.drop {n}) (callBits.drop {n})\n        \
         (exportSites.drop {n}) = true)"
    );
    for &k in starts.iter().rev() {
        let m = per_module.min(n - k);
        joined = format!(
            "AverCert.ScaleLayout.plansFrom_block (k := {k}) (m := {m}) plans_block_{k}\n    ({joined})"
        );
    }
    let end = format!(
        "theorem plans_packed : plansOf AverCert.manifest.fnPlans fnDecls callBits exportSites = true :=\n  \
           {joined}\n\n\
         theorem plans_checked : AverCert.manifest.fnPlans.all planOk = true ∧\n    \
           AverCert.manifest.fnPlans.map (AverCert.ScaleLayout.roleBits planM) = callBits :=\n  \
           AverCert.ScaleLayout.entries_of_packed bytes_eq chunks_fit layout_ok types_ok export_names_ok\n    \
           names_eq exports_cut_ok exports_head export_starts plans_packed\n\n\
         /-- The export accounting: the export walk, and every planned export read at\n\
         its site by its plan's check. -/\n\
         theorem exports_accounted : AverCert.AcceptedArtifact.exportsAccountedOf\n    \
           AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen\n    \
           (AverCert.AcceptedArtifact.certifiedExportEntries AverCert.manifest)\n    \
           (AverCert.AcceptedArtifact.declaredUncertifiedNames AverCert.manifest) = true :=\n  \
           AverCert.ScaleExports.exportsAccounted_of_walk bytes_eq chunks_fit exports_head export_starts\n    \
           exports_walk plans_packed names_eq cert_bits rfl\n\n\
         theorem plans_all : AverCert.manifest.fnPlans.all planOk = true := plans_checked.1\n\n\
         theorem plans_roles : AverCert.manifest.fnPlans.map (AverCert.ScaleLayout.roleBits planM) =\n    \
           callBits := plans_checked.2\n\n\
         end AverCert.Artifact\n"
    );
    let imports = format!(
        "import AcceptedArtifact\nimport ArtifactBytes\nimport Manifest\nimport {}\n{}\n",
        layout_facts_module(analysis),
        if split { "" } else { "import ArtifactExports\n" }
    );
    let module_body = |k: usize| {
        let m = per_module.min(n - k);
        let mut body: String = (k..k + m).map(plan).collect();
        body.push_str(&block(k, m));
        body
    };
    if !split {
        let body: String = starts.iter().map(|&k| module_body(k)).collect();
        return vec![(
            "ArtifactPlans.lean".to_string(),
            format!(
                "-- The per-plan acceptance checks, one declaration per plan, joined into\n\
                 -- the check over every plan.\n\
                 {imports}{header}{check}{names}{body}{end}"
            ),
        )];
    }
    let mut files = vec![(
        "ArtifactPlanCheck.lean".to_string(),
        format!(
            "-- The per-plan check the plan modules decide, and the facts every plan\n\
             -- check shares.\n\
             {imports}{header}{check}end AverCert.Artifact\n"
        ),
    )];
    files.push((
        "ArtifactPlanNames.lean".to_string(),
        format!(
            "-- The plan entries' names, as the layout declares them.\n\
             import Manifest\nimport ArtifactLayout\n\n\
             {header}{names}end AverCert.Artifact\n"
        ),
    ));
    let mut plan_imports = String::from("import ArtifactPlanNames\n");
    for &k in &starts {
        files.push((
            format!("ArtifactPlans{k}.lean"),
            format!(
                "-- The per-plan checks of plans {k} to {}, one declaration each.\n\
                 import ArtifactPlanCheck\n\n\
                 {header}{}end AverCert.Artifact\n",
                k + per_module.min(n - k) - 1,
                module_body(k)
            ),
        ));
        plan_imports.push_str(&format!("import ArtifactPlans{k}\n"));
    }
    files.push((
        "ArtifactPlans.lean".to_string(),
        format!(
            "-- The per-plan checks of the plan modules, joined into the check over\n\
             -- every plan.\n\
             {plan_imports}import ArtifactExports\n\n{header}{end}"
        ),
    ));
    files
}

/// Whether the package spreads its byte facts over several modules: a module
/// with more plans than one chunk checks the chunks, and the heaviest whole-
/// module facts, in modules of their own, which Lake builds in parallel when
/// it is given more than one worker (`AVER_CERT_BUILD_JOBS`). A smaller
/// package keeps one module per step, since each module pays its imports.
fn splits_artifact_modules(analysis: &Analysis) -> bool {
    analysis.entries.len() > PLAN_CHUNK
}

/// The module that proves the export accounting (`exports_ok`): its own
/// module in a split package, `Artifact.lean` otherwise.
fn exports_fact_module(analysis: &Analysis) -> &'static str {
    if splits_artifact_modules(analysis) {
        "ArtifactInterface"
    } else {
        "Artifact"
    }
}

const ARTIFACT_HEADER: &str = "set_option maxRecDepth 200000\n\
     -- Elaboration cost grows with the artifact; this moves a resource\n\
     -- limit only (no axiom, no hypothesis, nothing the kernel accepts).\n\
     set_option maxHeartbeats 1600000\n\n\
     namespace AverCert.Artifact\n\
     open AverCert AverCert.Schema AverCert.AcceptedArtifact\n\n";

/// `Artifact.lean` (and, for a split package, the modules it imports): the
/// artifact data and the byte facts of its acceptance.
fn render_artifact(
    analysis: &Analysis,
    envelope: Option<crate::format::Wasip2ComponentEnvelopeDeclaration>,
    string_blocks: Option<&str>,
    data_blocks: Option<&str>,
    helper_sites: &[(&str, usize, usize)],
) -> Vec<(String, String)> {
    let layout = string_blocks.is_some();
    let envelope = match envelope {
        None => "none".to_string(),
        Some(env) => format!(
            "some {{ prefixLen := {}, embeddedCoreModuleLen := {}, suffixLen := {} }}",
            env.prefix_len, env.embedded_core_module_len, env.suffix_len
        ),
    };
    let closure = &analysis.module_envelope.closure;
    let nats = |xs: &[u32]| {
        format!(
            "[{}]",
            xs.iter().map(u32::to_string).collect::<Vec<_>>().join(", ")
        )
    };
    let (roles_import, roles_proof) = match (
        &analysis.roles,
        analysis
            .roles
            .as_ref()
            .and_then(|r| r.arith_params_record_lean(analysis.carrier)),
    ) {
        (Some(r), Some(params)) => {
            // With a declared layout, each Int helper the module exports is
            // read at its export site (`ScaleTables.helperIdx_of_site`); a
            // helper the table declares absent is still searched for.
            let site = |name: &str| helper_sites.iter().find(|(n, _, _)| *n == name);
            let site_fact = |thm: &str, stmt: String, name: &str, lemma: &str| {
                let (_, off, l) = site(name)?;
                Some(format!(
                    "theorem {thm} : {stmt} :=\n  \
                     {lemma}\n    \
                     (AverCert.ScaleTables.helperIdx_of_site bytes_eq chunks_fit exports_head exports_cut_ok\n      \
                     export_starts export_names_ok (off := {off}) (l := {l}) (by decide +kernel))\n\n"
                ))
            };
            const B: &str = "AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen";
            let mut facts = String::new();
            let mut lemmas: Vec<String> = Vec::new();
            let mut by_name = |thm: &str, fun: &str, eq: &str, name: &str, idx: Option<u32>| {
                let fact = if layout {
                    idx.and_then(|fi| {
                        site_fact(
                            thm,
                            format!("CertDecode.AddSub.{fun} {B} = some {fi}"),
                            name,
                            &format!("(AverCert.DeclaredLayout.Chars.{eq} _ _).trans"),
                        )
                    })
                } else {
                    None
                };
                match fact {
                    Some(text) => {
                        facts.push_str(&text);
                        lemmas.push(thm.to_string());
                    }
                    None => lemmas.push(format!("AverCert.DeclaredLayout.Chars.{eq}")),
                }
            };
            by_name("helper_box", "boxIdx", "boxIdx_eq", "__rt_aint_from_i64", r.box_idx);
            by_name("helper_to_index", "toIndexIdx", "toIndexIdx_eq", "__aint_to_index", r.to_index_idx);
            by_name("helper_cmp", "cmpIdx", "cmpIdx_eq", "__aint_cmp", r.cmp_idx);
            // The carrier helper is present: its export site shows it.
            match (layout, r.box_idx, site("__rt_aint_from_i64")) {
                (true, Some(fi), Some((_, off, l))) => {
                    facts.push_str(&format!(
                        "theorem helper_present : CertDecode.AddSub.carrierHelperAbsent {B} = false :=\n  \
                         AverCert.ScaleTables.carrierHelperAbsent_of_site bytes_eq chunks_fit exports_head\n    \
                         exports_cut_ok export_starts export_names_ok (off := {off}) (l := {l}) (fi := {fi})\n    \
                         (by decide +kernel)\n\n"
                    ));
                    lemmas.push("helper_present".to_string());
                }
                _ => lemmas.push("AverCert.DeclaredLayout.Chars.carrierHelperAbsent_eq".to_string()),
            }
            (
                "import ArtifactHostRoles\n".to_string(),
                format!(
                    "{facts}theorem roles_ok : decodedHostRoleTable data := by\n  \
                     dsimp only [decodedHostRoleTable, data]\n  \
                     rw [show AverCert.manifest.subject.hostRoleTable = some {} from rfl,\n      \
                     show AverCert.manifest.subject.arithParams = some {params} from rfl]\n  \
                     simp only [arithTableCheck, decodedHostRole_box, decodedHostRole_toIndex, \
                     decodedHostRole_add, decodedHostRole_sub, decodedHostRole_mul, decodedHostRole_cmp, \
                     decodedHostRole_eq, decodedHostRole_divmod, decodedHostRole_bitwise, Bool.and_true, Bool.true_and,\n    \
                     {}{cuts}]\n  \
                     {carrier}decide +kernel",
                    r.roles_lean_value(),
                    lemmas.join(", "),
                    cuts = if layout { ", exports_cut" } else { "" },
                    // The carrier is read through the type section by index.
                    // Its definition is a `match` on the decoded type section,
                    // so it is unfolded by its unconditional equation with
                    // matcher reduction off: otherwise `simp` evaluates the
                    // whole type decode in the elaborator first.
                    carrier = if layout {
                        "simp -iota only [CertDecode.carrierState.eq_def, types_at]\n  "
                    } else {
                        ""
                    },
                ),
            )
        }
        _ => (
            String::new(),
            "theorem roles_ok : decodedHostRoleTable data := by\n  \
             unfold decodedHostRoleTable; decide +kernel"
                .to_string(),
        ),
    };
    let data = format!(
        "noncomputable def data : ArtifactData :=\n  \
           {{ modBytes := AverCert.ArtifactBytes.modBytes, modLen := AverCert.ArtifactBytes.modLen,\n    \
             manifest := AverCert.manifest, wasip2ComponentEnvelope := {envelope},\n    \
             closureFuel := {fuel},\n    \
             closureClaim := ⟨{roots}, {helpers}, {admitted}⟩ }}\n\n",
        fuel = analysis.module_envelope.closure_fuel,
        roots = nats(&closure.roots),
        helpers = nats(&closure.helpers),
        admitted = nats(&closure.admitted),
    );
    // The String roles are decided through `roleTableFast`, which reads a
    // function's signature only when its type has a helper's shape.
    // With a declared layout they read the type section through its
    // confirmed cut, and every code entry on its own chunk window.
    // The String roles: with a declared layout, every function classified by
    // its type's shape bit in blocks (`ScaleTypes.roleTable_of_blocks`);
    // without one, decided through `roleTableFast`, which reads a function's
    // signature only when its type has a helper's shape.
    let strings = match string_blocks {
        Some(blocks) => blocks.to_string(),
        None => "theorem strings_ok : decodedStringHostRoles data := by\n  \
         unfold decodedStringHostRoles\n  \
         rw [← AverCert.DeclaredLayout.StringFast.roleTableFast_eq]; decide +kernel\n\n"
            .to_string(),
    };
    // With a declared layout the closure is folded over declared callee
    // lists, each checked on its function's chunk window a block at a time
    // (`ScaleClosure.closureIsolation_of_callees`); without one it is decided
    // whole.
    let split = splits_artifact_modules(analysis);
    let (closure_blocks, closure_files) = if layout {
        render_closure_blocks(analysis, split)
    } else {
        (String::new(), Vec::new())
    };
    let closure_ok = if layout {
        format!(
            "{closure_blocks}theorem closure_ok : closureIsolation data = true :=\n  \
             AverCert.ScaleClosure.closureIsolation_of_callees bytes_eq chunks_fit layout_ok\n    \
             closure_callees (by decide +kernel)\n\n"
        )
    } else {
        "theorem closure_ok : closureIsolation data = true := by decide +kernel\n\n".to_string()
    };
    let closure_ok = closure_ok.as_str();
    let layout_import = if layout {
        format!(
            "import {}\nimport SortedKeys\nimport ScaleTables\n",
            layout_facts_module(analysis)
        )
    } else {
        String::new()
    };
    let layout_import = layout_import.as_str();
    // With a declared layout the framing is read from the declared headers.
    let framing_proof = if layout {
        "\n  AverCert.ScaleLayout.moduleFramingValid_of_framing bytes_eq chunks_fit framing_decl"
    } else {
        " by\n  decide +kernel"
    };
    let exports = format!(
        "theorem framing_ok : CertDecode.moduleFramingValid data.modBytes data.modLen = true :={framing_proof}\n\n\
         theorem exports_ok : exportsAccounted data = true :={exports_proof}\n\n\
         theorem imports_ok : importsWithinCapabilities data = true :=\n  \
           AverCert.DeclaredLayout.Chars.importsWithinCapabilities_of_chars data\n    \
           {capabilities}\n    \
           rfl (by decide +kernel)\n\n\
         theorem start_ok : startAccounted data = true := by decide +kernel\n\n",
        // With a declared layout the accounting is read from the export walk
        // and the plan checks (`ArtifactPlans`); without one it is decided on
        // the names as character lists.
        exports_proof = if layout {
            "\n  exports_accounted".to_string()
        } else {
            format!(
                "\n  exportsAccounted_of_chars data\n    {}\n    {}\n    rfl rfl (by decide +kernel)",
                lean_char_lists(
                    &analysis
                        .entries
                        .iter()
                        .filter(|e| e.exported)
                        .map(|e| e.name.clone())
                        .collect::<Vec<_>>(),
                    "\n     "
                ),
                lean_char_lists(
                    &declared_uncertified(analysis)
                        .into_iter()
                        .map(|(name, _)| name)
                        .collect::<Vec<_>>(),
                    "\n     "
                ),
            )
        },
        capabilities = lean_char_pairs(&analysis.module_envelope.capabilities),
    );
    // With a declared layout the helper types are read from it. The
    // definitions that `match` on the decoded type section are unfolded by
    // their unconditional equations with matcher reduction off, so the type
    // section is read only through its cut, in the kernel: `simp` with the
    // definitions themselves evaluates the whole type decode in the
    // elaborator first (btc-listener: over 10 minutes per theorem).
    // With a declared layout every conjunct of the rest is its own
    // declaration (`rest_parts`), joined by `plansAcceptedRestL_of_parts`:
    // one kernel check over all of them keeps every conjunct's terms alive
    // until the last one ends (btc-listener: 367 s and 15 GB as one
    // declaration, 80 s and at most 9 GB as its parts).
    let rest_proof = if layout {
        "(AverCert.DeclaredLayout.plansAcceptedRest_of_layout layout_ok\n    \
         (AverCert.DeclaredLayout.plansAcceptedRestL_of_parts rest_indices rest_types rest_data\n      \
         rest_roles rest_eqref rest_newtypes rest_inhabited rest_cons rest_helpers))"
    } else {
        "(by decide +kernel)"
    };
    let rest_parts = rest_parts(layout, data_blocks);
    // With a declared layout the helper calls behind the contracts are read
    // from the role bits every plan's declaration pins (`plans_roles`)
    // instead of lowering every plan again.
    // The obligations' policy answers are stated in blocks
    // (`ScaleTables.checkedBits_of_pols`), so no declaration computes every
    // obligation's call group.
    let (axes_blocks, axes_files) = if layout {
        render_axes_blocks(analysis, split)
    } else {
        (String::new(), Vec::new())
    };
    let axes_proof = if layout {
        "\n  AverCert.ScaleLayout.checked_of_bits plans_roles\n    \
         (AverCert.ScaleTables.checkedBits_of_pols axes_pols (by decide +kernel))"
    } else {
        " by decide +kernel"
    };
    let rest = format!(
        "theorem plans_ok : plansAccepted data = true :=\n  \
           plansAccepted_of_parts data plans_all {rest_proof}\n\n\
         {roles_proof}\n\n\
         {axes_blocks}\
         theorem axes_ok : AverCert.ClaimAxes.checked data = true :={axes_proof}\n\n"
    );
    let tail = "theorem whole_ok : acceptedWholeModule data :=\n  \
           ⟨framing_ok, exports_ok, imports_ok, start_ok, closure_ok⟩\n\n\
         theorem envelope_ok : artifactEnvelopeAccepted AverCert.ArtifactComponentBytes.componentBytes\n    \
           AverCert.ArtifactComponentBytes.componentLen data = true := by decide +kernel\n\n\
         end AverCert.Artifact\n";
    let base_imports =
        "import AcceptedArtifact\nimport DeclaredLayout\nimport ArtifactBytes\nimport Manifest\n";
    if !splits_artifact_modules(analysis) {
        let rest_all: String = rest_parts.iter().map(|(_, body)| body.as_str()).collect();
        return vec![(
            "Artifact.lean".to_string(),
            format!(
                "-- The artifact data and the byte facts of its acceptance, each by\n\
                 -- `decide +kernel` against the checker-staged `ArtifactBytes`.\n\
                 {base_imports}\
                 import ArtifactPlans\n\
                 {layout_import}\
                 {roles_import}\n\
                 {ARTIFACT_HEADER}\
                 {data}{rest_all}{rest}{strings}{exports}{closure_ok}{tail}"
            ),
        )];
    }
    let part = |comment: &str, imports: &str, body: &str| {
        format!(
            "-- {comment}\n\
             import ArtifactData\n\
             {imports}\n\
             {ARTIFACT_HEADER}\
             {body}\
             end AverCert.Artifact\n"
        )
    };
    // The parts of the rest, grouped into modules: the heavy ones alone, so
    // that each builds in a process of its own (and in parallel with more
    // than one Lake worker), the light ones together.
    let mut rest_modules: Vec<(String, String)> = Vec::new();
    for (module, body) in &rest_parts {
        match rest_modules.iter_mut().find(|(name, _)| name == module) {
            Some((_, text)) => text.push_str(body),
            None => rest_modules.push((module.to_string(), body.clone())),
        }
    }
    let axes_imports: String = axes_files
        .iter()
        .map(|(name, _)| format!("import {}\n", name.trim_end_matches(".lean")))
        .collect();
    let rest_imports: String = rest_modules
        .iter()
        .map(|(module, _)| format!("import {module}\n"))
        .collect();
    let mut files = vec![
        (
            "ArtifactData.lean".to_string(),
            format!(
                "-- The artifact data the byte facts speak about.\n\
                 {base_imports}\n\
                 {ARTIFACT_HEADER}\
                 {data}\
                 end AverCert.Artifact\n"
            ),
        ),
        (
            "ArtifactStrings.lean".to_string(),
            part("The String helper roles, decoded from the module.", layout_import, &strings),
        ),
        (
            "ArtifactClosure.lean".to_string(),
            part(
                "The certified closure's isolation.",
                &format!(
                    "{layout_import}{}",
                    closure_files
                        .iter()
                        .map(|(name, _)| format!("import {}\n", name.trim_end_matches(".lean")))
                        .collect::<String>()
                ),
                closure_ok,
            ),
        ),
        (
            "ArtifactInterface.lean".to_string(),
            part(
                "The module's framing, exports, imports and start function.",
                // The export accounting is read from the plan checks.
                &format!("{layout_import}import ArtifactPlans\n"),
                &exports,
            ),
        ),
        (
            "Artifact.lean".to_string(),
            format!(
                "-- The remaining byte facts of the artifact's acceptance, joined with\n\
                 -- the ones proved in the modules imported below.\n\
                 import ArtifactData\n\
                 import ArtifactStrings\n\
                 import ArtifactClosure\n\
                 import ArtifactInterface\n\
                 import ArtifactPlans\n\
                 {rest_imports}\
                 {axes_imports}\
                 {roles_import}\n\
                 {ARTIFACT_HEADER}\
                 {rest}{tail}"
            ),
        ),
    ];
    files.extend(closure_files);
    files.extend(axes_files);
    for (module, body) in rest_modules {
        files.push((
            format!("{module}.lean"),
            part(
                "Conjuncts of the plans' acceptance other than the per-plan checks.",
                &format!(
                    "import {}\nimport SortedKeys\nimport ScaleTables\n",
                    layout_facts_module(analysis)
                ),
                &body,
            ),
        ));
    }
    files
}

/// Obligations whose policy answers are stated per declaration.
const AXES_BLOCK: usize = 64;

/// Axes blocks per module of a split package.
const AXES_BLOCKS_PER_MODULE: usize = 4;

/// Each obligation's policy answers (`ScaleTables.polOf`: total, and total
/// with the `mul` role), [`AXES_BLOCK`] obligations per declaration, joined
/// into `axes_pols`. Returns the text that goes before `axes_ok` in its
/// module, and the block modules of a split package.
fn render_axes_blocks(analysis: &Analysis, split: bool) -> (String, Vec<(String, String)>) {
    const OBL: &str = "AverCert.manifest.obligations";
    const POL: &str = "AverCert.ScaleTables.polOf";
    let pols: Vec<String> = analysis
        .certified
        .iter()
        .map(|c| format!("({}, {})", c.total, c.total_mul))
        .collect();
    let blocks: Vec<&[String]> = pols.chunks(AXES_BLOCK).collect();
    let last = blocks.len().saturating_sub(1);
    let texts: Vec<String> = blocks
        .iter()
        .enumerate()
        .map(|(b, block)| {
            let k = b * AXES_BLOCK;
            let lhs = if b == last {
                format!("({OBL}.drop {k}).map {POL}")
            } else {
                format!("(({OBL}.drop {k}).take {AXES_BLOCK}).map {POL}")
            };
            format!(
                "def axesPols_{b} : List (Bool × Bool) :=\n  [{}]\n\n\
                 theorem pols_block_{b} : {lhs} = axesPols_{b} := by\n  \
                 decide +kernel\n\n",
                block.join(", ")
            )
        })
        .collect();
    let join = if blocks.is_empty() {
        format!(
            "def axesPols : List (Bool × Bool) := []\n\n\
             theorem axes_pols : ({OBL}.drop 0).map {POL} = axesPols := by\n  \
             decide +kernel\n\n"
        )
    } else {
        let names: Vec<String> = (0..blocks.len()).map(|b| format!("axesPols_{b}")).collect();
        let mut proof = format!("pols_block_{last}");
        for b in (0..last).rev() {
            proof = format!("AverCert.ScaleTables.pols_cons pols_block_{b}\n    ({proof})");
        }
        format!(
            "-- Every obligation's policy answers: total, and total with the `mul`\n\
             -- role, stated a block of obligations at a time.\n\
             def axesPols : List (Bool × Bool) :=\n  {}\n\n\
             theorem axes_pols : ({OBL}.drop 0).map {POL} = axesPols :=\n  {proof}\n\n",
            right_nested(&names)
        )
    };
    if !split {
        return (format!("{}{join}", texts.concat()), Vec::new());
    }
    let files = texts
        .chunks(AXES_BLOCKS_PER_MODULE)
        .enumerate()
        .map(|(m, chunk)| {
            (
                format!("ArtifactAxes{m}.lean"),
                format!(
                    "-- Blocks of the obligations' policy answers (`Artifact.axes_pols`).\n\
                     import Manifest\n\
                     import ScaleTables\n\n\
                     set_option maxRecDepth 200000\n\n\
                     namespace AverCert.Artifact\n\n\
                     {}\
                     end AverCert.Artifact\n",
                    chunk.concat()
                ),
            )
        })
        .collect();
    (join, files)
}

/// Callee lists checked per declaration of the closure.
const CLOSURE_BLOCK: usize = 64;

/// Closure blocks per module of a split package.
const CLOSURE_BLOCKS_PER_MODULE: usize = 4;

/// The closure's declared callee lists: every function the closure fold
/// scans, in the order it meets them, with its direct callees. Each block of
/// [`CLOSURE_BLOCK`] lists is one declaration that checks them against the
/// functions' code on their chunk windows (`ScaleClosure.calleesOk`); the
/// blocks are joined right-nested into `closureCallees` and `closure_callees`.
/// Returns the text that goes before `closure_ok` in its module, and the
/// block modules of a split package (empty otherwise, the blocks then being
/// part of the text).
fn render_closure_blocks(analysis: &Analysis, split: bool) -> (String, Vec<(String, String)>) {
    let scans = &analysis.module_envelope.closure_scans;
    let blocks: Vec<&[(u32, Vec<u32>)]> = if scans.is_empty() {
        vec![&[]]
    } else {
        scans.chunks(CLOSURE_BLOCK).collect()
    };
    let block_text = |b: usize, block: &[(u32, Vec<u32>)]| {
        let items = block
            .iter()
            .map(|(func, callees)| {
                format!(
                    "({func}, [{}])",
                    callees
                        .iter()
                        .map(u32::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect::<Vec<_>>()
            .join(",\n   ");
        format!(
            "def closureCallees_{b} : List (Nat × List Nat) :=\n  [{items}]\n\n\
             theorem closure_block_{b} : AverCert.ScaleClosure.calleesOk AverCert.ArtifactBytes.chunks\n    \
             layout closureCallees_{b} = true := by\n  \
             decide +kernel\n\n"
        )
    };
    let texts: Vec<String> = blocks
        .iter()
        .enumerate()
        .map(|(b, block)| block_text(b, block))
        .collect();
    let names: Vec<String> = (0..blocks.len()).map(|b| format!("closureCallees_{b}")).collect();
    let mut proof = format!("closure_block_{}", blocks.len() - 1);
    for b in (0..blocks.len() - 1).rev() {
        proof = format!("AverCert.ScaleClosure.calleesOk_append closure_block_{b}\n    ({proof})");
    }
    let join = format!(
        "-- Every function the closure fold scans, in the order it meets them, with\n\
         -- its direct callees: producer data, each list checked against its\n\
         -- function's code above.\n\
         def closureCallees : List (Nat × List Nat) :=\n  {}\n\n\
         theorem closure_callees : AverCert.ScaleClosure.calleesOk AverCert.ArtifactBytes.chunks\n    \
         layout closureCallees = true :=\n  {proof}\n\n",
        right_nested(&names)
    );
    if !split {
        return (format!("{}{join}", texts.concat()), Vec::new());
    }
    let files = texts
        .chunks(CLOSURE_BLOCKS_PER_MODULE)
        .enumerate()
        .map(|(m, chunk)| {
            (
                format!("ArtifactClosure{m}.lean"),
                format!(
                    "-- Blocks of the closure's declared callee lists (`ArtifactClosure`).\n\
                     import ArtifactLayout\n\
                     import ScaleClosure\n\n\
                     set_option maxRecDepth 200000\n\n\
                     namespace AverCert.Artifact\n\
                     open AverCert.DeclaredLayout\n\n\
                     {}\
                     end AverCert.Artifact\n",
                    chunk.concat()
                ),
            )
        })
        .collect();
    (join, files)
}

/// The conjuncts of `DeclaredLayout.plansAcceptedRestL`, one declaration
/// each, with the module a split package proves it in. Empty without a
/// declared layout, where the rest is decided whole. The helper types and
/// the type table read the type section through its cut: the definitions
/// that `match` on the decoded section are unfolded by their unconditional
/// equations with matcher reduction off, so `simp` does not evaluate the
/// whole type decode in the elaborator before the cut can rewrite it
/// (btc-listener: over 10 minutes per theorem).
fn rest_parts(layout: bool, data_blocks: Option<&str>) -> Vec<(&'static str, String)> {
    if !layout {
        return Vec::new();
    }
    const BYTES: &str = "AverCert.ArtifactBytes.modBytes AverCert.ArtifactBytes.modLen";
    const DECLS: &str = "AverCert.manifest.subject AverCert.manifest.types AverCert.manifest.fnPlans";
    const TYPES_PLANS: &str = "AverCert.manifest.types AverCert.manifest.fnPlans";
    let m = format!("(AverCert.TypeTable.mctxOf {DECLS})");
    vec![
        (
            "ArtifactRest",
            format!(
                "theorem rest_indices : indicesDistinct {m} AverCert.manifest.fnPlans = true :=\n  \
                 AverCert.SortedKeys.indicesDistinct_of_bits (by decide +kernel)\n\n"
            ),
        ),
        (
            "ArtifactRestTypes",
            // The rec group's entries are read on their own windows by index
            // (`ScaleTables.typeTableConfirmed_of_layout`), and the carrier
            // state from the type section read by index.
            format!(
                "theorem rest_types : AverCert.TypeTable.typeTableConfirmed {BYTES}\n    \
                 {DECLS} = true :=\n  \
                 AverCert.ScaleTables.typeTableConfirmed_of_layout bytes_eq chunks_fit types_head\n    \
                 types_walk types_tiled rec_tiled rec_subs types_single (by decide +kernel)\n\n"
            ),
        ),
        (
            "ArtifactRestData",
            // The data section in blocks when every segment is passive (see
            // `render_data_blocks`); otherwise decided whole, which declines.
            match data_blocks {
                Some(text) => text.to_string(),
                None => format!(
                    "theorem rest_data : AverCert.TypeTable.dataConfirmed {BYTES}\n    \
                     {DECLS} = true := by\n  \
                     decide +kernel\n\n"
                ),
            },
        ),
        (
            "ArtifactRestRoles",
            format!(
                "theorem rest_roles : AverCert.DeclaredLayout.roleTypesPinnedL layout {BYTES}\n    \
                 {m} = true := by\n  \
                 simp -iota only [AverCert.DeclaredLayout.roleTypesPinnedL,\n    \
                 AverCert.DeclaredLayout.roleTypePinnedL, type_matches]\n  \
                 decide +kernel\n\n"
            ),
        ),
        (
            "ArtifactRest",
            format!(
                "theorem rest_eqref : AverCert.TypeTable.eqrefConfined {TYPES_PLANS} = true := by\n  \
                 decide +kernel\n\n\
                 theorem rest_newtypes : AverCert.TypeTable.newtypesGrounded AverCert.manifest.types = true := by\n  \
                 decide +kernel\n\n\
                 theorem rest_inhabited : AverCert.TypeTable.typesInhabited {m}\n    \
                 {TYPES_PLANS} = true := by\n  \
                 decide +kernel\n\n\
                 theorem rest_cons : AverCert.AcceptedArtifact.consPinned {TYPES_PLANS} = true := by\n  \
                 decide +kernel\n\n"
            ),
        ),
        (
            "ArtifactRestHelpers",
            format!(
                "theorem rest_helpers : AverCert.DeclaredLayout.listHelpersPinnedL layout {BYTES}\n    \
                 {m} = true := by\n  \
                 simp -iota only [AverCert.DeclaredLayout.listHelpersPinnedL,\n    \
                 AverCert.AcceptedArtifact.listHelpersPinnedWith, AverCert.DeclaredLayout.roleTypePinnedL,\n    \
                 type_matches]\n  \
                 decide +kernel\n\n"
            ),
        ),
    ]
}

fn render_final() -> String {
    format!(
        "import Artifact\nimport AcceptanceSoundness\n\n\
         open AverCert AverCert.Schema\n\n\
         /-- THE certificate theorem: every certified export's emitted function\n\
         simulates its plan's model, from the acceptance's byte facts. -/\n\
         {FINAL_STATEMENT_LINE} :=\n  \
         AcceptanceSoundness.accept_sound CertModule.wasmSha256 AverCert.Artifact.data\n    \
         rfl rfl rfl rfl AverCert.Artifact.plans_ok\n\n\
         #print axioms {FINAL_THEOREM}\n"
    )
}

fn render_artifact_certificate() -> String {
    "import Artifact\nimport Final\nimport ArtifactReports\n\n\
     namespace AverCert.Artifact\n\n\
     theorem certificate : AverCert.AcceptedArtifact.accepted data :=\n  \
     ⟨AverCert.Final.cert, envelope_ok, rfl, rfl, plans_ok, roles_ok, strings_ok, axes_ok, whole_ok⟩\n\n\
     #print axioms AverCert.Artifact.certificate\n\n\
     end AverCert.Artifact\n"
        .to_string()
}

fn json_list<T>(items: &[T], render: impl Fn(&T) -> String) -> String {
    if items.is_empty() {
        return "[]".to_string();
    }
    format!(
        "[\n{}\n  ]",
        items
            .iter()
            .map(|x| format!("    {}", render(x)))
            .collect::<Vec<_>>()
            .join(",\n")
    )
}

fn render_manifest_json(
    analysis: &Analysis,
    artifact_file_name: &str,
    sha: &str,
    target: &str,
    abi: &str,
    envelope: Option<crate::format::Wasip2ComponentEnvelopeDeclaration>,
    surfaces: &Surfaces,
) -> String {
    let laws = &surfaces.law_claims;
    let law_bridges = &surfaces.law_bridge_exports;
    let bridges = surfaces.packaged_bridges();
    let declined_bridges = &surfaces.declined_bridges;
    let any_total = analysis.certified.iter().any(|c| c.total);
    let any_partial = analysis.certified.iter().any(|c| !c.total);
    let level = match (any_partial, any_total) {
        (true, true) => "mixed L1/L3",
        (false, true) => "L3",
        _ => CERT_LEVEL,
    };
    let mut s = String::from("{\n");
    s.push_str(&format!("  \"schema_version\": {CERT_SCHEMA_VERSION},\n"));
    s.push_str(&format!(
        "  \"format\": {{\"version\": {}, \"wall_id\": {}}},\n",
        wall::FORMAT_VERSION,
        json_str(wall::current_id())
    ));
    s.push_str(&format!("  \"wasm\": {},\n", json_str(artifact_file_name)));
    s.push_str(&format!("  \"wasm_sha256\": \"{sha}\",\n"));
    s.push_str(&format!("  \"target\": {},\n", json_str(target)));
    s.push_str(&format!("  \"level\": \"{level}\",\n"));
    s.push_str(&format!("  \"profile\": \"{PROFILE_ID}\",\n"));
    s.push_str(&format!("  \"abi\": {},\n", json_str(abi)));
    if let Some(envelope) = envelope {
        s.push_str(&format!(
            "  \"{}\": {{\"{}\": {}, \"{}\": {}, \"{}\": {}, \"{}\": {}}},\n",
            crate::format::WASIP2_COMPONENT_ENVELOPE_FIELD,
            crate::format::WASIP2_COMPONENT_ENVELOPE_KIND_FIELD,
            json_str(envelope.kind()),
            crate::format::WASIP2_COMPONENT_ENVELOPE_PREFIX_LEN_FIELD,
            envelope.prefix_len,
            crate::format::WASIP2_COMPONENT_ENVELOPE_CORE_LEN_FIELD,
            envelope.embedded_core_module_len,
            crate::format::WASIP2_COMPONENT_ENVELOPE_SUFFIX_LEN_FIELD,
            envelope.suffix_len,
        ));
    }
    s.push_str(&format!("  \"final_theorem\": \"{FINAL_THEOREM}\",\n"));
    s.push_str(&format!(
        "  \"artifact_certificate_root\": \"{ARTIFACT_CERTIFICATE_ROOT}\",\n"
    ));
    match analysis.carrier {
        Some(c) => s.push_str(&format!("  \"carrier_type_index\": {c},\n")),
        None => s.push_str("  \"carrier_type_index\": null,\n"),
    }
    s.push_str(&format!(
        "  \"runtime_contracts\": {},\n",
        json_list(&analysis.contracts, |c| json_str(c))
    ));
    // A law cites the bridges only when its bridged corollary is declared,
    // which needs every cited bridge in the package.
    let bridge_exports: Vec<&str> = bridges.iter().map(|b| b.export.as_str()).collect();
    s.push_str(&format!(
        "  \"laws\": {},\n",
        json_list(
            &laws.iter().zip(law_bridges).collect::<Vec<_>>(),
            |(claim, cited)| {
                let cited: Vec<&String> = if cited.iter().all(|e| bridge_exports.contains(&e.as_str())) {
                    cited.iter().collect()
                } else {
                    Vec::new()
                };
                format!(
                    "{{\"label\": {}, \"theorem\": {}, \"statement\": {}, \"corollary\": {}, \"bridges\": [{}]}}",
                    json_str(&claim.label),
                    json_str(&claim.qualified()),
                    json_str(&claim.statement),
                    json_str(&claim.corollary()),
                    cited.iter().map(|e| json_str(e)).collect::<Vec<_>>().join(", ")
                )
            }
        )
    ));
    s.push_str(&format!(
        "  \"sourceBridges\": {},\n",
        json_list(bridges, SourceBridge::to_json)
    ));
    s.push_str(&format!(
        "  \"sourceBridgesDeclined\": {},\n",
        json_list(declined_bridges, |(e, r)| format!(
            "{{\"export\": {}, \"reason\": {}}}",
            json_str(e),
            json_str(r)
        ))
    ));
    s.push_str(&format!(
        "  \"declaredUncertified\": {},\n",
        json_list(&declared_uncertified(analysis), |(n, r)| format!(
            "{{\"name\": {}, \"reason\": {}}}",
            json_str(n),
            json_str(r)
        ))
    ));
    s.push_str(&format!(
        "  \"capabilities\": {},\n",
        json_list(&analysis.module_envelope.capabilities, |(m, n)| format!(
            "{{\"module\": {}, \"name\": {}}}",
            json_str(m),
            json_str(n)
        ))
    ));
    match analysis.module_envelope.start {
        Some(i) => s.push_str(&format!(
            "  \"start\": {{\"present\": true, \"function_index\": {i}}},\n"
        )),
        None => s.push_str("  \"start\": {\"present\": false, \"function_index\": null},\n"),
    }
    let role = |i: Option<u32>| i.map_or_else(|| "null".to_string(), |i| i.to_string());
    match &analysis.roles {
        Some(r) => s.push_str(&format!(
            "  \"hostRoleTable\": {{\"box\": {}, \"add\": {}, \"mul\": {}, \"sub\": {}, \"toIndex\": {}, \"cmp\": {}, \"eq\": {}, \"divmod\": {}, \"bitwise\": {}}},\n",
            role(r.box_idx),
            role(r.add_idx),
            role(r.mul_idx),
            role(r.sub_idx),
            role(r.to_index_idx),
            role(r.cmp_idx),
            role(r.eq_idx),
            role(r.divmod_idx),
            role(r.bitwise_idx),
        )),
        None => s.push_str("  \"hostRoleTable\": null,\n"),
    }
    s.push_str(&format!(
        "  \"stringHostRoles\": [{}],\n",
        analysis
            .string_roles
            .iter()
            .map(|(i, r)| format!(
                "{{\"function_index\": {i}, \"role\": {}}}",
                json_str(r.manifest_value())
            ))
            .collect::<Vec<_>>()
            .join(", ")
    ));
    s.push_str(&format!(
        "  \"certified\": {},\n",
        json_list(&analysis.certified, |c| {
            let (policy, level, termination) = if c.total {
                (
                    "simulatesModelTotally",
                    "L3",
                    ", \"termination_witness\": {\"measure\": {\"kind\": \"intNatAbs\", \"param_index\": 0}, \"descent\": -1}",
                )
            } else {
                ("simulatesModel", "L1", "")
            };
            format!(
                "{{\"name\": {}, \"class\": \"{PLAN_CLASS}\", \"facets\": [{}], \"policy\": \"{policy}\", \"level\": \"{level}\", \"theorem\": \"{FN_CLAIM_DISCHARGE_THEOREM}\"{termination}}}",
                json_str(&c.name),
                c.facets.iter().map(|f| json_str(f)).collect::<Vec<_>>().join(", ")
            )
        })
    ));
    s.push_str(&format!(
        "  \"source_level_only\": {}\n",
        json_list(&analysis.declined, |(n, r)| format!(
            "{{\"name\": {}, \"reason\": {}}}",
            json_str(n),
            json_str(r)
        ))
    ));
    s.push_str("}\n");
    s
}

/// Write the artifact-specific `cert/` package: the plans, the manifest, the
/// artifact data with its byte-fact proofs, the final theorem, and the JSON
/// manifest the checker reads. Any existing `cert/` directory is replaced.
///
/// Every law-claim or source bridge the producer refused to declare comes back
/// in [`ProjectDeclines`] with its reason (the bridge list is also written to
/// the manifest as `sourceBridgesDeclined`).
pub fn write_project(
    out_dir: &Path,
    artifact: CertificateArtifact<'_>,
    analysis: &Analysis,
    model: &SourceModel,
) -> Result<ProjectDeclines, String> {
    artifact.validate()?;
    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}"))?;
    let sha = sha256_hex(artifact.delivered_bytes());
    let target = artifact.target();
    let abi = artifact.abi();
    let envelope = artifact.wasip2_component_envelope();

    // `Module.lean` (the artifact hash `Schema.Holds` reads) is not written:
    // the wall imports it, so the checker renders it from the bytes it reads.
    write(&cert_dir, "Plans.lean", &render_plans(analysis))?;
    // A package with plans declares the module layout its byte checks read.
    let layout = !analysis.entries.is_empty();
    let (decls, sites, declared_pieces, strings, data, helper_sites) = if layout {
        let LayoutParts {
            text,
            extra,
            decls,
            sites,
            walk,
            strings,
            data,
            helper_sites,
        } = render_artifact_layout(artifact.core_module_bytes(), analysis)?;
        write(&cert_dir, "ArtifactLayout.lean", &text)?;
        for (name, text) in extra {
            write(&cert_dir, &name, &text)?;
        }
        for (name, text) in render_artifact_exports(&walk) {
            write(&cert_dir, &name, &text)?;
        }
        (decls, sites, Some(walk.declared_pieces()), Some(strings), data, helper_sites)
    } else {
        (Vec::new(), Vec::new(), None, None, None, Vec::new())
    };
    write(
        &cert_dir,
        "Manifest.lean",
        &render_manifest_lean(analysis, &sha, target, abi, declared_pieces.as_deref()),
    )?;
    if let Some(params) = analysis
        .roles
        .as_ref()
        .and_then(|r| r.arith_params_record_lean(analysis.carrier))
    {
        write(
            &cert_dir,
            "ArtifactHostRoles.lean",
            &render_artifact_host_roles(analysis, &params, layout),
        )?;
    }
    for (name, text) in render_artifact_plans(analysis, &decls, &sites, layout) {
        write(&cert_dir, &name, &text)?;
    }
    for (name, text) in render_artifact(
        analysis,
        envelope,
        strings.as_deref(),
        data.as_deref(),
        &helper_sites,
    ) {
        write(&cert_dir, &name, &text)?;
    }
    write(&cert_dir, "Final.lean", &render_final())?;
    for (name, text) in render_report_blocks(analysis) {
        write(&cert_dir, &name, &text)?;
    }
    write(
        &cert_dir,
        "ArtifactCertificate.lean",
        &render_artifact_certificate(),
    )?;

    // The source model, the plan-equals-source bridges and the law-claims.
    // The model files ship only when a bridge or a law-claim speaks about
    // them: a package without either builds no model at all.
    let surfaces = plan_surfaces(analysis, model);
    if surfaces.bridge_lean.is_some() || surfaces.laws_lean.is_some() {
        for (path, content) in &surfaces.model.files {
            write_nested(&cert_dir, path, content)?;
        }
    }
    if let Some((corollaries, parts)) = &surfaces.bridge_lean {
        for (name, text) in parts {
            write(&cert_dir, name, text)?;
        }
        write(&cert_dir, "Bridge.lean", corollaries)?;
    }
    if let Some(laws_lean) = &surfaces.laws_lean {
        write(&cert_dir, "Laws.lean", laws_lean)?;
    }
    std::fs::write(
        cert_dir.join("cert-manifest.json"),
        render_manifest_json(
            analysis,
            artifact.file_name(),
            &sha,
            target,
            abi,
            envelope,
            &surfaces,
        ),
    )
    .map_err(|e| format!("write manifest: {e}"))?;
    Ok(ProjectDeclines {
        law_claims: surfaces.declined_laws,
        source_bridges: surfaces.declined_bridges,
    })
}

/// Write a model file, which may sit in a module subdirectory
/// (`Domain/Rational.lean`).
fn write_nested(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 {}: {e}", path.display()))
}

#[cfg(test)]
mod name_key_order_tests {
    use super::name_key_order;

    /// `WasmSlice.seqKey` of a name's code points, for names short enough
    /// to fit a `u128` (five 21-bit digits).
    fn seq_key(name: &str) -> u128 {
        name.chars().rev().fold(0u128, |key, c| {
            u128::from(u32::from(c)) + 1 + 2_097_152 * key
        })
    }

    /// The producer's sort order is the numeric order of the wall's keys,
    /// so a declared list it sorts passes `strictly` without a kernel sort.
    #[test]
    fn name_key_order_is_the_wall_key_order() {
        let names = [
            "", "a", "b", "z", "ab", "ba", "zz", "aaa", "_st", "size", "é", "aé", "éa", "mem",
            "__a", "abcde", "bbcde", "abcdf",
        ];
        for a in names {
            for b in names {
                assert_eq!(
                    name_key_order(a).cmp(&name_key_order(b)),
                    seq_key(a).cmp(&seq_key(b)),
                    "{a:?} vs {b:?}"
                );
            }
        }
    }
}