Skip to main content

domainforge_core/graph/
mod.rs

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