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