Skip to main content

domainforge_core/application/
resolve.rs

1//! AST-to-contract reference/type resolution and the public entry point
2//! (reference §7/§8). Every reference resolves through
3//! `ResolvedModuleSet::symbols`; nothing scans the AST by name.
4
5use crate::application::canonical::nfc;
6use crate::application::contract::*;
7use crate::application::diagnostic::{
8    sort_diagnostics, ApplicationDiagnostic, ApplicationDiagnosticCode,
9};
10use crate::application::validate::{
11    check_duplicate_fields, check_entity_key, check_enum, check_record_defaults, failure_kind,
12    validate_clause_shape, validate_failures, DeclSite,
13};
14use crate::concept_id::ConceptId;
15#[cfg(feature = "cli")]
16use crate::module::resolver::source_map_from_filesystem;
17use crate::module::resolver::{resolve_source_map, ResolvedModuleSet, ResolvedSymbol, SourceMap};
18use crate::parser::ast as past;
19use crate::policy::Expression;
20use std::collections::HashMap;
21use std::str::FromStr;
22
23pub const APPLICATION_CONTRACT_SCHEMA_VERSION: &str = "domainforge-application-contract/v1";
24pub const LANGUAGE_SCHEMA_VERSION: &str = "domainforge-ast/v3";
25pub const INTERPRETATION_VERSION: &str = "domainforge-interpretation/v1";
26
27/// Public-bound resource budgets for untrusted source maps (gate finding 7).
28/// A source map larger than this in entries or bytes is APP015 before any
29/// parse or resolution work runs. Generous enough for the flagship fixtures
30/// (two modules, ~2 KB), tight enough to deny conversational-workflow DoS.
31pub const SOURCE_MAP_MAX_MODULES: usize = 256;
32pub const SOURCE_MAP_MAX_BYTES: usize = 2 * 1024 * 1024; // 2 MiB
33
34/// Reject oversized source maps before parsing (APP015, authored source).
35pub(crate) fn enforce_source_map_budget(
36    sources_json: &str,
37) -> Result<(), Vec<ApplicationDiagnostic>> {
38    let mut diags = Vec::new();
39    if sources_json.len() > SOURCE_MAP_MAX_BYTES {
40        diags.push(
41            ApplicationDiagnostic::new(
42                ApplicationDiagnosticCode::App015,
43                format!(
44                    "sources_json is {} bytes, exceeds the {}-byte public boundary budget",
45                    sources_json.len(),
46                    SOURCE_MAP_MAX_BYTES
47                ),
48            )
49            .with_document_kind("authored_source"),
50        );
51    }
52    // Cheap module-count estimate: count string-literal openings (each
53    // key:value pair has at minimum two — key + value). The full structural
54    // parse happens next; this only gates DoS before it.
55    let mut quote_count = 0usize;
56    let mut in_string = false;
57    let mut escape = false;
58    for ch in sources_json.chars() {
59        if in_string {
60            if escape {
61                escape = false;
62            } else if ch == '\\' {
63                escape = true;
64            } else if ch == '"' {
65                in_string = false;
66            }
67        } else if ch == '"' {
68            in_string = true;
69            quote_count += 1;
70        }
71    }
72    // Two string-literal openings per key:value pair is a safe lower bound:
73    // extra string literals inside source text only reduce the pair count.
74    let approx_pairs = quote_count.saturating_div(2);
75    if approx_pairs > SOURCE_MAP_MAX_MODULES {
76        diags.push(
77            ApplicationDiagnostic::new(
78                ApplicationDiagnosticCode::App015,
79                format!(
80                    "sources_json has approximately {} modules, exceeds the {}-module public boundary budget",
81                    approx_pairs, SOURCE_MAP_MAX_MODULES
82                ),
83            )
84            .with_document_kind("authored_source"),
85        );
86    }
87    if diags.is_empty() {
88        Ok(())
89    } else {
90        Err(diags)
91    }
92}
93
94/// Resolve an in-memory source map into a validated application contract
95/// document, or the complete deterministic diagnostic list. Milestone 0
96/// binds the empty semantic-pack set at the fixed public boundary (§9).
97pub fn resolve_application_contract(
98    entry_logical_path: &str,
99    sources_json: &str,
100) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
101    resolve_application_contract_with_packs(entry_logical_path, sources_json, &[])
102}
103
104/// [`resolve_application_contract`] with explicit `(pack_id, content_hash)`
105/// semantic-pack inputs (D10): the pack set crosses the boundary into
106/// `inputs.semantic_pack_set_hash` and the envelope's `semantic_packs`.
107pub fn resolve_application_contract_with_packs(
108    entry_logical_path: &str,
109    sources_json: &str,
110    semantic_packs: &[(String, String)],
111) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
112    enforce_source_map_budget(sources_json)?;
113    let pack_set_hash = validated_pack_set_hash(semantic_packs)?;
114    let sources = SourceMap::parse_json(sources_json)?;
115    let resolved = resolve_source_map(entry_logical_path, &sources)?;
116    let contract = build_contract(&resolved)?;
117    let envelope =
118        crate::application::envelope::build_envelope(&resolved, &contract, semantic_packs);
119    let closure_hash = crate::application::envelope::semantic_closure_hash(&envelope);
120    let mut doc = ApplicationContractDocument {
121        schema_version: APPLICATION_CONTRACT_SCHEMA_VERSION.to_string(),
122        producer: ProducerIdentity {
123            name: "domainforge-core".to_string(),
124            version: env!("CARGO_PKG_VERSION").to_string(),
125        },
126        inputs: ApplicationContractInputs {
127            source_set_hash: source_set_hash(&sources),
128            semantic_pack_set_hash: pack_set_hash,
129            language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
130            interpretation_version: INTERPRETATION_VERSION.to_string(),
131        },
132        self_hash: zero_hash(),
133        semantic_closure_hash: closure_hash,
134        contract,
135    };
136    doc.self_hash = crate::application::canonical::document_self_hash(&doc);
137    Ok(doc)
138}
139
140/// Reject malformed or duplicate semantic-pack inputs before use (APP015),
141/// then compute the §6 pack-set hash.
142pub(crate) fn validated_pack_set_hash(
143    semantic_packs: &[(String, String)],
144) -> Result<String, Vec<ApplicationDiagnostic>> {
145    let mut diags = Vec::new();
146    for (pack_id, content_hash) in semantic_packs {
147        if pack_id.is_empty() {
148            diags.push(
149                ApplicationDiagnostic::new(
150                    ApplicationDiagnosticCode::App015,
151                    "semantic pack input has an empty pack id".to_string(),
152                )
153                .with_document_kind("authored_source"),
154            );
155        }
156        if !crate::application::envelope::is_hash(content_hash) {
157            diags.push(
158                ApplicationDiagnostic::new(
159                    ApplicationDiagnosticCode::App015,
160                    format!(
161                        "semantic pack '{pack_id}' content hash '{content_hash}' is not a lowercase sha256:<hex> hash"
162                    ),
163                )
164                .with_document_kind("authored_source"),
165            );
166        }
167    }
168    if diags.is_empty() {
169        crate::application::canonical::semantic_pack_set_hash(semantic_packs).map_err(|reason| {
170            vec![ApplicationDiagnostic::new(
171                ApplicationDiagnosticCode::App015,
172                format!("semantic pack inputs are invalid: {reason}"),
173            )
174            .with_document_kind("authored_source")]
175        })
176    } else {
177        Err(diags)
178    }
179}
180
181/// Build a Graph from the same resolved module set the application contract
182/// consumes (D3): one resolution, shared existing-concept identity, no
183/// independent module traversal.
184///
185/// Not part of the §9 fixed public boundary; exposed for identity proofs
186/// and diagnostics only.
187#[doc(hidden)]
188pub fn resolve_application_graph(
189    entry_logical_path: &str,
190    sources_json: &str,
191) -> Result<crate::graph::Graph, Vec<ApplicationDiagnostic>> {
192    enforce_source_map_budget(sources_json)?;
193    let sources = SourceMap::parse_json(sources_json)?;
194    let set = resolve_source_map(entry_logical_path, &sources)?;
195    build_graph_from_set(&set, entry_logical_path)
196}
197
198#[cfg(feature = "cli")]
199pub(crate) fn resolve_filesystem_graph(
200    entry_path: &std::path::Path,
201    entry_source: &str,
202    registry: Option<&crate::registry::NamespaceRegistry>,
203    default_namespace: Option<&str>,
204) -> Result<crate::graph::Graph, Vec<ApplicationDiagnostic>> {
205    let (entry_logical_path, sources) =
206        source_map_from_filesystem(entry_path, entry_source, registry, default_namespace)?;
207    let sources_json = serde_json::to_string(&sources.0).map_err(|error| {
208        vec![ApplicationDiagnostic::new(
209            ApplicationDiagnosticCode::App015,
210            format!("failed to serialize filesystem source map: {error}"),
211        )]
212    })?;
213    enforce_source_map_budget(&sources_json)?;
214    let set = resolve_source_map(&entry_logical_path, &sources)?;
215    build_graph_from_set(&set, &entry_logical_path)
216}
217
218pub(crate) fn build_graph_from_set(
219    set: &ResolvedModuleSet,
220    entry_logical_path: &str,
221) -> Result<crate::graph::Graph, Vec<ApplicationDiagnostic>> {
222    // Graph construction owns concrete entity-instance validation, not the
223    // application operation contract. Build only the enum/entity slice so an
224    // unrelated operation diagnostic cannot change legacy graph projections.
225    let contract = build_graph_type_contract(set)?;
226    // One conversion per effective namespace, so every declaration keeps its
227    // authoring module's concept identity (D3). Namespace-less modules use
228    // their logical ID, exactly like contract resolution.
229    let mut groups: indexmap::IndexMap<String, crate::parser::ast::Ast> = indexmap::IndexMap::new();
230    for module in &set.modules {
231        let namespace = module
232            .ast
233            .metadata
234            .namespace
235            .clone()
236            .unwrap_or_else(|| module.logical_id.clone());
237        let group = groups.entry(namespace.clone()).or_insert_with(|| {
238            let mut ast = module.ast.clone();
239            ast.metadata.namespace = Some(namespace);
240            ast.declarations = Vec::new();
241            ast
242        });
243        group
244            .declarations
245            .extend(module.ast.declarations.iter().cloned());
246    }
247    let mut graph = crate::graph::Graph::new();
248    // The model's @version comes from the entry module; absorb() does not merge it.
249    graph.set_version(
250        set.modules
251            .iter()
252            .find(|module| module.logical_id == entry_logical_path)
253            .and_then(|module| module.ast.metadata.version.clone()),
254    );
255    for (_, ast) in groups {
256        let converted = crate::parser::ast::ast_to_graph_with_options(
257            ast,
258            &crate::parser::ParseOptions::default(),
259        )
260        .map_err(|e| {
261            vec![ApplicationDiagnostic::new(
262                ApplicationDiagnosticCode::App015,
263                format!("resolved closure failed graph construction: {e}"),
264            )
265            .with_document_kind("authored_source")]
266        })?;
267        graph.absorb(converted);
268    }
269    graph
270        .attach_application_contract(contract)
271        .map_err(|errors| {
272            errors
273                .into_iter()
274                .map(|message| {
275                    ApplicationDiagnostic::new(ApplicationDiagnosticCode::App015, message)
276                        .with_document_kind("authored_source")
277                })
278                .collect::<Vec<_>>()
279        })?;
280    graph.mark_operation_bound_policies(collect_operation_bound_policy_names(set, &Ctx::new(set)));
281    Ok(graph)
282}
283
284/// Resolved identities of policies referenced by some operation's `access
285/// policy_governed by <name> ...` clause across the resolved module set.
286/// `Graph::validate()` must not evaluate these against the bare graph
287/// (limitation L9): their terms (e.g. an input record field) are only
288/// meaningful in the referencing operation's typed contract context, which
289/// `--application`/`contract`/`envelope` resolve separately. This reads the
290/// raw clause only — it does not build or validate the operation itself,
291/// preserving the "graph construction owns entity-instance validation, not
292/// the operation contract" boundary above.
293///
294/// Resolves each reference through `Ctx` (the same alias/import resolution
295/// used for envelope references) rather than matching on the bare authored
296/// name: two policies sharing a local name in different namespaces, only
297/// one of which is operation-bound, must not be conflated. A reference that
298/// fails to resolve is dropped rather than guessed at — an unresolvable
299/// `access policy_governed by` target is a separate authoring error,
300/// reported elsewhere, not something this skip-list should paper over by
301/// excluding an unrelated same-named policy from graph validation.
302fn collect_operation_bound_policy_names(
303    set: &ResolvedModuleSet,
304    ctx: &Ctx,
305) -> std::collections::HashSet<ConceptId> {
306    let mut ids = std::collections::HashSet::new();
307    for (module_index, module) in set.modules.iter().enumerate() {
308        for decl in &module.ast.declarations {
309            let node = match &decl.node {
310                past::AstNode::Export(inner) => &inner.node,
311                other => other,
312            };
313            let past::AstNode::Operation(op) = node else {
314                continue;
315            };
316            for clause in &op.clauses {
317                if let past::OperationClause::AccessPolicyGoverned { bindings } = clause {
318                    for binding in bindings {
319                        if let Some(id) =
320                            ctx.resolve_concept(module_index, &binding.policy, &["policy"])
321                        {
322                            ids.insert(id);
323                        }
324                    }
325                }
326            }
327        }
328    }
329    ids
330}
331
332/// JSON boundary twin of [`resolve_application_contract`].
333pub fn resolve_application_contract_json(
334    entry_logical_path: &str,
335    sources_json: &str,
336) -> Result<String, Vec<ApplicationDiagnostic>> {
337    let doc = resolve_application_contract(entry_logical_path, sources_json)?;
338    serde_json::to_string(&doc).map_err(|e| {
339        vec![ApplicationDiagnostic::new(
340            ApplicationDiagnosticCode::App015,
341            format!("failed to serialize application contract document: {e}"),
342        )]
343    })
344}
345
346fn zero_hash() -> String {
347    format!("sha256:{}", "0".repeat(64))
348}
349
350/// Reference §6 source-set hash over the authored source map.
351fn source_set_hash(sources: &SourceMap) -> String {
352    crate::application::canonical::source_set_hash(
353        sources
354            .0
355            .iter()
356            .map(|(id, src)| (id.as_str(), src.as_str())),
357    )
358    .expect("SourceMap::parse_json already rejected duplicate logical ids")
359}
360
361// ---- contract construction ----
362
363struct ModuleBindings {
364    namespace: String,
365    /// Locally visible name -> (target namespace, original name).
366    named: HashMap<String, (String, String)>,
367    /// Wildcard alias -> target namespace.
368    wildcard: HashMap<String, String>,
369}
370
371pub(crate) struct Ctx<'a> {
372    set: &'a ResolvedModuleSet,
373    bindings: Vec<ModuleBindings>,
374}
375
376const REFERENCEABLE_SLUGS: &[&str] = &[
377    "record", "enum", "entity", "unit", "pattern", "role", "policy",
378];
379
380impl<'a> Ctx<'a> {
381    pub(crate) fn new(set: &'a ResolvedModuleSet) -> Self {
382        let namespace_of: HashMap<&str, String> = set
383            .modules
384            .iter()
385            .map(|m| {
386                (
387                    m.logical_id.as_str(),
388                    m.ast
389                        .metadata
390                        .namespace
391                        .clone()
392                        .unwrap_or_else(|| m.logical_id.clone()),
393                )
394            })
395            .collect();
396        // The resolver pushed exactly one import edge per import statement,
397        // in statement order; a resolved set therefore maps each authored
398        // import to its edge positionally — no specifier re-matching (D3).
399        let mut edges_by_importer: HashMap<&str, Vec<&str>> = HashMap::new();
400        for edge in &set.import_graph {
401            edges_by_importer
402                .entry(edge.importer.as_str())
403                .or_default()
404                .push(edge.imported.as_str());
405        }
406        let bindings = set
407            .modules
408            .iter()
409            .map(|module| {
410                let mut named = HashMap::new();
411                let mut wildcard = HashMap::new();
412                let edges = edges_by_importer.get(module.logical_id.as_str());
413                for (index, import) in module.ast.metadata.imports.iter().enumerate() {
414                    let Some(target_id) = edges.and_then(|e| e.get(index).copied()) else {
415                        continue;
416                    };
417                    let Some(target_ns) = namespace_of.get(target_id) else {
418                        continue;
419                    };
420                    match &import.specifier {
421                        past::ImportSpecifier::Named(items) => {
422                            for item in items {
423                                let local = item.alias.clone().unwrap_or_else(|| item.name.clone());
424                                named.insert(local, (target_ns.clone(), item.name.clone()));
425                            }
426                        }
427                        past::ImportSpecifier::Wildcard(alias) => {
428                            wildcard.insert(alias.clone(), target_ns.clone());
429                        }
430                    }
431                }
432                ModuleBindings {
433                    namespace: namespace_of[module.logical_id.as_str()].clone(),
434                    named,
435                    wildcard,
436                }
437            })
438            .collect();
439        Self { set, bindings }
440    }
441
442    fn find_symbol(&self, namespace: &str, name: &str) -> Option<(&ResolvedSymbol, &'static str)> {
443        self.find_symbol_in(namespace, name, REFERENCEABLE_SLUGS)
444    }
445
446    fn find_symbol_in(
447        &self,
448        namespace: &str,
449        name: &str,
450        slugs: &'static [&'static str],
451    ) -> Option<(&ResolvedSymbol, &'static str)> {
452        slugs.iter().find_map(|slug| {
453            self.set
454                .symbols
455                .get(&format!("{namespace}.{slug}.{name}"))
456                .map(|s| (s, *slug))
457        })
458    }
459
460    /// Resolve a raw possibly alias-qualified reference against specific
461    /// declaration slugs, returning the exact target identity (§8 envelope
462    /// references). `None` when the reference does not resolve.
463    pub(crate) fn resolve_concept(
464        &self,
465        module_index: usize,
466        raw: &str,
467        slugs: &'static [&'static str],
468    ) -> Option<ConceptId> {
469        let (alias, name) = split_symbol_ref(raw);
470        let bindings = &self.bindings[module_index];
471        let found = match alias {
472            Some(alias) => {
473                let ns = bindings.wildcard.get(alias)?;
474                self.find_symbol_in(ns, name, slugs)
475                    .filter(|(symbol, _)| symbol.exported)
476            }
477            None => {
478                if let Some((ns, original)) = bindings.named.get(name) {
479                    self.find_symbol_in(ns, original, slugs)
480                } else {
481                    self.find_symbol_in(&bindings.namespace, name, slugs)
482                }
483            }
484        };
485        found.map(|(symbol, _)| self.symbol_concept(symbol))
486    }
487
488    /// Resolve a possibly alias-qualified reference from `module_index`.
489    fn resolve_ref(
490        &self,
491        module_index: usize,
492        alias: Option<&str>,
493        name: &str,
494    ) -> Option<(&ResolvedSymbol, &'static str)> {
495        let bindings = &self.bindings[module_index];
496        match alias {
497            Some(alias) => {
498                let ns = bindings.wildcard.get(alias)?;
499                let (symbol, slug) = self.find_symbol(ns, name)?;
500                symbol.exported.then_some((symbol, slug))
501            }
502            None => {
503                if let Some((ns, original)) = bindings.named.get(name) {
504                    self.find_symbol(ns, original)
505                } else {
506                    self.find_symbol(&bindings.namespace, name)
507                }
508            }
509        }
510    }
511
512    pub(crate) fn module_namespace(&self, module_index: usize) -> String {
513        let module = &self.set.modules[module_index];
514        module
515            .ast
516            .metadata
517            .namespace
518            .clone()
519            .unwrap_or_else(|| module.logical_id.clone())
520    }
521
522    /// Exact resolved identity of a symbol: its authoring module's namespace
523    /// plus its declared name — never a local alias (D3).
524    fn symbol_concept(&self, symbol: &ResolvedSymbol) -> ConceptId {
525        let name = declared_name(self.decl_node(symbol)).unwrap_or_default();
526        ConceptId::from_concept(&self.module_namespace(symbol.module_index), name)
527    }
528
529    fn decl_node(&self, symbol: &ResolvedSymbol) -> &past::AstNode {
530        let node =
531            &self.set.modules[symbol.module_index].ast.declarations[symbol.declaration_index].node;
532        match node {
533            past::AstNode::Export(inner) => &inner.node,
534            other => other,
535        }
536    }
537}
538
539/// The name a declaration itself declares (concept identity input).
540fn declared_name(node: &past::AstNode) -> Option<&str> {
541    match node {
542        past::AstNode::Entity { name, .. }
543        | past::AstNode::Role { name, .. }
544        | past::AstNode::Pattern { name, .. }
545        | past::AstNode::Policy { name, .. }
546        | past::AstNode::Dimension { name } => Some(name),
547        past::AstNode::UnitDeclaration { symbol, .. } => Some(symbol),
548        past::AstNode::Record(decl) => Some(&decl.name),
549        past::AstNode::Enum(decl) => Some(&decl.name),
550        past::AstNode::Operation(decl) => Some(&decl.name),
551        _ => None,
552    }
553}
554
555/// Split a raw `symbol_ref` text (`Name` or `alias.Name`) into parts.
556fn split_symbol_ref(raw: &str) -> (Option<&str>, &str) {
557    match raw.split_once('.') {
558        Some((alias, name)) if !alias.is_empty() && !name.is_empty() => (Some(alias), name),
559        _ => (None, raw),
560    }
561}
562
563pub(crate) fn build_contract(
564    set: &ResolvedModuleSet,
565) -> Result<ApplicationContract, Vec<ApplicationDiagnostic>> {
566    let ctx = Ctx::new(set);
567    let mut contract = ApplicationContract::default();
568    let mut diags: Vec<ApplicationDiagnostic> = Vec::new();
569    lower_data_contracts(&ctx, true, &mut contract, &mut diags);
570
571    let mut closure_codes: std::collections::HashSet<String> = std::collections::HashSet::new();
572    let mut operations = Vec::new();
573    for symbol in set.symbols.values() {
574        let site = DeclSite {
575            logical_module_id: &symbol.origin.logical_module_id,
576            line: symbol.origin.line,
577            column: symbol.origin.column,
578        };
579        if let past::AstNode::Operation(decl) = ctx.decl_node(symbol) {
580            if let Some(op) = lower_operation(
581                &ctx,
582                &contract,
583                symbol,
584                decl,
585                site,
586                &mut closure_codes,
587                &mut diags,
588            ) {
589                operations.push(op);
590            }
591        }
592    }
593    contract.operations = operations;
594
595    // §6 closure order: contract collections are sets, sorted by canonical
596    // identity; only field/member/failure/binding lists keep authored order.
597    contract.enums.sort_by(|a, b| a.id.0.cmp(&b.id.0));
598    contract.records.sort_by(|a, b| a.id.0.cmp(&b.id.0));
599    contract.entities.sort_by_key(|e| e.concept_id.to_string());
600    contract.operations.sort_by(|a, b| a.id.0.cmp(&b.id.0));
601
602    if diags.is_empty() {
603        Ok(contract)
604    } else {
605        sort_diagnostics(&mut diags);
606        Err(diags)
607    }
608}
609
610/// Lower the shared enum/entity contract slice once. Full application
611/// contracts additionally include records; Graph intentionally does not.
612fn lower_data_contracts(
613    ctx: &Ctx<'_>,
614    include_records: bool,
615    contract: &mut ApplicationContract,
616    diags: &mut Vec<ApplicationDiagnostic>,
617) {
618    for symbol in ctx.set.symbols.values() {
619        let site = DeclSite {
620            logical_module_id: &symbol.origin.logical_module_id,
621            line: symbol.origin.line,
622            column: symbol.origin.column,
623        };
624        match ctx.decl_node(symbol) {
625            past::AstNode::Enum(decl) => {
626                check_enum(decl, site, diags);
627                contract.enums.push(EnumContract {
628                    id: ApplicationSymbolId(symbol.qualified_id.clone()),
629                    name: nfc(&decl.name),
630                    members: decl
631                        .members
632                        .iter()
633                        .map(|member| EnumMember {
634                            name: nfc(&member.name),
635                            wire: nfc(&member.wire),
636                        })
637                        .collect(),
638                });
639            }
640            past::AstNode::Record(decl) if include_records => {
641                check_duplicate_fields(&decl.name, &decl.fields, site, diags);
642                check_record_defaults(&decl.name, &decl.fields, site, diags);
643                let fields = resolve_fields(ctx, symbol, &decl.fields, false, site, diags);
644                contract.records.push(RecordContract {
645                    id: ApplicationSymbolId(symbol.qualified_id.clone()),
646                    name: nfc(&decl.name),
647                    fields,
648                });
649            }
650            past::AstNode::Entity {
651                name,
652                body: Some(body),
653                ..
654            } => {
655                check_duplicate_fields(name, &body.fields, site, diags);
656                let key_field = check_entity_key(name, &body.fields, site, diags);
657                let fields = resolve_fields(ctx, symbol, &body.fields, true, site, diags);
658                if let Some(key_field) = key_field {
659                    contract.entities.push(EntityContract {
660                        concept_id: ctx.symbol_concept(symbol),
661                        name: name.clone(),
662                        key_field: nfc(&key_field),
663                        fields,
664                    });
665                }
666            }
667            _ => {}
668        }
669    }
670}
671
672/// Build the resolved type information that the graph needs to validate
673/// concrete entity instances. Records and operations remain application-only
674/// contracts (ADR-013) and therefore cannot make graph construction fail.
675fn build_graph_type_contract(
676    set: &ResolvedModuleSet,
677) -> Result<ApplicationContract, Vec<ApplicationDiagnostic>> {
678    let ctx = Ctx::new(set);
679    let mut contract = ApplicationContract::default();
680    let mut diags = Vec::new();
681    lower_data_contracts(&ctx, false, &mut contract, &mut diags);
682
683    contract
684        .enums
685        .sort_by(|left, right| left.id.0.cmp(&right.id.0));
686    contract
687        .entities
688        .sort_by_key(|entity| entity.concept_id.to_string());
689    if diags.is_empty() {
690        Ok(contract)
691    } else {
692        sort_diagnostics(&mut diags);
693        Err(diags)
694    }
695}
696
697// ---- operation lowering (reference §4) ----
698
699fn field<'a>(fields: &'a [FieldContract], name: &str) -> Option<&'a FieldContract> {
700    fields.iter().find(|f| f.name == name)
701}
702
703/// Same field type and canonical constraint set (order-free).
704fn type_and_constraints_match(a: &FieldContract, b: &FieldContract) -> bool {
705    a.field_type == b.field_type
706        && a.constraints.len() == b.constraints.len()
707        && a.constraints.iter().all(|c| b.constraints.contains(c))
708}
709
710/// Same field type, optionality, and canonical constraint set.
711fn fields_compatible(a: &FieldContract, b: &FieldContract) -> bool {
712    type_and_constraints_match(a, b) && a.optional == b.optional
713}
714
715fn is_scalar(f: &FieldContract) -> bool {
716    matches!(f.field_type, FieldType::Scalar { .. })
717}
718
719#[allow(clippy::too_many_arguments)]
720fn lower_operation(
721    ctx: &Ctx,
722    contract: &ApplicationContract,
723    symbol: &ResolvedSymbol,
724    decl: &past::OperationDecl,
725    site: DeclSite,
726    closure_codes: &mut std::collections::HashSet<String>,
727    diags: &mut Vec<ApplicationDiagnostic>,
728) -> Option<OperationContract> {
729    use past::OperationClause as C;
730
731    let defects = validate_clause_shape(&decl.clauses);
732    if !defects.is_empty() {
733        diags.push(site.diag(
734            ApplicationDiagnosticCode::App001,
735            format!(
736                "operation '{}' is not generation-ready: {}",
737                decl.name,
738                defects.join("; ")
739            ),
740        ));
741        return None;
742    }
743    let before = diags.len();
744
745    // Clause shape guarantees each of these appears exactly once.
746    let mut intent = String::new();
747    let mut actor_raw = "";
748    let mut access_clause: Option<&C> = None;
749    let mut input_raw = "";
750    let mut output_raw = "";
751    let mut state_raw = "";
752    let mut effect_kind_raw = "";
753    let mut effect_target_raw = "";
754    let mut transaction_raw = "";
755    let mut ast_failures: Vec<(String, Vec<FailureKind>, String)> = Vec::new();
756    let mut idem_clause: Option<&C> = None;
757    let mut conc_clause: Option<&C> = None;
758    for clause in &decl.clauses {
759        match clause {
760            C::Intent(text) => intent = text.clone(),
761            C::Actor { actor } => actor_raw = actor,
762            C::AccessPublic | C::AccessPolicyGoverned { .. } => access_clause = Some(clause),
763            C::Input { reference } => input_raw = reference,
764            C::Output { reference } => output_raw = reference,
765            C::State { reference } => state_raw = reference,
766            C::Effect { kind, reference } => {
767                effect_kind_raw = kind;
768                effect_target_raw = reference;
769            }
770            C::Transaction { kind } => transaction_raw = kind,
771            C::Failure {
772                code,
773                kinds,
774                message,
775            } => {
776                let mut mapped = Vec::new();
777                for raw in kinds {
778                    match failure_kind(raw) {
779                        Some(kind) => mapped.push(kind),
780                        None => diags.push(site.diag(
781                            ApplicationDiagnosticCode::App008,
782                            format!(
783                                "failure '{code}' of operation '{}' names unknown kind '{raw}'",
784                                decl.name
785                            ),
786                        )),
787                    }
788                }
789                ast_failures.push((code.clone(), mapped, message.clone()));
790            }
791            C::IdempotencyKeyed { .. }
792            | C::IdempotencyInherent
793            | C::IdempotencyNotApplicable { .. } => idem_clause = Some(clause),
794            C::ConcurrencyUnique { .. }
795            | C::ConcurrencyOptimistic { .. }
796            | C::ConcurrencyReadSnapshot => conc_clause = Some(clause),
797            C::Direction { .. }
798            | C::EvidenceOperationTrace
799            | C::LifecycleSynchronousRequestResponse => {}
800        }
801    }
802
803    let effect = match effect_kind_raw {
804        "creates" => EffectKind::Creates,
805        "mutates" => EffectKind::Mutates,
806        "reads" => EffectKind::Reads,
807        other => {
808            diags.push(site.diag(
809                ApplicationDiagnosticCode::App001,
810                format!(
811                    "effect '{other}' of operation '{}' is unsupported",
812                    decl.name
813                ),
814            ));
815            return None;
816        }
817    };
818    let transaction = match transaction_raw {
819        "single_aggregate" => TransactionBoundary::SingleAggregate,
820        _ => TransactionBoundary::ReadOnly, // pairing already validated
821    };
822
823    // Actor.
824    let actor = if actor_raw == "anonymous" {
825        ActorRef::Anonymous
826    } else {
827        let (alias, name) = split_symbol_ref(actor_raw);
828        match ctx.resolve_ref(symbol.module_index, alias, name) {
829            Some((role_symbol, "role")) => ActorRef::Role {
830                role: ctx.symbol_concept(role_symbol),
831            },
832            _ => {
833                diags.push(site.diag(
834                    ApplicationDiagnosticCode::App002,
835                    format!(
836                        "actor '{actor_raw}' of operation '{}' does not resolve to a role",
837                        decl.name
838                    ),
839                ));
840                ActorRef::Anonymous
841            }
842        }
843    };
844
845    // Input / output / state / effect target resolution.
846    let resolve_record = |label: &str, raw: &str, diags: &mut Vec<ApplicationDiagnostic>| {
847        let (alias, name) = split_symbol_ref(raw);
848        match ctx.resolve_ref(symbol.module_index, alias, name) {
849            Some((s, "record")) => contract
850                .records
851                .iter()
852                .find(|r| r.id.0 == s.qualified_id)
853                .map(|r| (s.qualified_id.clone(), r)),
854            Some((_, slug)) => {
855                diags.push(site.diag(
856                    ApplicationDiagnosticCode::App006,
857                    format!(
858                        "{label} '{raw}' of operation '{}' resolves to {slug}; a record is required",
859                        decl.name
860                    ),
861                ));
862                None
863            }
864            None => {
865                diags.push(site.diag(
866                    ApplicationDiagnosticCode::App002,
867                    format!(
868                        "{label} '{raw}' of operation '{}' does not resolve in the symbol table",
869                        decl.name
870                    ),
871                ));
872                None
873            }
874        }
875    };
876    let input = resolve_record("input", input_raw, diags);
877    let output = resolve_record("output", output_raw, diags);
878
879    let state = {
880        let (alias, name) = split_symbol_ref(state_raw);
881        match ctx.resolve_ref(symbol.module_index, alias, name) {
882            Some((s, "entity")) => {
883                if matches!(ctx.decl_node(s), past::AstNode::Entity { body: None, .. }) {
884                    diags.push(site.diag(
885                        ApplicationDiagnosticCode::App011,
886                        format!(
887                            "state '{state_raw}' of operation '{}' lacks a typed body",
888                            decl.name
889                        ),
890                    ));
891                    None
892                } else {
893                    let concept_id = ctx.symbol_concept(s);
894                    contract
895                        .entities
896                        .iter()
897                        .find(|e| e.concept_id == concept_id)
898                        .map(|e| (s.qualified_id.clone(), e))
899                }
900            }
901            _ => {
902                diags.push(site.diag(
903                    ApplicationDiagnosticCode::App002,
904                    format!(
905                        "state '{state_raw}' of operation '{}' does not resolve to an entity",
906                        decl.name
907                    ),
908                ));
909                None
910            }
911        }
912    };
913    {
914        let (alias, name) = split_symbol_ref(effect_target_raw);
915        let target = ctx.resolve_ref(symbol.module_index, alias, name);
916        match (&state, target) {
917            (Some((state_qid, _)), Some((t, "entity"))) if t.qualified_id != *state_qid => {
918                diags.push(site.diag(
919                    ApplicationDiagnosticCode::App011,
920                    format!(
921                        "effect target '{effect_target_raw}' of operation '{}' differs from state '{state_raw}'",
922                        decl.name
923                    ),
924                ));
925            }
926            (Some(_), Some((_, "entity"))) => {}
927            (Some(_), _) => diags.push(site.diag(
928                ApplicationDiagnosticCode::App002,
929                format!(
930                    "effect target '{effect_target_raw}' of operation '{}' does not resolve to an entity",
931                    decl.name
932                ),
933            )),
934            (None, _) => {}
935        }
936    }
937
938    // Failures.
939    let input_has_constraints = input
940        .as_ref()
941        .is_some_and(|(_, r)| r.fields.iter().any(|f| !f.constraints.is_empty()));
942    let mut required_kinds = Vec::new();
943    if input_has_constraints {
944        required_kinds.push(FailureKind::InputValidation);
945    }
946    if matches!(effect, EffectKind::Reads | EffectKind::Mutates) {
947        required_kinds.push(FailureKind::MissingState);
948    }
949    if matches!(idem_clause, Some(C::IdempotencyKeyed { .. })) {
950        required_kinds.push(FailureKind::IdempotencyConflict);
951    }
952    if matches!(
953        conc_clause,
954        Some(C::ConcurrencyUnique { .. } | C::ConcurrencyOptimistic { .. })
955    ) {
956        required_kinds.push(FailureKind::ConcurrencyConflict);
957    }
958    validate_failures(
959        &decl.name,
960        &ast_failures,
961        &required_kinds,
962        closure_codes,
963        site,
964        diags,
965    );
966    let declared_codes: Vec<&str> = ast_failures.iter().map(|(c, _, _)| c.as_str()).collect();
967
968    // Strategies (APP009/APP010).
969    let strategy_field = |field_name: &str,
970                          want_int: bool,
971                          need_state: bool,
972                          diags: &mut Vec<ApplicationDiagnostic>| {
973        let Some((_, input_rec)) = &input else { return };
974        match field(&input_rec.fields, field_name) {
975            Some(f) if !f.optional && is_scalar(f) => {
976                if want_int
977                    && !matches!(
978                        f.field_type,
979                        FieldType::Scalar {
980                            scalar: ScalarType::Int
981                        }
982                    )
983                {
984                    diags.push(site.diag(
985                        ApplicationDiagnosticCode::App009,
986                        format!(
987                            "strategy field '{field_name}' of operation '{}' must be a required int",
988                            decl.name
989                        ),
990                    ));
991                }
992                if need_state {
993                    let compatible = state.as_ref().is_some_and(|(_, e)| {
994                        field(&e.fields, field_name).is_some_and(|sf| {
995                            sf.field_type == f.field_type && !sf.optional
996                        })
997                    });
998                    if state.is_some() && !compatible {
999                        diags.push(site.diag(
1000                            ApplicationDiagnosticCode::App009,
1001                            format!(
1002                                "strategy field '{field_name}' of operation '{}' has no compatible required state field",
1003                                decl.name
1004                            ),
1005                        ));
1006                    }
1007                }
1008            }
1009            _ => diags.push(site.diag(
1010                ApplicationDiagnosticCode::App009,
1011                format!(
1012                    "strategy field '{field_name}' of operation '{}' must be a required scalar input field",
1013                    decl.name
1014                ),
1015            )),
1016        }
1017    };
1018    let pairing = |what: &str, diags: &mut Vec<ApplicationDiagnostic>| {
1019        diags.push(site.diag(
1020            ApplicationDiagnosticCode::App009,
1021            format!(
1022                "{what} of operation '{}' falls outside the §4 strategy/effect pairing",
1023                decl.name
1024            ),
1025        ));
1026    };
1027    let idempotency = match (effect, idem_clause) {
1028        (EffectKind::Creates | EffectKind::Mutates, Some(C::IdempotencyKeyed { field: f })) => {
1029            strategy_field(f, false, false, diags);
1030            IdempotencyStrategy::KeyedBy { field: f.clone() }
1031        }
1032        (EffectKind::Reads, Some(C::IdempotencyInherent)) => IdempotencyStrategy::Inherent,
1033        (
1034            EffectKind::Reads,
1035            Some(C::IdempotencyNotApplicable {
1036                reason,
1037                explanation,
1038            }),
1039        ) => {
1040            if reason != "read_only" {
1041                diags.push(site.diag(
1042                    ApplicationDiagnosticCode::App010,
1043                    format!(
1044                        "not_applicable reason '{reason}' on operation '{}' is not proven by its effect",
1045                        decl.name
1046                    ),
1047                ));
1048            }
1049            IdempotencyStrategy::NotApplicable(NotApplicable {
1050                explanation: explanation.clone(),
1051            })
1052        }
1053        (_, Some(C::IdempotencyNotApplicable { .. })) => {
1054            diags.push(site.diag(
1055                ApplicationDiagnosticCode::App010,
1056                format!(
1057                    "not_applicable idempotency on write operation '{}' has no reachable proof",
1058                    decl.name
1059                ),
1060            ));
1061            IdempotencyStrategy::Inherent
1062        }
1063        _ => {
1064            pairing("idempotency strategy", diags);
1065            IdempotencyStrategy::Inherent
1066        }
1067    };
1068    let concurrency = match (effect, conc_clause) {
1069        (EffectKind::Creates, Some(C::ConcurrencyUnique { field: f })) => {
1070            strategy_field(f, false, true, diags);
1071            ConcurrencyStrategy::UniqueKey { field: f.clone() }
1072        }
1073        (EffectKind::Mutates, Some(C::ConcurrencyOptimistic { field: f })) => {
1074            strategy_field(f, true, true, diags);
1075            ConcurrencyStrategy::OptimisticVersion { field: f.clone() }
1076        }
1077        (EffectKind::Reads, Some(C::ConcurrencyReadSnapshot)) => ConcurrencyStrategy::ReadSnapshot,
1078        _ => {
1079            pairing("concurrency strategy", diags);
1080            ConcurrencyStrategy::ReadSnapshot
1081        }
1082    };
1083
1084    // State lowering and output projection (APP011).
1085    if let (Some((_, input_rec)), Some((_, entity))) = (&input, &state) {
1086        let app011 = |msg: String, diags: &mut Vec<ApplicationDiagnostic>| {
1087            diags.push(site.diag(ApplicationDiagnosticCode::App011, msg));
1088        };
1089        let key_lookup = |diags: &mut Vec<ApplicationDiagnostic>| match field(
1090            &input_rec.fields,
1091            &entity.key_field,
1092        ) {
1093            Some(f) if !f.optional => {}
1094            _ => app011(
1095                format!(
1096                    "operation '{}' has no required input field matching entity key '{}'",
1097                    decl.name, entity.key_field
1098                ),
1099                diags,
1100            ),
1101        };
1102        match effect {
1103            EffectKind::Creates => {
1104                for sf in &entity.fields {
1105                    match field(&input_rec.fields, &sf.name) {
1106                        Some(inf) => {
1107                            if !type_and_constraints_match(inf, sf) {
1108                                app011(
1109                                    format!(
1110                                        "input field '{}' of operation '{}' is not compatible with its state field",
1111                                        sf.name, decl.name
1112                                    ),
1113                                    diags,
1114                                );
1115                            } else if inf.optional && !sf.optional && sf.default.is_none() {
1116                                app011(
1117                                    format!(
1118                                        "optional input field '{}' sources required state field of operation '{}' with no default",
1119                                        sf.name, decl.name
1120                                    ),
1121                                    diags,
1122                                );
1123                            }
1124                        }
1125                        None if sf.default.is_none() && !sf.optional => app011(
1126                            format!(
1127                                "create of operation '{}' cannot construct required state field '{}'",
1128                                decl.name, sf.name
1129                            ),
1130                            diags,
1131                        ),
1132                        None => {}
1133                    }
1134                }
1135            }
1136            EffectKind::Mutates => {
1137                key_lookup(diags);
1138                let strategy_fields: Vec<&str> = [
1139                    match &idempotency {
1140                        IdempotencyStrategy::KeyedBy { field } => Some(field.as_str()),
1141                        _ => None,
1142                    },
1143                    match &concurrency {
1144                        ConcurrencyStrategy::OptimisticVersion { field } => Some(field.as_str()),
1145                        _ => None,
1146                    },
1147                ]
1148                .into_iter()
1149                .flatten()
1150                .collect();
1151                for inf in &input_rec.fields {
1152                    if inf.name == entity.key_field || strategy_fields.contains(&inf.name.as_str())
1153                    {
1154                        continue;
1155                    }
1156                    match field(&entity.fields, &inf.name) {
1157                        Some(sf) if fields_compatible(inf, sf) => {}
1158                        Some(_) => app011(
1159                            format!(
1160                                "input field '{}' of operation '{}' is not compatible with its state field",
1161                                inf.name, decl.name
1162                            ),
1163                            diags,
1164                        ),
1165                        None => app011(
1166                            format!(
1167                                "mutate of operation '{}' contains unmapped input field '{}'",
1168                                decl.name, inf.name
1169                            ),
1170                            diags,
1171                        ),
1172                    }
1173                }
1174            }
1175            EffectKind::Reads => key_lookup(diags),
1176        }
1177        if let Some((_, output_rec)) = &output {
1178            for of in &output_rec.fields {
1179                match field(&entity.fields, &of.name) {
1180                    Some(sf) if fields_compatible(of, sf) => {}
1181                    _ => app011(
1182                        format!(
1183                            "output field '{}' of operation '{}' cannot project a same-named compatible state field",
1184                            of.name, decl.name
1185                        ),
1186                        diags,
1187                    ),
1188                }
1189            }
1190        }
1191    }
1192
1193    // Access.
1194    let access = match access_clause {
1195        Some(C::AccessPolicyGoverned { bindings }) => {
1196            let mut lowered = Vec::new();
1197            for binding in bindings {
1198                if binding.enforcement_point != "precondition" {
1199                    diags.push(site.diag(
1200                        ApplicationDiagnosticCode::App007,
1201                        format!(
1202                            "enforcement point '{}' on operation '{}' is reserved; only precondition is executable",
1203                            binding.enforcement_point, decl.name
1204                        ),
1205                    ));
1206                    continue;
1207                }
1208                let (alias, name) = split_symbol_ref(&binding.policy);
1209                let policy = match ctx.resolve_ref(symbol.module_index, alias, name) {
1210                    Some((s, "policy")) => {
1211                        if let past::AstNode::Policy {
1212                            metadata,
1213                            expression,
1214                            ..
1215                        } = ctx.decl_node(s)
1216                        {
1217                            if metadata.kind != Some(past::PolicyKind::Constraint) {
1218                                diags.push(site.diag(
1219                                    ApplicationDiagnosticCode::App007,
1220                                    format!(
1221                                        "policy '{}' bound by operation '{}' is not a constraint policy",
1222                                        binding.policy, decl.name
1223                                    ),
1224                                ));
1225                            }
1226                            let input_fields: Vec<&str> = input
1227                                .as_ref()
1228                                .map(|(_, r)| r.fields.iter().map(|f| f.name.as_str()).collect())
1229                                .unwrap_or_default();
1230                            let state_fields: Option<Vec<&str>> = state
1231                                .as_ref()
1232                                .map(|(_, e)| e.fields.iter().map(|f| f.name.as_str()).collect());
1233                            let mut resolve_role = |raw: &str| {
1234                                let (alias, name) = split_symbol_ref(raw);
1235                                matches!(
1236                                    ctx.resolve_ref(s.module_index, alias, name),
1237                                    Some((_, "role"))
1238                                )
1239                            };
1240                            for defect in crate::application::policy_context::validate_policy_subset(
1241                                expression,
1242                                &input_fields,
1243                                state_fields.as_deref(),
1244                                &mut resolve_role,
1245                            ) {
1246                                diags.push(site.diag(
1247                                    ApplicationDiagnosticCode::App007,
1248                                    format!(
1249                                        "policy '{}' bound by operation '{}' is not evaluable: {defect}",
1250                                        binding.policy, decl.name
1251                                    ),
1252                                ));
1253                            }
1254                        }
1255                        ctx.symbol_concept(s)
1256                    }
1257                    _ => {
1258                        diags.push(site.diag(
1259                            ApplicationDiagnosticCode::App007,
1260                            format!(
1261                                "policy '{}' bound by operation '{}' does not resolve",
1262                                binding.policy, decl.name
1263                            ),
1264                        ));
1265                        continue;
1266                    }
1267                };
1268                if !declared_codes.contains(&binding.failure_code.as_str()) {
1269                    diags.push(site.diag(
1270                        ApplicationDiagnosticCode::App008,
1271                        format!(
1272                            "policy binding of operation '{}' names undeclared failure code '{}'",
1273                            decl.name, binding.failure_code
1274                        ),
1275                    ));
1276                }
1277                lowered.push(PolicyBinding {
1278                    policy,
1279                    enforcement_point: EnforcementPoint::Precondition,
1280                    failure_code: binding.failure_code.clone(),
1281                });
1282            }
1283            AccessMode::PolicyGoverned { bindings: lowered }
1284        }
1285        _ => AccessMode::Public,
1286    };
1287
1288    if diags.len() != before {
1289        return None;
1290    }
1291    Some(OperationContract {
1292        id: ApplicationSymbolId(symbol.qualified_id.clone()),
1293        name: nfc(&decl.name),
1294        intent: nfc(&intent),
1295        direction: Direction::Inbound,
1296        actor,
1297        access,
1298        input: ApplicationSymbolId(input.map(|(id, _)| id).unwrap_or_default()),
1299        output: ApplicationSymbolId(output.map(|(id, _)| id).unwrap_or_default()),
1300        state: state
1301            .map(|(_, e)| e.concept_id.clone())
1302            .unwrap_or_else(|| ConceptId::from_concept("", "")),
1303        effect,
1304        transaction,
1305        failures: ast_failures
1306            .into_iter()
1307            .map(|(code, kinds, meaning)| FailureContract {
1308                code,
1309                kinds,
1310                meaning: nfc(&meaning),
1311            })
1312            .collect(),
1313        idempotency,
1314        concurrency,
1315        evidence: EvidenceKind::OperationTrace,
1316        lifecycle: LifecycleKind::SynchronousRequestResponse,
1317    })
1318}
1319
1320fn resolve_fields(
1321    ctx: &Ctx,
1322    symbol: &ResolvedSymbol,
1323    fields: &[past::FieldDecl],
1324    is_entity: bool,
1325    site: DeclSite,
1326    diags: &mut Vec<ApplicationDiagnostic>,
1327) -> Vec<FieldContract> {
1328    fields
1329        .iter()
1330        .filter_map(|field| {
1331            let field_type = resolve_field_type(
1332                ctx,
1333                symbol.module_index,
1334                &field.field_type,
1335                field,
1336                site,
1337                diags,
1338            )?;
1339            let constraints =
1340                resolve_constraints(ctx, symbol.module_index, &field_type, field, site, diags);
1341            let default = if is_entity {
1342                match &field.default {
1343                    Some(expr) => resolve_default(
1344                        ctx,
1345                        symbol,
1346                        &field_type,
1347                        &constraints,
1348                        expr,
1349                        field,
1350                        site,
1351                        diags,
1352                    ),
1353                    None => None,
1354                }
1355            } else {
1356                None // record defaults already reported by check_record_defaults
1357            };
1358            Some(FieldContract {
1359                name: nfc(&field.name),
1360                field_type,
1361                optional: field.is_optional,
1362                constraints,
1363                default,
1364            })
1365        })
1366        .collect()
1367}
1368
1369fn scalar_type(symbol: &str) -> Option<ScalarType> {
1370    Some(match symbol {
1371        "string" => ScalarType::String,
1372        "int" => ScalarType::Int,
1373        "decimal" => ScalarType::Decimal,
1374        "bool" => ScalarType::Bool,
1375        "timestamp" => ScalarType::Timestamp,
1376        "uuid" => ScalarType::Uuid,
1377        _ => return None,
1378    })
1379}
1380
1381fn resolve_field_type(
1382    ctx: &Ctx,
1383    module_index: usize,
1384    ty: &past::FieldType,
1385    field: &past::FieldDecl,
1386    site: DeclSite,
1387    diags: &mut Vec<ApplicationDiagnostic>,
1388) -> Option<FieldType> {
1389    let unknown = |diags: &mut Vec<ApplicationDiagnostic>, what: &str| {
1390        diags.push(site.diag(
1391            ApplicationDiagnosticCode::App002,
1392            format!(
1393                "{what} on field '{}' does not resolve in the symbol table",
1394                field.name
1395            ),
1396        ));
1397    };
1398    match ty {
1399        past::FieldType::Scalar(r) => match scalar_type(&r.symbol) {
1400            Some(scalar) => Some(FieldType::Scalar { scalar }),
1401            None => {
1402                unknown(diags, &format!("scalar type '{}'", r.symbol));
1403                None
1404            }
1405        },
1406        past::FieldType::Quantity(r) => {
1407            match ctx.resolve_ref(module_index, r.alias.as_deref(), &r.symbol) {
1408                Some((symbol, "unit")) => Some(FieldType::Quantity {
1409                    unit: ctx.symbol_concept(symbol),
1410                }),
1411                _ => {
1412                    unknown(diags, &format!("quantity unit '{}'", r.symbol));
1413                    None
1414                }
1415            }
1416        }
1417        past::FieldType::Ref(r) => {
1418            match ctx.resolve_ref(module_index, r.alias.as_deref(), &r.symbol) {
1419                Some((symbol, "entity")) => Some(FieldType::EntityRef {
1420                    entity: ctx.symbol_concept(symbol),
1421                }),
1422                Some(_) => {
1423                    diags.push(site.diag(
1424                        ApplicationDiagnosticCode::App002,
1425                        format!(
1426                            "ref '{}' on field '{}' resolves to a non-entity declaration",
1427                            r.symbol, field.name
1428                        ),
1429                    ));
1430                    None
1431                }
1432                None => {
1433                    unknown(diags, &format!("ref '{}'", r.symbol));
1434                    None
1435                }
1436            }
1437        }
1438        past::FieldType::Named(r) => {
1439            match ctx.resolve_ref(module_index, r.alias.as_deref(), &r.symbol) {
1440                Some((symbol, "enum")) => Some(FieldType::Enum {
1441                    symbol: ApplicationSymbolId(symbol.qualified_id.clone()),
1442                }),
1443                Some((_, "record")) => {
1444                    diags.push(site.diag(
1445                        ApplicationDiagnosticCode::App003,
1446                        format!(
1447                            "field '{}' nests record '{}'; the closed type model forbids nested records",
1448                            field.name, r.symbol
1449                        ),
1450                    ));
1451                    None
1452                }
1453                Some((_, slug)) => {
1454                    diags.push(site.diag(
1455                        ApplicationDiagnosticCode::App002,
1456                        format!(
1457                            "named type '{}' on field '{}' resolves to {slug}, which is not a field type",
1458                            r.symbol, field.name
1459                        ),
1460                    ));
1461                    None
1462                }
1463                None => {
1464                    unknown(diags, &format!("named type '{}'", r.symbol));
1465                    None
1466                }
1467            }
1468        }
1469        past::FieldType::List(inner) => {
1470            if matches!(**inner, past::FieldType::List(_)) {
1471                diags.push(site.diag(
1472                    ApplicationDiagnosticCode::App003,
1473                    format!("field '{}' nests a list inside a list", field.name),
1474                ));
1475                return None;
1476            }
1477            let element = resolve_field_type(ctx, module_index, inner, field, site, diags)?;
1478            Some(FieldType::List {
1479                element: Box::new(element),
1480            })
1481        }
1482    }
1483}
1484
1485/// True when `value` fits the §6 decimal envelope (28 significant digits;
1486/// rust_decimal already caps scale at 28).
1487fn decimal_fits(value: &rust_decimal::Decimal) -> bool {
1488    value.mantissa().unsigned_abs().to_string().len() <= 28
1489}
1490
1491fn describe_field_type(field_type: &FieldType) -> &'static str {
1492    match field_type {
1493        FieldType::Scalar { scalar } => match scalar {
1494            ScalarType::String => "string",
1495            ScalarType::Int => "int",
1496            ScalarType::Decimal => "decimal",
1497            ScalarType::Bool => "bool",
1498            ScalarType::Timestamp => "timestamp",
1499            ScalarType::Uuid => "uuid",
1500        },
1501        FieldType::Quantity { .. } => "quantity",
1502        FieldType::EntityRef { .. } => "ref",
1503        FieldType::Enum { .. } => "enum",
1504        FieldType::List { .. } => "list",
1505    }
1506}
1507
1508/// Reference §4/§5 constraint semantics (APP012): applicability per field
1509/// type, at most one member per bound family, non-empty intervals under the
1510/// inclusivity rules, the 28-digit decimal envelope, and pattern resolution.
1511/// Stored decimal bounds are scale-normalized so equal values share one
1512/// canonical spelling.
1513fn resolve_constraints(
1514    ctx: &Ctx,
1515    module_index: usize,
1516    field_type: &FieldType,
1517    field: &past::FieldDecl,
1518    site: DeclSite,
1519    diags: &mut Vec<ApplicationDiagnostic>,
1520) -> Vec<FieldConstraint> {
1521    use past::FieldConstraintDecl as C;
1522    let numeric = matches!(
1523        field_type,
1524        FieldType::Scalar {
1525            scalar: ScalarType::Int | ScalarType::Decimal
1526        } | FieldType::Quantity { .. }
1527    );
1528    let stringy = matches!(
1529        field_type,
1530        FieldType::Scalar {
1531            scalar: ScalarType::String
1532        }
1533    );
1534    let listy = matches!(field_type, FieldType::List { .. });
1535    let app012 = |msg: String, diags: &mut Vec<ApplicationDiagnostic>| {
1536        diags.push(site.diag(ApplicationDiagnosticCode::App012, msg));
1537    };
1538    let inapplicable = |slug: &str, diags: &mut Vec<ApplicationDiagnostic>| {
1539        app012(
1540            format!(
1541                "constraint '{slug}' on field '{}' does not apply to its {} type",
1542                field.name,
1543                describe_field_type(field_type)
1544            ),
1545            diags,
1546        );
1547    };
1548    let u32_bound = |value: u64, diags: &mut Vec<ApplicationDiagnostic>| -> Option<u32> {
1549        u32::try_from(value).ok().or_else(|| {
1550            app012(
1551                format!(
1552                    "length/item bound {value} on field '{}' overflows",
1553                    field.name
1554                ),
1555                diags,
1556            );
1557            None
1558        })
1559    };
1560    // (slug, applicable) per bound family; > 1 member is a duplicate.
1561    let mut family_counts: HashMap<&'static str, u32> = HashMap::new();
1562    let mut lower: Option<(rust_decimal::Decimal, bool)> = None; // (value, inclusive)
1563    let mut upper: Option<(rust_decimal::Decimal, bool)> = None;
1564    let mut min_len: Option<u32> = None;
1565    let mut max_len: Option<u32> = None;
1566    let mut min_items: Option<u32> = None;
1567    let mut max_items: Option<u32> = None;
1568    let mut resolved = Vec::new();
1569
1570    for constraint in &field.constraints {
1571        let (slug, family, applicable) = match constraint {
1572            C::Min(_) => ("min", "lower bound", numeric),
1573            C::ExclusiveMin(_) => ("exclusive_min", "lower bound", numeric),
1574            C::Max(_) => ("max", "upper bound", numeric),
1575            C::ExclusiveMax(_) => ("exclusive_max", "upper bound", numeric),
1576            C::MinLength(_) => ("min_length", "min_length", stringy),
1577            C::MaxLength(_) => ("max_length", "max_length", stringy),
1578            C::MinItems(_) => ("min_items", "min_items", listy),
1579            C::MaxItems(_) => ("max_items", "max_items", listy),
1580            C::Pattern(_) => ("pattern", "pattern", stringy),
1581        };
1582        if !applicable {
1583            inapplicable(slug, diags);
1584            continue;
1585        }
1586        let count = family_counts.entry(family).or_insert(0);
1587        *count += 1;
1588        if *count > 1 {
1589            app012(
1590                format!(
1591                    "field '{}' declares more than one {family} constraint",
1592                    field.name
1593                ),
1594                diags,
1595            );
1596            continue;
1597        }
1598        let decimal_bound =
1599            |v: &rust_decimal::Decimal, diags: &mut Vec<ApplicationDiagnostic>| -> Option<_> {
1600                if decimal_fits(v) {
1601                    Some(v.normalize())
1602                } else {
1603                    app012(
1604                        format!(
1605                            "bound on field '{}' exceeds 28 significant decimal digits",
1606                            field.name
1607                        ),
1608                        diags,
1609                    );
1610                    None
1611                }
1612            };
1613        match constraint {
1614            C::Min(v) => {
1615                let Some(v) = decimal_bound(v, diags) else {
1616                    continue;
1617                };
1618                lower = Some((v, true));
1619                resolved.push(FieldConstraint::Min { value: v });
1620            }
1621            C::ExclusiveMin(v) => {
1622                let Some(v) = decimal_bound(v, diags) else {
1623                    continue;
1624                };
1625                lower = Some((v, false));
1626                resolved.push(FieldConstraint::ExclusiveMin { value: v });
1627            }
1628            C::Max(v) => {
1629                let Some(v) = decimal_bound(v, diags) else {
1630                    continue;
1631                };
1632                upper = Some((v, true));
1633                resolved.push(FieldConstraint::Max { value: v });
1634            }
1635            C::ExclusiveMax(v) => {
1636                let Some(v) = decimal_bound(v, diags) else {
1637                    continue;
1638                };
1639                upper = Some((v, false));
1640                resolved.push(FieldConstraint::ExclusiveMax { value: v });
1641            }
1642            C::MinLength(v) => {
1643                if let Some(v) = u32_bound(*v, diags) {
1644                    min_len = Some(v);
1645                    resolved.push(FieldConstraint::MinLength { value: v });
1646                }
1647            }
1648            C::MaxLength(v) => {
1649                if let Some(v) = u32_bound(*v, diags) {
1650                    max_len = Some(v);
1651                    resolved.push(FieldConstraint::MaxLength { value: v });
1652                }
1653            }
1654            C::MinItems(v) => {
1655                if let Some(v) = u32_bound(*v, diags) {
1656                    min_items = Some(v);
1657                    resolved.push(FieldConstraint::MinItems { value: v });
1658                }
1659            }
1660            C::MaxItems(v) => {
1661                if let Some(v) = u32_bound(*v, diags) {
1662                    max_items = Some(v);
1663                    resolved.push(FieldConstraint::MaxItems { value: v });
1664                }
1665            }
1666            C::Pattern(raw) => {
1667                let (alias, name) = split_symbol_ref(raw);
1668                match ctx.resolve_ref(module_index, alias, name) {
1669                    Some((symbol, "pattern")) => resolved.push(FieldConstraint::Pattern {
1670                        pattern: ctx.symbol_concept(symbol),
1671                    }),
1672                    _ => app012(
1673                        format!(
1674                            "pattern '{raw}' on field '{}' does not resolve to a declared SEA Pattern",
1675                            field.name
1676                        ),
1677                        diags,
1678                    ),
1679                }
1680            }
1681        }
1682    }
1683
1684    // Interval rules: quantity bounds share the field's declared unit, so the
1685    // §4 base-unit normalization cancels out and values compare directly.
1686    if let (Some((lo, lo_inclusive)), Some((hi, hi_inclusive))) = (lower, upper) {
1687        if lo > hi || (lo == hi && !(lo_inclusive && hi_inclusive)) {
1688            app012(
1689                format!(
1690                    "bounds on field '{}' describe an empty interval under the inclusivity rules",
1691                    field.name
1692                ),
1693                diags,
1694            );
1695        }
1696    }
1697    for (label, min, max) in [("length", min_len, max_len), ("item", min_items, max_items)] {
1698        if let (Some(min), Some(max)) = (min, max) {
1699            if min > max {
1700                app012(
1701                    format!(
1702                        "{label} bounds on field '{}' describe an empty interval",
1703                        field.name
1704                    ),
1705                    diags,
1706                );
1707            }
1708        }
1709    }
1710    resolved
1711}
1712
1713/// The declared unit of a quantity field: (namespace, factor, base symbol).
1714fn quantity_unit_info(
1715    ctx: &Ctx,
1716    module_index: usize,
1717    field: &past::FieldDecl,
1718) -> Option<(String, rust_decimal::Decimal, String)> {
1719    let past::FieldType::Quantity(r) = &field.field_type else {
1720        return None;
1721    };
1722    let (symbol, _) = ctx.resolve_ref(module_index, r.alias.as_deref(), &r.symbol)?;
1723    let past::AstNode::UnitDeclaration {
1724        factor, base_unit, ..
1725    } = ctx.decl_node(symbol)
1726    else {
1727        return None;
1728    };
1729    Some((
1730        ctx.module_namespace(symbol.module_index),
1731        *factor,
1732        base_unit.clone(),
1733    ))
1734}
1735
1736/// Numeric magnitude a default contributes to bound checks. Quantity bounds
1737/// are authored in the field's declared unit, so the stored base value is
1738/// divided back through the declared factor.
1739fn default_magnitude(
1740    typed: &TypedValue,
1741    unit_factor: Option<rust_decimal::Decimal>,
1742) -> Option<rust_decimal::Decimal> {
1743    match typed {
1744        TypedValue::Int(i) => Some(rust_decimal::Decimal::from(*i)),
1745        TypedValue::Decimal(d) => Some(*d),
1746        TypedValue::Quantity { base_value, .. } => {
1747            let factor = unit_factor?;
1748            base_value.checked_div(factor)
1749        }
1750        _ => None,
1751    }
1752}
1753
1754/// First constraint the default violates, as display text (reference §4:
1755/// defaults are validated against every field constraint).
1756fn default_constraint_violation(
1757    ctx: &Ctx,
1758    module_index: usize,
1759    typed: &TypedValue,
1760    constraints: &[FieldConstraint],
1761    field: &past::FieldDecl,
1762) -> Option<String> {
1763    let magnitude = default_magnitude(
1764        typed,
1765        quantity_unit_info(ctx, module_index, field).map(|(_, f, _)| f),
1766    );
1767    let text = match typed {
1768        TypedValue::String(s) => Some(s.as_str()),
1769        _ => None,
1770    };
1771    for constraint in constraints {
1772        let violated = match constraint {
1773            FieldConstraint::Min { value } => magnitude.is_some_and(|m| m < *value),
1774            FieldConstraint::Max { value } => magnitude.is_some_and(|m| m > *value),
1775            FieldConstraint::ExclusiveMin { value } => magnitude.is_some_and(|m| m <= *value),
1776            FieldConstraint::ExclusiveMax { value } => magnitude.is_some_and(|m| m >= *value),
1777            FieldConstraint::MinLength { value } => {
1778                text.is_some_and(|t| t.chars().count() < *value as usize)
1779            }
1780            FieldConstraint::MaxLength { value } => {
1781                text.is_some_and(|t| t.chars().count() > *value as usize)
1782            }
1783            FieldConstraint::MinItems { .. } | FieldConstraint::MaxItems { .. } => false,
1784            FieldConstraint::Pattern { .. } => text.is_some_and(|t| {
1785                // Recover the declared regex through the authored pattern ref.
1786                field.constraints.iter().any(|c| {
1787                    let past::FieldConstraintDecl::Pattern(raw) = c else {
1788                        return false;
1789                    };
1790                    let (alias, name) = split_symbol_ref(raw);
1791                    let Some((symbol, "pattern")) = ctx.resolve_ref(module_index, alias, name)
1792                    else {
1793                        return false;
1794                    };
1795                    let past::AstNode::Pattern { regex, .. } = ctx.decl_node(symbol) else {
1796                        return false;
1797                    };
1798                    !regex::Regex::new(regex).is_ok_and(|re| re.is_match(t))
1799                })
1800            }),
1801        };
1802        if violated {
1803            return Some(
1804                serde_json::to_value(constraint)
1805                    .ok()
1806                    .and_then(|v| v["kind"].as_str().map(str::to_string))
1807                    .unwrap_or_else(|| "constraint".to_string()),
1808            );
1809        }
1810    }
1811    None
1812}
1813
1814/// Convert an authored entity-field default literal into a normalized
1815/// `TypedValue` that satisfies the resolved field type and every field
1816/// constraint (reference §4; APP003 on violation). Only required, non-key
1817/// fields of scalar, quantity, or enum type may carry a default.
1818#[allow(clippy::too_many_arguments)]
1819fn resolve_default(
1820    ctx: &Ctx,
1821    owner: &ResolvedSymbol,
1822    field_type: &FieldType,
1823    constraints: &[FieldConstraint],
1824    expr: &Expression,
1825    field: &past::FieldDecl,
1826    site: DeclSite,
1827    diags: &mut Vec<ApplicationDiagnostic>,
1828) -> Option<TypedValue> {
1829    let app003 = |msg: String, diags: &mut Vec<ApplicationDiagnostic>| {
1830        diags.push(site.diag(ApplicationDiagnosticCode::App003, msg));
1831    };
1832    if field.is_optional {
1833        app003(
1834            format!(
1835                "optional field '{}' declares a default; defaults are required-field-only",
1836                field.name
1837            ),
1838            diags,
1839        );
1840        return None;
1841    }
1842    if field.is_key {
1843        return None; // APP005 already reported by check_entity_key
1844    }
1845    if matches!(
1846        field_type,
1847        FieldType::EntityRef { .. } | FieldType::List { .. }
1848    ) {
1849        app003(
1850            format!(
1851                "field '{}' declares a default on a {} type; refs and lists must not",
1852                field.name,
1853                describe_field_type(field_type)
1854            ),
1855            diags,
1856        );
1857        return None;
1858    }
1859    let mismatch = |diags: &mut Vec<ApplicationDiagnostic>| {
1860        diags.push(site.diag(
1861            ApplicationDiagnosticCode::App003,
1862            format!(
1863                "default on field '{}' does not satisfy its declared type",
1864                field.name
1865            ),
1866        ));
1867    };
1868
1869    // Quantity defaults lower to the base-unit value (§6).
1870    if let FieldType::Quantity { .. } = field_type {
1871        let Some((unit_namespace, field_factor, base_symbol)) =
1872            quantity_unit_info(ctx, owner.module_index, field)
1873        else {
1874            mismatch(diags);
1875            return None;
1876        };
1877        let authored = match expr {
1878            Expression::Literal(serde_json::Value::Number(n)) => Some((
1879                rust_decimal::Decimal::from_str(&n.to_string()).ok()?,
1880                field_factor,
1881            )),
1882            Expression::QuantityLiteral { value, unit } => {
1883                // Any unit sharing the field unit's base is convertible.
1884                match ctx.resolve_ref(owner.module_index, None, unit) {
1885                    Some((s, "unit")) => match ctx.decl_node(s) {
1886                        past::AstNode::UnitDeclaration {
1887                            factor, base_unit, ..
1888                        } if *base_unit == base_symbol => Some((*value, *factor)),
1889                        _ => None,
1890                    },
1891                    _ => None,
1892                }
1893            }
1894            _ => None,
1895        };
1896        let Some((value, factor)) = authored else {
1897            mismatch(diags);
1898            return None;
1899        };
1900        let Some(base_value) = value.checked_mul(factor).filter(decimal_fits) else {
1901            diags.push(site.diag(
1902                ApplicationDiagnosticCode::App012,
1903                format!(
1904                    "base-unit normalization of the default on field '{}' overflows the decimal envelope",
1905                    field.name
1906                ),
1907            ));
1908            return None;
1909        };
1910        let typed = TypedValue::Quantity {
1911            base_value: base_value.normalize(),
1912            unit: ConceptId::from_concept(&unit_namespace, &base_symbol),
1913        };
1914        if let Some(kind) =
1915            default_constraint_violation(ctx, owner.module_index, &typed, constraints, field)
1916        {
1917            app003(
1918                format!(
1919                    "default on field '{}' violates its {kind} constraint",
1920                    field.name
1921                ),
1922                diags,
1923            );
1924            return None;
1925        }
1926        return Some(typed);
1927    }
1928
1929    let Expression::Literal(value) = expr else {
1930        mismatch(diags);
1931        return None;
1932    };
1933    let typed = match (field_type, value) {
1934        (
1935            FieldType::Scalar {
1936                scalar: ScalarType::String,
1937            },
1938            serde_json::Value::String(s),
1939        ) => TypedValue::String(nfc(s)),
1940        (
1941            FieldType::Scalar {
1942                scalar: ScalarType::Bool,
1943            },
1944            serde_json::Value::Bool(b),
1945        ) => TypedValue::Bool(*b),
1946        (
1947            FieldType::Scalar {
1948                scalar: ScalarType::Int,
1949            },
1950            serde_json::Value::Number(n),
1951        ) => {
1952            // The parser carries numeric literals as JSON floats; accept any
1953            // integral spelling that fits i64.
1954            use rust_decimal::prelude::ToPrimitive;
1955            let value = rust_decimal::Decimal::from_str(&n.to_string())
1956                .ok()
1957                .filter(rust_decimal::Decimal::is_integer)
1958                .and_then(|d| d.to_i64());
1959            match value {
1960                Some(i) => TypedValue::Int(i),
1961                None => {
1962                    mismatch(diags);
1963                    return None;
1964                }
1965            }
1966        }
1967        (
1968            FieldType::Scalar {
1969                scalar: ScalarType::Decimal,
1970            },
1971            serde_json::Value::Number(n),
1972        ) => {
1973            let d = rust_decimal::Decimal::from_str(&n.to_string()).ok()?;
1974            if !decimal_fits(&d) {
1975                diags.push(site.diag(
1976                    ApplicationDiagnosticCode::App012,
1977                    format!(
1978                        "default on field '{}' exceeds 28 significant decimal digits",
1979                        field.name
1980                    ),
1981                ));
1982                return None;
1983            }
1984            TypedValue::Decimal(d.normalize())
1985        }
1986        (
1987            FieldType::Scalar {
1988                scalar: ScalarType::Uuid,
1989            },
1990            serde_json::Value::String(s),
1991        ) => TypedValue::Uuid(uuid::Uuid::from_str(s).ok().or_else(|| {
1992            mismatch(diags);
1993            None
1994        })?),
1995        (
1996            FieldType::Scalar {
1997                scalar: ScalarType::Timestamp,
1998            },
1999            serde_json::Value::String(s),
2000        ) => TypedValue::Timestamp(
2001            crate::timefmt::parse_rfc3339_exact(s)
2002                .ok()
2003                .map(|t| t.to_offset(time::UtcOffset::UTC))
2004                .or_else(|| {
2005                    mismatch(diags);
2006                    None
2007                })?,
2008        ),
2009        (FieldType::Enum { symbol }, serde_json::Value::String(wire)) => {
2010            let enum_symbol = ctx.set.symbols.get(&symbol.0)?;
2011            let past::AstNode::Enum(decl) = ctx.decl_node(enum_symbol) else {
2012                return None;
2013            };
2014            if decl.members.iter().any(|m| m.wire == *wire) {
2015                TypedValue::Enum {
2016                    symbol: symbol.clone(),
2017                    wire: nfc(wire),
2018                }
2019            } else {
2020                diags.push(site.diag(
2021                    ApplicationDiagnosticCode::App003,
2022                    format!(
2023                        "default \"{wire}\" on field '{}' of '{}' is not a wire value of the referenced enum",
2024                        field.name, owner.qualified_id
2025                    ),
2026                ));
2027                return None;
2028            }
2029        }
2030        _ => {
2031            mismatch(diags);
2032            return None;
2033        }
2034    };
2035    if let Some(kind) =
2036        default_constraint_violation(ctx, owner.module_index, &typed, constraints, field)
2037    {
2038        app003(
2039            format!(
2040                "default on field '{}' violates its {kind} constraint",
2041                field.name
2042            ),
2043            diags,
2044        );
2045        return None;
2046    }
2047    Some(typed)
2048}