Skip to main content

domainforge_core/graph/
mod.rs

1use crate::application::{ApplicationContract, ApplicationSymbolId, EntityContract, EnumContract};
2use crate::patterns::Pattern;
3use crate::policy::{Policy, Severity, Violation};
4use crate::primitives::{
5    ConceptChange, Entity, Flow, Instance, MappingContract, Metric, ProjectionContract,
6    RelationType, Resource, ResourceInstance, Role,
7};
8use crate::validation_result::ValidationResult;
9use crate::ConceptId;
10use indexmap::IndexMap;
11use serde::{Deserialize, Serialize};
12
13/// A dimension declared by the parsed SEA source.
14///
15/// This is intentionally graph-owned rather than read from `UnitRegistry`:
16/// the registry also contains ambient builtins and uses an unordered map.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18pub struct DeclaredDimension {
19    pub id: ConceptId,
20    pub name: String,
21    pub namespace: String,
22}
23
24/// A unit declared by the parsed SEA source.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct DeclaredUnit {
27    pub id: ConceptId,
28    pub name: String,
29    pub namespace: String,
30    pub dimension: String,
31    pub base_factor: String,
32    pub base_unit: String,
33}
34
35mod entity_validation;
36pub mod to_ast;
37
38/// Configuration for graph evaluation behavior
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct GraphConfig {
41    /// Enable three-valued logic (True, False, NULL) for policy evaluation.
42    /// When false, uses strict boolean logic (True, False).
43    pub use_three_valued_logic: bool,
44}
45
46impl Default for GraphConfig {
47    fn default() -> Self {
48        Self {
49            // Default to three-valued logic for backward compatibility with the feature flag
50            use_three_valued_logic: true,
51        }
52    }
53}
54
55#[derive(Debug, Clone, Default, Serialize, Deserialize)]
56pub struct Graph {
57    entities: IndexMap<ConceptId, Entity>,
58    roles: IndexMap<ConceptId, Role>,
59    resources: IndexMap<ConceptId, Resource>,
60    flows: IndexMap<ConceptId, Flow>,
61    relations: IndexMap<ConceptId, RelationType>,
62    instances: IndexMap<ConceptId, ResourceInstance>,
63    /// Entity instances keyed by ConceptId for consistency with other graph collections.
64    entity_instances: IndexMap<ConceptId, Instance>,
65    policies: IndexMap<ConceptId, Policy>,
66    #[serde(default)]
67    patterns: IndexMap<ConceptId, Pattern>,
68    #[serde(default)]
69    concept_changes: IndexMap<ConceptId, ConceptChange>,
70    #[serde(default)]
71    metrics: IndexMap<ConceptId, Metric>,
72    #[serde(default)]
73    mappings: IndexMap<ConceptId, MappingContract>,
74    #[serde(default)]
75    projections: IndexMap<ConceptId, ProjectionContract>,
76    /// Source declarations, kept separately from the global unit registry so
77    /// bindings can expose only this graph's declarations in source order.
78    #[serde(default)]
79    declared_dimensions: IndexMap<ConceptId, DeclaredDimension>,
80    #[serde(default)]
81    declared_units: IndexMap<ConceptId, DeclaredUnit>,
82    #[serde(default)]
83    entity_roles: IndexMap<ConceptId, Vec<ConceptId>>,
84    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
85    entity_contracts: IndexMap<ConceptId, EntityContract>,
86    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
87    enum_contracts: IndexMap<ApplicationSymbolId, EnumContract>,
88    /// Resolved identities of policies referenced by some operation's
89    /// `access policy_governed by <name> at precondition ...` clause.
90    /// `validate()` evaluates these in the operation's typed contract
91    /// context, not against the bare graph, where their terms (e.g. an
92    /// input record field) do not resolve (limitation L9). Keyed by
93    /// `ConceptId` (not bare name) so two same-named policies in different
94    /// namespaces, only one of which is operation-bound, are not conflated.
95    #[serde(default, skip_serializing_if = "std::collections::HashSet::is_empty")]
96    operation_bound_policy_names: std::collections::HashSet<ConceptId>,
97    #[serde(default)]
98    config: GraphConfig,
99    /// Model-level `@version` declared in the source header. `None` when the
100    /// model declares no version. Set only by the parse/resolve entry points.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    version: Option<String>,
103}
104
105impl Graph {
106    pub fn new() -> Self {
107        Self::default()
108    }
109
110    pub fn is_empty(&self) -> bool {
111        self.entities.is_empty()
112            && self.roles.is_empty()
113            && self.resources.is_empty()
114            && self.flows.is_empty()
115            && self.relations.is_empty()
116            && self.instances.is_empty()
117            && self.entity_instances.is_empty()
118            && self.policies.is_empty()
119            && self.patterns.is_empty()
120            && self.concept_changes.is_empty()
121            && self.concept_changes.is_empty()
122            && self.metrics.is_empty()
123            && self.mappings.is_empty()
124            && self.projections.is_empty()
125            && self.declared_dimensions.is_empty()
126            && self.declared_units.is_empty()
127    }
128
129    pub fn add_declared_dimension(&mut self, name: String, namespace: String) {
130        let id = ConceptId::from_concept(&namespace, &name);
131        self.declared_dimensions.insert(
132            id.clone(),
133            DeclaredDimension {
134                id,
135                name,
136                namespace,
137            },
138        );
139    }
140
141    pub fn add_declared_unit(
142        &mut self,
143        name: String,
144        namespace: String,
145        dimension: String,
146        base_factor: String,
147        base_unit: String,
148    ) {
149        let id = ConceptId::from_concept(&namespace, &name);
150        self.declared_units.insert(
151            id.clone(),
152            DeclaredUnit {
153                id,
154                name,
155                namespace,
156                dimension,
157                base_factor,
158                base_unit,
159            },
160        );
161    }
162
163    pub fn all_declared_dimensions(&self) -> Vec<&DeclaredDimension> {
164        self.declared_dimensions.values().collect()
165    }
166
167    pub fn all_declared_units(&self) -> Vec<&DeclaredUnit> {
168        self.declared_units.values().collect()
169    }
170
171    /// Set the evaluation mode for policy evaluation.
172    /// When `use_three_valued_logic` is true, policies will use three-valued logic (True, False, NULL).
173    /// When false, policies will use strict boolean logic (True, False).
174    pub fn set_evaluation_mode(&mut self, use_three_valued_logic: bool) {
175        self.config.use_three_valued_logic = use_three_valued_logic;
176    }
177
178    /// Get the current evaluation mode.
179    pub fn use_three_valued_logic(&self) -> bool {
180        self.config.use_three_valued_logic
181    }
182
183    pub fn config(&self) -> &GraphConfig {
184        &self.config
185    }
186
187    /// The model's declared `@version`, if the source header declares one.
188    pub fn version(&self) -> Option<&str> {
189        self.version.as_deref()
190    }
191
192    pub(crate) fn set_version(&mut self, version: Option<String>) {
193        self.version = version;
194    }
195
196    pub fn config_mut(&mut self) -> &mut GraphConfig {
197        &mut self.config
198    }
199
200    pub fn entity_count(&self) -> usize {
201        self.entities.len()
202    }
203
204    /// Merge another graph's nodes into this one. Callers pass graphs built
205    /// from disjoint namespaces, so key overlap cannot occur; the resolver
206    /// rejects duplicate qualified IDs before conversion.
207    pub(crate) fn absorb(&mut self, other: Graph) {
208        self.entities.extend(other.entities);
209        self.roles.extend(other.roles);
210        self.resources.extend(other.resources);
211        self.flows.extend(other.flows);
212        self.relations.extend(other.relations);
213        self.instances.extend(other.instances);
214        self.entity_instances.extend(other.entity_instances);
215        self.policies.extend(other.policies);
216        self.patterns.extend(other.patterns);
217        self.concept_changes.extend(other.concept_changes);
218        self.metrics.extend(other.metrics);
219        self.mappings.extend(other.mappings);
220        self.projections.extend(other.projections);
221        self.declared_dimensions.extend(other.declared_dimensions);
222        self.declared_units.extend(other.declared_units);
223        self.entity_roles.extend(other.entity_roles);
224        self.entity_contracts.extend(other.entity_contracts);
225        self.enum_contracts.extend(other.enum_contracts);
226        self.operation_bound_policy_names
227            .extend(other.operation_bound_policy_names);
228    }
229
230    /// Record that `id` is bound to some operation's `access
231    /// policy_governed by` clause, so `validate()` skips it: its terms are
232    /// meaningful only in that operation's typed contract context.
233    pub(crate) fn mark_operation_bound_policies(
234        &mut self,
235        ids: impl IntoIterator<Item = ConceptId>,
236    ) {
237        self.operation_bound_policy_names.extend(ids);
238    }
239
240    /// Whether `id` is bound to an operation's `access policy_governed by`
241    /// clause (and so is skipped by `validate()`).
242    pub fn is_operation_bound_policy(&self, id: &ConceptId) -> bool {
243        self.operation_bound_policy_names.contains(id)
244    }
245
246    pub fn add_entity(&mut self, entity: Entity) -> Result<(), String> {
247        let id = entity.id().clone();
248        if self.entities.contains_key(&id) {
249            return Err(format!("Entity with ID {} already exists", id));
250        }
251        self.entities.insert(id, entity);
252        Ok(())
253    }
254
255    pub fn has_entity(&self, id: &ConceptId) -> bool {
256        self.entities.contains_key(id)
257    }
258
259    pub fn get_entity(&self, id: &ConceptId) -> Option<&Entity> {
260        self.entities.get(id)
261    }
262
263    /// Returns a mutable reference to an Entity identified by `id`.
264    /// This method is necessary for operations that need to update attributes
265    /// on existing entities (such as association relationships).
266    pub fn get_entity_mut(&mut self, id: &ConceptId) -> Option<&mut Entity> {
267        self.entities.get_mut(id)
268    }
269
270    pub fn remove_entity(&mut self, id: &ConceptId) -> Result<Entity, String> {
271        // Check for references in flows
272        let referencing_flows: Vec<String> = self
273            .flows
274            .values()
275            .filter(|flow| flow.from_id() == id || flow.to_id() == id)
276            .map(|flow| flow.id().to_string())
277            .collect();
278
279        // Check for references in instances
280        let referencing_instances: Vec<String> = self
281            .instances
282            .values()
283            .filter(|instance| instance.entity_id() == id)
284            .map(|instance| instance.id().to_string())
285            .collect();
286
287        if !referencing_flows.is_empty() || !referencing_instances.is_empty() {
288            let mut error_msg = format!("Cannot remove entity {} because it is referenced", id);
289            if !referencing_flows.is_empty() {
290                error_msg.push_str(&format!(" by flows: {}", referencing_flows.join(", ")));
291            }
292            if !referencing_instances.is_empty() {
293                error_msg.push_str(&format!(
294                    " by instances: {}",
295                    referencing_instances.join(", ")
296                ));
297            }
298            return Err(error_msg);
299        }
300
301        self.entities
302            .shift_remove(id)
303            .ok_or_else(|| format!("Entity with ID {} not found", id))
304    }
305
306    pub fn role_count(&self) -> usize {
307        self.roles.len()
308    }
309
310    pub fn add_role(&mut self, role: Role) -> Result<(), String> {
311        let id = role.id().clone();
312        if self.roles.contains_key(&id) {
313            return Err(format!("Role with ID {} already exists", id));
314        }
315        self.roles.insert(id, role);
316        Ok(())
317    }
318
319    pub fn get_role(&self, id: &ConceptId) -> Option<&Role> {
320        self.roles.get(id)
321    }
322
323    pub fn has_role(&self, id: &ConceptId) -> bool {
324        self.roles.contains_key(id)
325    }
326
327    pub fn assign_role_to_entity(
328        &mut self,
329        entity_id: ConceptId,
330        role_id: ConceptId,
331    ) -> Result<(), String> {
332        if !self.entities.contains_key(&entity_id) {
333            return Err(format!("Entity with ID {} not found", entity_id));
334        }
335        if !self.roles.contains_key(&role_id) {
336            return Err(format!("Role with ID {} not found", role_id));
337        }
338
339        let roles = self.entity_roles.entry(entity_id).or_default();
340        if !roles.contains(&role_id) {
341            roles.push(role_id);
342        }
343        Ok(())
344    }
345
346    pub fn roles_for_entity(&self, entity_id: &ConceptId) -> Option<&Vec<ConceptId>> {
347        self.entity_roles.get(entity_id)
348    }
349
350    pub fn role_names_for_entity(&self, entity_id: &ConceptId) -> Vec<String> {
351        self.entity_roles
352            .get(entity_id)
353            .into_iter()
354            .flat_map(|roles| roles.iter())
355            .filter_map(|role_id| self.roles.get(role_id))
356            .map(|role| role.name().to_string())
357            .collect()
358    }
359
360    pub fn resource_count(&self) -> usize {
361        self.resources.len()
362    }
363
364    pub fn add_resource(&mut self, resource: Resource) -> Result<(), String> {
365        let id = resource.id().clone();
366        if self.resources.contains_key(&id) {
367            return Err(format!("Resource with ID {} already exists", id));
368        }
369        self.resources.insert(id, resource);
370        Ok(())
371    }
372
373    pub fn has_resource(&self, id: &ConceptId) -> bool {
374        self.resources.contains_key(id)
375    }
376
377    pub fn get_resource(&self, id: &ConceptId) -> Option<&Resource> {
378        self.resources.get(id)
379    }
380
381    pub fn remove_resource(&mut self, id: &ConceptId) -> Result<Resource, String> {
382        // Check for references in flows
383        let referencing_flows: Vec<String> = self
384            .flows
385            .values()
386            .filter(|flow| flow.resource_id() == id)
387            .map(|flow| flow.id().to_string())
388            .collect();
389
390        // Check for references in instances
391        let referencing_instances: Vec<String> = self
392            .instances
393            .values()
394            .filter(|instance| instance.resource_id() == id)
395            .map(|instance| instance.id().to_string())
396            .collect();
397
398        if !referencing_flows.is_empty() || !referencing_instances.is_empty() {
399            let mut error_msg = format!("Cannot remove resource {} because it is referenced", id);
400            if !referencing_flows.is_empty() {
401                error_msg.push_str(&format!(" by flows: {}", referencing_flows.join(", ")));
402            }
403            if !referencing_instances.is_empty() {
404                error_msg.push_str(&format!(
405                    " by instances: {}",
406                    referencing_instances.join(", ")
407                ));
408            }
409            return Err(error_msg);
410        }
411
412        self.resources
413            .shift_remove(id)
414            .ok_or_else(|| format!("Resource with ID {} not found", id))
415    }
416
417    pub fn flow_count(&self) -> usize {
418        self.flows.len()
419    }
420
421    pub fn pattern_count(&self) -> usize {
422        self.patterns.len()
423    }
424
425    pub fn relation_count(&self) -> usize {
426        self.relations.len()
427    }
428
429    pub fn add_relation_type(&mut self, relation: RelationType) -> Result<(), String> {
430        let id = relation.id().clone();
431        if self.relations.contains_key(&id) {
432            return Err(format!("Relation with ID {} already exists", id));
433        }
434        self.relations.insert(id, relation);
435        Ok(())
436    }
437
438    pub fn all_relations(&self) -> Vec<&RelationType> {
439        self.relations.values().collect()
440    }
441
442    pub fn add_flow(&mut self, flow: Flow) -> Result<(), String> {
443        let id = flow.id().clone();
444        if self.flows.contains_key(&id) {
445            return Err(format!("Flow with ID {} already exists", id));
446        }
447        if !self.entities.contains_key(flow.from_id()) {
448            return Err("Source entity not found".to_string());
449        }
450        if !self.entities.contains_key(flow.to_id()) {
451            return Err("Target entity not found".to_string());
452        }
453        if !self.resources.contains_key(flow.resource_id()) {
454            return Err("Resource not found".to_string());
455        }
456        self.flows.insert(id, flow);
457        Ok(())
458    }
459
460    pub fn add_pattern(&mut self, pattern: Pattern) -> Result<(), String> {
461        let id = pattern.id().clone();
462        if self.patterns.contains_key(&id) {
463            return Err(format!("Pattern with ID {} already exists", id));
464        }
465
466        if self.patterns.values().any(|existing| {
467            existing.name() == pattern.name() && existing.namespace() == pattern.namespace()
468        }) {
469            return Err(format!(
470                "Pattern '{}' already declared in namespace '{}'",
471                pattern.name(),
472                pattern.namespace()
473            ));
474        }
475
476        self.patterns.insert(id, pattern);
477        Ok(())
478    }
479
480    pub fn add_concept_change(&mut self, change: ConceptChange) -> Result<(), String> {
481        let id = change.id().clone();
482        if self.concept_changes.contains_key(&id) {
483            return Err(format!("ConceptChange with ID {} already exists", id));
484        }
485        self.concept_changes.insert(id, change);
486        Ok(())
487    }
488
489    pub fn get_concept_change(&self, id: &ConceptId) -> Option<&ConceptChange> {
490        self.concept_changes.get(id)
491    }
492
493    pub fn all_concept_changes(&self) -> Vec<&ConceptChange> {
494        self.concept_changes.values().collect()
495    }
496
497    pub fn has_flow(&self, id: &ConceptId) -> bool {
498        self.flows.contains_key(id)
499    }
500
501    pub fn get_flow(&self, id: &ConceptId) -> Option<&Flow> {
502        self.flows.get(id)
503    }
504
505    pub fn remove_flow(&mut self, id: &ConceptId) -> Result<Flow, String> {
506        self.flows
507            .shift_remove(id)
508            .ok_or_else(|| format!("Flow with ID {} not found", id))
509    }
510
511    pub fn instance_count(&self) -> usize {
512        self.instances.len()
513    }
514
515    pub fn add_instance(&mut self, instance: ResourceInstance) -> Result<(), String> {
516        let id = instance.id().clone();
517        if self.instances.contains_key(&id) {
518            return Err(format!("Instance with ID {} already exists", id));
519        }
520        if !self.entities.contains_key(instance.entity_id()) {
521            return Err("Entity not found".to_string());
522        }
523        if !self.resources.contains_key(instance.resource_id()) {
524            return Err("Resource not found".to_string());
525        }
526        self.instances.insert(id, instance);
527        Ok(())
528    }
529
530    /// Adds an association relationship from `owner` -> `owned` using a named `rel_type`.
531    /// Associations are represented as a JSON attribute `associations` on the source entity to
532    /// maintain a simple, serializable representation without introducing a new primitive.
533    pub fn add_association(
534        &mut self,
535        owner: &ConceptId,
536        owned: &ConceptId,
537        rel_type: &str,
538    ) -> Result<(), String> {
539        if !self.entities.contains_key(owner) {
540            return Err("Source entity not found".to_string());
541        }
542        if !self.entities.contains_key(owned) {
543            return Err("Destination entity not found".to_string());
544        }
545
546        let owned_str = owned.to_string();
547        let rel_type_str = rel_type.to_string();
548
549        // Mutably borrow the entity and insert/update the `associations` attribute.
550        if let Some(entity) = self.entities.get_mut(owner) {
551            use serde_json::{json, Value};
552            let mut associations: Value = entity
553                .get_attribute("associations")
554                .cloned()
555                .unwrap_or_else(|| json!([]));
556
557            if let Value::Array(arr) = &mut associations {
558                arr.push(json!({"type": rel_type_str, "target": owned_str}));
559            } else {
560                // Replace non-array associations with an array structure.
561                associations = json!([ {"type": rel_type_str, "target": owned_str} ]);
562            }
563
564            entity.set_attribute("associations", associations);
565            Ok(())
566        } else {
567            Err("Failed to retrieve entity for association".to_string())
568        }
569    }
570
571    pub fn has_instance(&self, id: &ConceptId) -> bool {
572        self.instances.contains_key(id)
573    }
574
575    pub fn get_instance(&self, id: &ConceptId) -> Option<&ResourceInstance> {
576        self.instances.get(id)
577    }
578
579    pub fn remove_instance(&mut self, id: &ConceptId) -> Result<ResourceInstance, String> {
580        self.instances
581            .shift_remove(id)
582            .ok_or_else(|| format!("Instance with ID {} not found", id))
583    }
584
585    // Entity Instance methods
586    pub fn entity_instance_count(&self) -> usize {
587        self.entity_instances.len()
588    }
589
590    pub fn add_entity_instance(&mut self, instance: Instance) -> Result<(), String> {
591        let id = instance.id().clone();
592        self.insert_entity_instance(instance)?;
593        if let Err(errors) = self.validate_entity_instances() {
594            self.entity_instances.shift_remove(&id);
595            return Err(errors.join("; "));
596        }
597        Ok(())
598    }
599
600    /// Insert several entity instances and validate the graph once, after all
601    /// of them are present, so references between the new instances do not
602    /// depend on their order. If any insert or the final validation fails,
603    /// every instance inserted by this call is removed and the graph is
604    /// unchanged. Duplicate ids and names are rejected as in
605    /// [`Graph::add_entity_instance`], including duplicates inside the batch.
606    pub fn add_entity_instances(&mut self, instances: Vec<Instance>) -> Result<(), String> {
607        let mut inserted: Vec<ConceptId> = Vec::with_capacity(instances.len());
608        for instance in instances {
609            let id = instance.id().clone();
610            if let Err(error) = self.insert_entity_instance(instance) {
611                self.rollback_entity_instances(&inserted);
612                return Err(error);
613            }
614            inserted.push(id);
615        }
616        if let Err(errors) = self.validate_entity_instances() {
617            self.rollback_entity_instances(&inserted);
618            return Err(errors.join("; "));
619        }
620        Ok(())
621    }
622
623    fn rollback_entity_instances(&mut self, ids: &[ConceptId]) {
624        for id in ids {
625            self.entity_instances.shift_remove(id);
626        }
627    }
628
629    fn insert_entity_instance(&mut self, instance: Instance) -> Result<(), String> {
630        let id = instance.id().clone();
631        if self.entity_instances.contains_key(&id) {
632            return Err(format!(
633                "Entity instance '{}' already exists",
634                instance.name()
635            ));
636        }
637        if self.find_entity_instance_by_name(instance.name()).is_some() {
638            return Err(format!(
639                "Entity instance '{}' already exists",
640                instance.name()
641            ));
642        }
643
644        let namespace = instance.namespace();
645        let entity_type = instance.entity_type();
646
647        self.find_entity_by_name_and_namespace(entity_type, namespace)
648            .ok_or_else(|| {
649                format!(
650                    "Entity '{}' not found in namespace '{}'",
651                    entity_type, namespace
652                )
653            })?;
654
655        self.entity_instances.insert(id, instance);
656        Ok(())
657    }
658
659    pub(crate) fn attach_application_contract(
660        &mut self,
661        contract: ApplicationContract,
662    ) -> Result<(), Vec<String>> {
663        let mut candidate = self.clone();
664        candidate.entity_contracts = contract
665            .entities
666            .into_iter()
667            .map(|contract| (contract.concept_id.clone(), contract))
668            .collect();
669        candidate.enum_contracts = contract
670            .enums
671            .into_iter()
672            .map(|contract| (contract.id.clone(), contract))
673            .collect();
674        candidate.validate_entity_instances()?;
675        *self = candidate;
676        Ok(())
677    }
678
679    pub fn entity_contract(&self, entity_id: &ConceptId) -> Option<&EntityContract> {
680        self.entity_contracts.get(entity_id)
681    }
682
683    pub fn validate_entity_instances(&self) -> Result<(), Vec<String>> {
684        entity_validation::validate(self)
685    }
686
687    pub fn get_entity_instance(&self, name: &str) -> Option<&Instance> {
688        self.find_entity_instance_by_name(name)
689            .and_then(|id| self.entity_instances.get(&id))
690    }
691
692    pub fn get_entity_instance_mut(&mut self, name: &str) -> Option<&mut Instance> {
693        let id = self.find_entity_instance_by_name(name)?;
694        self.entity_instances.get_mut(&id)
695    }
696
697    pub fn all_entity_instances(&self) -> Vec<&Instance> {
698        self.entity_instances.values().collect()
699    }
700
701    pub fn remove_entity_instance(&mut self, name: &str) -> Result<Instance, String> {
702        let id = self
703            .find_entity_instance_by_name(name)
704            .ok_or_else(|| format!("Entity instance '{}' not found", name))?;
705
706        self.entity_instances
707            .shift_remove(&id)
708            .ok_or_else(|| format!("Entity instance '{}' not found", name))
709    }
710
711    pub fn has_entity_instance_by_id(&self, id: &ConceptId) -> bool {
712        self.entity_instances.contains_key(id)
713    }
714
715    pub fn get_entity_instance_by_id(&self, id: &ConceptId) -> Option<&Instance> {
716        self.entity_instances.get(id)
717    }
718
719    pub fn remove_entity_instance_by_id(&mut self, id: &ConceptId) -> Result<Instance, String> {
720        self.entity_instances
721            .shift_remove(id)
722            .ok_or_else(|| format!("Entity instance with id '{}' not found", id))
723    }
724
725    pub fn flows_from(&self, entity_id: &ConceptId) -> Vec<&Flow> {
726        self.flows
727            .values()
728            .filter(|flow| flow.from_id() == entity_id)
729            .collect()
730    }
731
732    pub fn flows_to(&self, entity_id: &ConceptId) -> Vec<&Flow> {
733        self.flows
734            .values()
735            .filter(|flow| flow.to_id() == entity_id)
736            .collect()
737    }
738
739    pub fn upstream_entities(&self, entity_id: &ConceptId) -> Vec<&Entity> {
740        self.flows_to(entity_id)
741            .iter()
742            .filter_map(|flow| self.get_entity(flow.from_id()))
743            .collect()
744    }
745
746    pub fn downstream_entities(&self, entity_id: &ConceptId) -> Vec<&Entity> {
747        self.flows_from(entity_id)
748            .iter()
749            .filter_map(|flow| self.get_entity(flow.to_id()))
750            .collect()
751    }
752
753    pub fn find_entity_by_name_and_namespace(
754        &self,
755        name: &str,
756        namespace: &str,
757    ) -> Option<ConceptId> {
758        self.entities
759            .iter()
760            .find(|(_, entity)| entity.name() == name && entity.namespace() == namespace)
761            .map(|(id, _)| id.clone())
762    }
763
764    pub fn find_entity_by_name(&self, name: &str) -> Option<ConceptId> {
765        self.entities
766            .iter()
767            .find(|(_, entity)| entity.name() == name)
768            .map(|(id, _)| id.clone())
769    }
770
771    pub fn find_resource_by_name(&self, name: &str) -> Option<ConceptId> {
772        self.resources
773            .iter()
774            .find(|(_, resource)| resource.name() == name)
775            .map(|(id, _)| id.clone())
776    }
777
778    pub fn find_role_by_name(&self, name: &str) -> Option<ConceptId> {
779        self.roles
780            .iter()
781            .find(|(_, role)| role.name() == name)
782            .map(|(id, _)| id.clone())
783    }
784
785    pub fn find_entity_instance_by_name(&self, name: &str) -> Option<ConceptId> {
786        self.entity_instances
787            .iter()
788            .find(|(_, instance)| instance.name() == name)
789            .map(|(id, _)| id.clone())
790    }
791
792    pub fn find_entity_instance_by_name_and_namespace(
793        &self,
794        name: &str,
795        namespace: &str,
796    ) -> Option<ConceptId> {
797        self.entity_instances
798            .iter()
799            .find(|(_, instance)| instance.name() == name && instance.namespace() == namespace)
800            .map(|(id, _)| id.clone())
801    }
802
803    pub fn find_pattern(&self, name: &str, namespace: Option<&str>) -> Option<&Pattern> {
804        if let Some(ns) = namespace {
805            if let Some((_, pattern)) = self
806                .patterns
807                .iter()
808                .find(|(_, pattern)| pattern.name() == name && pattern.namespace() == ns)
809            {
810                return Some(pattern);
811            }
812        }
813
814        self.patterns
815            .iter()
816            .find(|(_, pattern)| pattern.name() == name)
817            .map(|(_, pattern)| pattern)
818    }
819
820    pub fn all_entities(&self) -> Vec<&Entity> {
821        self.entities.values().collect()
822    }
823
824    pub fn all_roles(&self) -> Vec<&Role> {
825        self.roles.values().collect()
826    }
827
828    pub fn all_resources(&self) -> Vec<&Resource> {
829        self.resources.values().collect()
830    }
831
832    pub fn all_flows(&self) -> Vec<&Flow> {
833        self.flows.values().collect()
834    }
835
836    pub fn all_instances(&self) -> Vec<&ResourceInstance> {
837        self.instances.values().collect()
838    }
839
840    pub fn all_patterns(&self) -> Vec<&Pattern> {
841        self.patterns.values().collect()
842    }
843
844    pub fn policy_count(&self) -> usize {
845        self.policies.len()
846    }
847
848    pub fn add_policy(&mut self, policy: Policy) -> Result<(), String> {
849        let id = policy.id.clone();
850        if self.policies.contains_key(&id) {
851            return Err(format!("Policy with ID {} already exists", id));
852        }
853        self.policies.insert(id, policy);
854        Ok(())
855    }
856
857    pub fn has_policy(&self, id: &ConceptId) -> bool {
858        self.policies.contains_key(id)
859    }
860
861    pub fn get_policy(&self, id: &ConceptId) -> Option<&Policy> {
862        self.policies.get(id)
863    }
864
865    pub fn remove_policy(&mut self, id: &ConceptId) -> Result<Policy, String> {
866        self.policies
867            .shift_remove(id)
868            .ok_or_else(|| format!("Policy with ID {} not found", id))
869    }
870
871    pub fn all_policies(&self) -> Vec<&Policy> {
872        self.policies.values().collect()
873    }
874
875    pub fn metric_count(&self) -> usize {
876        self.metrics.len()
877    }
878
879    pub fn add_metric(&mut self, metric: Metric) -> Result<(), String> {
880        metric.validate()?;
881        let id = metric.id().clone();
882        if self.metrics.contains_key(&id) {
883            return Err(format!("Metric with ID {} already exists", id));
884        }
885        self.metrics.insert(id, metric);
886        Ok(())
887    }
888
889    pub fn has_metric(&self, id: &ConceptId) -> bool {
890        self.metrics.contains_key(id)
891    }
892
893    pub fn get_metric(&self, id: &ConceptId) -> Option<&Metric> {
894        self.metrics.get(id)
895    }
896
897    pub fn all_metrics(&self) -> Vec<&Metric> {
898        self.metrics.values().collect()
899    }
900
901    pub fn mapping_count(&self) -> usize {
902        self.mappings.len()
903    }
904
905    pub fn add_mapping(&mut self, mapping: MappingContract) -> Result<(), String> {
906        let id = mapping.id().clone();
907        if self.mappings.contains_key(&id) {
908            return Err(format!("Mapping with ID {} already exists", id));
909        }
910        self.mappings.insert(id, mapping);
911        Ok(())
912    }
913
914    pub fn has_mapping(&self, id: &ConceptId) -> bool {
915        self.mappings.contains_key(id)
916    }
917
918    pub fn get_mapping(&self, id: &ConceptId) -> Option<&MappingContract> {
919        self.mappings.get(id)
920    }
921
922    pub fn all_mappings(&self) -> Vec<&MappingContract> {
923        self.mappings.values().collect()
924    }
925
926    pub fn projection_count(&self) -> usize {
927        self.projections.len()
928    }
929
930    pub fn add_projection(&mut self, projection: ProjectionContract) -> Result<(), String> {
931        let id = projection.id().clone();
932        if self.projections.contains_key(&id) {
933            return Err(format!("Projection with ID {} already exists", id));
934        }
935        self.projections.insert(id, projection);
936        Ok(())
937    }
938
939    pub fn has_projection(&self, id: &ConceptId) -> bool {
940        self.projections.contains_key(id)
941    }
942
943    pub fn get_projection(&self, id: &ConceptId) -> Option<&ProjectionContract> {
944        self.projections.get(id)
945    }
946
947    pub fn all_projections(&self) -> Vec<&ProjectionContract> {
948        self.projections.values().collect()
949    }
950
951    /// Extend this graph with all nodes and policies from another graph.
952    /// The operation is atomic: the existing graph is only modified if the entire
953    /// merge succeeds, which prevents partial state when errors occur.
954    pub fn extend(&mut self, other: Graph) -> Result<(), String> {
955        let mut merged = self.clone();
956        merged.extend_from_graph(other)?;
957        *self = merged;
958        Ok(())
959    }
960
961    fn extend_from_graph(&mut self, other: Graph) -> Result<(), String> {
962        let Graph {
963            entities,
964            roles,
965            resources,
966            flows,
967            relations,
968            instances,
969            entity_instances,
970            policies,
971            patterns,
972            concept_changes,
973            metrics,
974            mappings,
975            projections,
976            declared_dimensions,
977            declared_units,
978            entity_roles,
979            entity_contracts,
980            enum_contracts,
981            operation_bound_policy_names,
982            config: _,
983            version: _,
984        } = other;
985
986        for entity in entities.into_values() {
987            self.add_entity(entity)?;
988        }
989
990        for role in roles.into_values() {
991            self.add_role(role)?;
992        }
993
994        for resource in resources.into_values() {
995            self.add_resource(resource)?;
996        }
997
998        for instance in instances.into_values() {
999            self.add_instance(instance)?;
1000        }
1001
1002        for entity_instance in entity_instances.into_values() {
1003            // The incoming contracts are installed below, so defer schema
1004            // validation until the complete atomic merge candidate exists.
1005            self.insert_entity_instance(entity_instance)?;
1006        }
1007
1008        for flow in flows.into_values() {
1009            self.add_flow(flow)?;
1010        }
1011
1012        for relation in relations.into_values() {
1013            self.add_relation_type(relation)?;
1014        }
1015
1016        for pattern in patterns.into_values() {
1017            self.add_pattern(pattern)?;
1018        }
1019
1020        for (entity_id, roles_for_entity) in entity_roles.into_iter() {
1021            for role_id in roles_for_entity {
1022                self.assign_role_to_entity(entity_id.clone(), role_id)?;
1023            }
1024        }
1025
1026        self.entity_contracts.extend(entity_contracts);
1027        self.enum_contracts.extend(enum_contracts);
1028        self.operation_bound_policy_names
1029            .extend(operation_bound_policy_names);
1030        self.validate_entity_instances()
1031            .map_err(|errors| errors.join("; "))?;
1032
1033        for policy in policies.into_values() {
1034            self.add_policy(policy)?;
1035        }
1036
1037        for change in concept_changes.into_values() {
1038            self.add_concept_change(change)?;
1039        }
1040
1041        for metric in metrics.into_values() {
1042            self.add_metric(metric)?;
1043        }
1044
1045        for mapping in mappings.into_values() {
1046            self.add_mapping(mapping)?;
1047        }
1048
1049        for projection in projections.into_values() {
1050            self.add_projection(projection)?;
1051        }
1052
1053        for (id, dimension) in declared_dimensions {
1054            match self.declared_dimensions.get(&id) {
1055                Some(existing) if existing != &dimension => {
1056                    return Err(format!(
1057                        "Conflicting dimension '{}' already declared (existing namespace='{}'; new namespace='{}')",
1058                        dimension.name, existing.namespace, dimension.namespace
1059                    ));
1060                }
1061                _ => {
1062                    self.declared_dimensions.insert(id, dimension);
1063                }
1064            }
1065        }
1066
1067        for (id, unit) in declared_units {
1068            match self.declared_units.get(&id) {
1069                Some(existing) if existing != &unit => {
1070                    return Err(format!(
1071                        "Conflicting unit '{}' already declared (existing: dimension={}, base_factor={}, base_unit={}; new: dimension={}, base_factor={}, base_unit={})",
1072                        unit.name,
1073                        existing.dimension,
1074                        existing.base_factor,
1075                        existing.base_unit,
1076                        unit.dimension,
1077                        unit.base_factor,
1078                        unit.base_unit
1079                    ));
1080                }
1081                _ => {
1082                    self.declared_units.insert(id, unit);
1083                }
1084            }
1085        }
1086
1087        Ok(())
1088    }
1089
1090    /// Validate the graph by evaluating all policies against it and
1091    /// collecting any violations produced. Returns a `ValidationResult`.
1092    pub fn validate(&self) -> ValidationResult {
1093        let mut all_violations: Vec<Violation> = Vec::new();
1094        let use_three_valued_logic = self.config.use_three_valued_logic;
1095
1096        if let Err(errors) = self.validate_entity_instances() {
1097            all_violations.extend(
1098                errors
1099                    .into_iter()
1100                    .map(|error| Violation::new("entity_instance_schema", error, Severity::Error)),
1101            );
1102        }
1103
1104        // Policies bound to an operation's `access policy_governed by`
1105        // clause are meant to be evaluated in that operation's typed
1106        // contract context (an input record field, a state precondition),
1107        // not against the bare graph, where their terms do not resolve and
1108        // evaluation returns UNKNOWN (limitation L9). `--application`/
1109        // `contract`/`envelope` check them in the right context instead.
1110        let mut evaluated = 0usize;
1111        for policy in self.policies.values() {
1112            if self.operation_bound_policy_names.contains(&policy.id) {
1113                continue;
1114            }
1115            evaluated += 1;
1116            match policy.evaluate_with_mode(self, use_three_valued_logic) {
1117                Ok(eval) => {
1118                    all_violations.extend(eval.violations);
1119                }
1120                Err(err) => {
1121                    // If a policy evaluation fails, produce an ERROR severity
1122                    // violation indicating evaluation failure so the user can
1123                    // see the issue.
1124                    let v = Violation::new(
1125                        &policy.name,
1126                        format!("Policy evaluation failed: {}", err),
1127                        Severity::Error,
1128                    );
1129                    all_violations.push(v);
1130                }
1131            }
1132        }
1133
1134        ValidationResult::new(evaluated, all_violations)
1135    }
1136}