Skip to main content

domainforge_core/application/
envelope.rs

1//! Canonical semantic envelope (reference §6/§8): every normalized semantic
2//! declaration in one resolved closure, its import meaning, and the
3//! application contract — formatting- and comment-independent.
4
5use crate::application::canonical::{canonical_decimal, nfc};
6use crate::application::contract::*;
7use crate::application::diagnostic::{ApplicationDiagnostic, ApplicationDiagnosticCode};
8use crate::application::resolve::{
9    Ctx, APPLICATION_CONTRACT_SCHEMA_VERSION, INTERPRETATION_VERSION, LANGUAGE_SCHEMA_VERSION,
10};
11use crate::concept_id::ConceptId;
12use crate::module::resolver::ResolvedModuleSet;
13use crate::parser::ast as past;
14use crate::parser::ast_schema as schema;
15use crate::semantic_pack::{canonical_json, compute_sha256};
16use serde::{Deserialize, Serialize};
17use std::collections::BTreeMap;
18
19pub const ENVELOPE_SCHEMA_VERSION: &str = "domainforge-semantic-envelope/v1";
20pub const CANONICALIZATION_VERSION: &str = "domainforge-canonicalization/v1";
21
22// ---- reference §8 envelope types ----
23
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct CanonicalSemanticEnvelopeDocument {
27    pub schema_version: String,
28    pub producer: ProducerIdentity,
29    pub inputs: ApplicationContractInputs,
30    pub self_hash: String,
31    pub semantic_closure_hash: String,
32    pub envelope: CanonicalSemanticEnvelope,
33}
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct CanonicalSemanticEnvelope {
38    pub language_schema_version: String,
39    pub canonicalization_version: String,
40    pub compiler_interpretation_version: String,
41    pub modules: Vec<CanonicalModuleRef>,
42    pub import_graph: Vec<CanonicalImportEdge>,
43    pub namespace_bindings: Vec<CanonicalNamespaceBinding>,
44    pub semantic_packs: Vec<CanonicalSemanticPackRef>,
45    pub semantic_declarations: Vec<CanonicalSemanticDeclaration>,
46    pub resolved_references: Vec<CanonicalResolvedReference>,
47    pub application_contract: ApplicationContract,
48}
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct CanonicalModuleRef {
53    pub logical_id: String,
54    pub semantic_content_hash: String,
55    pub namespace: String,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct CanonicalImportEdge {
61    pub importer: String,
62    pub imported: String,
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[serde(deny_unknown_fields)]
67pub struct CanonicalNamespaceBinding {
68    pub namespace: String,
69    pub logical_id: String,
70}
71
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct CanonicalSemanticPackRef {
75    pub pack_id: String,
76    pub content_hash: String,
77}
78
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80#[serde(deny_unknown_fields)]
81pub struct CanonicalSemanticDeclaration {
82    pub id: CanonicalDeclarationId,
83    pub logical_module_id: String,
84    pub declaration: CanonicalSemanticPayload,
85}
86
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88#[serde(
89    tag = "kind",
90    content = "data",
91    rename_all = "snake_case",
92    deny_unknown_fields
93)]
94pub enum CanonicalDeclarationId {
95    Concept {
96        id: ConceptId,
97    },
98    Application {
99        id: ApplicationSymbolId,
100    },
101    Occurrence {
102        kind: String,
103        content_hash: String,
104        duplicate_index: u32,
105    },
106}
107
108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
109#[serde(
110    tag = "kind",
111    content = "data",
112    rename_all = "snake_case",
113    deny_unknown_fields
114)]
115pub enum CanonicalReferenceTarget {
116    Declaration {
117        id: CanonicalDeclarationId,
118    },
119    Namespace {
120        exact_name: String,
121        logical_module_id: String,
122    },
123}
124
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126#[serde(deny_unknown_fields)]
127pub struct CanonicalResolvedReference {
128    pub source: CanonicalDeclarationId,
129    pub field_path: String,
130    pub target: CanonicalReferenceTarget,
131}
132
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
134#[serde(
135    tag = "kind",
136    content = "data",
137    rename_all = "snake_case",
138    deny_unknown_fields
139)]
140pub enum CanonicalSemanticPayload {
141    Dimension(CanonicalDimensionDecl),
142    Unit(CanonicalUnitDecl),
143    Record(RecordContract),
144    Enum(EnumContract),
145    Operation(OperationContract),
146    Entity(CanonicalEntityDecl),
147    Resource(CanonicalResourceDecl),
148    Flow(CanonicalFlowDecl),
149    Pattern(CanonicalPatternDecl),
150    Role(CanonicalRoleDecl),
151    Relation(CanonicalRelationDecl),
152    RoleBinding(CanonicalRoleBindingDecl),
153    Instance(CanonicalInstanceDecl),
154    Policy(CanonicalPolicyDecl),
155    ConceptChange(CanonicalConceptChangeDecl),
156    Metric(CanonicalMetricDecl),
157}
158
159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
160#[serde(deny_unknown_fields)]
161pub struct CanonicalDimensionDecl {
162    pub name: String,
163}
164
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166#[serde(deny_unknown_fields)]
167pub struct CanonicalUnitDecl {
168    pub symbol: String,
169    pub dimension: CanonicalReferenceTarget,
170    pub factor: String,
171    pub base_unit: String,
172}
173
174#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
175#[serde(deny_unknown_fields)]
176pub struct CanonicalEntityDecl {
177    pub name: String,
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub version: Option<String>,
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub domain: Option<String>,
182    pub annotations: BTreeMap<String, serde_json::Value>,
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub contract: Option<EntityContract>,
185}
186
187#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
188#[serde(deny_unknown_fields)]
189pub struct CanonicalResourceDecl {
190    pub name: String,
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub unit: Option<CanonicalReferenceTarget>,
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub domain: Option<String>,
195    pub annotations: BTreeMap<String, serde_json::Value>,
196}
197
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199#[serde(deny_unknown_fields)]
200pub struct CanonicalFlowDecl {
201    pub resource: CanonicalReferenceTarget,
202    pub from_entity: CanonicalReferenceTarget,
203    pub to_entity: CanonicalReferenceTarget,
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub quantity: Option<String>,
206    pub annotations: BTreeMap<String, serde_json::Value>,
207}
208
209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
210#[serde(deny_unknown_fields)]
211pub struct CanonicalPatternDecl {
212    pub name: String,
213    pub regex: String,
214}
215
216#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct CanonicalRoleDecl {
219    pub name: String,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub domain: Option<String>,
222}
223
224#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
225#[serde(deny_unknown_fields)]
226pub struct CanonicalRelationDecl {
227    pub name: String,
228    pub subject_role: CanonicalReferenceTarget,
229    pub predicate: String,
230    pub object_role: CanonicalReferenceTarget,
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub via_flow: Option<CanonicalReferenceTarget>,
233}
234
235/// A role-to-entity binding (`role_binding "Role" for "Entity"`). Unlike
236/// `CanonicalRelationDecl` this declaration has no name of its own — its
237/// identity is the resolved (role, entity) pair.
238#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
239#[serde(deny_unknown_fields)]
240pub struct CanonicalRoleBindingDecl {
241    pub role: CanonicalReferenceTarget,
242    pub entity: CanonicalReferenceTarget,
243}
244
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246#[serde(deny_unknown_fields)]
247pub struct CanonicalInstanceDecl {
248    pub name: String,
249    pub entity_type: CanonicalReferenceTarget,
250    /// Field name -> serialized normalized expression (ast-v3 schema form).
251    pub fields: BTreeMap<String, serde_json::Value>,
252}
253
254#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
255#[serde(deny_unknown_fields)]
256pub struct CanonicalPolicyDecl {
257    pub name: String,
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub version: Option<String>,
260    /// Serialized ast-v3 schema policy metadata.
261    pub metadata: serde_json::Value,
262    /// Serialized ast-v3 schema expression with every `role<...>` leaf
263    /// rewritten to its resolved role `ConceptId`.
264    pub expression: serde_json::Value,
265}
266
267#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
268#[serde(deny_unknown_fields)]
269pub struct CanonicalConceptChangeDecl {
270    pub name: String,
271    pub from_version: String,
272    pub to_version: String,
273    pub migration_policy: String,
274    pub breaking_change: bool,
275}
276
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278#[serde(deny_unknown_fields)]
279pub struct CanonicalMetricDecl {
280    pub name: String,
281    pub expression: serde_json::Value,
282    pub metadata: serde_json::Value,
283}
284
285// ---- construction ----
286
287const KIND_RANK: [&str; 15] = [
288    "dimension",
289    "unit",
290    "record",
291    "enum",
292    "operation",
293    "entity",
294    "resource",
295    "flow",
296    "pattern",
297    "role",
298    "relation",
299    "instance",
300    "policy",
301    "concept_change",
302    "metric",
303];
304
305fn kind_rank(kind: &str) -> usize {
306    KIND_RANK
307        .iter()
308        .position(|k| *k == kind)
309        .unwrap_or(usize::MAX)
310}
311
312/// Resolve a reference through the shared symbol table (imports and aliases
313/// included); an unresolved reference keeps deterministic local identity so
314/// classification never invents a third form.
315fn resolved_target(
316    ctx: &Ctx,
317    module_index: usize,
318    namespace: &str,
319    raw: &str,
320    slugs: &'static [&'static str],
321) -> CanonicalReferenceTarget {
322    let id = ctx
323        .resolve_concept(module_index, raw, slugs)
324        .unwrap_or_else(|| ConceptId::from_concept(namespace, raw));
325    CanonicalReferenceTarget::Declaration {
326        id: CanonicalDeclarationId::Concept { id },
327    }
328}
329
330/// Rewrite every `role<...>` leaf in a serialized policy expression to the
331/// resolved role `ConceptId` (§8: envelopes carry resolved identities).
332/// Unresolvable references keep their authored text; APP007 reports them at
333/// binding validation.
334fn rewrite_role_references(value: &mut serde_json::Value, ctx: &Ctx, module_index: usize) {
335    match value {
336        serde_json::Value::Object(map) => {
337            if map.get("type").and_then(serde_json::Value::as_str) == Some("RoleReference") {
338                if let Some(serde_json::Value::String(role)) = map.get_mut("role") {
339                    if let Some(id) = ctx.resolve_concept(module_index, role, &["role"]) {
340                        *role = id.to_string();
341                    }
342                }
343            }
344            for (_, nested) in map.iter_mut() {
345                rewrite_role_references(nested, ctx, module_index);
346            }
347        }
348        serde_json::Value::Array(items) => {
349            for item in items {
350                rewrite_role_references(item, ctx, module_index);
351            }
352        }
353        _ => {}
354    }
355}
356
357fn sorted_annotations(
358    annotations: &std::collections::HashMap<String, serde_json::Value>,
359) -> BTreeMap<String, serde_json::Value> {
360    annotations
361        .iter()
362        .map(|(k, v)| (k.clone(), v.clone()))
363        .collect()
364}
365
366fn expr_value(expr: &crate::policy::Expression) -> serde_json::Value {
367    serde_json::to_value(schema::Expression::from(expr)).expect("schema expression serializes")
368}
369
370/// Classify one non-export declaration. Returns `None` for realization and
371/// Cell-environment declarations, which are configuration inputs excluded from
372/// the envelope (§6). The match is exhaustive by design: a new AST variant
373/// fails compilation until classified.
374#[allow(clippy::too_many_lines)]
375fn classify(
376    node: &past::AstNode,
377    namespace: &str,
378    contract: &ApplicationContract,
379    ctx: &Ctx,
380    module_index: usize,
381) -> Option<(
382    &'static str,
383    CanonicalDeclarationId,
384    CanonicalSemanticPayload,
385)> {
386    use past::AstNode as N;
387    let target = |raw: &str, slugs: &'static [&'static str]| {
388        resolved_target(ctx, module_index, namespace, raw, slugs)
389    };
390    let concept_id = |name: &str| CanonicalDeclarationId::Concept {
391        id: ConceptId::from_concept(namespace, name),
392    };
393    let app_id = |slug: &str, name: &str| CanonicalDeclarationId::Application {
394        id: ApplicationSymbolId(format!("{namespace}.{slug}.{}", nfc(name))),
395    };
396    Some(match node {
397        N::Export(_) => unreachable!("export wrappers are unwrapped before classification"),
398        N::Dimension { name } => (
399            "dimension",
400            concept_id(name),
401            CanonicalSemanticPayload::Dimension(CanonicalDimensionDecl { name: name.clone() }),
402        ),
403        N::UnitDeclaration {
404            symbol,
405            dimension,
406            factor,
407            base_unit,
408        } => (
409            "unit",
410            concept_id(symbol),
411            CanonicalSemanticPayload::Unit(CanonicalUnitDecl {
412                symbol: symbol.clone(),
413                dimension: target(dimension, &["dimension"]),
414                factor: canonical_decimal(*factor),
415                base_unit: base_unit.clone(),
416            }),
417        ),
418        N::Record(decl) => {
419            let id = app_id("record", &decl.name);
420            let payload = contract
421                .records
422                .iter()
423                .find(|r| matches!(&id, CanonicalDeclarationId::Application { id } if *id == r.id))?
424                .clone();
425            ("record", id, CanonicalSemanticPayload::Record(payload))
426        }
427        N::Enum(decl) => {
428            let id = app_id("enum", &decl.name);
429            let payload = contract
430                .enums
431                .iter()
432                .find(|e| matches!(&id, CanonicalDeclarationId::Application { id } if *id == e.id))?
433                .clone();
434            ("enum", id, CanonicalSemanticPayload::Enum(payload))
435        }
436        N::Operation(decl) => {
437            let id = app_id("operation", &decl.name);
438            let payload = contract
439                .operations
440                .iter()
441                .find(|o| matches!(&id, CanonicalDeclarationId::Application { id } if *id == o.id))?
442                .clone();
443            (
444                "operation",
445                id,
446                CanonicalSemanticPayload::Operation(payload),
447            )
448        }
449        N::Entity {
450            name,
451            version,
452            annotations,
453            domain,
454            body,
455        } => {
456            let entity_concept = ConceptId::from_concept(namespace, name);
457            let entity_contract = body.as_ref().and_then(|_| {
458                contract
459                    .entities
460                    .iter()
461                    .find(|e| e.concept_id == entity_concept)
462                    .cloned()
463            });
464            (
465                "entity",
466                concept_id(name),
467                CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
468                    name: name.clone(),
469                    version: version.clone(),
470                    domain: domain.clone(),
471                    annotations: sorted_annotations(annotations),
472                    contract: entity_contract,
473                }),
474            )
475        }
476        N::Resource {
477            name,
478            annotations,
479            unit_name,
480            domain,
481        } => (
482            "resource",
483            concept_id(name),
484            CanonicalSemanticPayload::Resource(CanonicalResourceDecl {
485                name: name.clone(),
486                unit: unit_name.as_ref().map(|u| target(u, &["unit"])),
487                domain: domain.clone(),
488                annotations: sorted_annotations(annotations),
489            }),
490        ),
491        N::Flow {
492            resource_name,
493            annotations,
494            from_entity,
495            to_entity,
496            quantity,
497        } => {
498            let payload = CanonicalSemanticPayload::Flow(CanonicalFlowDecl {
499                resource: target(resource_name, &["resource"]),
500                from_entity: target(from_entity, &["entity"]),
501                to_entity: target(to_entity, &["entity"]),
502                quantity: quantity.map(canonical_decimal),
503                annotations: sorted_annotations(annotations),
504            });
505            // duplicate_index is assigned after grouping equal payload hashes.
506            let content_hash = compute_sha256(
507                canonical_json(&serde_json::to_value(&payload).expect("flow serializes"))
508                    .as_bytes(),
509            );
510            (
511                "flow",
512                CanonicalDeclarationId::Occurrence {
513                    kind: "flow".to_string(),
514                    content_hash,
515                    duplicate_index: 0,
516                },
517                payload,
518            )
519        }
520        N::Pattern { name, regex } => (
521            "pattern",
522            concept_id(name),
523            CanonicalSemanticPayload::Pattern(CanonicalPatternDecl {
524                name: name.clone(),
525                regex: regex.clone(),
526            }),
527        ),
528        N::Role { name, domain } => (
529            "role",
530            concept_id(name),
531            CanonicalSemanticPayload::Role(CanonicalRoleDecl {
532                name: name.clone(),
533                domain: domain.clone(),
534            }),
535        ),
536        N::Relation {
537            name,
538            subject_role,
539            predicate,
540            object_role,
541            via_flow,
542        } => (
543            "relation",
544            concept_id(name),
545            CanonicalSemanticPayload::Relation(CanonicalRelationDecl {
546                name: name.clone(),
547                subject_role: target(subject_role, &["role"]),
548                predicate: predicate.clone(),
549                object_role: target(object_role, &["role"]),
550                via_flow: via_flow.as_ref().map(|f| target(f, &["flow"])),
551            }),
552        ),
553        N::RoleBinding { role, entity } => (
554            "role_binding",
555            // No declaration name of its own: identity is the resolved
556            // (role, entity) pair, matching how the graph key's uniqueness
557            // works (Graph::assign_role_to_entity is idempotent per pair).
558            // Encoded as a JSON array (not raw `role:entity` interpolation)
559            // so a `:` inside either name cannot make two distinct pairs
560            // collide on the same id — e.g. ("A:B", "C") vs ("A", "B:C").
561            concept_id(&format!(
562                "role_binding:{}",
563                serde_json::to_string(&[role.as_str(), entity.as_str()])
564                    .expect("role/entity pair serializes")
565            )),
566            CanonicalSemanticPayload::RoleBinding(CanonicalRoleBindingDecl {
567                role: target(role, &["role"]),
568                entity: target(entity, &["entity"]),
569            }),
570        ),
571        N::Instance {
572            name,
573            entity_type,
574            fields,
575        } => (
576            "instance",
577            CanonicalDeclarationId::Concept {
578                // Deterministic instance identity matches Graph.
579                id: ConceptId::from_concept(namespace, &format!("{entity_type}:{name}")),
580            },
581            CanonicalSemanticPayload::Instance(CanonicalInstanceDecl {
582                name: name.clone(),
583                entity_type: target(entity_type, &["entity"]),
584                fields: fields
585                    .iter()
586                    .map(|(k, v)| (k.clone(), expr_value(v)))
587                    .collect(),
588            }),
589        ),
590        N::Policy {
591            name,
592            version,
593            metadata,
594            expression,
595        } => {
596            let mut expression = expr_value(expression);
597            rewrite_role_references(&mut expression, ctx, module_index);
598            (
599                "policy",
600                concept_id(name),
601                CanonicalSemanticPayload::Policy(CanonicalPolicyDecl {
602                    name: name.clone(),
603                    version: version.clone(),
604                    metadata: serde_json::to_value(schema::PolicyMetadata::from(metadata))
605                        .expect("policy metadata serializes"),
606                    expression,
607                }),
608            )
609        }
610        N::ConceptChange {
611            name,
612            from_version,
613            to_version,
614            migration_policy,
615            breaking_change,
616        } => (
617            "concept_change",
618            concept_id(name),
619            CanonicalSemanticPayload::ConceptChange(CanonicalConceptChangeDecl {
620                name: name.clone(),
621                from_version: from_version.clone(),
622                to_version: to_version.clone(),
623                migration_policy: migration_policy.clone(),
624                breaking_change: *breaking_change,
625            }),
626        ),
627        N::Metric {
628            name,
629            expression,
630            metadata,
631        } => (
632            "metric",
633            concept_id(name),
634            CanonicalSemanticPayload::Metric(CanonicalMetricDecl {
635                name: name.clone(),
636                expression: expr_value(expression),
637                metadata: serde_json::to_value(schema::MetricMetadata::from(metadata))
638                    .expect("metric metadata serializes"),
639            }),
640        ),
641        // Realization/configuration declarations: excluded from the envelope
642        // per §6; their hashes belong to the later resolution/plan lock.
643        N::MappingDecl { .. }
644        | N::ProjectionDecl { .. }
645        | N::Cell { .. }
646        | N::SystemDependency { .. }
647        | N::Runtime { .. }
648        | N::Tool { .. }
649        | N::DependencySet { .. }
650        | N::Service { .. }
651        | N::Mount { .. }
652        | N::Endpoint { .. }
653        | N::NetworkFlow { .. }
654        | N::Credential { .. } => return None,
655    })
656}
657
658fn id_sort_key(id: &CanonicalDeclarationId) -> String {
659    canonical_json(&serde_json::to_value(id).expect("declaration id serializes"))
660}
661
662pub(crate) fn build_envelope(
663    set: &ResolvedModuleSet,
664    contract: &ApplicationContract,
665    semantic_packs: &[(String, String)],
666) -> CanonicalSemanticEnvelope {
667    let ctx = Ctx::new(set);
668    let mut declarations: Vec<(usize, CanonicalSemanticDeclaration)> = Vec::new();
669    let mut namespace_bindings = Vec::new();
670    let mut module_decl_hashes: Vec<(String, String, Vec<serde_json::Value>)> = Vec::new();
671
672    for (module_index, module) in set.modules.iter().enumerate() {
673        let namespace = module
674            .ast
675            .metadata
676            .namespace
677            .clone()
678            .unwrap_or_else(|| module.logical_id.clone());
679        namespace_bindings.push(CanonicalNamespaceBinding {
680            namespace: namespace.clone(),
681            logical_id: module.logical_id.clone(),
682        });
683        let mut module_payloads = Vec::new();
684        for spanned in &module.ast.declarations {
685            let node = match &spanned.node {
686                past::AstNode::Export(inner) => &inner.node,
687                other => other,
688            };
689            if let Some((kind, id, payload)) =
690                classify(node, &namespace, contract, &ctx, module_index)
691            {
692                module_payloads.push(serde_json::to_value(&payload).expect("payload serializes"));
693                declarations.push((
694                    kind_rank(kind),
695                    CanonicalSemanticDeclaration {
696                        id,
697                        logical_module_id: module.logical_id.clone(),
698                        declaration: payload,
699                    },
700                ));
701            }
702        }
703        module_decl_hashes.push((module.logical_id.clone(), namespace, module_payloads));
704    }
705
706    // Assign flow occurrence duplicate indexes within equal-hash groups.
707    let mut occurrence_counts: BTreeMap<String, u32> = BTreeMap::new();
708    for (_, decl) in &mut declarations {
709        if let CanonicalDeclarationId::Occurrence {
710            content_hash,
711            duplicate_index,
712            ..
713        } = &mut decl.id
714        {
715            let count = occurrence_counts.entry(content_hash.clone()).or_default();
716            *duplicate_index = *count;
717            *count += 1;
718        }
719    }
720
721    // §6 closure order: logical module ID first, then kind rank, then
722    // canonical declaration ID — authored declaration order never survives.
723    declarations.sort_by(|a, b| {
724        (&a.1.logical_module_id, a.0, id_sort_key(&a.1.id)).cmp(&(
725            &b.1.logical_module_id,
726            b.0,
727            id_sort_key(&b.1.id),
728        ))
729    });
730    let semantic_declarations: Vec<CanonicalSemanticDeclaration> =
731        declarations.into_iter().map(|(_, d)| d).collect();
732
733    module_decl_hashes.sort_by(|a, b| a.0.cmp(&b.0));
734    let modules = module_decl_hashes
735        .into_iter()
736        .map(|(logical_id, namespace, mut payloads)| {
737            // A module's semantic content hash covers its normalized payload
738            // set, not authored declaration order.
739            payloads.sort_by_key(canonical_json);
740            CanonicalModuleRef {
741                logical_id,
742                semantic_content_hash: compute_sha256(
743                    canonical_json(&serde_json::Value::Array(payloads)).as_bytes(),
744                ),
745                namespace,
746            }
747        })
748        .collect();
749
750    namespace_bindings.sort_by(
751        |a: &CanonicalNamespaceBinding, b: &CanonicalNamespaceBinding| {
752            (&a.namespace, &a.logical_id).cmp(&(&b.namespace, &b.logical_id))
753        },
754    );
755
756    let mut import_graph: Vec<CanonicalImportEdge> = set
757        .import_graph
758        .iter()
759        .map(|e| CanonicalImportEdge {
760            importer: e.importer.clone(),
761            imported: e.imported.clone(),
762        })
763        .collect();
764    import_graph.sort_by(|a, b| (&a.importer, &a.imported).cmp(&(&b.importer, &b.imported)));
765    import_graph.dedup();
766
767    let mut resolved_references = collect_references(&semantic_declarations);
768    resolved_references.sort_by_key(|r| {
769        (
770            id_sort_key(&r.source),
771            r.field_path.clone(),
772            canonical_json(&serde_json::to_value(&r.target).expect("target serializes")),
773        )
774    });
775
776    CanonicalSemanticEnvelope {
777        language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
778        canonicalization_version: CANONICALIZATION_VERSION.to_string(),
779        compiler_interpretation_version: INTERPRETATION_VERSION.to_string(),
780        modules,
781        import_graph,
782        namespace_bindings,
783        semantic_packs: semantic_packs
784            .iter()
785            .map(|(pack_id, content_hash)| CanonicalSemanticPackRef {
786                pack_id: pack_id.clone(),
787                content_hash: content_hash.clone(),
788            })
789            .collect(),
790        semantic_declarations,
791        resolved_references,
792        application_contract: contract.clone(),
793    }
794}
795
796/// Duplicate the application contract's typed reference edges for indexing
797/// and audit (§8). Field paths are canonical schema paths, never source
798/// coordinates.
799fn collect_references(
800    declarations: &[CanonicalSemanticDeclaration],
801) -> Vec<CanonicalResolvedReference> {
802    let mut refs = Vec::new();
803    let mut push =
804        |source: &CanonicalDeclarationId, path: String, target: CanonicalReferenceTarget| {
805            refs.push(CanonicalResolvedReference {
806                source: source.clone(),
807                field_path: path,
808                target,
809            });
810        };
811    let field_refs =
812        |source: &CanonicalDeclarationId,
813         fields: &[FieldContract],
814         refs: &mut dyn FnMut(&CanonicalDeclarationId, String, CanonicalReferenceTarget)| {
815            for field in fields {
816                let base = format!("fields.{}.field_type", field.name);
817                match &field.field_type {
818                    FieldType::Quantity { unit } => refs(
819                        source,
820                        format!("{base}.unit"),
821                        CanonicalReferenceTarget::Declaration {
822                            id: CanonicalDeclarationId::Concept { id: unit.clone() },
823                        },
824                    ),
825                    FieldType::EntityRef { entity } => refs(
826                        source,
827                        format!("{base}.entity"),
828                        CanonicalReferenceTarget::Declaration {
829                            id: CanonicalDeclarationId::Concept { id: entity.clone() },
830                        },
831                    ),
832                    FieldType::Enum { symbol } => refs(
833                        source,
834                        format!("{base}.symbol"),
835                        CanonicalReferenceTarget::Declaration {
836                            id: CanonicalDeclarationId::Application { id: symbol.clone() },
837                        },
838                    ),
839                    FieldType::Scalar { .. } | FieldType::List { .. } => {}
840                }
841                for (index, constraint) in field.constraints.iter().enumerate() {
842                    if let FieldConstraint::Pattern { pattern } = constraint {
843                        refs(
844                            source,
845                            format!("fields.{}.constraints.{index}.pattern", field.name),
846                            CanonicalReferenceTarget::Declaration {
847                                id: CanonicalDeclarationId::Concept {
848                                    id: pattern.clone(),
849                                },
850                            },
851                        );
852                    }
853                }
854            }
855        };
856    for decl in declarations {
857        match &decl.declaration {
858            CanonicalSemanticPayload::Record(record) => {
859                field_refs(&decl.id, &record.fields, &mut push)
860            }
861            CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
862                contract: Some(entity),
863                ..
864            }) => field_refs(&decl.id, &entity.fields, &mut push),
865            CanonicalSemanticPayload::Operation(op) => {
866                push(
867                    &decl.id,
868                    "input".to_string(),
869                    CanonicalReferenceTarget::Declaration {
870                        id: CanonicalDeclarationId::Application {
871                            id: op.input.clone(),
872                        },
873                    },
874                );
875                push(
876                    &decl.id,
877                    "output".to_string(),
878                    CanonicalReferenceTarget::Declaration {
879                        id: CanonicalDeclarationId::Application {
880                            id: op.output.clone(),
881                        },
882                    },
883                );
884                push(
885                    &decl.id,
886                    "state".to_string(),
887                    CanonicalReferenceTarget::Declaration {
888                        id: CanonicalDeclarationId::Concept {
889                            id: op.state.clone(),
890                        },
891                    },
892                );
893                if let ActorRef::Role { role } = &op.actor {
894                    push(
895                        &decl.id,
896                        "actor.role".to_string(),
897                        CanonicalReferenceTarget::Declaration {
898                            id: CanonicalDeclarationId::Concept { id: role.clone() },
899                        },
900                    );
901                }
902                if let AccessMode::PolicyGoverned { bindings } = &op.access {
903                    for (index, binding) in bindings.iter().enumerate() {
904                        push(
905                            &decl.id,
906                            format!("access.bindings.{index}.policy"),
907                            CanonicalReferenceTarget::Declaration {
908                                id: CanonicalDeclarationId::Concept {
909                                    id: binding.policy.clone(),
910                                },
911                            },
912                        );
913                    }
914                }
915            }
916            _ => {}
917        }
918    }
919    refs
920}
921
922/// Resolve an in-memory source map into a validated canonical semantic
923/// envelope document, or the complete deterministic diagnostic list.
924/// Milestone 0 binds the empty semantic-pack set at the fixed public
925/// boundary (§9).
926pub fn resolve_semantic_envelope(
927    entry_logical_path: &str,
928    sources_json: &str,
929) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
930    resolve_semantic_envelope_with_packs(entry_logical_path, sources_json, &[])
931}
932
933/// [`resolve_semantic_envelope`] with explicit `(pack_id, content_hash)`
934/// semantic-pack inputs (D10): the pack set crosses the boundary into
935/// `inputs.semantic_pack_set_hash` and the envelope's `semantic_packs`.
936pub fn resolve_semantic_envelope_with_packs(
937    entry_logical_path: &str,
938    sources_json: &str,
939    semantic_packs: &[(String, String)],
940) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
941    use crate::module::resolver::{resolve_source_map, SourceMap};
942    crate::application::resolve::enforce_source_map_budget(sources_json)?;
943    let pack_set_hash = crate::application::resolve::validated_pack_set_hash(semantic_packs)?;
944    let sources = SourceMap::parse_json(sources_json)?;
945    let resolved = resolve_source_map(entry_logical_path, &sources)?;
946    let contract = crate::application::resolve::build_contract(&resolved)?;
947    let envelope = build_envelope(&resolved, &contract, semantic_packs);
948    let closure_hash = semantic_closure_hash(&envelope);
949    let mut doc = CanonicalSemanticEnvelopeDocument {
950        schema_version: ENVELOPE_SCHEMA_VERSION.to_string(),
951        producer: ProducerIdentity {
952            name: "domainforge-core".to_string(),
953            version: env!("CARGO_PKG_VERSION").to_string(),
954        },
955        inputs: ApplicationContractInputs {
956            source_set_hash: crate::application::canonical::source_set_hash(
957                sources
958                    .0
959                    .iter()
960                    .map(|(id, src)| (id.as_str(), src.as_str())),
961            )
962            .expect("duplicates already rejected"),
963            semantic_pack_set_hash: pack_set_hash,
964            language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
965            interpretation_version: INTERPRETATION_VERSION.to_string(),
966        },
967        self_hash: format!("sha256:{}", "0".repeat(64)),
968        semantic_closure_hash: closure_hash,
969        envelope,
970    };
971    doc.self_hash = envelope_document_self_hash(&doc);
972    Ok(doc)
973}
974
975// ---- hashing and validation ----
976
977/// Reference §6 semantic-closure hash over the canonical envelope payload.
978pub fn semantic_closure_hash(envelope: &CanonicalSemanticEnvelope) -> String {
979    compute_sha256(
980        canonical_json(&serde_json::to_value(envelope).expect("envelope serializes")).as_bytes(),
981    )
982}
983
984pub fn envelope_document_self_hash(doc: &CanonicalSemanticEnvelopeDocument) -> String {
985    let mut value = serde_json::to_value(doc).expect("envelope document serializes");
986    value
987        .as_object_mut()
988        .expect("document is an object")
989        .remove("self_hash");
990    compute_sha256(canonical_json(&value).as_bytes())
991}
992
993pub(crate) fn is_hash(value: &str) -> bool {
994    value.strip_prefix("sha256:").is_some_and(|hex| {
995        hex.len() == 64
996            && hex
997                .chars()
998                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
999    })
1000}
1001
1002fn app015(document_kind: &str, field_path: &str, message: String) -> ApplicationDiagnostic {
1003    let mut d = ApplicationDiagnostic::new(ApplicationDiagnosticCode::App015, message);
1004    d.context.document_kind = Some(document_kind.to_string());
1005    d.context.field_path = Some(field_path.to_string());
1006    d
1007}
1008
1009/// Producer identities this implementation emits; a persisted document from
1010/// any other producer is APP015 at `/producer/name`.
1011const KNOWN_PRODUCERS: &[&str] = &["domainforge-core"];
1012
1013fn validate_producer(
1014    diags: &mut Vec<ApplicationDiagnostic>,
1015    kind: &str,
1016    producer: &ProducerIdentity,
1017) {
1018    if !KNOWN_PRODUCERS.contains(&producer.name.as_str()) {
1019        diags.push(app015(
1020            kind,
1021            "/producer/name",
1022            format!("unknown producer '{}'", producer.name),
1023        ));
1024    }
1025    if producer.version.trim().is_empty() {
1026        diags.push(app015(
1027            kind,
1028            "/producer/version",
1029            "producer version is empty".to_string(),
1030        ));
1031    }
1032}
1033
1034fn validate_inputs(
1035    diags: &mut Vec<ApplicationDiagnostic>,
1036    kind: &str,
1037    inputs: &ApplicationContractInputs,
1038) {
1039    for (path, value) in [
1040        ("/inputs/source_set_hash", &inputs.source_set_hash),
1041        (
1042            "/inputs/semantic_pack_set_hash",
1043            &inputs.semantic_pack_set_hash,
1044        ),
1045    ] {
1046        if !is_hash(value) {
1047            diags.push(app015(
1048                kind,
1049                path,
1050                format!("'{value}' is not a lowercase sha256:<hex> hash"),
1051            ));
1052        }
1053    }
1054    if inputs.language_schema_version != LANGUAGE_SCHEMA_VERSION {
1055        let mut d = app015(
1056            kind,
1057            "/inputs/language_schema_version",
1058            format!(
1059                "expected language_schema_version '{}', got '{}'",
1060                LANGUAGE_SCHEMA_VERSION, inputs.language_schema_version
1061            ),
1062        );
1063        d.context.expected = Some(LANGUAGE_SCHEMA_VERSION.to_string());
1064        d.context.actual = Some(inputs.language_schema_version.clone());
1065        diags.push(d);
1066    }
1067    if inputs.interpretation_version != INTERPRETATION_VERSION {
1068        let mut d = app015(
1069            kind,
1070            "/inputs/interpretation_version",
1071            format!(
1072                "expected interpretation_version '{}', got '{}'",
1073                INTERPRETATION_VERSION, inputs.interpretation_version
1074            ),
1075        );
1076        d.context.expected = Some(INTERPRETATION_VERSION.to_string());
1077        d.context.actual = Some(inputs.interpretation_version.clone());
1078        diags.push(d);
1079    }
1080}
1081
1082/// Validate schema, inputs, and self-hash of a persisted application contract
1083/// document before use (APP015 on violation).
1084pub fn validate_application_contract_document_json(
1085    json: &str,
1086) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
1087    let kind = "application_contract";
1088    let doc: ApplicationContractDocument = serde_json::from_str(json)
1089        .map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
1090    let mut diags = Vec::new();
1091    if doc.schema_version != APPLICATION_CONTRACT_SCHEMA_VERSION {
1092        let mut d = app015(
1093            kind,
1094            "/schema_version",
1095            format!("unexpected schema_version '{}'", doc.schema_version),
1096        );
1097        d.context.schema_version = Some(doc.schema_version.clone());
1098        diags.push(d);
1099    }
1100    validate_producer(&mut diags, kind, &doc.producer);
1101    validate_inputs(&mut diags, kind, &doc.inputs);
1102    for (path, value) in [
1103        ("/self_hash", &doc.self_hash),
1104        ("/semantic_closure_hash", &doc.semantic_closure_hash),
1105    ] {
1106        if !is_hash(value) {
1107            diags.push(app015(
1108                kind,
1109                path,
1110                format!("'{value}' is not a lowercase sha256:<hex> hash"),
1111            ));
1112        }
1113    }
1114    if diags.is_empty() && doc.self_hash != crate::application::canonical::document_self_hash(&doc)
1115    {
1116        diags.push(app015(
1117            kind,
1118            "/self_hash",
1119            "self_hash does not match the canonical document bytes".to_string(),
1120        ));
1121    }
1122    if diags.is_empty() {
1123        Ok(doc)
1124    } else {
1125        Err(diags)
1126    }
1127}
1128
1129/// Validate schema, inputs, and hashes of a persisted canonical semantic
1130/// envelope document before use (APP015 on violation).
1131pub fn validate_semantic_envelope_document_json(
1132    json: &str,
1133) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
1134    let kind = "canonical_semantic_envelope";
1135    let doc: CanonicalSemanticEnvelopeDocument = serde_json::from_str(json)
1136        .map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
1137    let mut diags = Vec::new();
1138    if doc.schema_version != ENVELOPE_SCHEMA_VERSION {
1139        let mut d = app015(
1140            kind,
1141            "/schema_version",
1142            format!("unexpected schema_version '{}'", doc.schema_version),
1143        );
1144        d.context.schema_version = Some(doc.schema_version.clone());
1145        diags.push(d);
1146    }
1147    validate_producer(&mut diags, kind, &doc.producer);
1148    validate_inputs(&mut diags, kind, &doc.inputs);
1149    for (path, value) in [
1150        ("/self_hash", &doc.self_hash),
1151        ("/semantic_closure_hash", &doc.semantic_closure_hash),
1152    ] {
1153        if !is_hash(value) {
1154            diags.push(app015(
1155                kind,
1156                path,
1157                format!("'{value}' is not a lowercase sha256:<hex> hash"),
1158            ));
1159        }
1160    }
1161    // Envelope metadata invariants.
1162    let env = &doc.envelope;
1163    if env.language_schema_version != doc.inputs.language_schema_version {
1164        diags.push(app015(
1165            kind,
1166            "/envelope/language_schema_version",
1167            format!(
1168                "envelope language_schema_version '{}' does not match inputs '{}'",
1169                env.language_schema_version, doc.inputs.language_schema_version
1170            ),
1171        ));
1172    }
1173    if env.compiler_interpretation_version != doc.inputs.interpretation_version {
1174        diags.push(app015(
1175            kind,
1176            "/envelope/compiler_interpretation_version",
1177            format!(
1178                "envelope compiler_interpretation_version '{}' does not match inputs '{}'",
1179                env.compiler_interpretation_version, doc.inputs.interpretation_version
1180            ),
1181        ));
1182    }
1183    if env.canonicalization_version != CANONICALIZATION_VERSION {
1184        diags.push(app015(
1185            kind,
1186            "/envelope/canonicalization_version",
1187            format!(
1188                "expected canonicalization_version '{}', got '{}'",
1189                CANONICALIZATION_VERSION, env.canonicalization_version
1190            ),
1191        ));
1192    }
1193    for (index, pack) in env.semantic_packs.iter().enumerate() {
1194        if pack.pack_id.is_empty() {
1195            diags.push(app015(
1196                kind,
1197                &format!("/envelope/semantic_packs/{index}/pack_id"),
1198                "semantic pack has an empty pack_id".to_string(),
1199            ));
1200        }
1201        if !is_hash(&pack.content_hash) {
1202            diags.push(app015(
1203                kind,
1204                &format!("/envelope/semantic_packs/{index}/content_hash"),
1205                format!(
1206                    "semantic pack '{}' content_hash '{}' is not a lowercase sha256:<hex> hash",
1207                    pack.pack_id, pack.content_hash
1208                ),
1209            ));
1210        }
1211    }
1212    // Cross-consistency: the persisted pack-set hash must match the packs
1213    // actually listed in the envelope, recomputed under the §6 frame.
1214    if diags.is_empty() {
1215        let pack_pairs: Vec<(String, String)> = env
1216            .semantic_packs
1217            .iter()
1218            .map(|p| (p.pack_id.clone(), p.content_hash.clone()))
1219            .collect();
1220        match crate::application::canonical::semantic_pack_set_hash(&pack_pairs) {
1221            Ok(recomputed) if recomputed == doc.inputs.semantic_pack_set_hash => {}
1222            Ok(recomputed) => diags.push(app015(
1223                kind,
1224                "/inputs/semantic_pack_set_hash",
1225                format!(
1226                    "semantic_pack_set_hash '{}' does not match the envelope's packs ('{}')",
1227                    doc.inputs.semantic_pack_set_hash, recomputed
1228                ),
1229            )),
1230            Err(reason) => diags.push(app015(
1231                kind,
1232                "/inputs/semantic_pack_set_hash",
1233                format!("semantic_pack_set_hash cannot be recomputed: {reason}"),
1234            )),
1235        }
1236    }
1237    if diags.is_empty() {
1238        if doc.semantic_closure_hash != semantic_closure_hash(&doc.envelope) {
1239            diags.push(app015(
1240                kind,
1241                "/semantic_closure_hash",
1242                "semantic_closure_hash does not match the canonical envelope bytes".to_string(),
1243            ));
1244        }
1245        if doc.self_hash != envelope_document_self_hash(&doc) {
1246            diags.push(app015(
1247                kind,
1248                "/self_hash",
1249                "self_hash does not match the canonical document bytes".to_string(),
1250            ));
1251        }
1252    }
1253    if diags.is_empty() {
1254        Ok(doc)
1255    } else {
1256        Err(diags)
1257    }
1258}
1259
1260// ---- CEP-0008 semantic snapshot emission (Slice 0B) ----
1261
1262/// §5.2.1: every sxr snapshot Representation MUST carry these known omissions.
1263pub const CEP_SNAPSHOT_KNOWN_OMISSIONS: [&str; 3] = [
1264    "source_comments",
1265    "source_formatting",
1266    "source_line_positions",
1267];
1268
1269/// §5.2.1 reason text for the mandatory representation omission record.
1270pub const CEP_SNAPSHOT_OMISSION_REASON: &str =
1271    "domainforge canonical envelope is formatting- and comment-independent by construction";
1272
1273/// §5.2.1 recoverable-from text for the mandatory representation omission record.
1274pub const CEP_SNAPSHOT_OMISSION_RECOVERABLE_FROM: &str =
1275    "the .sea sources at the recorded git blob hashes";
1276
1277/// CEP envelope version emitted by DomainForge (spec §5.4 table).
1278pub const CEP_ENVELOPE_VERSION: &str = "1.0.0";
1279
1280/// CEP envelope kind for resolved semantic closures (spec §5.3b).
1281pub const CEP_ENVELOPE_KIND_SEMANTIC_SNAPSHOT: &str = "semantic_snapshot";
1282
1283/// Producer name used in emitted CEP envelopes (spec §5.4 `created_by`).
1284pub const CEP_PRODUCER_NAME: &str = "domainforge";
1285
1286/// CEP version declared by DomainForge emissions.
1287pub const CEP_VERSION: &str = "0.1.0";
1288
1289/// Deterministic inputs for [`build_cep_envelope`]. `doc` is present exactly
1290/// when the declared model produced a canonical D; on the failure path the
1291/// checkpoint hash and diagnostics carry the §14.4 failure identity.
1292pub struct CepEnvelopeParams<'a> {
1293    pub doc: Option<&'a CanonicalSemanticEnvelopeDocument>,
1294    pub model_valid: bool,
1295    pub source_set_hash: &'a str,
1296    pub invalid_declared_checkpoint_hash: Option<&'a str>,
1297    pub diagnostics: &'a [String],
1298    pub scope: serde_json::Value,
1299    pub entry_logical_path: &'a str,
1300    pub inline_threshold_bytes: u64,
1301    pub envelope_id: &'a str,
1302    pub created_at: &'a str,
1303    pub registry_content_hash: Option<&'a str>,
1304    pub resolved_namespaces: &'a [(String, String)],
1305    /// Opt-in world binding (GodSpeed `semantic_snapshot` profile). `None`
1306    /// leaves the emission exactly as before.
1307    pub world: Option<CepWorldParams<'a>>,
1308}
1309
1310/// Names for the semantic world a snapshot describes. The `world_ref` itself
1311/// is derived from the model's DomainModelIdentity; it is never supplied.
1312#[derive(Debug, Clone, Copy)]
1313pub struct CepWorldParams<'a> {
1314    pub name: &'a super::world::WorldName,
1315    pub alias: Option<&'a super::world::WorldAlias>,
1316    pub label: Option<&'a super::world::WorldLabel>,
1317}
1318
1319/// Profile declared at `extensions["cep.profile"]` (CEP-0008 §18.2).
1320pub const CEP_PROFILE_SEMANTIC_SNAPSHOT: &str = "godspeed.semantic_snapshot";
1321pub const CEP_PROFILE_VERSION: &str = "1.0.0";
1322
1323/// Build the CEP-0008 canonical full-profile `semantic_snapshot` envelope for
1324/// one DomainForge emission (spec §5.2/§5.4/§10.7a/§14.4). Pure and
1325/// deterministic given inputs; the CLI supplies a fresh `envelope_id` and
1326/// `created_at` per emission (I-DET: only those two fields vary across runs).
1327pub fn build_cep_envelope(p: &CepEnvelopeParams<'_>) -> serde_json::Value {
1328    let created_by = format!("{} {}", CEP_PRODUCER_NAME, env!("CARGO_PKG_VERSION"));
1329    let source_set_ref = format!("source-set:{}", p.source_set_hash);
1330
1331    let mut known_omissions: Vec<String> = CEP_SNAPSHOT_KNOWN_OMISSIONS
1332        .iter()
1333        .map(|s| s.to_string())
1334        .collect();
1335    if p.doc.is_none() {
1336        known_omissions.push("canonical_representation_D".to_string());
1337    }
1338    let included_sections: Vec<&str> = if p.doc.is_some() {
1339        vec!["representations", "references", "provenance"]
1340    } else {
1341        vec!["omissions", "references", "provenance"]
1342    };
1343
1344    let mut envelope = serde_json::Map::new();
1345    envelope.insert("envelope_id".to_string(), serde_json::json!(p.envelope_id));
1346    envelope.insert("cep_version".to_string(), serde_json::json!(CEP_VERSION));
1347    envelope.insert(
1348        "envelope_version".to_string(),
1349        serde_json::json!(CEP_ENVELOPE_VERSION),
1350    );
1351    envelope.insert(
1352        "envelope_kind".to_string(),
1353        serde_json::json!(CEP_ENVELOPE_KIND_SEMANTIC_SNAPSHOT),
1354    );
1355    envelope.insert("created_at".to_string(), serde_json::json!(p.created_at));
1356    envelope.insert("created_by".to_string(), serde_json::json!(created_by));
1357    // A world is pinned only when the model is valid and a canonical D exists; an
1358    // invalid world must not masquerade as one (it is flagged below instead).
1359    let pinned = match (p.world, p.doc) {
1360        (Some(world), Some(doc)) if p.model_valid => {
1361            let identity = DomainModelIdentity::from_document(doc, p.registry_content_hash);
1362            super::world::WorldRef::from_identity(world.name.clone(), &identity)
1363                .ok()
1364                .map(|world_ref| (world, identity, world_ref))
1365        }
1366        _ => None,
1367    };
1368    let mut scope = p.scope.clone();
1369    if let (Some((world, _, world_ref)), Some(object)) = (&pinned, scope.as_object_mut()) {
1370        object.insert(
1371            "world_ref".to_string(),
1372            serde_json::json!(world_ref.to_string()),
1373        );
1374        if let Some(alias) = world.alias {
1375            object.insert(
1376                "world_alias".to_string(),
1377                serde_json::json!(alias.to_string()),
1378            );
1379        }
1380        if let Some(label) = world.label {
1381            object.insert("world_label".to_string(), serde_json::json!(label.as_str()));
1382        }
1383    }
1384    envelope.insert("scope".to_string(), scope);
1385    envelope.insert(
1386        "boundary_record".to_string(),
1387        serde_json::json!({
1388            "scope": p.entry_logical_path,
1389            "included_sections": included_sections,
1390            "excluded_sections": [],
1391            "known_omissions": known_omissions,
1392            "unknowns": [],
1393            "redactions": [],
1394            "compression_notes": [],
1395            "out_of_scope_entities": [],
1396            "limitations": [],
1397        }),
1398    );
1399    envelope.insert(
1400        "completeness_status".to_string(),
1401        serde_json::json!(if p.doc.is_some() {
1402            "complete_for_declared_state"
1403        } else {
1404            "incomplete_for_declared_state"
1405        }),
1406    );
1407    envelope.insert(
1408        "provenance_refs".to_string(),
1409        serde_json::json!([source_set_ref]),
1410    );
1411    envelope.insert(
1412        "omission_status".to_string(),
1413        serde_json::json!("known_omissions_recorded"),
1414    );
1415    envelope.insert("lineage_refs".to_string(), serde_json::json!([]));
1416
1417    // §15.1 provenance section: this envelope's own production provenance.
1418    envelope.insert(
1419        "provenance".to_string(),
1420        serde_json::json!([{
1421            "provenance_id": format!("provenance:{}", p.envelope_id),
1422            "source_system_refs": [format!("source-set:{}", p.source_set_hash)],
1423            "producer_refs": [created_by],
1424            "production_method": "domainforge envelope --emit cep",
1425            "created_at": p.created_at,
1426            "verification_status": "unverified",
1427            "review_status": "unreviewed",
1428        }]),
1429    );
1430
1431    // §13.1 reference record: the resolved source set this snapshot derives from.
1432    envelope.insert(
1433        "references".to_string(),
1434        serde_json::json!([{
1435            "ref_id": format!(
1436                "source-set:{}",
1437                p.source_set_hash.strip_prefix("sha256:").unwrap_or(p.source_set_hash)
1438            ),
1439            "ref_type": "source_set",
1440            "target_uri_or_id": p.entry_logical_path,
1441            "target_hash": p.source_set_hash,
1442            "availability_status": "available",
1443            "integrity_status": "verifiable",
1444            "scope": p.entry_logical_path,
1445        }]),
1446    );
1447
1448    let mut extensions = serde_json::Map::new();
1449    match p.doc {
1450        Some(doc) => {
1451            envelope.insert(
1452                "validation_status".to_string(),
1453                serde_json::json!("validated"),
1454            );
1455            let representation = build_representation(p, doc, &created_by);
1456            envelope.insert(
1457                "representations".to_string(),
1458                serde_json::json!([representation]),
1459            );
1460            if !p.model_valid {
1461                extensions.insert(
1462                    "domainforge".to_string(),
1463                    serde_json::json!({
1464                        "model_validation_status": "invalid",
1465                        "diagnostics": p.diagnostics,
1466                    }),
1467                );
1468            }
1469            if let Some((_, identity, _)) = &pinned {
1470                envelope.insert(
1471                    "integrity".to_string(),
1472                    serde_json::json!({
1473                        "content_hash": identity.content_hash,
1474                        "semantic_hash": identity.semantic_closure_hash,
1475                    }),
1476                );
1477                extensions.insert(
1478                    "domainforge.identity".to_string(),
1479                    serde_json::json!({
1480                        "domain_model_identity": identity,
1481                        "semantic_closure_hash": identity.semantic_closure_hash,
1482                    }),
1483                );
1484            }
1485        }
1486        None => {
1487            // F-03: A valid failure envelope is conformant to CEP-0008,
1488            // with representation_unavailable omission and model status invalid.
1489            envelope.insert(
1490                "conformance_status".to_string(),
1491                serde_json::json!("conformant"),
1492            );
1493            envelope.insert(
1494                "validation_status".to_string(),
1495                serde_json::json!("validated"),
1496            );
1497            envelope.insert(
1498                "omissions".to_string(),
1499                serde_json::json!([{
1500                    "omission_id": format!(
1501                        "omission:representation:{}",
1502                        p.invalid_declared_checkpoint_hash
1503                            .unwrap_or_default()
1504                            .strip_prefix("sha256:")
1505                            .unwrap_or_default()
1506                    ),
1507                    "omission_type": "representation_unavailable",
1508                    "description": "canonical D not constructed; declared model invalid",
1509                    "reason": "model validation failed",
1510                    "known_or_suspected": "known",
1511                    "impact": "no semantic hash derivable",
1512                    "affected_entities": [p.entry_logical_path],
1513                }]),
1514            );
1515            extensions.insert(
1516                "domainforge".to_string(),
1517                serde_json::json!({
1518                    "model_validation_status": "invalid",
1519                    "invalid_declared_checkpoint_hash": p.invalid_declared_checkpoint_hash,
1520                    "diagnostics": p.diagnostics,
1521                }),
1522            );
1523        }
1524    }
1525    if p.world.is_some() {
1526        extensions.insert(
1527            "cep.profile".to_string(),
1528            serde_json::json!({
1529                "profile_id": CEP_PROFILE_SEMANTIC_SNAPSHOT,
1530                "profile_version": CEP_PROFILE_VERSION,
1531            }),
1532        );
1533    }
1534    if !extensions.is_empty() {
1535        envelope.insert(
1536            "extensions".to_string(),
1537            serde_json::Value::Object(extensions),
1538        );
1539    }
1540
1541    serde_json::Value::Object(envelope)
1542}
1543
1544/// §22 representation record for the canonical document D (spec §5.2/§10.7a).
1545fn build_representation(
1546    p: &CepEnvelopeParams<'_>,
1547    doc: &CanonicalSemanticEnvelopeDocument,
1548    created_by: &str,
1549) -> serde_json::Value {
1550    let canonical_bytes = canonical_json(&serde_json::to_value(doc).expect("document serializes"));
1551    let size_bytes = canonical_bytes.len() as u64;
1552
1553    let inline = size_bytes <= p.inline_threshold_bytes;
1554    let mut representation = serde_json::Map::new();
1555    representation.insert(
1556        "representation_id".to_string(),
1557        serde_json::json!(format!("representation:{}", doc.self_hash)),
1558    );
1559    representation.insert(
1560        "representation_kind".to_string(),
1561        serde_json::json!("derived"),
1562    );
1563    representation.insert(
1564        "representation_type".to_string(),
1565        serde_json::json!("domainforge_semantic_envelope_document"),
1566    );
1567    representation.insert("scope".to_string(), serde_json::json!(p.entry_logical_path));
1568    representation.insert("source".to_string(), serde_json::json!(created_by));
1569    if inline {
1570        representation.insert(
1571            "inline_content".to_string(),
1572            serde_json::json!(canonical_bytes),
1573        );
1574    } else {
1575        representation.insert(
1576            "content_ref".to_string(),
1577            serde_json::json!(format!(
1578                "cas://sha256:{}",
1579                doc.self_hash
1580                    .strip_prefix("sha256:")
1581                    .unwrap_or(&doc.self_hash)
1582            )),
1583        );
1584    }
1585    representation.insert("content_hash".to_string(), serde_json::json!(doc.self_hash));
1586    representation.insert(
1587        "semantic_hash".to_string(),
1588        serde_json::json!(doc.semantic_closure_hash),
1589    );
1590    representation.insert(
1591        "content_availability".to_string(),
1592        serde_json::json!("available"),
1593    );
1594    representation.insert("size_bytes".to_string(), serde_json::json!(size_bytes));
1595    representation.insert(
1596        "media_type".to_string(),
1597        serde_json::json!("application/json"),
1598    );
1599    representation.insert(
1600        "preserved_entities".to_string(),
1601        serde_json::json!(doc
1602            .envelope
1603            .semantic_declarations
1604            .iter()
1605            .map(|declaration| declaration_entity_ref(&declaration.id))
1606            .collect::<Vec<_>>()),
1607    );
1608    representation.insert(
1609        "preserved_distinctions".to_string(),
1610        serde_json::json!(["declared_vs_observed", "representation_vs_reality"]),
1611    );
1612    representation.insert(
1613        "omission_record".to_string(),
1614        serde_json::json!({
1615            "known_omissions": CEP_SNAPSHOT_KNOWN_OMISSIONS,
1616            "reason": CEP_SNAPSHOT_OMISSION_REASON,
1617            "recoverable_from": CEP_SNAPSHOT_OMISSION_RECOVERABLE_FROM,
1618        }),
1619    );
1620    representation.insert(
1621        "provenance_record".to_string(),
1622        serde_json::json!({
1623            "producer": {
1624                "name": doc.producer.name,
1625                "version": doc.producer.version,
1626            },
1627            "inputs": {
1628                "source_set_hash": doc.inputs.source_set_hash,
1629                "semantic_pack_set_hash": doc.inputs.semantic_pack_set_hash,
1630                "language_schema_version": doc.inputs.language_schema_version,
1631                "interpretation_version": doc.inputs.interpretation_version,
1632            },
1633            "resolution_inputs": {
1634                "entry_logical_path": p.entry_logical_path,
1635                "registry_content_hash": p.registry_content_hash,
1636                "resolved_namespaces": p.resolved_namespaces
1637                    .iter()
1638                    .map(|(id, namespace)| (id.clone(), namespace.clone()))
1639                    .collect::<BTreeMap<String, String>>(),
1640            },
1641        }),
1642    );
1643    representation.insert(
1644        "validation_status".to_string(),
1645        serde_json::json!(if p.model_valid { "valid" } else { "invalid" }),
1646    );
1647    serde_json::Value::Object(representation)
1648}
1649
1650/// Entity reference strings for one canonical declaration id.
1651pub fn declaration_entity_ref(id: &CanonicalDeclarationId) -> String {
1652    match id {
1653        CanonicalDeclarationId::Concept { id } => format!("concept:{}", id),
1654        CanonicalDeclarationId::Application { id } => format!("application:{}", id.0),
1655        CanonicalDeclarationId::Occurrence {
1656            kind,
1657            content_hash,
1658            duplicate_index,
1659        } => format!("occurrence:{}:{}:{}", kind, content_hash, duplicate_index),
1660    }
1661}
1662
1663/// §14.4: deterministic identity of a declared model whose canonical D could
1664/// not be constructed. Field encodings are DomainForge's; the formula
1665/// sha256(canonical_json(8 fields)) is normative.
1666pub fn invalid_declared_checkpoint_hash(
1667    source_set_hash: &str,
1668    semantic_pack_set_hash: &str,
1669    entry_logical_path: &str,
1670    registry_content_hash: Option<&str>,
1671    resolved_namespaces: &[(String, String)],
1672) -> String {
1673    let namespaces: serde_json::Map<String, serde_json::Value> = resolved_namespaces
1674        .iter()
1675        .map(|(id, namespace)| (id.clone(), serde_json::Value::String(namespace.clone())))
1676        .collect();
1677    let payload = serde_json::json!({
1678        "source_set_hash": source_set_hash,
1679        "semantic_pack_set_hash": semantic_pack_set_hash,
1680        "language_schema_version": LANGUAGE_SCHEMA_VERSION,
1681        "interpretation_version": INTERPRETATION_VERSION,
1682        "producer": {
1683            "name": CEP_PRODUCER_NAME,
1684            "version": env!("CARGO_PKG_VERSION"),
1685        },
1686        "entry_logical_path": entry_logical_path,
1687        "registry_content_hash": registry_content_hash,
1688        "resolved_namespaces": namespaces,
1689    });
1690    compute_sha256(canonical_json(&payload).as_bytes())
1691}
1692
1693/// Typed identity struct for a domain model across interface boundaries (F-04).
1694#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1695pub struct DomainModelIdentity {
1696    pub identity_scheme_version: String,
1697    pub producer: String,
1698    pub producer_version: String,
1699    pub language_schema_version: String,
1700    pub compiler_interpretation_version: String,
1701    pub canonicalization_version: String,
1702    pub source_set_hash: String,
1703    pub content_hash: String,
1704    pub semantic_closure_hash: String,
1705    pub semantic_pack_set_hash: Option<String>,
1706    pub registry_content_hash: Option<String>,
1707}
1708
1709impl DomainModelIdentity {
1710    pub fn canonical_digest(&self) -> String {
1711        let value = serde_json::to_value(self).expect("DomainModelIdentity serializes");
1712        compute_sha256(canonical_json(&value).as_bytes())
1713    }
1714}