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    Instance(CanonicalInstanceDecl),
153    Policy(CanonicalPolicyDecl),
154    ConceptChange(CanonicalConceptChangeDecl),
155    Metric(CanonicalMetricDecl),
156}
157
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159#[serde(deny_unknown_fields)]
160pub struct CanonicalDimensionDecl {
161    pub name: String,
162}
163
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165#[serde(deny_unknown_fields)]
166pub struct CanonicalUnitDecl {
167    pub symbol: String,
168    pub dimension: CanonicalReferenceTarget,
169    pub factor: String,
170    pub base_unit: String,
171}
172
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(deny_unknown_fields)]
175pub struct CanonicalEntityDecl {
176    pub name: String,
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub version: Option<String>,
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub domain: Option<String>,
181    pub annotations: BTreeMap<String, serde_json::Value>,
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub contract: Option<EntityContract>,
184}
185
186#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
187#[serde(deny_unknown_fields)]
188pub struct CanonicalResourceDecl {
189    pub name: String,
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub unit: Option<CanonicalReferenceTarget>,
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub domain: Option<String>,
194    pub annotations: BTreeMap<String, serde_json::Value>,
195}
196
197#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
198#[serde(deny_unknown_fields)]
199pub struct CanonicalFlowDecl {
200    pub resource: CanonicalReferenceTarget,
201    pub from_entity: CanonicalReferenceTarget,
202    pub to_entity: CanonicalReferenceTarget,
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub quantity: Option<String>,
205    pub annotations: BTreeMap<String, serde_json::Value>,
206}
207
208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
209#[serde(deny_unknown_fields)]
210pub struct CanonicalPatternDecl {
211    pub name: String,
212    pub regex: String,
213}
214
215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
216#[serde(deny_unknown_fields)]
217pub struct CanonicalRoleDecl {
218    pub name: String,
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub domain: Option<String>,
221}
222
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
224#[serde(deny_unknown_fields)]
225pub struct CanonicalRelationDecl {
226    pub name: String,
227    pub subject_role: CanonicalReferenceTarget,
228    pub predicate: String,
229    pub object_role: CanonicalReferenceTarget,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub via_flow: Option<CanonicalReferenceTarget>,
232}
233
234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct CanonicalInstanceDecl {
237    pub name: String,
238    pub entity_type: CanonicalReferenceTarget,
239    /// Field name -> serialized normalized expression (ast-v3 schema form).
240    pub fields: BTreeMap<String, serde_json::Value>,
241}
242
243#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
244#[serde(deny_unknown_fields)]
245pub struct CanonicalPolicyDecl {
246    pub name: String,
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub version: Option<String>,
249    /// Serialized ast-v3 schema policy metadata.
250    pub metadata: serde_json::Value,
251    /// Serialized ast-v3 schema expression with every `role<...>` leaf
252    /// rewritten to its resolved role `ConceptId`.
253    pub expression: serde_json::Value,
254}
255
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257#[serde(deny_unknown_fields)]
258pub struct CanonicalConceptChangeDecl {
259    pub name: String,
260    pub from_version: String,
261    pub to_version: String,
262    pub migration_policy: String,
263    pub breaking_change: bool,
264}
265
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
267#[serde(deny_unknown_fields)]
268pub struct CanonicalMetricDecl {
269    pub name: String,
270    pub expression: serde_json::Value,
271    pub metadata: serde_json::Value,
272}
273
274// ---- construction ----
275
276const KIND_RANK: [&str; 15] = [
277    "dimension",
278    "unit",
279    "record",
280    "enum",
281    "operation",
282    "entity",
283    "resource",
284    "flow",
285    "pattern",
286    "role",
287    "relation",
288    "instance",
289    "policy",
290    "concept_change",
291    "metric",
292];
293
294fn kind_rank(kind: &str) -> usize {
295    KIND_RANK
296        .iter()
297        .position(|k| *k == kind)
298        .unwrap_or(usize::MAX)
299}
300
301/// Resolve a reference through the shared symbol table (imports and aliases
302/// included); an unresolved reference keeps deterministic local identity so
303/// classification never invents a third form.
304fn resolved_target(
305    ctx: &Ctx,
306    module_index: usize,
307    namespace: &str,
308    raw: &str,
309    slugs: &'static [&'static str],
310) -> CanonicalReferenceTarget {
311    let id = ctx
312        .resolve_concept(module_index, raw, slugs)
313        .unwrap_or_else(|| ConceptId::from_concept(namespace, raw));
314    CanonicalReferenceTarget::Declaration {
315        id: CanonicalDeclarationId::Concept { id },
316    }
317}
318
319/// Rewrite every `role<...>` leaf in a serialized policy expression to the
320/// resolved role `ConceptId` (§8: envelopes carry resolved identities).
321/// Unresolvable references keep their authored text; APP007 reports them at
322/// binding validation.
323fn rewrite_role_references(value: &mut serde_json::Value, ctx: &Ctx, module_index: usize) {
324    match value {
325        serde_json::Value::Object(map) => {
326            if map.get("type").and_then(serde_json::Value::as_str) == Some("RoleReference") {
327                if let Some(serde_json::Value::String(role)) = map.get_mut("role") {
328                    if let Some(id) = ctx.resolve_concept(module_index, role, &["role"]) {
329                        *role = id.to_string();
330                    }
331                }
332            }
333            for (_, nested) in map.iter_mut() {
334                rewrite_role_references(nested, ctx, module_index);
335            }
336        }
337        serde_json::Value::Array(items) => {
338            for item in items {
339                rewrite_role_references(item, ctx, module_index);
340            }
341        }
342        _ => {}
343    }
344}
345
346fn sorted_annotations(
347    annotations: &std::collections::HashMap<String, serde_json::Value>,
348) -> BTreeMap<String, serde_json::Value> {
349    annotations
350        .iter()
351        .map(|(k, v)| (k.clone(), v.clone()))
352        .collect()
353}
354
355fn expr_value(expr: &crate::policy::Expression) -> serde_json::Value {
356    serde_json::to_value(schema::Expression::from(expr)).expect("schema expression serializes")
357}
358
359/// Classify one non-export declaration. Returns `None` for realization and
360/// Cell-environment declarations, which are configuration inputs excluded from
361/// the envelope (§6). The match is exhaustive by design: a new AST variant
362/// fails compilation until classified.
363#[allow(clippy::too_many_lines)]
364fn classify(
365    node: &past::AstNode,
366    namespace: &str,
367    contract: &ApplicationContract,
368    ctx: &Ctx,
369    module_index: usize,
370) -> Option<(
371    &'static str,
372    CanonicalDeclarationId,
373    CanonicalSemanticPayload,
374)> {
375    use past::AstNode as N;
376    let target = |raw: &str, slugs: &'static [&'static str]| {
377        resolved_target(ctx, module_index, namespace, raw, slugs)
378    };
379    let concept_id = |name: &str| CanonicalDeclarationId::Concept {
380        id: ConceptId::from_concept(namespace, name),
381    };
382    let app_id = |slug: &str, name: &str| CanonicalDeclarationId::Application {
383        id: ApplicationSymbolId(format!("{namespace}.{slug}.{}", nfc(name))),
384    };
385    Some(match node {
386        N::Export(_) => unreachable!("export wrappers are unwrapped before classification"),
387        N::Dimension { name } => (
388            "dimension",
389            concept_id(name),
390            CanonicalSemanticPayload::Dimension(CanonicalDimensionDecl { name: name.clone() }),
391        ),
392        N::UnitDeclaration {
393            symbol,
394            dimension,
395            factor,
396            base_unit,
397        } => (
398            "unit",
399            concept_id(symbol),
400            CanonicalSemanticPayload::Unit(CanonicalUnitDecl {
401                symbol: symbol.clone(),
402                dimension: target(dimension, &["dimension"]),
403                factor: canonical_decimal(*factor),
404                base_unit: base_unit.clone(),
405            }),
406        ),
407        N::Record(decl) => {
408            let id = app_id("record", &decl.name);
409            let payload = contract
410                .records
411                .iter()
412                .find(|r| matches!(&id, CanonicalDeclarationId::Application { id } if *id == r.id))?
413                .clone();
414            ("record", id, CanonicalSemanticPayload::Record(payload))
415        }
416        N::Enum(decl) => {
417            let id = app_id("enum", &decl.name);
418            let payload = contract
419                .enums
420                .iter()
421                .find(|e| matches!(&id, CanonicalDeclarationId::Application { id } if *id == e.id))?
422                .clone();
423            ("enum", id, CanonicalSemanticPayload::Enum(payload))
424        }
425        N::Operation(decl) => {
426            let id = app_id("operation", &decl.name);
427            let payload = contract
428                .operations
429                .iter()
430                .find(|o| matches!(&id, CanonicalDeclarationId::Application { id } if *id == o.id))?
431                .clone();
432            (
433                "operation",
434                id,
435                CanonicalSemanticPayload::Operation(payload),
436            )
437        }
438        N::Entity {
439            name,
440            version,
441            annotations,
442            domain,
443            body,
444        } => {
445            let entity_concept = ConceptId::from_concept(namespace, name);
446            let entity_contract = body.as_ref().and_then(|_| {
447                contract
448                    .entities
449                    .iter()
450                    .find(|e| e.concept_id == entity_concept)
451                    .cloned()
452            });
453            (
454                "entity",
455                concept_id(name),
456                CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
457                    name: name.clone(),
458                    version: version.clone(),
459                    domain: domain.clone(),
460                    annotations: sorted_annotations(annotations),
461                    contract: entity_contract,
462                }),
463            )
464        }
465        N::Resource {
466            name,
467            annotations,
468            unit_name,
469            domain,
470        } => (
471            "resource",
472            concept_id(name),
473            CanonicalSemanticPayload::Resource(CanonicalResourceDecl {
474                name: name.clone(),
475                unit: unit_name.as_ref().map(|u| target(u, &["unit"])),
476                domain: domain.clone(),
477                annotations: sorted_annotations(annotations),
478            }),
479        ),
480        N::Flow {
481            resource_name,
482            annotations,
483            from_entity,
484            to_entity,
485            quantity,
486        } => {
487            let payload = CanonicalSemanticPayload::Flow(CanonicalFlowDecl {
488                resource: target(resource_name, &["resource"]),
489                from_entity: target(from_entity, &["entity"]),
490                to_entity: target(to_entity, &["entity"]),
491                quantity: quantity.map(canonical_decimal),
492                annotations: sorted_annotations(annotations),
493            });
494            // duplicate_index is assigned after grouping equal payload hashes.
495            let content_hash = compute_sha256(
496                canonical_json(&serde_json::to_value(&payload).expect("flow serializes"))
497                    .as_bytes(),
498            );
499            (
500                "flow",
501                CanonicalDeclarationId::Occurrence {
502                    kind: "flow".to_string(),
503                    content_hash,
504                    duplicate_index: 0,
505                },
506                payload,
507            )
508        }
509        N::Pattern { name, regex } => (
510            "pattern",
511            concept_id(name),
512            CanonicalSemanticPayload::Pattern(CanonicalPatternDecl {
513                name: name.clone(),
514                regex: regex.clone(),
515            }),
516        ),
517        N::Role { name, domain } => (
518            "role",
519            concept_id(name),
520            CanonicalSemanticPayload::Role(CanonicalRoleDecl {
521                name: name.clone(),
522                domain: domain.clone(),
523            }),
524        ),
525        N::Relation {
526            name,
527            subject_role,
528            predicate,
529            object_role,
530            via_flow,
531        } => (
532            "relation",
533            concept_id(name),
534            CanonicalSemanticPayload::Relation(CanonicalRelationDecl {
535                name: name.clone(),
536                subject_role: target(subject_role, &["role"]),
537                predicate: predicate.clone(),
538                object_role: target(object_role, &["role"]),
539                via_flow: via_flow.as_ref().map(|f| target(f, &["flow"])),
540            }),
541        ),
542        N::Instance {
543            name,
544            entity_type,
545            fields,
546        } => (
547            "instance",
548            CanonicalDeclarationId::Concept {
549                // Deterministic instance identity matches Graph.
550                id: ConceptId::from_concept(namespace, &format!("{entity_type}:{name}")),
551            },
552            CanonicalSemanticPayload::Instance(CanonicalInstanceDecl {
553                name: name.clone(),
554                entity_type: target(entity_type, &["entity"]),
555                fields: fields
556                    .iter()
557                    .map(|(k, v)| (k.clone(), expr_value(v)))
558                    .collect(),
559            }),
560        ),
561        N::Policy {
562            name,
563            version,
564            metadata,
565            expression,
566        } => {
567            let mut expression = expr_value(expression);
568            rewrite_role_references(&mut expression, ctx, module_index);
569            (
570                "policy",
571                concept_id(name),
572                CanonicalSemanticPayload::Policy(CanonicalPolicyDecl {
573                    name: name.clone(),
574                    version: version.clone(),
575                    metadata: serde_json::to_value(schema::PolicyMetadata::from(metadata))
576                        .expect("policy metadata serializes"),
577                    expression,
578                }),
579            )
580        }
581        N::ConceptChange {
582            name,
583            from_version,
584            to_version,
585            migration_policy,
586            breaking_change,
587        } => (
588            "concept_change",
589            concept_id(name),
590            CanonicalSemanticPayload::ConceptChange(CanonicalConceptChangeDecl {
591                name: name.clone(),
592                from_version: from_version.clone(),
593                to_version: to_version.clone(),
594                migration_policy: migration_policy.clone(),
595                breaking_change: *breaking_change,
596            }),
597        ),
598        N::Metric {
599            name,
600            expression,
601            metadata,
602        } => (
603            "metric",
604            concept_id(name),
605            CanonicalSemanticPayload::Metric(CanonicalMetricDecl {
606                name: name.clone(),
607                expression: expr_value(expression),
608                metadata: serde_json::to_value(schema::MetricMetadata::from(metadata))
609                    .expect("metric metadata serializes"),
610            }),
611        ),
612        // Realization/configuration declarations: excluded from the envelope
613        // per §6; their hashes belong to the later resolution/plan lock.
614        N::MappingDecl { .. }
615        | N::ProjectionDecl { .. }
616        | N::Cell { .. }
617        | N::SystemDependency { .. }
618        | N::Runtime { .. }
619        | N::Tool { .. }
620        | N::DependencySet { .. }
621        | N::Service { .. }
622        | N::Mount { .. }
623        | N::Endpoint { .. }
624        | N::NetworkFlow { .. }
625        | N::Credential { .. } => return None,
626    })
627}
628
629fn id_sort_key(id: &CanonicalDeclarationId) -> String {
630    canonical_json(&serde_json::to_value(id).expect("declaration id serializes"))
631}
632
633pub(crate) fn build_envelope(
634    set: &ResolvedModuleSet,
635    contract: &ApplicationContract,
636    semantic_packs: &[(String, String)],
637) -> CanonicalSemanticEnvelope {
638    let ctx = Ctx::new(set);
639    let mut declarations: Vec<(usize, CanonicalSemanticDeclaration)> = Vec::new();
640    let mut namespace_bindings = Vec::new();
641    let mut module_decl_hashes: Vec<(String, String, Vec<serde_json::Value>)> = Vec::new();
642
643    for (module_index, module) in set.modules.iter().enumerate() {
644        let namespace = module
645            .ast
646            .metadata
647            .namespace
648            .clone()
649            .unwrap_or_else(|| module.logical_id.clone());
650        namespace_bindings.push(CanonicalNamespaceBinding {
651            namespace: namespace.clone(),
652            logical_id: module.logical_id.clone(),
653        });
654        let mut module_payloads = Vec::new();
655        for spanned in &module.ast.declarations {
656            let node = match &spanned.node {
657                past::AstNode::Export(inner) => &inner.node,
658                other => other,
659            };
660            if let Some((kind, id, payload)) =
661                classify(node, &namespace, contract, &ctx, module_index)
662            {
663                module_payloads.push(serde_json::to_value(&payload).expect("payload serializes"));
664                declarations.push((
665                    kind_rank(kind),
666                    CanonicalSemanticDeclaration {
667                        id,
668                        logical_module_id: module.logical_id.clone(),
669                        declaration: payload,
670                    },
671                ));
672            }
673        }
674        module_decl_hashes.push((module.logical_id.clone(), namespace, module_payloads));
675    }
676
677    // Assign flow occurrence duplicate indexes within equal-hash groups.
678    let mut occurrence_counts: BTreeMap<String, u32> = BTreeMap::new();
679    for (_, decl) in &mut declarations {
680        if let CanonicalDeclarationId::Occurrence {
681            content_hash,
682            duplicate_index,
683            ..
684        } = &mut decl.id
685        {
686            let count = occurrence_counts.entry(content_hash.clone()).or_default();
687            *duplicate_index = *count;
688            *count += 1;
689        }
690    }
691
692    // §6 closure order: logical module ID first, then kind rank, then
693    // canonical declaration ID — authored declaration order never survives.
694    declarations.sort_by(|a, b| {
695        (&a.1.logical_module_id, a.0, id_sort_key(&a.1.id)).cmp(&(
696            &b.1.logical_module_id,
697            b.0,
698            id_sort_key(&b.1.id),
699        ))
700    });
701    let semantic_declarations: Vec<CanonicalSemanticDeclaration> =
702        declarations.into_iter().map(|(_, d)| d).collect();
703
704    module_decl_hashes.sort_by(|a, b| a.0.cmp(&b.0));
705    let modules = module_decl_hashes
706        .into_iter()
707        .map(|(logical_id, namespace, mut payloads)| {
708            // A module's semantic content hash covers its normalized payload
709            // set, not authored declaration order.
710            payloads.sort_by_key(canonical_json);
711            CanonicalModuleRef {
712                logical_id,
713                semantic_content_hash: compute_sha256(
714                    canonical_json(&serde_json::Value::Array(payloads)).as_bytes(),
715                ),
716                namespace,
717            }
718        })
719        .collect();
720
721    namespace_bindings.sort_by(
722        |a: &CanonicalNamespaceBinding, b: &CanonicalNamespaceBinding| {
723            (&a.namespace, &a.logical_id).cmp(&(&b.namespace, &b.logical_id))
724        },
725    );
726
727    let mut import_graph: Vec<CanonicalImportEdge> = set
728        .import_graph
729        .iter()
730        .map(|e| CanonicalImportEdge {
731            importer: e.importer.clone(),
732            imported: e.imported.clone(),
733        })
734        .collect();
735    import_graph.sort_by(|a, b| (&a.importer, &a.imported).cmp(&(&b.importer, &b.imported)));
736    import_graph.dedup();
737
738    let mut resolved_references = collect_references(&semantic_declarations);
739    resolved_references.sort_by_key(|r| {
740        (
741            id_sort_key(&r.source),
742            r.field_path.clone(),
743            canonical_json(&serde_json::to_value(&r.target).expect("target serializes")),
744        )
745    });
746
747    CanonicalSemanticEnvelope {
748        language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
749        canonicalization_version: CANONICALIZATION_VERSION.to_string(),
750        compiler_interpretation_version: INTERPRETATION_VERSION.to_string(),
751        modules,
752        import_graph,
753        namespace_bindings,
754        semantic_packs: semantic_packs
755            .iter()
756            .map(|(pack_id, content_hash)| CanonicalSemanticPackRef {
757                pack_id: pack_id.clone(),
758                content_hash: content_hash.clone(),
759            })
760            .collect(),
761        semantic_declarations,
762        resolved_references,
763        application_contract: contract.clone(),
764    }
765}
766
767/// Duplicate the application contract's typed reference edges for indexing
768/// and audit (§8). Field paths are canonical schema paths, never source
769/// coordinates.
770fn collect_references(
771    declarations: &[CanonicalSemanticDeclaration],
772) -> Vec<CanonicalResolvedReference> {
773    let mut refs = Vec::new();
774    let mut push =
775        |source: &CanonicalDeclarationId, path: String, target: CanonicalReferenceTarget| {
776            refs.push(CanonicalResolvedReference {
777                source: source.clone(),
778                field_path: path,
779                target,
780            });
781        };
782    let field_refs =
783        |source: &CanonicalDeclarationId,
784         fields: &[FieldContract],
785         refs: &mut dyn FnMut(&CanonicalDeclarationId, String, CanonicalReferenceTarget)| {
786            for field in fields {
787                let base = format!("fields.{}.field_type", field.name);
788                match &field.field_type {
789                    FieldType::Quantity { unit } => refs(
790                        source,
791                        format!("{base}.unit"),
792                        CanonicalReferenceTarget::Declaration {
793                            id: CanonicalDeclarationId::Concept { id: unit.clone() },
794                        },
795                    ),
796                    FieldType::EntityRef { entity } => refs(
797                        source,
798                        format!("{base}.entity"),
799                        CanonicalReferenceTarget::Declaration {
800                            id: CanonicalDeclarationId::Concept { id: entity.clone() },
801                        },
802                    ),
803                    FieldType::Enum { symbol } => refs(
804                        source,
805                        format!("{base}.symbol"),
806                        CanonicalReferenceTarget::Declaration {
807                            id: CanonicalDeclarationId::Application { id: symbol.clone() },
808                        },
809                    ),
810                    FieldType::Scalar { .. } | FieldType::List { .. } => {}
811                }
812                for (index, constraint) in field.constraints.iter().enumerate() {
813                    if let FieldConstraint::Pattern { pattern } = constraint {
814                        refs(
815                            source,
816                            format!("fields.{}.constraints.{index}.pattern", field.name),
817                            CanonicalReferenceTarget::Declaration {
818                                id: CanonicalDeclarationId::Concept {
819                                    id: pattern.clone(),
820                                },
821                            },
822                        );
823                    }
824                }
825            }
826        };
827    for decl in declarations {
828        match &decl.declaration {
829            CanonicalSemanticPayload::Record(record) => {
830                field_refs(&decl.id, &record.fields, &mut push)
831            }
832            CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
833                contract: Some(entity),
834                ..
835            }) => field_refs(&decl.id, &entity.fields, &mut push),
836            CanonicalSemanticPayload::Operation(op) => {
837                push(
838                    &decl.id,
839                    "input".to_string(),
840                    CanonicalReferenceTarget::Declaration {
841                        id: CanonicalDeclarationId::Application {
842                            id: op.input.clone(),
843                        },
844                    },
845                );
846                push(
847                    &decl.id,
848                    "output".to_string(),
849                    CanonicalReferenceTarget::Declaration {
850                        id: CanonicalDeclarationId::Application {
851                            id: op.output.clone(),
852                        },
853                    },
854                );
855                push(
856                    &decl.id,
857                    "state".to_string(),
858                    CanonicalReferenceTarget::Declaration {
859                        id: CanonicalDeclarationId::Concept {
860                            id: op.state.clone(),
861                        },
862                    },
863                );
864                if let ActorRef::Role { role } = &op.actor {
865                    push(
866                        &decl.id,
867                        "actor.role".to_string(),
868                        CanonicalReferenceTarget::Declaration {
869                            id: CanonicalDeclarationId::Concept { id: role.clone() },
870                        },
871                    );
872                }
873                if let AccessMode::PolicyGoverned { bindings } = &op.access {
874                    for (index, binding) in bindings.iter().enumerate() {
875                        push(
876                            &decl.id,
877                            format!("access.bindings.{index}.policy"),
878                            CanonicalReferenceTarget::Declaration {
879                                id: CanonicalDeclarationId::Concept {
880                                    id: binding.policy.clone(),
881                                },
882                            },
883                        );
884                    }
885                }
886            }
887            _ => {}
888        }
889    }
890    refs
891}
892
893/// Resolve an in-memory source map into a validated canonical semantic
894/// envelope document, or the complete deterministic diagnostic list.
895/// Milestone 0 binds the empty semantic-pack set at the fixed public
896/// boundary (§9).
897pub fn resolve_semantic_envelope(
898    entry_logical_path: &str,
899    sources_json: &str,
900) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
901    resolve_semantic_envelope_with_packs(entry_logical_path, sources_json, &[])
902}
903
904/// [`resolve_semantic_envelope`] with explicit `(pack_id, content_hash)`
905/// semantic-pack inputs (D10): the pack set crosses the boundary into
906/// `inputs.semantic_pack_set_hash` and the envelope's `semantic_packs`.
907pub fn resolve_semantic_envelope_with_packs(
908    entry_logical_path: &str,
909    sources_json: &str,
910    semantic_packs: &[(String, String)],
911) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
912    use crate::module::resolver::{resolve_source_map, SourceMap};
913    crate::application::resolve::enforce_source_map_budget(sources_json)?;
914    let pack_set_hash = crate::application::resolve::validated_pack_set_hash(semantic_packs)?;
915    let sources = SourceMap::parse_json(sources_json)?;
916    let resolved = resolve_source_map(entry_logical_path, &sources)?;
917    let contract = crate::application::resolve::build_contract(&resolved)?;
918    let envelope = build_envelope(&resolved, &contract, semantic_packs);
919    let closure_hash = semantic_closure_hash(&envelope);
920    let mut doc = CanonicalSemanticEnvelopeDocument {
921        schema_version: ENVELOPE_SCHEMA_VERSION.to_string(),
922        producer: ProducerIdentity {
923            name: "domainforge-core".to_string(),
924            version: env!("CARGO_PKG_VERSION").to_string(),
925        },
926        inputs: ApplicationContractInputs {
927            source_set_hash: crate::application::canonical::source_set_hash(
928                sources
929                    .0
930                    .iter()
931                    .map(|(id, src)| (id.as_str(), src.as_str())),
932            )
933            .expect("duplicates already rejected"),
934            semantic_pack_set_hash: pack_set_hash,
935            language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
936            interpretation_version: INTERPRETATION_VERSION.to_string(),
937        },
938        self_hash: format!("sha256:{}", "0".repeat(64)),
939        semantic_closure_hash: closure_hash,
940        envelope,
941    };
942    doc.self_hash = envelope_document_self_hash(&doc);
943    Ok(doc)
944}
945
946// ---- hashing and validation ----
947
948/// Reference §6 semantic-closure hash over the canonical envelope payload.
949pub fn semantic_closure_hash(envelope: &CanonicalSemanticEnvelope) -> String {
950    compute_sha256(
951        canonical_json(&serde_json::to_value(envelope).expect("envelope serializes")).as_bytes(),
952    )
953}
954
955pub fn envelope_document_self_hash(doc: &CanonicalSemanticEnvelopeDocument) -> String {
956    let mut value = serde_json::to_value(doc).expect("envelope document serializes");
957    value
958        .as_object_mut()
959        .expect("document is an object")
960        .remove("self_hash");
961    compute_sha256(canonical_json(&value).as_bytes())
962}
963
964pub(crate) fn is_hash(value: &str) -> bool {
965    value.strip_prefix("sha256:").is_some_and(|hex| {
966        hex.len() == 64
967            && hex
968                .chars()
969                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
970    })
971}
972
973fn app015(document_kind: &str, field_path: &str, message: String) -> ApplicationDiagnostic {
974    let mut d = ApplicationDiagnostic::new(ApplicationDiagnosticCode::App015, message);
975    d.context.document_kind = Some(document_kind.to_string());
976    d.context.field_path = Some(field_path.to_string());
977    d
978}
979
980/// Producer identities this implementation emits; a persisted document from
981/// any other producer is APP015 at `/producer/name`.
982const KNOWN_PRODUCERS: &[&str] = &["domainforge-core"];
983
984fn validate_producer(
985    diags: &mut Vec<ApplicationDiagnostic>,
986    kind: &str,
987    producer: &ProducerIdentity,
988) {
989    if !KNOWN_PRODUCERS.contains(&producer.name.as_str()) {
990        diags.push(app015(
991            kind,
992            "/producer/name",
993            format!("unknown producer '{}'", producer.name),
994        ));
995    }
996    if producer.version.trim().is_empty() {
997        diags.push(app015(
998            kind,
999            "/producer/version",
1000            "producer version is empty".to_string(),
1001        ));
1002    }
1003}
1004
1005fn validate_inputs(
1006    diags: &mut Vec<ApplicationDiagnostic>,
1007    kind: &str,
1008    inputs: &ApplicationContractInputs,
1009) {
1010    for (path, value) in [
1011        ("/inputs/source_set_hash", &inputs.source_set_hash),
1012        (
1013            "/inputs/semantic_pack_set_hash",
1014            &inputs.semantic_pack_set_hash,
1015        ),
1016    ] {
1017        if !is_hash(value) {
1018            diags.push(app015(
1019                kind,
1020                path,
1021                format!("'{value}' is not a lowercase sha256:<hex> hash"),
1022            ));
1023        }
1024    }
1025    if inputs.language_schema_version != LANGUAGE_SCHEMA_VERSION {
1026        let mut d = app015(
1027            kind,
1028            "/inputs/language_schema_version",
1029            format!(
1030                "expected language_schema_version '{}', got '{}'",
1031                LANGUAGE_SCHEMA_VERSION, inputs.language_schema_version
1032            ),
1033        );
1034        d.context.expected = Some(LANGUAGE_SCHEMA_VERSION.to_string());
1035        d.context.actual = Some(inputs.language_schema_version.clone());
1036        diags.push(d);
1037    }
1038    if inputs.interpretation_version != INTERPRETATION_VERSION {
1039        let mut d = app015(
1040            kind,
1041            "/inputs/interpretation_version",
1042            format!(
1043                "expected interpretation_version '{}', got '{}'",
1044                INTERPRETATION_VERSION, inputs.interpretation_version
1045            ),
1046        );
1047        d.context.expected = Some(INTERPRETATION_VERSION.to_string());
1048        d.context.actual = Some(inputs.interpretation_version.clone());
1049        diags.push(d);
1050    }
1051}
1052
1053/// Validate schema, inputs, and self-hash of a persisted application contract
1054/// document before use (APP015 on violation).
1055pub fn validate_application_contract_document_json(
1056    json: &str,
1057) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
1058    let kind = "application_contract";
1059    let doc: ApplicationContractDocument = serde_json::from_str(json)
1060        .map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
1061    let mut diags = Vec::new();
1062    if doc.schema_version != APPLICATION_CONTRACT_SCHEMA_VERSION {
1063        let mut d = app015(
1064            kind,
1065            "/schema_version",
1066            format!("unexpected schema_version '{}'", doc.schema_version),
1067        );
1068        d.context.schema_version = Some(doc.schema_version.clone());
1069        diags.push(d);
1070    }
1071    validate_producer(&mut diags, kind, &doc.producer);
1072    validate_inputs(&mut diags, kind, &doc.inputs);
1073    for (path, value) in [
1074        ("/self_hash", &doc.self_hash),
1075        ("/semantic_closure_hash", &doc.semantic_closure_hash),
1076    ] {
1077        if !is_hash(value) {
1078            diags.push(app015(
1079                kind,
1080                path,
1081                format!("'{value}' is not a lowercase sha256:<hex> hash"),
1082            ));
1083        }
1084    }
1085    if diags.is_empty() && doc.self_hash != crate::application::canonical::document_self_hash(&doc)
1086    {
1087        diags.push(app015(
1088            kind,
1089            "/self_hash",
1090            "self_hash does not match the canonical document bytes".to_string(),
1091        ));
1092    }
1093    if diags.is_empty() {
1094        Ok(doc)
1095    } else {
1096        Err(diags)
1097    }
1098}
1099
1100/// Validate schema, inputs, and hashes of a persisted canonical semantic
1101/// envelope document before use (APP015 on violation).
1102pub fn validate_semantic_envelope_document_json(
1103    json: &str,
1104) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
1105    let kind = "canonical_semantic_envelope";
1106    let doc: CanonicalSemanticEnvelopeDocument = serde_json::from_str(json)
1107        .map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
1108    let mut diags = Vec::new();
1109    if doc.schema_version != ENVELOPE_SCHEMA_VERSION {
1110        let mut d = app015(
1111            kind,
1112            "/schema_version",
1113            format!("unexpected schema_version '{}'", doc.schema_version),
1114        );
1115        d.context.schema_version = Some(doc.schema_version.clone());
1116        diags.push(d);
1117    }
1118    validate_producer(&mut diags, kind, &doc.producer);
1119    validate_inputs(&mut diags, kind, &doc.inputs);
1120    for (path, value) in [
1121        ("/self_hash", &doc.self_hash),
1122        ("/semantic_closure_hash", &doc.semantic_closure_hash),
1123    ] {
1124        if !is_hash(value) {
1125            diags.push(app015(
1126                kind,
1127                path,
1128                format!("'{value}' is not a lowercase sha256:<hex> hash"),
1129            ));
1130        }
1131    }
1132    // Envelope metadata invariants.
1133    let env = &doc.envelope;
1134    if env.language_schema_version != doc.inputs.language_schema_version {
1135        diags.push(app015(
1136            kind,
1137            "/envelope/language_schema_version",
1138            format!(
1139                "envelope language_schema_version '{}' does not match inputs '{}'",
1140                env.language_schema_version, doc.inputs.language_schema_version
1141            ),
1142        ));
1143    }
1144    if env.compiler_interpretation_version != doc.inputs.interpretation_version {
1145        diags.push(app015(
1146            kind,
1147            "/envelope/compiler_interpretation_version",
1148            format!(
1149                "envelope compiler_interpretation_version '{}' does not match inputs '{}'",
1150                env.compiler_interpretation_version, doc.inputs.interpretation_version
1151            ),
1152        ));
1153    }
1154    if env.canonicalization_version != CANONICALIZATION_VERSION {
1155        diags.push(app015(
1156            kind,
1157            "/envelope/canonicalization_version",
1158            format!(
1159                "expected canonicalization_version '{}', got '{}'",
1160                CANONICALIZATION_VERSION, env.canonicalization_version
1161            ),
1162        ));
1163    }
1164    for (index, pack) in env.semantic_packs.iter().enumerate() {
1165        if pack.pack_id.is_empty() {
1166            diags.push(app015(
1167                kind,
1168                &format!("/envelope/semantic_packs/{index}/pack_id"),
1169                "semantic pack has an empty pack_id".to_string(),
1170            ));
1171        }
1172        if !is_hash(&pack.content_hash) {
1173            diags.push(app015(
1174                kind,
1175                &format!("/envelope/semantic_packs/{index}/content_hash"),
1176                format!(
1177                    "semantic pack '{}' content_hash '{}' is not a lowercase sha256:<hex> hash",
1178                    pack.pack_id, pack.content_hash
1179                ),
1180            ));
1181        }
1182    }
1183    // Cross-consistency: the persisted pack-set hash must match the packs
1184    // actually listed in the envelope, recomputed under the §6 frame.
1185    if diags.is_empty() {
1186        let pack_pairs: Vec<(String, String)> = env
1187            .semantic_packs
1188            .iter()
1189            .map(|p| (p.pack_id.clone(), p.content_hash.clone()))
1190            .collect();
1191        match crate::application::canonical::semantic_pack_set_hash(&pack_pairs) {
1192            Ok(recomputed) if recomputed == doc.inputs.semantic_pack_set_hash => {}
1193            Ok(recomputed) => diags.push(app015(
1194                kind,
1195                "/inputs/semantic_pack_set_hash",
1196                format!(
1197                    "semantic_pack_set_hash '{}' does not match the envelope's packs ('{}')",
1198                    doc.inputs.semantic_pack_set_hash, recomputed
1199                ),
1200            )),
1201            Err(reason) => diags.push(app015(
1202                kind,
1203                "/inputs/semantic_pack_set_hash",
1204                format!("semantic_pack_set_hash cannot be recomputed: {reason}"),
1205            )),
1206        }
1207    }
1208    if diags.is_empty() {
1209        if doc.semantic_closure_hash != semantic_closure_hash(&doc.envelope) {
1210            diags.push(app015(
1211                kind,
1212                "/semantic_closure_hash",
1213                "semantic_closure_hash does not match the canonical envelope bytes".to_string(),
1214            ));
1215        }
1216        if doc.self_hash != envelope_document_self_hash(&doc) {
1217            diags.push(app015(
1218                kind,
1219                "/self_hash",
1220                "self_hash does not match the canonical document bytes".to_string(),
1221            ));
1222        }
1223    }
1224    if diags.is_empty() {
1225        Ok(doc)
1226    } else {
1227        Err(diags)
1228    }
1229}