domainforge-core 0.19.0

Rust core library implementing the SEA DSL primitives and validation engine.
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
//! Canonical semantic envelope (reference ยง6/ยง8): every normalized semantic
//! declaration in one resolved closure, its import meaning, and the
//! application contract โ€” formatting- and comment-independent.

use crate::application::canonical::{canonical_decimal, nfc};
use crate::application::contract::*;
use crate::application::diagnostic::{ApplicationDiagnostic, ApplicationDiagnosticCode};
use crate::application::resolve::{
    Ctx, APPLICATION_CONTRACT_SCHEMA_VERSION, INTERPRETATION_VERSION, LANGUAGE_SCHEMA_VERSION,
};
use crate::concept_id::ConceptId;
use crate::module::resolver::ResolvedModuleSet;
use crate::parser::ast as past;
use crate::parser::ast_schema as schema;
use crate::semantic_pack::{canonical_json, compute_sha256};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

pub const ENVELOPE_SCHEMA_VERSION: &str = "domainforge-semantic-envelope/v1";
pub const CANONICALIZATION_VERSION: &str = "domainforge-canonicalization/v1";

// ---- reference ยง8 envelope types ----

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticEnvelopeDocument {
    pub schema_version: String,
    pub producer: ProducerIdentity,
    pub inputs: ApplicationContractInputs,
    pub self_hash: String,
    pub semantic_closure_hash: String,
    pub envelope: CanonicalSemanticEnvelope,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticEnvelope {
    pub language_schema_version: String,
    pub canonicalization_version: String,
    pub compiler_interpretation_version: String,
    pub modules: Vec<CanonicalModuleRef>,
    pub import_graph: Vec<CanonicalImportEdge>,
    pub namespace_bindings: Vec<CanonicalNamespaceBinding>,
    pub semantic_packs: Vec<CanonicalSemanticPackRef>,
    pub semantic_declarations: Vec<CanonicalSemanticDeclaration>,
    pub resolved_references: Vec<CanonicalResolvedReference>,
    pub application_contract: ApplicationContract,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalModuleRef {
    pub logical_id: String,
    pub semantic_content_hash: String,
    pub namespace: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalImportEdge {
    pub importer: String,
    pub imported: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalNamespaceBinding {
    pub namespace: String,
    pub logical_id: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticPackRef {
    pub pack_id: String,
    pub content_hash: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticDeclaration {
    pub id: CanonicalDeclarationId,
    pub logical_module_id: String,
    pub declaration: CanonicalSemanticPayload,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    content = "data",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum CanonicalDeclarationId {
    Concept {
        id: ConceptId,
    },
    Application {
        id: ApplicationSymbolId,
    },
    Occurrence {
        kind: String,
        content_hash: String,
        duplicate_index: u32,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    content = "data",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum CanonicalReferenceTarget {
    Declaration {
        id: CanonicalDeclarationId,
    },
    Namespace {
        exact_name: String,
        logical_module_id: String,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalResolvedReference {
    pub source: CanonicalDeclarationId,
    pub field_path: String,
    pub target: CanonicalReferenceTarget,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    content = "data",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum CanonicalSemanticPayload {
    Dimension(CanonicalDimensionDecl),
    Unit(CanonicalUnitDecl),
    Record(RecordContract),
    Enum(EnumContract),
    Operation(OperationContract),
    Entity(CanonicalEntityDecl),
    Resource(CanonicalResourceDecl),
    Flow(CanonicalFlowDecl),
    Pattern(CanonicalPatternDecl),
    Role(CanonicalRoleDecl),
    Relation(CanonicalRelationDecl),
    RoleBinding(CanonicalRoleBindingDecl),
    Instance(CanonicalInstanceDecl),
    Policy(CanonicalPolicyDecl),
    ConceptChange(CanonicalConceptChangeDecl),
    Metric(CanonicalMetricDecl),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalDimensionDecl {
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalUnitDecl {
    pub symbol: String,
    pub dimension: CanonicalReferenceTarget,
    pub factor: String,
    pub base_unit: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalEntityDecl {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    pub annotations: BTreeMap<String, serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contract: Option<EntityContract>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalResourceDecl {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<CanonicalReferenceTarget>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    pub annotations: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalFlowDecl {
    pub resource: CanonicalReferenceTarget,
    pub from_entity: CanonicalReferenceTarget,
    pub to_entity: CanonicalReferenceTarget,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quantity: Option<String>,
    pub annotations: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalPatternDecl {
    pub name: String,
    pub regex: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalRoleDecl {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalRelationDecl {
    pub name: String,
    pub subject_role: CanonicalReferenceTarget,
    pub predicate: String,
    pub object_role: CanonicalReferenceTarget,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub via_flow: Option<CanonicalReferenceTarget>,
}

/// A role-to-entity binding (`role_binding "Role" for "Entity"`). Unlike
/// `CanonicalRelationDecl` this declaration has no name of its own โ€” its
/// identity is the resolved (role, entity) pair.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalRoleBindingDecl {
    pub role: CanonicalReferenceTarget,
    pub entity: CanonicalReferenceTarget,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalInstanceDecl {
    pub name: String,
    pub entity_type: CanonicalReferenceTarget,
    /// Field name -> serialized normalized expression (ast-v3 schema form).
    pub fields: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalPolicyDecl {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Serialized ast-v3 schema policy metadata.
    pub metadata: serde_json::Value,
    /// Serialized ast-v3 schema expression with every `role<...>` leaf
    /// rewritten to its resolved role `ConceptId`.
    pub expression: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalConceptChangeDecl {
    pub name: String,
    pub from_version: String,
    pub to_version: String,
    pub migration_policy: String,
    pub breaking_change: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalMetricDecl {
    pub name: String,
    pub expression: serde_json::Value,
    pub metadata: serde_json::Value,
}

// ---- construction ----

const KIND_RANK: [&str; 15] = [
    "dimension",
    "unit",
    "record",
    "enum",
    "operation",
    "entity",
    "resource",
    "flow",
    "pattern",
    "role",
    "relation",
    "instance",
    "policy",
    "concept_change",
    "metric",
];

fn kind_rank(kind: &str) -> usize {
    KIND_RANK
        .iter()
        .position(|k| *k == kind)
        .unwrap_or(usize::MAX)
}

/// Resolve a reference through the shared symbol table (imports and aliases
/// included); an unresolved reference keeps deterministic local identity so
/// classification never invents a third form.
fn resolved_target(
    ctx: &Ctx,
    module_index: usize,
    namespace: &str,
    raw: &str,
    slugs: &'static [&'static str],
) -> CanonicalReferenceTarget {
    let id = ctx
        .resolve_concept(module_index, raw, slugs)
        .unwrap_or_else(|| ConceptId::from_concept(namespace, raw));
    CanonicalReferenceTarget::Declaration {
        id: CanonicalDeclarationId::Concept { id },
    }
}

/// Rewrite every `role<...>` leaf in a serialized policy expression to the
/// resolved role `ConceptId` (ยง8: envelopes carry resolved identities).
/// Unresolvable references keep their authored text; APP007 reports them at
/// binding validation.
fn rewrite_role_references(value: &mut serde_json::Value, ctx: &Ctx, module_index: usize) {
    match value {
        serde_json::Value::Object(map) => {
            if map.get("type").and_then(serde_json::Value::as_str) == Some("RoleReference") {
                if let Some(serde_json::Value::String(role)) = map.get_mut("role") {
                    if let Some(id) = ctx.resolve_concept(module_index, role, &["role"]) {
                        *role = id.to_string();
                    }
                }
            }
            for (_, nested) in map.iter_mut() {
                rewrite_role_references(nested, ctx, module_index);
            }
        }
        serde_json::Value::Array(items) => {
            for item in items {
                rewrite_role_references(item, ctx, module_index);
            }
        }
        _ => {}
    }
}

fn sorted_annotations(
    annotations: &std::collections::HashMap<String, serde_json::Value>,
) -> BTreeMap<String, serde_json::Value> {
    annotations
        .iter()
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect()
}

fn expr_value(expr: &crate::policy::Expression) -> serde_json::Value {
    serde_json::to_value(schema::Expression::from(expr)).expect("schema expression serializes")
}

/// Classify one non-export declaration. Returns `None` for realization and
/// Cell-environment declarations, which are configuration inputs excluded from
/// the envelope (ยง6). The match is exhaustive by design: a new AST variant
/// fails compilation until classified.
#[allow(clippy::too_many_lines)]
fn classify(
    node: &past::AstNode,
    namespace: &str,
    contract: &ApplicationContract,
    ctx: &Ctx,
    module_index: usize,
) -> Option<(
    &'static str,
    CanonicalDeclarationId,
    CanonicalSemanticPayload,
)> {
    use past::AstNode as N;
    let target = |raw: &str, slugs: &'static [&'static str]| {
        resolved_target(ctx, module_index, namespace, raw, slugs)
    };
    let concept_id = |name: &str| CanonicalDeclarationId::Concept {
        id: ConceptId::from_concept(namespace, name),
    };
    let app_id = |slug: &str, name: &str| CanonicalDeclarationId::Application {
        id: ApplicationSymbolId(format!("{namespace}.{slug}.{}", nfc(name))),
    };
    Some(match node {
        N::Export(_) => unreachable!("export wrappers are unwrapped before classification"),
        N::Dimension { name } => (
            "dimension",
            concept_id(name),
            CanonicalSemanticPayload::Dimension(CanonicalDimensionDecl { name: name.clone() }),
        ),
        N::UnitDeclaration {
            symbol,
            dimension,
            factor,
            base_unit,
        } => (
            "unit",
            concept_id(symbol),
            CanonicalSemanticPayload::Unit(CanonicalUnitDecl {
                symbol: symbol.clone(),
                dimension: target(dimension, &["dimension"]),
                factor: canonical_decimal(*factor),
                base_unit: base_unit.clone(),
            }),
        ),
        N::Record(decl) => {
            let id = app_id("record", &decl.name);
            let payload = contract
                .records
                .iter()
                .find(|r| matches!(&id, CanonicalDeclarationId::Application { id } if *id == r.id))?
                .clone();
            ("record", id, CanonicalSemanticPayload::Record(payload))
        }
        N::Enum(decl) => {
            let id = app_id("enum", &decl.name);
            let payload = contract
                .enums
                .iter()
                .find(|e| matches!(&id, CanonicalDeclarationId::Application { id } if *id == e.id))?
                .clone();
            ("enum", id, CanonicalSemanticPayload::Enum(payload))
        }
        N::Operation(decl) => {
            let id = app_id("operation", &decl.name);
            let payload = contract
                .operations
                .iter()
                .find(|o| matches!(&id, CanonicalDeclarationId::Application { id } if *id == o.id))?
                .clone();
            (
                "operation",
                id,
                CanonicalSemanticPayload::Operation(payload),
            )
        }
        N::Entity {
            name,
            version,
            annotations,
            domain,
            body,
        } => {
            let entity_concept = ConceptId::from_concept(namespace, name);
            let entity_contract = body.as_ref().and_then(|_| {
                contract
                    .entities
                    .iter()
                    .find(|e| e.concept_id == entity_concept)
                    .cloned()
            });
            (
                "entity",
                concept_id(name),
                CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
                    name: name.clone(),
                    version: version.clone(),
                    domain: domain.clone(),
                    annotations: sorted_annotations(annotations),
                    contract: entity_contract,
                }),
            )
        }
        N::Resource {
            name,
            annotations,
            unit_name,
            domain,
        } => (
            "resource",
            concept_id(name),
            CanonicalSemanticPayload::Resource(CanonicalResourceDecl {
                name: name.clone(),
                unit: unit_name.as_ref().map(|u| target(u, &["unit"])),
                domain: domain.clone(),
                annotations: sorted_annotations(annotations),
            }),
        ),
        N::Flow {
            resource_name,
            annotations,
            from_entity,
            to_entity,
            quantity,
        } => {
            let payload = CanonicalSemanticPayload::Flow(CanonicalFlowDecl {
                resource: target(resource_name, &["resource"]),
                from_entity: target(from_entity, &["entity"]),
                to_entity: target(to_entity, &["entity"]),
                quantity: quantity.map(canonical_decimal),
                annotations: sorted_annotations(annotations),
            });
            // duplicate_index is assigned after grouping equal payload hashes.
            let content_hash = compute_sha256(
                canonical_json(&serde_json::to_value(&payload).expect("flow serializes"))
                    .as_bytes(),
            );
            (
                "flow",
                CanonicalDeclarationId::Occurrence {
                    kind: "flow".to_string(),
                    content_hash,
                    duplicate_index: 0,
                },
                payload,
            )
        }
        N::Pattern { name, regex } => (
            "pattern",
            concept_id(name),
            CanonicalSemanticPayload::Pattern(CanonicalPatternDecl {
                name: name.clone(),
                regex: regex.clone(),
            }),
        ),
        N::Role { name, domain } => (
            "role",
            concept_id(name),
            CanonicalSemanticPayload::Role(CanonicalRoleDecl {
                name: name.clone(),
                domain: domain.clone(),
            }),
        ),
        N::Relation {
            name,
            subject_role,
            predicate,
            object_role,
            via_flow,
        } => (
            "relation",
            concept_id(name),
            CanonicalSemanticPayload::Relation(CanonicalRelationDecl {
                name: name.clone(),
                subject_role: target(subject_role, &["role"]),
                predicate: predicate.clone(),
                object_role: target(object_role, &["role"]),
                via_flow: via_flow.as_ref().map(|f| target(f, &["flow"])),
            }),
        ),
        N::RoleBinding { role, entity } => (
            "role_binding",
            // No declaration name of its own: identity is the resolved
            // (role, entity) pair, matching how the graph key's uniqueness
            // works (Graph::assign_role_to_entity is idempotent per pair).
            // Encoded as a JSON array (not raw `role:entity` interpolation)
            // so a `:` inside either name cannot make two distinct pairs
            // collide on the same id โ€” e.g. ("A:B", "C") vs ("A", "B:C").
            concept_id(&format!(
                "role_binding:{}",
                serde_json::to_string(&[role.as_str(), entity.as_str()])
                    .expect("role/entity pair serializes")
            )),
            CanonicalSemanticPayload::RoleBinding(CanonicalRoleBindingDecl {
                role: target(role, &["role"]),
                entity: target(entity, &["entity"]),
            }),
        ),
        N::Instance {
            name,
            entity_type,
            fields,
        } => (
            "instance",
            CanonicalDeclarationId::Concept {
                // Deterministic instance identity matches Graph.
                id: ConceptId::from_concept(namespace, &format!("{entity_type}:{name}")),
            },
            CanonicalSemanticPayload::Instance(CanonicalInstanceDecl {
                name: name.clone(),
                entity_type: target(entity_type, &["entity"]),
                fields: fields
                    .iter()
                    .map(|(k, v)| (k.clone(), expr_value(v)))
                    .collect(),
            }),
        ),
        N::Policy {
            name,
            version,
            metadata,
            expression,
        } => {
            let mut expression = expr_value(expression);
            rewrite_role_references(&mut expression, ctx, module_index);
            (
                "policy",
                concept_id(name),
                CanonicalSemanticPayload::Policy(CanonicalPolicyDecl {
                    name: name.clone(),
                    version: version.clone(),
                    metadata: serde_json::to_value(schema::PolicyMetadata::from(metadata))
                        .expect("policy metadata serializes"),
                    expression,
                }),
            )
        }
        N::ConceptChange {
            name,
            from_version,
            to_version,
            migration_policy,
            breaking_change,
        } => (
            "concept_change",
            concept_id(name),
            CanonicalSemanticPayload::ConceptChange(CanonicalConceptChangeDecl {
                name: name.clone(),
                from_version: from_version.clone(),
                to_version: to_version.clone(),
                migration_policy: migration_policy.clone(),
                breaking_change: *breaking_change,
            }),
        ),
        N::Metric {
            name,
            expression,
            metadata,
        } => (
            "metric",
            concept_id(name),
            CanonicalSemanticPayload::Metric(CanonicalMetricDecl {
                name: name.clone(),
                expression: expr_value(expression),
                metadata: serde_json::to_value(schema::MetricMetadata::from(metadata))
                    .expect("metric metadata serializes"),
            }),
        ),
        // Realization/configuration declarations: excluded from the envelope
        // per ยง6; their hashes belong to the later resolution/plan lock.
        N::MappingDecl { .. }
        | N::ProjectionDecl { .. }
        | N::Cell { .. }
        | N::SystemDependency { .. }
        | N::Runtime { .. }
        | N::Tool { .. }
        | N::DependencySet { .. }
        | N::Service { .. }
        | N::Mount { .. }
        | N::Endpoint { .. }
        | N::NetworkFlow { .. }
        | N::Credential { .. } => return None,
    })
}

fn id_sort_key(id: &CanonicalDeclarationId) -> String {
    canonical_json(&serde_json::to_value(id).expect("declaration id serializes"))
}

pub(crate) fn build_envelope(
    set: &ResolvedModuleSet,
    contract: &ApplicationContract,
    semantic_packs: &[(String, String)],
) -> CanonicalSemanticEnvelope {
    let ctx = Ctx::new(set);
    let mut declarations: Vec<(usize, CanonicalSemanticDeclaration)> = Vec::new();
    let mut namespace_bindings = Vec::new();
    let mut module_decl_hashes: Vec<(String, String, Vec<serde_json::Value>)> = Vec::new();

    for (module_index, module) in set.modules.iter().enumerate() {
        let namespace = module
            .ast
            .metadata
            .namespace
            .clone()
            .unwrap_or_else(|| module.logical_id.clone());
        namespace_bindings.push(CanonicalNamespaceBinding {
            namespace: namespace.clone(),
            logical_id: module.logical_id.clone(),
        });
        let mut module_payloads = Vec::new();
        for spanned in &module.ast.declarations {
            let node = match &spanned.node {
                past::AstNode::Export(inner) => &inner.node,
                other => other,
            };
            if let Some((kind, id, payload)) =
                classify(node, &namespace, contract, &ctx, module_index)
            {
                module_payloads.push(serde_json::to_value(&payload).expect("payload serializes"));
                declarations.push((
                    kind_rank(kind),
                    CanonicalSemanticDeclaration {
                        id,
                        logical_module_id: module.logical_id.clone(),
                        declaration: payload,
                    },
                ));
            }
        }
        module_decl_hashes.push((module.logical_id.clone(), namespace, module_payloads));
    }

    // Assign flow occurrence duplicate indexes within equal-hash groups.
    let mut occurrence_counts: BTreeMap<String, u32> = BTreeMap::new();
    for (_, decl) in &mut declarations {
        if let CanonicalDeclarationId::Occurrence {
            content_hash,
            duplicate_index,
            ..
        } = &mut decl.id
        {
            let count = occurrence_counts.entry(content_hash.clone()).or_default();
            *duplicate_index = *count;
            *count += 1;
        }
    }

    // ยง6 closure order: logical module ID first, then kind rank, then
    // canonical declaration ID โ€” authored declaration order never survives.
    declarations.sort_by(|a, b| {
        (&a.1.logical_module_id, a.0, id_sort_key(&a.1.id)).cmp(&(
            &b.1.logical_module_id,
            b.0,
            id_sort_key(&b.1.id),
        ))
    });
    let semantic_declarations: Vec<CanonicalSemanticDeclaration> =
        declarations.into_iter().map(|(_, d)| d).collect();

    module_decl_hashes.sort_by(|a, b| a.0.cmp(&b.0));
    let modules = module_decl_hashes
        .into_iter()
        .map(|(logical_id, namespace, mut payloads)| {
            // A module's semantic content hash covers its normalized payload
            // set, not authored declaration order.
            payloads.sort_by_key(canonical_json);
            CanonicalModuleRef {
                logical_id,
                semantic_content_hash: compute_sha256(
                    canonical_json(&serde_json::Value::Array(payloads)).as_bytes(),
                ),
                namespace,
            }
        })
        .collect();

    namespace_bindings.sort_by(
        |a: &CanonicalNamespaceBinding, b: &CanonicalNamespaceBinding| {
            (&a.namespace, &a.logical_id).cmp(&(&b.namespace, &b.logical_id))
        },
    );

    let mut import_graph: Vec<CanonicalImportEdge> = set
        .import_graph
        .iter()
        .map(|e| CanonicalImportEdge {
            importer: e.importer.clone(),
            imported: e.imported.clone(),
        })
        .collect();
    import_graph.sort_by(|a, b| (&a.importer, &a.imported).cmp(&(&b.importer, &b.imported)));
    import_graph.dedup();

    let mut resolved_references = collect_references(&semantic_declarations);
    resolved_references.sort_by_key(|r| {
        (
            id_sort_key(&r.source),
            r.field_path.clone(),
            canonical_json(&serde_json::to_value(&r.target).expect("target serializes")),
        )
    });

    CanonicalSemanticEnvelope {
        language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
        canonicalization_version: CANONICALIZATION_VERSION.to_string(),
        compiler_interpretation_version: INTERPRETATION_VERSION.to_string(),
        modules,
        import_graph,
        namespace_bindings,
        semantic_packs: semantic_packs
            .iter()
            .map(|(pack_id, content_hash)| CanonicalSemanticPackRef {
                pack_id: pack_id.clone(),
                content_hash: content_hash.clone(),
            })
            .collect(),
        semantic_declarations,
        resolved_references,
        application_contract: contract.clone(),
    }
}

/// Duplicate the application contract's typed reference edges for indexing
/// and audit (ยง8). Field paths are canonical schema paths, never source
/// coordinates.
fn collect_references(
    declarations: &[CanonicalSemanticDeclaration],
) -> Vec<CanonicalResolvedReference> {
    let mut refs = Vec::new();
    let mut push =
        |source: &CanonicalDeclarationId, path: String, target: CanonicalReferenceTarget| {
            refs.push(CanonicalResolvedReference {
                source: source.clone(),
                field_path: path,
                target,
            });
        };
    let field_refs =
        |source: &CanonicalDeclarationId,
         fields: &[FieldContract],
         refs: &mut dyn FnMut(&CanonicalDeclarationId, String, CanonicalReferenceTarget)| {
            for field in fields {
                let base = format!("fields.{}.field_type", field.name);
                match &field.field_type {
                    FieldType::Quantity { unit } => refs(
                        source,
                        format!("{base}.unit"),
                        CanonicalReferenceTarget::Declaration {
                            id: CanonicalDeclarationId::Concept { id: unit.clone() },
                        },
                    ),
                    FieldType::EntityRef { entity } => refs(
                        source,
                        format!("{base}.entity"),
                        CanonicalReferenceTarget::Declaration {
                            id: CanonicalDeclarationId::Concept { id: entity.clone() },
                        },
                    ),
                    FieldType::Enum { symbol } => refs(
                        source,
                        format!("{base}.symbol"),
                        CanonicalReferenceTarget::Declaration {
                            id: CanonicalDeclarationId::Application { id: symbol.clone() },
                        },
                    ),
                    FieldType::Scalar { .. } | FieldType::List { .. } => {}
                }
                for (index, constraint) in field.constraints.iter().enumerate() {
                    if let FieldConstraint::Pattern { pattern } = constraint {
                        refs(
                            source,
                            format!("fields.{}.constraints.{index}.pattern", field.name),
                            CanonicalReferenceTarget::Declaration {
                                id: CanonicalDeclarationId::Concept {
                                    id: pattern.clone(),
                                },
                            },
                        );
                    }
                }
            }
        };
    for decl in declarations {
        match &decl.declaration {
            CanonicalSemanticPayload::Record(record) => {
                field_refs(&decl.id, &record.fields, &mut push)
            }
            CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
                contract: Some(entity),
                ..
            }) => field_refs(&decl.id, &entity.fields, &mut push),
            CanonicalSemanticPayload::Operation(op) => {
                push(
                    &decl.id,
                    "input".to_string(),
                    CanonicalReferenceTarget::Declaration {
                        id: CanonicalDeclarationId::Application {
                            id: op.input.clone(),
                        },
                    },
                );
                push(
                    &decl.id,
                    "output".to_string(),
                    CanonicalReferenceTarget::Declaration {
                        id: CanonicalDeclarationId::Application {
                            id: op.output.clone(),
                        },
                    },
                );
                push(
                    &decl.id,
                    "state".to_string(),
                    CanonicalReferenceTarget::Declaration {
                        id: CanonicalDeclarationId::Concept {
                            id: op.state.clone(),
                        },
                    },
                );
                if let ActorRef::Role { role } = &op.actor {
                    push(
                        &decl.id,
                        "actor.role".to_string(),
                        CanonicalReferenceTarget::Declaration {
                            id: CanonicalDeclarationId::Concept { id: role.clone() },
                        },
                    );
                }
                if let AccessMode::PolicyGoverned { bindings } = &op.access {
                    for (index, binding) in bindings.iter().enumerate() {
                        push(
                            &decl.id,
                            format!("access.bindings.{index}.policy"),
                            CanonicalReferenceTarget::Declaration {
                                id: CanonicalDeclarationId::Concept {
                                    id: binding.policy.clone(),
                                },
                            },
                        );
                    }
                }
            }
            _ => {}
        }
    }
    refs
}

/// Resolve an in-memory source map into a validated canonical semantic
/// envelope document, or the complete deterministic diagnostic list.
/// Milestone 0 binds the empty semantic-pack set at the fixed public
/// boundary (ยง9).
pub fn resolve_semantic_envelope(
    entry_logical_path: &str,
    sources_json: &str,
) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
    resolve_semantic_envelope_with_packs(entry_logical_path, sources_json, &[])
}

/// [`resolve_semantic_envelope`] with explicit `(pack_id, content_hash)`
/// semantic-pack inputs (D10): the pack set crosses the boundary into
/// `inputs.semantic_pack_set_hash` and the envelope's `semantic_packs`.
pub fn resolve_semantic_envelope_with_packs(
    entry_logical_path: &str,
    sources_json: &str,
    semantic_packs: &[(String, String)],
) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
    use crate::module::resolver::{resolve_source_map, SourceMap};
    crate::application::resolve::enforce_source_map_budget(sources_json)?;
    let pack_set_hash = crate::application::resolve::validated_pack_set_hash(semantic_packs)?;
    let sources = SourceMap::parse_json(sources_json)?;
    let resolved = resolve_source_map(entry_logical_path, &sources)?;
    let contract = crate::application::resolve::build_contract(&resolved)?;
    let envelope = build_envelope(&resolved, &contract, semantic_packs);
    let closure_hash = semantic_closure_hash(&envelope);
    let mut doc = CanonicalSemanticEnvelopeDocument {
        schema_version: ENVELOPE_SCHEMA_VERSION.to_string(),
        producer: ProducerIdentity {
            name: "domainforge-core".to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
        },
        inputs: ApplicationContractInputs {
            source_set_hash: crate::application::canonical::source_set_hash(
                sources
                    .0
                    .iter()
                    .map(|(id, src)| (id.as_str(), src.as_str())),
            )
            .expect("duplicates already rejected"),
            semantic_pack_set_hash: pack_set_hash,
            language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
            interpretation_version: INTERPRETATION_VERSION.to_string(),
        },
        self_hash: format!("sha256:{}", "0".repeat(64)),
        semantic_closure_hash: closure_hash,
        envelope,
    };
    doc.self_hash = envelope_document_self_hash(&doc);
    Ok(doc)
}

// ---- hashing and validation ----

/// Reference ยง6 semantic-closure hash over the canonical envelope payload.
pub fn semantic_closure_hash(envelope: &CanonicalSemanticEnvelope) -> String {
    compute_sha256(
        canonical_json(&serde_json::to_value(envelope).expect("envelope serializes")).as_bytes(),
    )
}

pub fn envelope_document_self_hash(doc: &CanonicalSemanticEnvelopeDocument) -> String {
    let mut value = serde_json::to_value(doc).expect("envelope document serializes");
    value
        .as_object_mut()
        .expect("document is an object")
        .remove("self_hash");
    compute_sha256(canonical_json(&value).as_bytes())
}

pub(crate) fn is_hash(value: &str) -> bool {
    value.strip_prefix("sha256:").is_some_and(|hex| {
        hex.len() == 64
            && hex
                .chars()
                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
    })
}

fn app015(document_kind: &str, field_path: &str, message: String) -> ApplicationDiagnostic {
    let mut d = ApplicationDiagnostic::new(ApplicationDiagnosticCode::App015, message);
    d.context.document_kind = Some(document_kind.to_string());
    d.context.field_path = Some(field_path.to_string());
    d
}

/// Producer identities this implementation emits; a persisted document from
/// any other producer is APP015 at `/producer/name`.
const KNOWN_PRODUCERS: &[&str] = &["domainforge-core"];

fn validate_producer(
    diags: &mut Vec<ApplicationDiagnostic>,
    kind: &str,
    producer: &ProducerIdentity,
) {
    if !KNOWN_PRODUCERS.contains(&producer.name.as_str()) {
        diags.push(app015(
            kind,
            "/producer/name",
            format!("unknown producer '{}'", producer.name),
        ));
    }
    if producer.version.trim().is_empty() {
        diags.push(app015(
            kind,
            "/producer/version",
            "producer version is empty".to_string(),
        ));
    }
}

fn validate_inputs(
    diags: &mut Vec<ApplicationDiagnostic>,
    kind: &str,
    inputs: &ApplicationContractInputs,
) {
    for (path, value) in [
        ("/inputs/source_set_hash", &inputs.source_set_hash),
        (
            "/inputs/semantic_pack_set_hash",
            &inputs.semantic_pack_set_hash,
        ),
    ] {
        if !is_hash(value) {
            diags.push(app015(
                kind,
                path,
                format!("'{value}' is not a lowercase sha256:<hex> hash"),
            ));
        }
    }
    if inputs.language_schema_version != LANGUAGE_SCHEMA_VERSION {
        let mut d = app015(
            kind,
            "/inputs/language_schema_version",
            format!(
                "expected language_schema_version '{}', got '{}'",
                LANGUAGE_SCHEMA_VERSION, inputs.language_schema_version
            ),
        );
        d.context.expected = Some(LANGUAGE_SCHEMA_VERSION.to_string());
        d.context.actual = Some(inputs.language_schema_version.clone());
        diags.push(d);
    }
    if inputs.interpretation_version != INTERPRETATION_VERSION {
        let mut d = app015(
            kind,
            "/inputs/interpretation_version",
            format!(
                "expected interpretation_version '{}', got '{}'",
                INTERPRETATION_VERSION, inputs.interpretation_version
            ),
        );
        d.context.expected = Some(INTERPRETATION_VERSION.to_string());
        d.context.actual = Some(inputs.interpretation_version.clone());
        diags.push(d);
    }
}

/// Validate schema, inputs, and self-hash of a persisted application contract
/// document before use (APP015 on violation).
pub fn validate_application_contract_document_json(
    json: &str,
) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
    let kind = "application_contract";
    let doc: ApplicationContractDocument = serde_json::from_str(json)
        .map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
    let mut diags = Vec::new();
    if doc.schema_version != APPLICATION_CONTRACT_SCHEMA_VERSION {
        let mut d = app015(
            kind,
            "/schema_version",
            format!("unexpected schema_version '{}'", doc.schema_version),
        );
        d.context.schema_version = Some(doc.schema_version.clone());
        diags.push(d);
    }
    validate_producer(&mut diags, kind, &doc.producer);
    validate_inputs(&mut diags, kind, &doc.inputs);
    for (path, value) in [
        ("/self_hash", &doc.self_hash),
        ("/semantic_closure_hash", &doc.semantic_closure_hash),
    ] {
        if !is_hash(value) {
            diags.push(app015(
                kind,
                path,
                format!("'{value}' is not a lowercase sha256:<hex> hash"),
            ));
        }
    }
    if diags.is_empty() && doc.self_hash != crate::application::canonical::document_self_hash(&doc)
    {
        diags.push(app015(
            kind,
            "/self_hash",
            "self_hash does not match the canonical document bytes".to_string(),
        ));
    }
    if diags.is_empty() {
        Ok(doc)
    } else {
        Err(diags)
    }
}

/// Validate schema, inputs, and hashes of a persisted canonical semantic
/// envelope document before use (APP015 on violation).
pub fn validate_semantic_envelope_document_json(
    json: &str,
) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
    let kind = "canonical_semantic_envelope";
    let doc: CanonicalSemanticEnvelopeDocument = serde_json::from_str(json)
        .map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
    let mut diags = Vec::new();
    if doc.schema_version != ENVELOPE_SCHEMA_VERSION {
        let mut d = app015(
            kind,
            "/schema_version",
            format!("unexpected schema_version '{}'", doc.schema_version),
        );
        d.context.schema_version = Some(doc.schema_version.clone());
        diags.push(d);
    }
    validate_producer(&mut diags, kind, &doc.producer);
    validate_inputs(&mut diags, kind, &doc.inputs);
    for (path, value) in [
        ("/self_hash", &doc.self_hash),
        ("/semantic_closure_hash", &doc.semantic_closure_hash),
    ] {
        if !is_hash(value) {
            diags.push(app015(
                kind,
                path,
                format!("'{value}' is not a lowercase sha256:<hex> hash"),
            ));
        }
    }
    // Envelope metadata invariants.
    let env = &doc.envelope;
    if env.language_schema_version != doc.inputs.language_schema_version {
        diags.push(app015(
            kind,
            "/envelope/language_schema_version",
            format!(
                "envelope language_schema_version '{}' does not match inputs '{}'",
                env.language_schema_version, doc.inputs.language_schema_version
            ),
        ));
    }
    if env.compiler_interpretation_version != doc.inputs.interpretation_version {
        diags.push(app015(
            kind,
            "/envelope/compiler_interpretation_version",
            format!(
                "envelope compiler_interpretation_version '{}' does not match inputs '{}'",
                env.compiler_interpretation_version, doc.inputs.interpretation_version
            ),
        ));
    }
    if env.canonicalization_version != CANONICALIZATION_VERSION {
        diags.push(app015(
            kind,
            "/envelope/canonicalization_version",
            format!(
                "expected canonicalization_version '{}', got '{}'",
                CANONICALIZATION_VERSION, env.canonicalization_version
            ),
        ));
    }
    for (index, pack) in env.semantic_packs.iter().enumerate() {
        if pack.pack_id.is_empty() {
            diags.push(app015(
                kind,
                &format!("/envelope/semantic_packs/{index}/pack_id"),
                "semantic pack has an empty pack_id".to_string(),
            ));
        }
        if !is_hash(&pack.content_hash) {
            diags.push(app015(
                kind,
                &format!("/envelope/semantic_packs/{index}/content_hash"),
                format!(
                    "semantic pack '{}' content_hash '{}' is not a lowercase sha256:<hex> hash",
                    pack.pack_id, pack.content_hash
                ),
            ));
        }
    }
    // Cross-consistency: the persisted pack-set hash must match the packs
    // actually listed in the envelope, recomputed under the ยง6 frame.
    if diags.is_empty() {
        let pack_pairs: Vec<(String, String)> = env
            .semantic_packs
            .iter()
            .map(|p| (p.pack_id.clone(), p.content_hash.clone()))
            .collect();
        match crate::application::canonical::semantic_pack_set_hash(&pack_pairs) {
            Ok(recomputed) if recomputed == doc.inputs.semantic_pack_set_hash => {}
            Ok(recomputed) => diags.push(app015(
                kind,
                "/inputs/semantic_pack_set_hash",
                format!(
                    "semantic_pack_set_hash '{}' does not match the envelope's packs ('{}')",
                    doc.inputs.semantic_pack_set_hash, recomputed
                ),
            )),
            Err(reason) => diags.push(app015(
                kind,
                "/inputs/semantic_pack_set_hash",
                format!("semantic_pack_set_hash cannot be recomputed: {reason}"),
            )),
        }
    }
    if diags.is_empty() {
        if doc.semantic_closure_hash != semantic_closure_hash(&doc.envelope) {
            diags.push(app015(
                kind,
                "/semantic_closure_hash",
                "semantic_closure_hash does not match the canonical envelope bytes".to_string(),
            ));
        }
        if doc.self_hash != envelope_document_self_hash(&doc) {
            diags.push(app015(
                kind,
                "/self_hash",
                "self_hash does not match the canonical document bytes".to_string(),
            ));
        }
    }
    if diags.is_empty() {
        Ok(doc)
    } else {
        Err(diags)
    }
}

// ---- CEP-0008 semantic snapshot emission (Slice 0B) ----

/// ยง5.2.1: every sxr snapshot Representation MUST carry these known omissions.
pub const CEP_SNAPSHOT_KNOWN_OMISSIONS: [&str; 3] = [
    "source_comments",
    "source_formatting",
    "source_line_positions",
];

/// ยง5.2.1 reason text for the mandatory representation omission record.
pub const CEP_SNAPSHOT_OMISSION_REASON: &str =
    "domainforge canonical envelope is formatting- and comment-independent by construction";

/// ยง5.2.1 recoverable-from text for the mandatory representation omission record.
pub const CEP_SNAPSHOT_OMISSION_RECOVERABLE_FROM: &str =
    "the .sea sources at the recorded git blob hashes";

/// CEP envelope version emitted by DomainForge (spec ยง5.4 table).
pub const CEP_ENVELOPE_VERSION: &str = "1.0.0";

/// CEP envelope kind for resolved semantic closures (spec ยง5.3b).
pub const CEP_ENVELOPE_KIND_SEMANTIC_SNAPSHOT: &str = "semantic_snapshot";

/// Producer name used in emitted CEP envelopes (spec ยง5.4 `created_by`).
pub const CEP_PRODUCER_NAME: &str = "domainforge";

/// CEP version declared by DomainForge emissions.
pub const CEP_VERSION: &str = "0.1.0";

/// Deterministic inputs for [`build_cep_envelope`]. `doc` is present exactly
/// when the declared model produced a canonical D; on the failure path the
/// checkpoint hash and diagnostics carry the ยง14.4 failure identity.
pub struct CepEnvelopeParams<'a> {
    pub doc: Option<&'a CanonicalSemanticEnvelopeDocument>,
    pub model_valid: bool,
    pub source_set_hash: &'a str,
    pub invalid_declared_checkpoint_hash: Option<&'a str>,
    pub diagnostics: &'a [String],
    pub scope: serde_json::Value,
    pub entry_logical_path: &'a str,
    pub inline_threshold_bytes: u64,
    pub envelope_id: &'a str,
    pub created_at: &'a str,
    pub registry_content_hash: Option<&'a str>,
    pub resolved_namespaces: &'a [(String, String)],
    /// Opt-in world binding (GodSpeed `semantic_snapshot` profile). `None`
    /// leaves the emission exactly as before.
    pub world: Option<CepWorldParams<'a>>,
}

/// Names for the semantic world a snapshot describes. The `world_ref` itself
/// is derived from the model's DomainModelIdentity; it is never supplied.
#[derive(Debug, Clone, Copy)]
pub struct CepWorldParams<'a> {
    pub name: &'a super::world::WorldName,
    pub alias: Option<&'a super::world::WorldAlias>,
    pub label: Option<&'a super::world::WorldLabel>,
}

/// Profile declared at `extensions["cep.profile"]` (CEP-0008 ยง18.2).
pub const CEP_PROFILE_SEMANTIC_SNAPSHOT: &str = "godspeed.semantic_snapshot";
pub const CEP_PROFILE_VERSION: &str = "1.0.0";

/// Build the CEP-0008 canonical full-profile `semantic_snapshot` envelope for
/// one DomainForge emission (spec ยง5.2/ยง5.4/ยง10.7a/ยง14.4). Pure and
/// deterministic given inputs; the CLI supplies a fresh `envelope_id` and
/// `created_at` per emission (I-DET: only those two fields vary across runs).
pub fn build_cep_envelope(p: &CepEnvelopeParams<'_>) -> serde_json::Value {
    let created_by = format!("{} {}", CEP_PRODUCER_NAME, env!("CARGO_PKG_VERSION"));
    let source_set_ref = format!("source-set:{}", p.source_set_hash);

    let mut known_omissions: Vec<String> = CEP_SNAPSHOT_KNOWN_OMISSIONS
        .iter()
        .map(|s| s.to_string())
        .collect();
    if p.doc.is_none() {
        known_omissions.push("canonical_representation_D".to_string());
    }
    let included_sections: Vec<&str> = if p.doc.is_some() {
        vec!["representations", "references", "provenance"]
    } else {
        vec!["omissions", "references", "provenance"]
    };

    let mut envelope = serde_json::Map::new();
    envelope.insert("envelope_id".to_string(), serde_json::json!(p.envelope_id));
    envelope.insert("cep_version".to_string(), serde_json::json!(CEP_VERSION));
    envelope.insert(
        "envelope_version".to_string(),
        serde_json::json!(CEP_ENVELOPE_VERSION),
    );
    envelope.insert(
        "envelope_kind".to_string(),
        serde_json::json!(CEP_ENVELOPE_KIND_SEMANTIC_SNAPSHOT),
    );
    envelope.insert("created_at".to_string(), serde_json::json!(p.created_at));
    envelope.insert("created_by".to_string(), serde_json::json!(created_by));
    // A world is pinned only when the model is valid and a canonical D exists; an
    // invalid world must not masquerade as one (it is flagged below instead).
    let pinned = match (p.world, p.doc) {
        (Some(world), Some(doc)) if p.model_valid => {
            let identity = DomainModelIdentity::from_document(doc, p.registry_content_hash);
            super::world::WorldRef::from_identity(world.name.clone(), &identity)
                .ok()
                .map(|world_ref| (world, identity, world_ref))
        }
        _ => None,
    };
    let mut scope = p.scope.clone();
    if let (Some((world, _, world_ref)), Some(object)) = (&pinned, scope.as_object_mut()) {
        object.insert(
            "world_ref".to_string(),
            serde_json::json!(world_ref.to_string()),
        );
        if let Some(alias) = world.alias {
            object.insert(
                "world_alias".to_string(),
                serde_json::json!(alias.to_string()),
            );
        }
        if let Some(label) = world.label {
            object.insert("world_label".to_string(), serde_json::json!(label.as_str()));
        }
    }
    envelope.insert("scope".to_string(), scope);
    envelope.insert(
        "boundary_record".to_string(),
        serde_json::json!({
            "scope": p.entry_logical_path,
            "included_sections": included_sections,
            "excluded_sections": [],
            "known_omissions": known_omissions,
            "unknowns": [],
            "redactions": [],
            "compression_notes": [],
            "out_of_scope_entities": [],
            "limitations": [],
        }),
    );
    envelope.insert(
        "completeness_status".to_string(),
        serde_json::json!(if p.doc.is_some() {
            "complete_for_declared_state"
        } else {
            "incomplete_for_declared_state"
        }),
    );
    envelope.insert(
        "provenance_refs".to_string(),
        serde_json::json!([source_set_ref]),
    );
    envelope.insert(
        "omission_status".to_string(),
        serde_json::json!("known_omissions_recorded"),
    );
    envelope.insert("lineage_refs".to_string(), serde_json::json!([]));

    // ยง15.1 provenance section: this envelope's own production provenance.
    envelope.insert(
        "provenance".to_string(),
        serde_json::json!([{
            "provenance_id": format!("provenance:{}", p.envelope_id),
            "source_system_refs": [format!("source-set:{}", p.source_set_hash)],
            "producer_refs": [created_by],
            "production_method": "domainforge envelope --emit cep",
            "created_at": p.created_at,
            "verification_status": "unverified",
            "review_status": "unreviewed",
        }]),
    );

    // ยง13.1 reference record: the resolved source set this snapshot derives from.
    envelope.insert(
        "references".to_string(),
        serde_json::json!([{
            "ref_id": format!(
                "source-set:{}",
                p.source_set_hash.strip_prefix("sha256:").unwrap_or(p.source_set_hash)
            ),
            "ref_type": "source_set",
            "target_uri_or_id": p.entry_logical_path,
            "target_hash": p.source_set_hash,
            "availability_status": "available",
            "integrity_status": "verifiable",
            "scope": p.entry_logical_path,
        }]),
    );

    let mut extensions = serde_json::Map::new();
    match p.doc {
        Some(doc) => {
            envelope.insert(
                "validation_status".to_string(),
                serde_json::json!("validated"),
            );
            let representation = build_representation(p, doc, &created_by);
            envelope.insert(
                "representations".to_string(),
                serde_json::json!([representation]),
            );
            if !p.model_valid {
                extensions.insert(
                    "domainforge".to_string(),
                    serde_json::json!({
                        "model_validation_status": "invalid",
                        "diagnostics": p.diagnostics,
                    }),
                );
            }
            if let Some((_, identity, _)) = &pinned {
                envelope.insert(
                    "integrity".to_string(),
                    serde_json::json!({
                        "content_hash": identity.content_hash,
                        "semantic_hash": identity.semantic_closure_hash,
                    }),
                );
                extensions.insert(
                    "domainforge.identity".to_string(),
                    serde_json::json!({
                        "domain_model_identity": identity,
                        "semantic_closure_hash": identity.semantic_closure_hash,
                    }),
                );
            }
        }
        None => {
            // F-03: A valid failure envelope is conformant to CEP-0008,
            // with representation_unavailable omission and model status invalid.
            envelope.insert(
                "conformance_status".to_string(),
                serde_json::json!("conformant"),
            );
            envelope.insert(
                "validation_status".to_string(),
                serde_json::json!("validated"),
            );
            envelope.insert(
                "omissions".to_string(),
                serde_json::json!([{
                    "omission_id": format!(
                        "omission:representation:{}",
                        p.invalid_declared_checkpoint_hash
                            .unwrap_or_default()
                            .strip_prefix("sha256:")
                            .unwrap_or_default()
                    ),
                    "omission_type": "representation_unavailable",
                    "description": "canonical D not constructed; declared model invalid",
                    "reason": "model validation failed",
                    "known_or_suspected": "known",
                    "impact": "no semantic hash derivable",
                    "affected_entities": [p.entry_logical_path],
                }]),
            );
            extensions.insert(
                "domainforge".to_string(),
                serde_json::json!({
                    "model_validation_status": "invalid",
                    "invalid_declared_checkpoint_hash": p.invalid_declared_checkpoint_hash,
                    "diagnostics": p.diagnostics,
                }),
            );
        }
    }
    if p.world.is_some() {
        extensions.insert(
            "cep.profile".to_string(),
            serde_json::json!({
                "profile_id": CEP_PROFILE_SEMANTIC_SNAPSHOT,
                "profile_version": CEP_PROFILE_VERSION,
            }),
        );
    }
    if !extensions.is_empty() {
        envelope.insert(
            "extensions".to_string(),
            serde_json::Value::Object(extensions),
        );
    }

    serde_json::Value::Object(envelope)
}

/// ยง22 representation record for the canonical document D (spec ยง5.2/ยง10.7a).
fn build_representation(
    p: &CepEnvelopeParams<'_>,
    doc: &CanonicalSemanticEnvelopeDocument,
    created_by: &str,
) -> serde_json::Value {
    let canonical_bytes = canonical_json(&serde_json::to_value(doc).expect("document serializes"));
    let size_bytes = canonical_bytes.len() as u64;

    let inline = size_bytes <= p.inline_threshold_bytes;
    let mut representation = serde_json::Map::new();
    representation.insert(
        "representation_id".to_string(),
        serde_json::json!(format!("representation:{}", doc.self_hash)),
    );
    representation.insert(
        "representation_kind".to_string(),
        serde_json::json!("derived"),
    );
    representation.insert(
        "representation_type".to_string(),
        serde_json::json!("domainforge_semantic_envelope_document"),
    );
    representation.insert("scope".to_string(), serde_json::json!(p.entry_logical_path));
    representation.insert("source".to_string(), serde_json::json!(created_by));
    if inline {
        representation.insert(
            "inline_content".to_string(),
            serde_json::json!(canonical_bytes),
        );
    } else {
        representation.insert(
            "content_ref".to_string(),
            serde_json::json!(format!(
                "cas://sha256:{}",
                doc.self_hash
                    .strip_prefix("sha256:")
                    .unwrap_or(&doc.self_hash)
            )),
        );
    }
    representation.insert("content_hash".to_string(), serde_json::json!(doc.self_hash));
    representation.insert(
        "semantic_hash".to_string(),
        serde_json::json!(doc.semantic_closure_hash),
    );
    representation.insert(
        "content_availability".to_string(),
        serde_json::json!("available"),
    );
    representation.insert("size_bytes".to_string(), serde_json::json!(size_bytes));
    representation.insert(
        "media_type".to_string(),
        serde_json::json!("application/json"),
    );
    representation.insert(
        "preserved_entities".to_string(),
        serde_json::json!(doc
            .envelope
            .semantic_declarations
            .iter()
            .map(|declaration| declaration_entity_ref(&declaration.id))
            .collect::<Vec<_>>()),
    );
    representation.insert(
        "preserved_distinctions".to_string(),
        serde_json::json!(["declared_vs_observed", "representation_vs_reality"]),
    );
    representation.insert(
        "omission_record".to_string(),
        serde_json::json!({
            "known_omissions": CEP_SNAPSHOT_KNOWN_OMISSIONS,
            "reason": CEP_SNAPSHOT_OMISSION_REASON,
            "recoverable_from": CEP_SNAPSHOT_OMISSION_RECOVERABLE_FROM,
        }),
    );
    representation.insert(
        "provenance_record".to_string(),
        serde_json::json!({
            "producer": {
                "name": doc.producer.name,
                "version": doc.producer.version,
            },
            "inputs": {
                "source_set_hash": doc.inputs.source_set_hash,
                "semantic_pack_set_hash": doc.inputs.semantic_pack_set_hash,
                "language_schema_version": doc.inputs.language_schema_version,
                "interpretation_version": doc.inputs.interpretation_version,
            },
            "resolution_inputs": {
                "entry_logical_path": p.entry_logical_path,
                "registry_content_hash": p.registry_content_hash,
                "resolved_namespaces": p.resolved_namespaces
                    .iter()
                    .map(|(id, namespace)| (id.clone(), namespace.clone()))
                    .collect::<BTreeMap<String, String>>(),
            },
        }),
    );
    representation.insert(
        "validation_status".to_string(),
        serde_json::json!(if p.model_valid { "valid" } else { "invalid" }),
    );
    serde_json::Value::Object(representation)
}

/// Entity reference strings for one canonical declaration id.
pub fn declaration_entity_ref(id: &CanonicalDeclarationId) -> String {
    match id {
        CanonicalDeclarationId::Concept { id } => format!("concept:{}", id),
        CanonicalDeclarationId::Application { id } => format!("application:{}", id.0),
        CanonicalDeclarationId::Occurrence {
            kind,
            content_hash,
            duplicate_index,
        } => format!("occurrence:{}:{}:{}", kind, content_hash, duplicate_index),
    }
}

/// ยง14.4: deterministic identity of a declared model whose canonical D could
/// not be constructed. Field encodings are DomainForge's; the formula
/// sha256(canonical_json(8 fields)) is normative.
pub fn invalid_declared_checkpoint_hash(
    source_set_hash: &str,
    semantic_pack_set_hash: &str,
    entry_logical_path: &str,
    registry_content_hash: Option<&str>,
    resolved_namespaces: &[(String, String)],
) -> String {
    let namespaces: serde_json::Map<String, serde_json::Value> = resolved_namespaces
        .iter()
        .map(|(id, namespace)| (id.clone(), serde_json::Value::String(namespace.clone())))
        .collect();
    let payload = serde_json::json!({
        "source_set_hash": source_set_hash,
        "semantic_pack_set_hash": semantic_pack_set_hash,
        "language_schema_version": LANGUAGE_SCHEMA_VERSION,
        "interpretation_version": INTERPRETATION_VERSION,
        "producer": {
            "name": CEP_PRODUCER_NAME,
            "version": env!("CARGO_PKG_VERSION"),
        },
        "entry_logical_path": entry_logical_path,
        "registry_content_hash": registry_content_hash,
        "resolved_namespaces": namespaces,
    });
    compute_sha256(canonical_json(&payload).as_bytes())
}

/// Typed identity struct for a domain model across interface boundaries (F-04).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DomainModelIdentity {
    pub identity_scheme_version: String,
    pub producer: String,
    pub producer_version: String,
    pub language_schema_version: String,
    pub compiler_interpretation_version: String,
    pub canonicalization_version: String,
    pub source_set_hash: String,
    pub content_hash: String,
    pub semantic_closure_hash: String,
    pub semantic_pack_set_hash: Option<String>,
    pub registry_content_hash: Option<String>,
}

impl DomainModelIdentity {
    pub fn canonical_digest(&self) -> String {
        let value = serde_json::to_value(self).expect("DomainModelIdentity serializes");
        compute_sha256(canonical_json(&value).as_bytes())
    }
}