Skip to main content

domainforge_core/graph/
mod.rs

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