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