use crate::application::canonical::{canonical_decimal, nfc};
use crate::application::contract::*;
use crate::application::diagnostic::{ApplicationDiagnostic, ApplicationDiagnosticCode};
use crate::application::resolve::{
Ctx, APPLICATION_CONTRACT_SCHEMA_VERSION, INTERPRETATION_VERSION, LANGUAGE_SCHEMA_VERSION,
};
use crate::concept_id::ConceptId;
use crate::module::resolver::ResolvedModuleSet;
use crate::parser::ast as past;
use crate::parser::ast_schema as schema;
use crate::semantic_pack::{canonical_json, compute_sha256};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub const ENVELOPE_SCHEMA_VERSION: &str = "domainforge-semantic-envelope/v1";
pub const CANONICALIZATION_VERSION: &str = "domainforge-canonicalization/v1";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticEnvelopeDocument {
pub schema_version: String,
pub producer: ProducerIdentity,
pub inputs: ApplicationContractInputs,
pub self_hash: String,
pub semantic_closure_hash: String,
pub envelope: CanonicalSemanticEnvelope,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticEnvelope {
pub language_schema_version: String,
pub canonicalization_version: String,
pub compiler_interpretation_version: String,
pub modules: Vec<CanonicalModuleRef>,
pub import_graph: Vec<CanonicalImportEdge>,
pub namespace_bindings: Vec<CanonicalNamespaceBinding>,
pub semantic_packs: Vec<CanonicalSemanticPackRef>,
pub semantic_declarations: Vec<CanonicalSemanticDeclaration>,
pub resolved_references: Vec<CanonicalResolvedReference>,
pub application_contract: ApplicationContract,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalModuleRef {
pub logical_id: String,
pub semantic_content_hash: String,
pub namespace: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalImportEdge {
pub importer: String,
pub imported: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalNamespaceBinding {
pub namespace: String,
pub logical_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticPackRef {
pub pack_id: String,
pub content_hash: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalSemanticDeclaration {
pub id: CanonicalDeclarationId,
pub logical_module_id: String,
pub declaration: CanonicalSemanticPayload,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "kind",
content = "data",
rename_all = "snake_case",
deny_unknown_fields
)]
pub enum CanonicalDeclarationId {
Concept {
id: ConceptId,
},
Application {
id: ApplicationSymbolId,
},
Occurrence {
kind: String,
content_hash: String,
duplicate_index: u32,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "kind",
content = "data",
rename_all = "snake_case",
deny_unknown_fields
)]
pub enum CanonicalReferenceTarget {
Declaration {
id: CanonicalDeclarationId,
},
Namespace {
exact_name: String,
logical_module_id: String,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalResolvedReference {
pub source: CanonicalDeclarationId,
pub field_path: String,
pub target: CanonicalReferenceTarget,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
tag = "kind",
content = "data",
rename_all = "snake_case",
deny_unknown_fields
)]
pub enum CanonicalSemanticPayload {
Dimension(CanonicalDimensionDecl),
Unit(CanonicalUnitDecl),
Record(RecordContract),
Enum(EnumContract),
Operation(OperationContract),
Entity(CanonicalEntityDecl),
Resource(CanonicalResourceDecl),
Flow(CanonicalFlowDecl),
Pattern(CanonicalPatternDecl),
Role(CanonicalRoleDecl),
Relation(CanonicalRelationDecl),
RoleBinding(CanonicalRoleBindingDecl),
Instance(CanonicalInstanceDecl),
Policy(CanonicalPolicyDecl),
ConceptChange(CanonicalConceptChangeDecl),
Metric(CanonicalMetricDecl),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalDimensionDecl {
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalUnitDecl {
pub symbol: String,
pub dimension: CanonicalReferenceTarget,
pub factor: String,
pub base_unit: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalEntityDecl {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
pub annotations: BTreeMap<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub contract: Option<EntityContract>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalResourceDecl {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unit: Option<CanonicalReferenceTarget>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
pub annotations: BTreeMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalFlowDecl {
pub resource: CanonicalReferenceTarget,
pub from_entity: CanonicalReferenceTarget,
pub to_entity: CanonicalReferenceTarget,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quantity: Option<String>,
pub annotations: BTreeMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalPatternDecl {
pub name: String,
pub regex: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalRoleDecl {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalRelationDecl {
pub name: String,
pub subject_role: CanonicalReferenceTarget,
pub predicate: String,
pub object_role: CanonicalReferenceTarget,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub via_flow: Option<CanonicalReferenceTarget>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalRoleBindingDecl {
pub role: CanonicalReferenceTarget,
pub entity: CanonicalReferenceTarget,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalInstanceDecl {
pub name: String,
pub entity_type: CanonicalReferenceTarget,
pub fields: BTreeMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalPolicyDecl {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
pub metadata: serde_json::Value,
pub expression: serde_json::Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalConceptChangeDecl {
pub name: String,
pub from_version: String,
pub to_version: String,
pub migration_policy: String,
pub breaking_change: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CanonicalMetricDecl {
pub name: String,
pub expression: serde_json::Value,
pub metadata: serde_json::Value,
}
const KIND_RANK: [&str; 15] = [
"dimension",
"unit",
"record",
"enum",
"operation",
"entity",
"resource",
"flow",
"pattern",
"role",
"relation",
"instance",
"policy",
"concept_change",
"metric",
];
fn kind_rank(kind: &str) -> usize {
KIND_RANK
.iter()
.position(|k| *k == kind)
.unwrap_or(usize::MAX)
}
fn resolved_target(
ctx: &Ctx,
module_index: usize,
namespace: &str,
raw: &str,
slugs: &'static [&'static str],
) -> CanonicalReferenceTarget {
let id = ctx
.resolve_concept(module_index, raw, slugs)
.unwrap_or_else(|| ConceptId::from_concept(namespace, raw));
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Concept { id },
}
}
fn rewrite_role_references(value: &mut serde_json::Value, ctx: &Ctx, module_index: usize) {
match value {
serde_json::Value::Object(map) => {
if map.get("type").and_then(serde_json::Value::as_str) == Some("RoleReference") {
if let Some(serde_json::Value::String(role)) = map.get_mut("role") {
if let Some(id) = ctx.resolve_concept(module_index, role, &["role"]) {
*role = id.to_string();
}
}
}
for (_, nested) in map.iter_mut() {
rewrite_role_references(nested, ctx, module_index);
}
}
serde_json::Value::Array(items) => {
for item in items {
rewrite_role_references(item, ctx, module_index);
}
}
_ => {}
}
}
fn sorted_annotations(
annotations: &std::collections::HashMap<String, serde_json::Value>,
) -> BTreeMap<String, serde_json::Value> {
annotations
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
fn expr_value(expr: &crate::policy::Expression) -> serde_json::Value {
serde_json::to_value(schema::Expression::from(expr)).expect("schema expression serializes")
}
#[allow(clippy::too_many_lines)]
fn classify(
node: &past::AstNode,
namespace: &str,
contract: &ApplicationContract,
ctx: &Ctx,
module_index: usize,
) -> Option<(
&'static str,
CanonicalDeclarationId,
CanonicalSemanticPayload,
)> {
use past::AstNode as N;
let target = |raw: &str, slugs: &'static [&'static str]| {
resolved_target(ctx, module_index, namespace, raw, slugs)
};
let concept_id = |name: &str| CanonicalDeclarationId::Concept {
id: ConceptId::from_concept(namespace, name),
};
let app_id = |slug: &str, name: &str| CanonicalDeclarationId::Application {
id: ApplicationSymbolId(format!("{namespace}.{slug}.{}", nfc(name))),
};
Some(match node {
N::Export(_) => unreachable!("export wrappers are unwrapped before classification"),
N::Dimension { name } => (
"dimension",
concept_id(name),
CanonicalSemanticPayload::Dimension(CanonicalDimensionDecl { name: name.clone() }),
),
N::UnitDeclaration {
symbol,
dimension,
factor,
base_unit,
} => (
"unit",
concept_id(symbol),
CanonicalSemanticPayload::Unit(CanonicalUnitDecl {
symbol: symbol.clone(),
dimension: target(dimension, &["dimension"]),
factor: canonical_decimal(*factor),
base_unit: base_unit.clone(),
}),
),
N::Record(decl) => {
let id = app_id("record", &decl.name);
let payload = contract
.records
.iter()
.find(|r| matches!(&id, CanonicalDeclarationId::Application { id } if *id == r.id))?
.clone();
("record", id, CanonicalSemanticPayload::Record(payload))
}
N::Enum(decl) => {
let id = app_id("enum", &decl.name);
let payload = contract
.enums
.iter()
.find(|e| matches!(&id, CanonicalDeclarationId::Application { id } if *id == e.id))?
.clone();
("enum", id, CanonicalSemanticPayload::Enum(payload))
}
N::Operation(decl) => {
let id = app_id("operation", &decl.name);
let payload = contract
.operations
.iter()
.find(|o| matches!(&id, CanonicalDeclarationId::Application { id } if *id == o.id))?
.clone();
(
"operation",
id,
CanonicalSemanticPayload::Operation(payload),
)
}
N::Entity {
name,
version,
annotations,
domain,
body,
} => {
let entity_concept = ConceptId::from_concept(namespace, name);
let entity_contract = body.as_ref().and_then(|_| {
contract
.entities
.iter()
.find(|e| e.concept_id == entity_concept)
.cloned()
});
(
"entity",
concept_id(name),
CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
name: name.clone(),
version: version.clone(),
domain: domain.clone(),
annotations: sorted_annotations(annotations),
contract: entity_contract,
}),
)
}
N::Resource {
name,
annotations,
unit_name,
domain,
} => (
"resource",
concept_id(name),
CanonicalSemanticPayload::Resource(CanonicalResourceDecl {
name: name.clone(),
unit: unit_name.as_ref().map(|u| target(u, &["unit"])),
domain: domain.clone(),
annotations: sorted_annotations(annotations),
}),
),
N::Flow {
resource_name,
annotations,
from_entity,
to_entity,
quantity,
} => {
let payload = CanonicalSemanticPayload::Flow(CanonicalFlowDecl {
resource: target(resource_name, &["resource"]),
from_entity: target(from_entity, &["entity"]),
to_entity: target(to_entity, &["entity"]),
quantity: quantity.map(canonical_decimal),
annotations: sorted_annotations(annotations),
});
let content_hash = compute_sha256(
canonical_json(&serde_json::to_value(&payload).expect("flow serializes"))
.as_bytes(),
);
(
"flow",
CanonicalDeclarationId::Occurrence {
kind: "flow".to_string(),
content_hash,
duplicate_index: 0,
},
payload,
)
}
N::Pattern { name, regex } => (
"pattern",
concept_id(name),
CanonicalSemanticPayload::Pattern(CanonicalPatternDecl {
name: name.clone(),
regex: regex.clone(),
}),
),
N::Role { name, domain } => (
"role",
concept_id(name),
CanonicalSemanticPayload::Role(CanonicalRoleDecl {
name: name.clone(),
domain: domain.clone(),
}),
),
N::Relation {
name,
subject_role,
predicate,
object_role,
via_flow,
} => (
"relation",
concept_id(name),
CanonicalSemanticPayload::Relation(CanonicalRelationDecl {
name: name.clone(),
subject_role: target(subject_role, &["role"]),
predicate: predicate.clone(),
object_role: target(object_role, &["role"]),
via_flow: via_flow.as_ref().map(|f| target(f, &["flow"])),
}),
),
N::RoleBinding { role, entity } => (
"role_binding",
concept_id(&format!(
"role_binding:{}",
serde_json::to_string(&[role.as_str(), entity.as_str()])
.expect("role/entity pair serializes")
)),
CanonicalSemanticPayload::RoleBinding(CanonicalRoleBindingDecl {
role: target(role, &["role"]),
entity: target(entity, &["entity"]),
}),
),
N::Instance {
name,
entity_type,
fields,
} => (
"instance",
CanonicalDeclarationId::Concept {
id: ConceptId::from_concept(namespace, &format!("{entity_type}:{name}")),
},
CanonicalSemanticPayload::Instance(CanonicalInstanceDecl {
name: name.clone(),
entity_type: target(entity_type, &["entity"]),
fields: fields
.iter()
.map(|(k, v)| (k.clone(), expr_value(v)))
.collect(),
}),
),
N::Policy {
name,
version,
metadata,
expression,
} => {
let mut expression = expr_value(expression);
rewrite_role_references(&mut expression, ctx, module_index);
(
"policy",
concept_id(name),
CanonicalSemanticPayload::Policy(CanonicalPolicyDecl {
name: name.clone(),
version: version.clone(),
metadata: serde_json::to_value(schema::PolicyMetadata::from(metadata))
.expect("policy metadata serializes"),
expression,
}),
)
}
N::ConceptChange {
name,
from_version,
to_version,
migration_policy,
breaking_change,
} => (
"concept_change",
concept_id(name),
CanonicalSemanticPayload::ConceptChange(CanonicalConceptChangeDecl {
name: name.clone(),
from_version: from_version.clone(),
to_version: to_version.clone(),
migration_policy: migration_policy.clone(),
breaking_change: *breaking_change,
}),
),
N::Metric {
name,
expression,
metadata,
} => (
"metric",
concept_id(name),
CanonicalSemanticPayload::Metric(CanonicalMetricDecl {
name: name.clone(),
expression: expr_value(expression),
metadata: serde_json::to_value(schema::MetricMetadata::from(metadata))
.expect("metric metadata serializes"),
}),
),
N::MappingDecl { .. }
| N::ProjectionDecl { .. }
| N::Cell { .. }
| N::SystemDependency { .. }
| N::Runtime { .. }
| N::Tool { .. }
| N::DependencySet { .. }
| N::Service { .. }
| N::Mount { .. }
| N::Endpoint { .. }
| N::NetworkFlow { .. }
| N::Credential { .. } => return None,
})
}
fn id_sort_key(id: &CanonicalDeclarationId) -> String {
canonical_json(&serde_json::to_value(id).expect("declaration id serializes"))
}
pub(crate) fn build_envelope(
set: &ResolvedModuleSet,
contract: &ApplicationContract,
semantic_packs: &[(String, String)],
) -> CanonicalSemanticEnvelope {
let ctx = Ctx::new(set);
let mut declarations: Vec<(usize, CanonicalSemanticDeclaration)> = Vec::new();
let mut namespace_bindings = Vec::new();
let mut module_decl_hashes: Vec<(String, String, Vec<serde_json::Value>)> = Vec::new();
for (module_index, module) in set.modules.iter().enumerate() {
let namespace = module
.ast
.metadata
.namespace
.clone()
.unwrap_or_else(|| module.logical_id.clone());
namespace_bindings.push(CanonicalNamespaceBinding {
namespace: namespace.clone(),
logical_id: module.logical_id.clone(),
});
let mut module_payloads = Vec::new();
for spanned in &module.ast.declarations {
let node = match &spanned.node {
past::AstNode::Export(inner) => &inner.node,
other => other,
};
if let Some((kind, id, payload)) =
classify(node, &namespace, contract, &ctx, module_index)
{
module_payloads.push(serde_json::to_value(&payload).expect("payload serializes"));
declarations.push((
kind_rank(kind),
CanonicalSemanticDeclaration {
id,
logical_module_id: module.logical_id.clone(),
declaration: payload,
},
));
}
}
module_decl_hashes.push((module.logical_id.clone(), namespace, module_payloads));
}
let mut occurrence_counts: BTreeMap<String, u32> = BTreeMap::new();
for (_, decl) in &mut declarations {
if let CanonicalDeclarationId::Occurrence {
content_hash,
duplicate_index,
..
} = &mut decl.id
{
let count = occurrence_counts.entry(content_hash.clone()).or_default();
*duplicate_index = *count;
*count += 1;
}
}
declarations.sort_by(|a, b| {
(&a.1.logical_module_id, a.0, id_sort_key(&a.1.id)).cmp(&(
&b.1.logical_module_id,
b.0,
id_sort_key(&b.1.id),
))
});
let semantic_declarations: Vec<CanonicalSemanticDeclaration> =
declarations.into_iter().map(|(_, d)| d).collect();
module_decl_hashes.sort_by(|a, b| a.0.cmp(&b.0));
let modules = module_decl_hashes
.into_iter()
.map(|(logical_id, namespace, mut payloads)| {
payloads.sort_by_key(canonical_json);
CanonicalModuleRef {
logical_id,
semantic_content_hash: compute_sha256(
canonical_json(&serde_json::Value::Array(payloads)).as_bytes(),
),
namespace,
}
})
.collect();
namespace_bindings.sort_by(
|a: &CanonicalNamespaceBinding, b: &CanonicalNamespaceBinding| {
(&a.namespace, &a.logical_id).cmp(&(&b.namespace, &b.logical_id))
},
);
let mut import_graph: Vec<CanonicalImportEdge> = set
.import_graph
.iter()
.map(|e| CanonicalImportEdge {
importer: e.importer.clone(),
imported: e.imported.clone(),
})
.collect();
import_graph.sort_by(|a, b| (&a.importer, &a.imported).cmp(&(&b.importer, &b.imported)));
import_graph.dedup();
let mut resolved_references = collect_references(&semantic_declarations);
resolved_references.sort_by_key(|r| {
(
id_sort_key(&r.source),
r.field_path.clone(),
canonical_json(&serde_json::to_value(&r.target).expect("target serializes")),
)
});
CanonicalSemanticEnvelope {
language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
canonicalization_version: CANONICALIZATION_VERSION.to_string(),
compiler_interpretation_version: INTERPRETATION_VERSION.to_string(),
modules,
import_graph,
namespace_bindings,
semantic_packs: semantic_packs
.iter()
.map(|(pack_id, content_hash)| CanonicalSemanticPackRef {
pack_id: pack_id.clone(),
content_hash: content_hash.clone(),
})
.collect(),
semantic_declarations,
resolved_references,
application_contract: contract.clone(),
}
}
fn collect_references(
declarations: &[CanonicalSemanticDeclaration],
) -> Vec<CanonicalResolvedReference> {
let mut refs = Vec::new();
let mut push =
|source: &CanonicalDeclarationId, path: String, target: CanonicalReferenceTarget| {
refs.push(CanonicalResolvedReference {
source: source.clone(),
field_path: path,
target,
});
};
let field_refs =
|source: &CanonicalDeclarationId,
fields: &[FieldContract],
refs: &mut dyn FnMut(&CanonicalDeclarationId, String, CanonicalReferenceTarget)| {
for field in fields {
let base = format!("fields.{}.field_type", field.name);
match &field.field_type {
FieldType::Quantity { unit } => refs(
source,
format!("{base}.unit"),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Concept { id: unit.clone() },
},
),
FieldType::EntityRef { entity } => refs(
source,
format!("{base}.entity"),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Concept { id: entity.clone() },
},
),
FieldType::Enum { symbol } => refs(
source,
format!("{base}.symbol"),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Application { id: symbol.clone() },
},
),
FieldType::Scalar { .. } | FieldType::List { .. } => {}
}
for (index, constraint) in field.constraints.iter().enumerate() {
if let FieldConstraint::Pattern { pattern } = constraint {
refs(
source,
format!("fields.{}.constraints.{index}.pattern", field.name),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Concept {
id: pattern.clone(),
},
},
);
}
}
}
};
for decl in declarations {
match &decl.declaration {
CanonicalSemanticPayload::Record(record) => {
field_refs(&decl.id, &record.fields, &mut push)
}
CanonicalSemanticPayload::Entity(CanonicalEntityDecl {
contract: Some(entity),
..
}) => field_refs(&decl.id, &entity.fields, &mut push),
CanonicalSemanticPayload::Operation(op) => {
push(
&decl.id,
"input".to_string(),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Application {
id: op.input.clone(),
},
},
);
push(
&decl.id,
"output".to_string(),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Application {
id: op.output.clone(),
},
},
);
push(
&decl.id,
"state".to_string(),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Concept {
id: op.state.clone(),
},
},
);
if let ActorRef::Role { role } = &op.actor {
push(
&decl.id,
"actor.role".to_string(),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Concept { id: role.clone() },
},
);
}
if let AccessMode::PolicyGoverned { bindings } = &op.access {
for (index, binding) in bindings.iter().enumerate() {
push(
&decl.id,
format!("access.bindings.{index}.policy"),
CanonicalReferenceTarget::Declaration {
id: CanonicalDeclarationId::Concept {
id: binding.policy.clone(),
},
},
);
}
}
}
_ => {}
}
}
refs
}
pub fn resolve_semantic_envelope(
entry_logical_path: &str,
sources_json: &str,
) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
resolve_semantic_envelope_with_packs(entry_logical_path, sources_json, &[])
}
pub fn resolve_semantic_envelope_with_packs(
entry_logical_path: &str,
sources_json: &str,
semantic_packs: &[(String, String)],
) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
use crate::module::resolver::{resolve_source_map, SourceMap};
crate::application::resolve::enforce_source_map_budget(sources_json)?;
let pack_set_hash = crate::application::resolve::validated_pack_set_hash(semantic_packs)?;
let sources = SourceMap::parse_json(sources_json)?;
let resolved = resolve_source_map(entry_logical_path, &sources)?;
let contract = crate::application::resolve::build_contract(&resolved)?;
let envelope = build_envelope(&resolved, &contract, semantic_packs);
let closure_hash = semantic_closure_hash(&envelope);
let mut doc = CanonicalSemanticEnvelopeDocument {
schema_version: ENVELOPE_SCHEMA_VERSION.to_string(),
producer: ProducerIdentity {
name: "domainforge-core".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
},
inputs: ApplicationContractInputs {
source_set_hash: crate::application::canonical::source_set_hash(
sources
.0
.iter()
.map(|(id, src)| (id.as_str(), src.as_str())),
)
.expect("duplicates already rejected"),
semantic_pack_set_hash: pack_set_hash,
language_schema_version: LANGUAGE_SCHEMA_VERSION.to_string(),
interpretation_version: INTERPRETATION_VERSION.to_string(),
},
self_hash: format!("sha256:{}", "0".repeat(64)),
semantic_closure_hash: closure_hash,
envelope,
};
doc.self_hash = envelope_document_self_hash(&doc);
Ok(doc)
}
pub fn semantic_closure_hash(envelope: &CanonicalSemanticEnvelope) -> String {
compute_sha256(
canonical_json(&serde_json::to_value(envelope).expect("envelope serializes")).as_bytes(),
)
}
pub fn envelope_document_self_hash(doc: &CanonicalSemanticEnvelopeDocument) -> String {
let mut value = serde_json::to_value(doc).expect("envelope document serializes");
value
.as_object_mut()
.expect("document is an object")
.remove("self_hash");
compute_sha256(canonical_json(&value).as_bytes())
}
pub(crate) fn is_hash(value: &str) -> bool {
value.strip_prefix("sha256:").is_some_and(|hex| {
hex.len() == 64
&& hex
.chars()
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
})
}
fn app015(document_kind: &str, field_path: &str, message: String) -> ApplicationDiagnostic {
let mut d = ApplicationDiagnostic::new(ApplicationDiagnosticCode::App015, message);
d.context.document_kind = Some(document_kind.to_string());
d.context.field_path = Some(field_path.to_string());
d
}
const KNOWN_PRODUCERS: &[&str] = &["domainforge-core"];
fn validate_producer(
diags: &mut Vec<ApplicationDiagnostic>,
kind: &str,
producer: &ProducerIdentity,
) {
if !KNOWN_PRODUCERS.contains(&producer.name.as_str()) {
diags.push(app015(
kind,
"/producer/name",
format!("unknown producer '{}'", producer.name),
));
}
if producer.version.trim().is_empty() {
diags.push(app015(
kind,
"/producer/version",
"producer version is empty".to_string(),
));
}
}
fn validate_inputs(
diags: &mut Vec<ApplicationDiagnostic>,
kind: &str,
inputs: &ApplicationContractInputs,
) {
for (path, value) in [
("/inputs/source_set_hash", &inputs.source_set_hash),
(
"/inputs/semantic_pack_set_hash",
&inputs.semantic_pack_set_hash,
),
] {
if !is_hash(value) {
diags.push(app015(
kind,
path,
format!("'{value}' is not a lowercase sha256:<hex> hash"),
));
}
}
if inputs.language_schema_version != LANGUAGE_SCHEMA_VERSION {
let mut d = app015(
kind,
"/inputs/language_schema_version",
format!(
"expected language_schema_version '{}', got '{}'",
LANGUAGE_SCHEMA_VERSION, inputs.language_schema_version
),
);
d.context.expected = Some(LANGUAGE_SCHEMA_VERSION.to_string());
d.context.actual = Some(inputs.language_schema_version.clone());
diags.push(d);
}
if inputs.interpretation_version != INTERPRETATION_VERSION {
let mut d = app015(
kind,
"/inputs/interpretation_version",
format!(
"expected interpretation_version '{}', got '{}'",
INTERPRETATION_VERSION, inputs.interpretation_version
),
);
d.context.expected = Some(INTERPRETATION_VERSION.to_string());
d.context.actual = Some(inputs.interpretation_version.clone());
diags.push(d);
}
}
pub fn validate_application_contract_document_json(
json: &str,
) -> Result<ApplicationContractDocument, Vec<ApplicationDiagnostic>> {
let kind = "application_contract";
let doc: ApplicationContractDocument = serde_json::from_str(json)
.map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
let mut diags = Vec::new();
if doc.schema_version != APPLICATION_CONTRACT_SCHEMA_VERSION {
let mut d = app015(
kind,
"/schema_version",
format!("unexpected schema_version '{}'", doc.schema_version),
);
d.context.schema_version = Some(doc.schema_version.clone());
diags.push(d);
}
validate_producer(&mut diags, kind, &doc.producer);
validate_inputs(&mut diags, kind, &doc.inputs);
for (path, value) in [
("/self_hash", &doc.self_hash),
("/semantic_closure_hash", &doc.semantic_closure_hash),
] {
if !is_hash(value) {
diags.push(app015(
kind,
path,
format!("'{value}' is not a lowercase sha256:<hex> hash"),
));
}
}
if diags.is_empty() && doc.self_hash != crate::application::canonical::document_self_hash(&doc)
{
diags.push(app015(
kind,
"/self_hash",
"self_hash does not match the canonical document bytes".to_string(),
));
}
if diags.is_empty() {
Ok(doc)
} else {
Err(diags)
}
}
pub fn validate_semantic_envelope_document_json(
json: &str,
) -> Result<CanonicalSemanticEnvelopeDocument, Vec<ApplicationDiagnostic>> {
let kind = "canonical_semantic_envelope";
let doc: CanonicalSemanticEnvelopeDocument = serde_json::from_str(json)
.map_err(|e| vec![app015(kind, "", format!("document fails its schema: {e}"))])?;
let mut diags = Vec::new();
if doc.schema_version != ENVELOPE_SCHEMA_VERSION {
let mut d = app015(
kind,
"/schema_version",
format!("unexpected schema_version '{}'", doc.schema_version),
);
d.context.schema_version = Some(doc.schema_version.clone());
diags.push(d);
}
validate_producer(&mut diags, kind, &doc.producer);
validate_inputs(&mut diags, kind, &doc.inputs);
for (path, value) in [
("/self_hash", &doc.self_hash),
("/semantic_closure_hash", &doc.semantic_closure_hash),
] {
if !is_hash(value) {
diags.push(app015(
kind,
path,
format!("'{value}' is not a lowercase sha256:<hex> hash"),
));
}
}
let env = &doc.envelope;
if env.language_schema_version != doc.inputs.language_schema_version {
diags.push(app015(
kind,
"/envelope/language_schema_version",
format!(
"envelope language_schema_version '{}' does not match inputs '{}'",
env.language_schema_version, doc.inputs.language_schema_version
),
));
}
if env.compiler_interpretation_version != doc.inputs.interpretation_version {
diags.push(app015(
kind,
"/envelope/compiler_interpretation_version",
format!(
"envelope compiler_interpretation_version '{}' does not match inputs '{}'",
env.compiler_interpretation_version, doc.inputs.interpretation_version
),
));
}
if env.canonicalization_version != CANONICALIZATION_VERSION {
diags.push(app015(
kind,
"/envelope/canonicalization_version",
format!(
"expected canonicalization_version '{}', got '{}'",
CANONICALIZATION_VERSION, env.canonicalization_version
),
));
}
for (index, pack) in env.semantic_packs.iter().enumerate() {
if pack.pack_id.is_empty() {
diags.push(app015(
kind,
&format!("/envelope/semantic_packs/{index}/pack_id"),
"semantic pack has an empty pack_id".to_string(),
));
}
if !is_hash(&pack.content_hash) {
diags.push(app015(
kind,
&format!("/envelope/semantic_packs/{index}/content_hash"),
format!(
"semantic pack '{}' content_hash '{}' is not a lowercase sha256:<hex> hash",
pack.pack_id, pack.content_hash
),
));
}
}
if diags.is_empty() {
let pack_pairs: Vec<(String, String)> = env
.semantic_packs
.iter()
.map(|p| (p.pack_id.clone(), p.content_hash.clone()))
.collect();
match crate::application::canonical::semantic_pack_set_hash(&pack_pairs) {
Ok(recomputed) if recomputed == doc.inputs.semantic_pack_set_hash => {}
Ok(recomputed) => diags.push(app015(
kind,
"/inputs/semantic_pack_set_hash",
format!(
"semantic_pack_set_hash '{}' does not match the envelope's packs ('{}')",
doc.inputs.semantic_pack_set_hash, recomputed
),
)),
Err(reason) => diags.push(app015(
kind,
"/inputs/semantic_pack_set_hash",
format!("semantic_pack_set_hash cannot be recomputed: {reason}"),
)),
}
}
if diags.is_empty() {
if doc.semantic_closure_hash != semantic_closure_hash(&doc.envelope) {
diags.push(app015(
kind,
"/semantic_closure_hash",
"semantic_closure_hash does not match the canonical envelope bytes".to_string(),
));
}
if doc.self_hash != envelope_document_self_hash(&doc) {
diags.push(app015(
kind,
"/self_hash",
"self_hash does not match the canonical document bytes".to_string(),
));
}
}
if diags.is_empty() {
Ok(doc)
} else {
Err(diags)
}
}
pub const CEP_SNAPSHOT_KNOWN_OMISSIONS: [&str; 3] = [
"source_comments",
"source_formatting",
"source_line_positions",
];
pub const CEP_SNAPSHOT_OMISSION_REASON: &str =
"domainforge canonical envelope is formatting- and comment-independent by construction";
pub const CEP_SNAPSHOT_OMISSION_RECOVERABLE_FROM: &str =
"the .sea sources at the recorded git blob hashes";
pub const CEP_ENVELOPE_VERSION: &str = "1.0.0";
pub const CEP_ENVELOPE_KIND_SEMANTIC_SNAPSHOT: &str = "semantic_snapshot";
pub const CEP_PRODUCER_NAME: &str = "domainforge";
pub const CEP_VERSION: &str = "0.1.0";
pub struct CepEnvelopeParams<'a> {
pub doc: Option<&'a CanonicalSemanticEnvelopeDocument>,
pub model_valid: bool,
pub source_set_hash: &'a str,
pub invalid_declared_checkpoint_hash: Option<&'a str>,
pub diagnostics: &'a [String],
pub scope: serde_json::Value,
pub entry_logical_path: &'a str,
pub inline_threshold_bytes: u64,
pub envelope_id: &'a str,
pub created_at: &'a str,
pub registry_content_hash: Option<&'a str>,
pub resolved_namespaces: &'a [(String, String)],
pub world: Option<CepWorldParams<'a>>,
}
#[derive(Debug, Clone, Copy)]
pub struct CepWorldParams<'a> {
pub name: &'a super::world::WorldName,
pub alias: Option<&'a super::world::WorldAlias>,
pub label: Option<&'a super::world::WorldLabel>,
}
pub const CEP_PROFILE_SEMANTIC_SNAPSHOT: &str = "godspeed.semantic_snapshot";
pub const CEP_PROFILE_VERSION: &str = "1.0.0";
pub fn build_cep_envelope(p: &CepEnvelopeParams<'_>) -> serde_json::Value {
let created_by = format!("{} {}", CEP_PRODUCER_NAME, env!("CARGO_PKG_VERSION"));
let source_set_ref = format!("source-set:{}", p.source_set_hash);
let mut known_omissions: Vec<String> = CEP_SNAPSHOT_KNOWN_OMISSIONS
.iter()
.map(|s| s.to_string())
.collect();
if p.doc.is_none() {
known_omissions.push("canonical_representation_D".to_string());
}
let included_sections: Vec<&str> = if p.doc.is_some() {
vec!["representations", "references", "provenance"]
} else {
vec!["omissions", "references", "provenance"]
};
let mut envelope = serde_json::Map::new();
envelope.insert("envelope_id".to_string(), serde_json::json!(p.envelope_id));
envelope.insert("cep_version".to_string(), serde_json::json!(CEP_VERSION));
envelope.insert(
"envelope_version".to_string(),
serde_json::json!(CEP_ENVELOPE_VERSION),
);
envelope.insert(
"envelope_kind".to_string(),
serde_json::json!(CEP_ENVELOPE_KIND_SEMANTIC_SNAPSHOT),
);
envelope.insert("created_at".to_string(), serde_json::json!(p.created_at));
envelope.insert("created_by".to_string(), serde_json::json!(created_by));
let pinned = match (p.world, p.doc) {
(Some(world), Some(doc)) if p.model_valid => {
let identity = DomainModelIdentity::from_document(doc, p.registry_content_hash);
super::world::WorldRef::from_identity(world.name.clone(), &identity)
.ok()
.map(|world_ref| (world, identity, world_ref))
}
_ => None,
};
let mut scope = p.scope.clone();
if let (Some((world, _, world_ref)), Some(object)) = (&pinned, scope.as_object_mut()) {
object.insert(
"world_ref".to_string(),
serde_json::json!(world_ref.to_string()),
);
if let Some(alias) = world.alias {
object.insert(
"world_alias".to_string(),
serde_json::json!(alias.to_string()),
);
}
if let Some(label) = world.label {
object.insert("world_label".to_string(), serde_json::json!(label.as_str()));
}
}
envelope.insert("scope".to_string(), scope);
envelope.insert(
"boundary_record".to_string(),
serde_json::json!({
"scope": p.entry_logical_path,
"included_sections": included_sections,
"excluded_sections": [],
"known_omissions": known_omissions,
"unknowns": [],
"redactions": [],
"compression_notes": [],
"out_of_scope_entities": [],
"limitations": [],
}),
);
envelope.insert(
"completeness_status".to_string(),
serde_json::json!(if p.doc.is_some() {
"complete_for_declared_state"
} else {
"incomplete_for_declared_state"
}),
);
envelope.insert(
"provenance_refs".to_string(),
serde_json::json!([source_set_ref]),
);
envelope.insert(
"omission_status".to_string(),
serde_json::json!("known_omissions_recorded"),
);
envelope.insert("lineage_refs".to_string(), serde_json::json!([]));
envelope.insert(
"provenance".to_string(),
serde_json::json!([{
"provenance_id": format!("provenance:{}", p.envelope_id),
"source_system_refs": [format!("source-set:{}", p.source_set_hash)],
"producer_refs": [created_by],
"production_method": "domainforge envelope --emit cep",
"created_at": p.created_at,
"verification_status": "unverified",
"review_status": "unreviewed",
}]),
);
envelope.insert(
"references".to_string(),
serde_json::json!([{
"ref_id": format!(
"source-set:{}",
p.source_set_hash.strip_prefix("sha256:").unwrap_or(p.source_set_hash)
),
"ref_type": "source_set",
"target_uri_or_id": p.entry_logical_path,
"target_hash": p.source_set_hash,
"availability_status": "available",
"integrity_status": "verifiable",
"scope": p.entry_logical_path,
}]),
);
let mut extensions = serde_json::Map::new();
match p.doc {
Some(doc) => {
envelope.insert(
"validation_status".to_string(),
serde_json::json!("validated"),
);
let representation = build_representation(p, doc, &created_by);
envelope.insert(
"representations".to_string(),
serde_json::json!([representation]),
);
if !p.model_valid {
extensions.insert(
"domainforge".to_string(),
serde_json::json!({
"model_validation_status": "invalid",
"diagnostics": p.diagnostics,
}),
);
}
if let Some((_, identity, _)) = &pinned {
envelope.insert(
"integrity".to_string(),
serde_json::json!({
"content_hash": identity.content_hash,
"semantic_hash": identity.semantic_closure_hash,
}),
);
extensions.insert(
"domainforge.identity".to_string(),
serde_json::json!({
"domain_model_identity": identity,
"semantic_closure_hash": identity.semantic_closure_hash,
}),
);
}
}
None => {
envelope.insert(
"conformance_status".to_string(),
serde_json::json!("conformant"),
);
envelope.insert(
"validation_status".to_string(),
serde_json::json!("validated"),
);
envelope.insert(
"omissions".to_string(),
serde_json::json!([{
"omission_id": format!(
"omission:representation:{}",
p.invalid_declared_checkpoint_hash
.unwrap_or_default()
.strip_prefix("sha256:")
.unwrap_or_default()
),
"omission_type": "representation_unavailable",
"description": "canonical D not constructed; declared model invalid",
"reason": "model validation failed",
"known_or_suspected": "known",
"impact": "no semantic hash derivable",
"affected_entities": [p.entry_logical_path],
}]),
);
extensions.insert(
"domainforge".to_string(),
serde_json::json!({
"model_validation_status": "invalid",
"invalid_declared_checkpoint_hash": p.invalid_declared_checkpoint_hash,
"diagnostics": p.diagnostics,
}),
);
}
}
if p.world.is_some() {
extensions.insert(
"cep.profile".to_string(),
serde_json::json!({
"profile_id": CEP_PROFILE_SEMANTIC_SNAPSHOT,
"profile_version": CEP_PROFILE_VERSION,
}),
);
}
if !extensions.is_empty() {
envelope.insert(
"extensions".to_string(),
serde_json::Value::Object(extensions),
);
}
serde_json::Value::Object(envelope)
}
fn build_representation(
p: &CepEnvelopeParams<'_>,
doc: &CanonicalSemanticEnvelopeDocument,
created_by: &str,
) -> serde_json::Value {
let canonical_bytes = canonical_json(&serde_json::to_value(doc).expect("document serializes"));
let size_bytes = canonical_bytes.len() as u64;
let inline = size_bytes <= p.inline_threshold_bytes;
let mut representation = serde_json::Map::new();
representation.insert(
"representation_id".to_string(),
serde_json::json!(format!("representation:{}", doc.self_hash)),
);
representation.insert(
"representation_kind".to_string(),
serde_json::json!("derived"),
);
representation.insert(
"representation_type".to_string(),
serde_json::json!("domainforge_semantic_envelope_document"),
);
representation.insert("scope".to_string(), serde_json::json!(p.entry_logical_path));
representation.insert("source".to_string(), serde_json::json!(created_by));
if inline {
representation.insert(
"inline_content".to_string(),
serde_json::json!(canonical_bytes),
);
} else {
representation.insert(
"content_ref".to_string(),
serde_json::json!(format!(
"cas://sha256:{}",
doc.self_hash
.strip_prefix("sha256:")
.unwrap_or(&doc.self_hash)
)),
);
}
representation.insert("content_hash".to_string(), serde_json::json!(doc.self_hash));
representation.insert(
"semantic_hash".to_string(),
serde_json::json!(doc.semantic_closure_hash),
);
representation.insert(
"content_availability".to_string(),
serde_json::json!("available"),
);
representation.insert("size_bytes".to_string(), serde_json::json!(size_bytes));
representation.insert(
"media_type".to_string(),
serde_json::json!("application/json"),
);
representation.insert(
"preserved_entities".to_string(),
serde_json::json!(doc
.envelope
.semantic_declarations
.iter()
.map(|declaration| declaration_entity_ref(&declaration.id))
.collect::<Vec<_>>()),
);
representation.insert(
"preserved_distinctions".to_string(),
serde_json::json!(["declared_vs_observed", "representation_vs_reality"]),
);
representation.insert(
"omission_record".to_string(),
serde_json::json!({
"known_omissions": CEP_SNAPSHOT_KNOWN_OMISSIONS,
"reason": CEP_SNAPSHOT_OMISSION_REASON,
"recoverable_from": CEP_SNAPSHOT_OMISSION_RECOVERABLE_FROM,
}),
);
representation.insert(
"provenance_record".to_string(),
serde_json::json!({
"producer": {
"name": doc.producer.name,
"version": doc.producer.version,
},
"inputs": {
"source_set_hash": doc.inputs.source_set_hash,
"semantic_pack_set_hash": doc.inputs.semantic_pack_set_hash,
"language_schema_version": doc.inputs.language_schema_version,
"interpretation_version": doc.inputs.interpretation_version,
},
"resolution_inputs": {
"entry_logical_path": p.entry_logical_path,
"registry_content_hash": p.registry_content_hash,
"resolved_namespaces": p.resolved_namespaces
.iter()
.map(|(id, namespace)| (id.clone(), namespace.clone()))
.collect::<BTreeMap<String, String>>(),
},
}),
);
representation.insert(
"validation_status".to_string(),
serde_json::json!(if p.model_valid { "valid" } else { "invalid" }),
);
serde_json::Value::Object(representation)
}
pub fn declaration_entity_ref(id: &CanonicalDeclarationId) -> String {
match id {
CanonicalDeclarationId::Concept { id } => format!("concept:{}", id),
CanonicalDeclarationId::Application { id } => format!("application:{}", id.0),
CanonicalDeclarationId::Occurrence {
kind,
content_hash,
duplicate_index,
} => format!("occurrence:{}:{}:{}", kind, content_hash, duplicate_index),
}
}
pub fn invalid_declared_checkpoint_hash(
source_set_hash: &str,
semantic_pack_set_hash: &str,
entry_logical_path: &str,
registry_content_hash: Option<&str>,
resolved_namespaces: &[(String, String)],
) -> String {
let namespaces: serde_json::Map<String, serde_json::Value> = resolved_namespaces
.iter()
.map(|(id, namespace)| (id.clone(), serde_json::Value::String(namespace.clone())))
.collect();
let payload = serde_json::json!({
"source_set_hash": source_set_hash,
"semantic_pack_set_hash": semantic_pack_set_hash,
"language_schema_version": LANGUAGE_SCHEMA_VERSION,
"interpretation_version": INTERPRETATION_VERSION,
"producer": {
"name": CEP_PRODUCER_NAME,
"version": env!("CARGO_PKG_VERSION"),
},
"entry_logical_path": entry_logical_path,
"registry_content_hash": registry_content_hash,
"resolved_namespaces": namespaces,
});
compute_sha256(canonical_json(&payload).as_bytes())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DomainModelIdentity {
pub identity_scheme_version: String,
pub producer: String,
pub producer_version: String,
pub language_schema_version: String,
pub compiler_interpretation_version: String,
pub canonicalization_version: String,
pub source_set_hash: String,
pub content_hash: String,
pub semantic_closure_hash: String,
pub semantic_pack_set_hash: Option<String>,
pub registry_content_hash: Option<String>,
}
impl DomainModelIdentity {
pub fn canonical_digest(&self) -> String {
let value = serde_json::to_value(self).expect("DomainModelIdentity serializes");
compute_sha256(canonical_json(&value).as_bytes())
}
}