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