domainforge-core 0.18.1

Rust core library implementing the SEA DSL primitives and validation engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
use crate::application::{ApplicationContract, ApplicationSymbolId, EntityContract, EnumContract};
use crate::patterns::Pattern;
use crate::policy::{Policy, Severity, Violation};
use crate::primitives::{
    ConceptChange, Entity, Flow, Instance, MappingContract, Metric, ProjectionContract,
    RelationType, Resource, ResourceInstance, Role,
};
use crate::validation_result::ValidationResult;
use crate::ConceptId;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

/// A dimension declared by the parsed SEA source.
///
/// This is intentionally graph-owned rather than read from `UnitRegistry`:
/// the registry also contains ambient builtins and uses an unordered map.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeclaredDimension {
    pub id: ConceptId,
    pub name: String,
    pub namespace: String,
}

/// A unit declared by the parsed SEA source.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeclaredUnit {
    pub id: ConceptId,
    pub name: String,
    pub namespace: String,
    pub dimension: String,
    pub base_factor: String,
    pub base_unit: String,
}

mod entity_validation;
pub mod to_ast;

/// Configuration for graph evaluation behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphConfig {
    /// Enable three-valued logic (True, False, NULL) for policy evaluation.
    /// When false, uses strict boolean logic (True, False).
    pub use_three_valued_logic: bool,
}

impl Default for GraphConfig {
    fn default() -> Self {
        Self {
            // Default to three-valued logic for backward compatibility with the feature flag
            use_three_valued_logic: true,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Graph {
    entities: IndexMap<ConceptId, Entity>,
    roles: IndexMap<ConceptId, Role>,
    resources: IndexMap<ConceptId, Resource>,
    flows: IndexMap<ConceptId, Flow>,
    relations: IndexMap<ConceptId, RelationType>,
    instances: IndexMap<ConceptId, ResourceInstance>,
    /// Entity instances keyed by ConceptId for consistency with other graph collections.
    entity_instances: IndexMap<ConceptId, Instance>,
    policies: IndexMap<ConceptId, Policy>,
    #[serde(default)]
    patterns: IndexMap<ConceptId, Pattern>,
    #[serde(default)]
    concept_changes: IndexMap<ConceptId, ConceptChange>,
    #[serde(default)]
    metrics: IndexMap<ConceptId, Metric>,
    #[serde(default)]
    mappings: IndexMap<ConceptId, MappingContract>,
    #[serde(default)]
    projections: IndexMap<ConceptId, ProjectionContract>,
    /// Source declarations, kept separately from the global unit registry so
    /// bindings can expose only this graph's declarations in source order.
    #[serde(default)]
    declared_dimensions: IndexMap<ConceptId, DeclaredDimension>,
    #[serde(default)]
    declared_units: IndexMap<ConceptId, DeclaredUnit>,
    #[serde(default)]
    entity_roles: IndexMap<ConceptId, Vec<ConceptId>>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    entity_contracts: IndexMap<ConceptId, EntityContract>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    enum_contracts: IndexMap<ApplicationSymbolId, EnumContract>,
    /// Resolved identities of policies referenced by some operation's
    /// `access policy_governed by <name> at precondition ...` clause.
    /// `validate()` evaluates these in the operation's typed contract
    /// context, not against the bare graph, where their terms (e.g. an
    /// input record field) do not resolve (limitation L9). Keyed by
    /// `ConceptId` (not bare name) so two same-named policies in different
    /// namespaces, only one of which is operation-bound, are not conflated.
    #[serde(default, skip_serializing_if = "std::collections::HashSet::is_empty")]
    operation_bound_policy_names: std::collections::HashSet<ConceptId>,
    #[serde(default)]
    config: GraphConfig,
}

impl Graph {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn is_empty(&self) -> bool {
        self.entities.is_empty()
            && self.roles.is_empty()
            && self.resources.is_empty()
            && self.flows.is_empty()
            && self.relations.is_empty()
            && self.instances.is_empty()
            && self.entity_instances.is_empty()
            && self.policies.is_empty()
            && self.patterns.is_empty()
            && self.concept_changes.is_empty()
            && self.concept_changes.is_empty()
            && self.metrics.is_empty()
            && self.mappings.is_empty()
            && self.projections.is_empty()
            && self.declared_dimensions.is_empty()
            && self.declared_units.is_empty()
    }

    pub fn add_declared_dimension(&mut self, name: String, namespace: String) {
        let id = ConceptId::from_concept(&namespace, &name);
        self.declared_dimensions.insert(
            id.clone(),
            DeclaredDimension {
                id,
                name,
                namespace,
            },
        );
    }

    pub fn add_declared_unit(
        &mut self,
        name: String,
        namespace: String,
        dimension: String,
        base_factor: String,
        base_unit: String,
    ) {
        let id = ConceptId::from_concept(&namespace, &name);
        self.declared_units.insert(
            id.clone(),
            DeclaredUnit {
                id,
                name,
                namespace,
                dimension,
                base_factor,
                base_unit,
            },
        );
    }

    pub fn all_declared_dimensions(&self) -> Vec<&DeclaredDimension> {
        self.declared_dimensions.values().collect()
    }

    pub fn all_declared_units(&self) -> Vec<&DeclaredUnit> {
        self.declared_units.values().collect()
    }

    /// Set the evaluation mode for policy evaluation.
    /// When `use_three_valued_logic` is true, policies will use three-valued logic (True, False, NULL).
    /// When false, policies will use strict boolean logic (True, False).
    pub fn set_evaluation_mode(&mut self, use_three_valued_logic: bool) {
        self.config.use_three_valued_logic = use_three_valued_logic;
    }

    /// Get the current evaluation mode.
    pub fn use_three_valued_logic(&self) -> bool {
        self.config.use_three_valued_logic
    }

    pub fn config(&self) -> &GraphConfig {
        &self.config
    }

    pub fn config_mut(&mut self) -> &mut GraphConfig {
        &mut self.config
    }

    pub fn entity_count(&self) -> usize {
        self.entities.len()
    }

    /// Merge another graph's nodes into this one. Callers pass graphs built
    /// from disjoint namespaces, so key overlap cannot occur; the resolver
    /// rejects duplicate qualified IDs before conversion.
    pub(crate) fn absorb(&mut self, other: Graph) {
        self.entities.extend(other.entities);
        self.roles.extend(other.roles);
        self.resources.extend(other.resources);
        self.flows.extend(other.flows);
        self.relations.extend(other.relations);
        self.instances.extend(other.instances);
        self.entity_instances.extend(other.entity_instances);
        self.policies.extend(other.policies);
        self.patterns.extend(other.patterns);
        self.concept_changes.extend(other.concept_changes);
        self.metrics.extend(other.metrics);
        self.mappings.extend(other.mappings);
        self.projections.extend(other.projections);
        self.declared_dimensions.extend(other.declared_dimensions);
        self.declared_units.extend(other.declared_units);
        self.entity_roles.extend(other.entity_roles);
        self.entity_contracts.extend(other.entity_contracts);
        self.enum_contracts.extend(other.enum_contracts);
        self.operation_bound_policy_names
            .extend(other.operation_bound_policy_names);
    }

    /// Record that `id` is bound to some operation's `access
    /// policy_governed by` clause, so `validate()` skips it: its terms are
    /// meaningful only in that operation's typed contract context.
    pub(crate) fn mark_operation_bound_policies(
        &mut self,
        ids: impl IntoIterator<Item = ConceptId>,
    ) {
        self.operation_bound_policy_names.extend(ids);
    }

    pub fn add_entity(&mut self, entity: Entity) -> Result<(), String> {
        let id = entity.id().clone();
        if self.entities.contains_key(&id) {
            return Err(format!("Entity with ID {} already exists", id));
        }
        self.entities.insert(id, entity);
        Ok(())
    }

    pub fn has_entity(&self, id: &ConceptId) -> bool {
        self.entities.contains_key(id)
    }

    pub fn get_entity(&self, id: &ConceptId) -> Option<&Entity> {
        self.entities.get(id)
    }

    /// Returns a mutable reference to an Entity identified by `id`.
    /// This method is necessary for operations that need to update attributes
    /// on existing entities (such as association relationships).
    pub fn get_entity_mut(&mut self, id: &ConceptId) -> Option<&mut Entity> {
        self.entities.get_mut(id)
    }

    pub fn remove_entity(&mut self, id: &ConceptId) -> Result<Entity, String> {
        // Check for references in flows
        let referencing_flows: Vec<String> = self
            .flows
            .values()
            .filter(|flow| flow.from_id() == id || flow.to_id() == id)
            .map(|flow| flow.id().to_string())
            .collect();

        // Check for references in instances
        let referencing_instances: Vec<String> = self
            .instances
            .values()
            .filter(|instance| instance.entity_id() == id)
            .map(|instance| instance.id().to_string())
            .collect();

        if !referencing_flows.is_empty() || !referencing_instances.is_empty() {
            let mut error_msg = format!("Cannot remove entity {} because it is referenced", id);
            if !referencing_flows.is_empty() {
                error_msg.push_str(&format!(" by flows: {}", referencing_flows.join(", ")));
            }
            if !referencing_instances.is_empty() {
                error_msg.push_str(&format!(
                    " by instances: {}",
                    referencing_instances.join(", ")
                ));
            }
            return Err(error_msg);
        }

        self.entities
            .shift_remove(id)
            .ok_or_else(|| format!("Entity with ID {} not found", id))
    }

    pub fn role_count(&self) -> usize {
        self.roles.len()
    }

    pub fn add_role(&mut self, role: Role) -> Result<(), String> {
        let id = role.id().clone();
        if self.roles.contains_key(&id) {
            return Err(format!("Role with ID {} already exists", id));
        }
        self.roles.insert(id, role);
        Ok(())
    }

    pub fn get_role(&self, id: &ConceptId) -> Option<&Role> {
        self.roles.get(id)
    }

    pub fn has_role(&self, id: &ConceptId) -> bool {
        self.roles.contains_key(id)
    }

    pub fn assign_role_to_entity(
        &mut self,
        entity_id: ConceptId,
        role_id: ConceptId,
    ) -> Result<(), String> {
        if !self.entities.contains_key(&entity_id) {
            return Err(format!("Entity with ID {} not found", entity_id));
        }
        if !self.roles.contains_key(&role_id) {
            return Err(format!("Role with ID {} not found", role_id));
        }

        let roles = self.entity_roles.entry(entity_id).or_default();
        if !roles.contains(&role_id) {
            roles.push(role_id);
        }
        Ok(())
    }

    pub fn roles_for_entity(&self, entity_id: &ConceptId) -> Option<&Vec<ConceptId>> {
        self.entity_roles.get(entity_id)
    }

    pub fn role_names_for_entity(&self, entity_id: &ConceptId) -> Vec<String> {
        self.entity_roles
            .get(entity_id)
            .into_iter()
            .flat_map(|roles| roles.iter())
            .filter_map(|role_id| self.roles.get(role_id))
            .map(|role| role.name().to_string())
            .collect()
    }

    pub fn resource_count(&self) -> usize {
        self.resources.len()
    }

    pub fn add_resource(&mut self, resource: Resource) -> Result<(), String> {
        let id = resource.id().clone();
        if self.resources.contains_key(&id) {
            return Err(format!("Resource with ID {} already exists", id));
        }
        self.resources.insert(id, resource);
        Ok(())
    }

    pub fn has_resource(&self, id: &ConceptId) -> bool {
        self.resources.contains_key(id)
    }

    pub fn get_resource(&self, id: &ConceptId) -> Option<&Resource> {
        self.resources.get(id)
    }

    pub fn remove_resource(&mut self, id: &ConceptId) -> Result<Resource, String> {
        // Check for references in flows
        let referencing_flows: Vec<String> = self
            .flows
            .values()
            .filter(|flow| flow.resource_id() == id)
            .map(|flow| flow.id().to_string())
            .collect();

        // Check for references in instances
        let referencing_instances: Vec<String> = self
            .instances
            .values()
            .filter(|instance| instance.resource_id() == id)
            .map(|instance| instance.id().to_string())
            .collect();

        if !referencing_flows.is_empty() || !referencing_instances.is_empty() {
            let mut error_msg = format!("Cannot remove resource {} because it is referenced", id);
            if !referencing_flows.is_empty() {
                error_msg.push_str(&format!(" by flows: {}", referencing_flows.join(", ")));
            }
            if !referencing_instances.is_empty() {
                error_msg.push_str(&format!(
                    " by instances: {}",
                    referencing_instances.join(", ")
                ));
            }
            return Err(error_msg);
        }

        self.resources
            .shift_remove(id)
            .ok_or_else(|| format!("Resource with ID {} not found", id))
    }

    pub fn flow_count(&self) -> usize {
        self.flows.len()
    }

    pub fn pattern_count(&self) -> usize {
        self.patterns.len()
    }

    pub fn relation_count(&self) -> usize {
        self.relations.len()
    }

    pub fn add_relation_type(&mut self, relation: RelationType) -> Result<(), String> {
        let id = relation.id().clone();
        if self.relations.contains_key(&id) {
            return Err(format!("Relation with ID {} already exists", id));
        }
        self.relations.insert(id, relation);
        Ok(())
    }

    pub fn all_relations(&self) -> Vec<&RelationType> {
        self.relations.values().collect()
    }

    pub fn add_flow(&mut self, flow: Flow) -> Result<(), String> {
        let id = flow.id().clone();
        if self.flows.contains_key(&id) {
            return Err(format!("Flow with ID {} already exists", id));
        }
        if !self.entities.contains_key(flow.from_id()) {
            return Err("Source entity not found".to_string());
        }
        if !self.entities.contains_key(flow.to_id()) {
            return Err("Target entity not found".to_string());
        }
        if !self.resources.contains_key(flow.resource_id()) {
            return Err("Resource not found".to_string());
        }
        self.flows.insert(id, flow);
        Ok(())
    }

    pub fn add_pattern(&mut self, pattern: Pattern) -> Result<(), String> {
        let id = pattern.id().clone();
        if self.patterns.contains_key(&id) {
            return Err(format!("Pattern with ID {} already exists", id));
        }

        if self.patterns.values().any(|existing| {
            existing.name() == pattern.name() && existing.namespace() == pattern.namespace()
        }) {
            return Err(format!(
                "Pattern '{}' already declared in namespace '{}'",
                pattern.name(),
                pattern.namespace()
            ));
        }

        self.patterns.insert(id, pattern);
        Ok(())
    }

    pub fn add_concept_change(&mut self, change: ConceptChange) -> Result<(), String> {
        let id = change.id().clone();
        if self.concept_changes.contains_key(&id) {
            return Err(format!("ConceptChange with ID {} already exists", id));
        }
        self.concept_changes.insert(id, change);
        Ok(())
    }

    pub fn get_concept_change(&self, id: &ConceptId) -> Option<&ConceptChange> {
        self.concept_changes.get(id)
    }

    pub fn all_concept_changes(&self) -> Vec<&ConceptChange> {
        self.concept_changes.values().collect()
    }

    pub fn has_flow(&self, id: &ConceptId) -> bool {
        self.flows.contains_key(id)
    }

    pub fn get_flow(&self, id: &ConceptId) -> Option<&Flow> {
        self.flows.get(id)
    }

    pub fn remove_flow(&mut self, id: &ConceptId) -> Result<Flow, String> {
        self.flows
            .shift_remove(id)
            .ok_or_else(|| format!("Flow with ID {} not found", id))
    }

    pub fn instance_count(&self) -> usize {
        self.instances.len()
    }

    pub fn add_instance(&mut self, instance: ResourceInstance) -> Result<(), String> {
        let id = instance.id().clone();
        if self.instances.contains_key(&id) {
            return Err(format!("Instance with ID {} already exists", id));
        }
        if !self.entities.contains_key(instance.entity_id()) {
            return Err("Entity not found".to_string());
        }
        if !self.resources.contains_key(instance.resource_id()) {
            return Err("Resource not found".to_string());
        }
        self.instances.insert(id, instance);
        Ok(())
    }

    /// Adds an association relationship from `owner` -> `owned` using a named `rel_type`.
    /// Associations are represented as a JSON attribute `associations` on the source entity to
    /// maintain a simple, serializable representation without introducing a new primitive.
    pub fn add_association(
        &mut self,
        owner: &ConceptId,
        owned: &ConceptId,
        rel_type: &str,
    ) -> Result<(), String> {
        if !self.entities.contains_key(owner) {
            return Err("Source entity not found".to_string());
        }
        if !self.entities.contains_key(owned) {
            return Err("Destination entity not found".to_string());
        }

        let owned_str = owned.to_string();
        let rel_type_str = rel_type.to_string();

        // Mutably borrow the entity and insert/update the `associations` attribute.
        if let Some(entity) = self.entities.get_mut(owner) {
            use serde_json::{json, Value};
            let mut associations: Value = entity
                .get_attribute("associations")
                .cloned()
                .unwrap_or_else(|| json!([]));

            if let Value::Array(arr) = &mut associations {
                arr.push(json!({"type": rel_type_str, "target": owned_str}));
            } else {
                // Replace non-array associations with an array structure.
                associations = json!([ {"type": rel_type_str, "target": owned_str} ]);
            }

            entity.set_attribute("associations", associations);
            Ok(())
        } else {
            Err("Failed to retrieve entity for association".to_string())
        }
    }

    pub fn has_instance(&self, id: &ConceptId) -> bool {
        self.instances.contains_key(id)
    }

    pub fn get_instance(&self, id: &ConceptId) -> Option<&ResourceInstance> {
        self.instances.get(id)
    }

    pub fn remove_instance(&mut self, id: &ConceptId) -> Result<ResourceInstance, String> {
        self.instances
            .shift_remove(id)
            .ok_or_else(|| format!("Instance with ID {} not found", id))
    }

    // Entity Instance methods
    pub fn entity_instance_count(&self) -> usize {
        self.entity_instances.len()
    }

    pub fn add_entity_instance(&mut self, instance: Instance) -> Result<(), String> {
        let id = instance.id().clone();
        self.insert_entity_instance(instance)?;
        if let Err(errors) = self.validate_entity_instances() {
            self.entity_instances.shift_remove(&id);
            return Err(errors.join("; "));
        }
        Ok(())
    }

    fn insert_entity_instance(&mut self, instance: Instance) -> Result<(), String> {
        let id = instance.id().clone();
        if self.entity_instances.contains_key(&id) {
            return Err(format!(
                "Entity instance '{}' already exists",
                instance.name()
            ));
        }
        if self.find_entity_instance_by_name(instance.name()).is_some() {
            return Err(format!(
                "Entity instance '{}' already exists",
                instance.name()
            ));
        }

        let namespace = instance.namespace();
        let entity_type = instance.entity_type();

        self.find_entity_by_name_and_namespace(entity_type, namespace)
            .ok_or_else(|| {
                format!(
                    "Entity '{}' not found in namespace '{}'",
                    entity_type, namespace
                )
            })?;

        self.entity_instances.insert(id, instance);
        Ok(())
    }

    pub(crate) fn attach_application_contract(
        &mut self,
        contract: ApplicationContract,
    ) -> Result<(), Vec<String>> {
        let mut candidate = self.clone();
        candidate.entity_contracts = contract
            .entities
            .into_iter()
            .map(|contract| (contract.concept_id.clone(), contract))
            .collect();
        candidate.enum_contracts = contract
            .enums
            .into_iter()
            .map(|contract| (contract.id.clone(), contract))
            .collect();
        candidate.validate_entity_instances()?;
        *self = candidate;
        Ok(())
    }

    pub fn entity_contract(&self, entity_id: &ConceptId) -> Option<&EntityContract> {
        self.entity_contracts.get(entity_id)
    }

    pub fn validate_entity_instances(&self) -> Result<(), Vec<String>> {
        entity_validation::validate(self)
    }

    pub fn get_entity_instance(&self, name: &str) -> Option<&Instance> {
        self.find_entity_instance_by_name(name)
            .and_then(|id| self.entity_instances.get(&id))
    }

    pub fn get_entity_instance_mut(&mut self, name: &str) -> Option<&mut Instance> {
        let id = self.find_entity_instance_by_name(name)?;
        self.entity_instances.get_mut(&id)
    }

    pub fn all_entity_instances(&self) -> Vec<&Instance> {
        self.entity_instances.values().collect()
    }

    pub fn remove_entity_instance(&mut self, name: &str) -> Result<Instance, String> {
        let id = self
            .find_entity_instance_by_name(name)
            .ok_or_else(|| format!("Entity instance '{}' not found", name))?;

        self.entity_instances
            .shift_remove(&id)
            .ok_or_else(|| format!("Entity instance '{}' not found", name))
    }

    pub fn has_entity_instance_by_id(&self, id: &ConceptId) -> bool {
        self.entity_instances.contains_key(id)
    }

    pub fn get_entity_instance_by_id(&self, id: &ConceptId) -> Option<&Instance> {
        self.entity_instances.get(id)
    }

    pub fn remove_entity_instance_by_id(&mut self, id: &ConceptId) -> Result<Instance, String> {
        self.entity_instances
            .shift_remove(id)
            .ok_or_else(|| format!("Entity instance with id '{}' not found", id))
    }

    pub fn flows_from(&self, entity_id: &ConceptId) -> Vec<&Flow> {
        self.flows
            .values()
            .filter(|flow| flow.from_id() == entity_id)
            .collect()
    }

    pub fn flows_to(&self, entity_id: &ConceptId) -> Vec<&Flow> {
        self.flows
            .values()
            .filter(|flow| flow.to_id() == entity_id)
            .collect()
    }

    pub fn upstream_entities(&self, entity_id: &ConceptId) -> Vec<&Entity> {
        self.flows_to(entity_id)
            .iter()
            .filter_map(|flow| self.get_entity(flow.from_id()))
            .collect()
    }

    pub fn downstream_entities(&self, entity_id: &ConceptId) -> Vec<&Entity> {
        self.flows_from(entity_id)
            .iter()
            .filter_map(|flow| self.get_entity(flow.to_id()))
            .collect()
    }

    pub fn find_entity_by_name_and_namespace(
        &self,
        name: &str,
        namespace: &str,
    ) -> Option<ConceptId> {
        self.entities
            .iter()
            .find(|(_, entity)| entity.name() == name && entity.namespace() == namespace)
            .map(|(id, _)| id.clone())
    }

    pub fn find_entity_by_name(&self, name: &str) -> Option<ConceptId> {
        self.entities
            .iter()
            .find(|(_, entity)| entity.name() == name)
            .map(|(id, _)| id.clone())
    }

    pub fn find_resource_by_name(&self, name: &str) -> Option<ConceptId> {
        self.resources
            .iter()
            .find(|(_, resource)| resource.name() == name)
            .map(|(id, _)| id.clone())
    }

    pub fn find_role_by_name(&self, name: &str) -> Option<ConceptId> {
        self.roles
            .iter()
            .find(|(_, role)| role.name() == name)
            .map(|(id, _)| id.clone())
    }

    pub fn find_entity_instance_by_name(&self, name: &str) -> Option<ConceptId> {
        self.entity_instances
            .iter()
            .find(|(_, instance)| instance.name() == name)
            .map(|(id, _)| id.clone())
    }

    pub fn find_entity_instance_by_name_and_namespace(
        &self,
        name: &str,
        namespace: &str,
    ) -> Option<ConceptId> {
        self.entity_instances
            .iter()
            .find(|(_, instance)| instance.name() == name && instance.namespace() == namespace)
            .map(|(id, _)| id.clone())
    }

    pub fn find_pattern(&self, name: &str, namespace: Option<&str>) -> Option<&Pattern> {
        if let Some(ns) = namespace {
            if let Some((_, pattern)) = self
                .patterns
                .iter()
                .find(|(_, pattern)| pattern.name() == name && pattern.namespace() == ns)
            {
                return Some(pattern);
            }
        }

        self.patterns
            .iter()
            .find(|(_, pattern)| pattern.name() == name)
            .map(|(_, pattern)| pattern)
    }

    pub fn all_entities(&self) -> Vec<&Entity> {
        self.entities.values().collect()
    }

    pub fn all_roles(&self) -> Vec<&Role> {
        self.roles.values().collect()
    }

    pub fn all_resources(&self) -> Vec<&Resource> {
        self.resources.values().collect()
    }

    pub fn all_flows(&self) -> Vec<&Flow> {
        self.flows.values().collect()
    }

    pub fn all_instances(&self) -> Vec<&ResourceInstance> {
        self.instances.values().collect()
    }

    pub fn all_patterns(&self) -> Vec<&Pattern> {
        self.patterns.values().collect()
    }

    pub fn policy_count(&self) -> usize {
        self.policies.len()
    }

    pub fn add_policy(&mut self, policy: Policy) -> Result<(), String> {
        let id = policy.id.clone();
        if self.policies.contains_key(&id) {
            return Err(format!("Policy with ID {} already exists", id));
        }
        self.policies.insert(id, policy);
        Ok(())
    }

    pub fn has_policy(&self, id: &ConceptId) -> bool {
        self.policies.contains_key(id)
    }

    pub fn get_policy(&self, id: &ConceptId) -> Option<&Policy> {
        self.policies.get(id)
    }

    pub fn remove_policy(&mut self, id: &ConceptId) -> Result<Policy, String> {
        self.policies
            .shift_remove(id)
            .ok_or_else(|| format!("Policy with ID {} not found", id))
    }

    pub fn all_policies(&self) -> Vec<&Policy> {
        self.policies.values().collect()
    }

    pub fn metric_count(&self) -> usize {
        self.metrics.len()
    }

    pub fn add_metric(&mut self, metric: Metric) -> Result<(), String> {
        metric.validate()?;
        let id = metric.id().clone();
        if self.metrics.contains_key(&id) {
            return Err(format!("Metric with ID {} already exists", id));
        }
        self.metrics.insert(id, metric);
        Ok(())
    }

    pub fn has_metric(&self, id: &ConceptId) -> bool {
        self.metrics.contains_key(id)
    }

    pub fn get_metric(&self, id: &ConceptId) -> Option<&Metric> {
        self.metrics.get(id)
    }

    pub fn all_metrics(&self) -> Vec<&Metric> {
        self.metrics.values().collect()
    }

    pub fn mapping_count(&self) -> usize {
        self.mappings.len()
    }

    pub fn add_mapping(&mut self, mapping: MappingContract) -> Result<(), String> {
        let id = mapping.id().clone();
        if self.mappings.contains_key(&id) {
            return Err(format!("Mapping with ID {} already exists", id));
        }
        self.mappings.insert(id, mapping);
        Ok(())
    }

    pub fn has_mapping(&self, id: &ConceptId) -> bool {
        self.mappings.contains_key(id)
    }

    pub fn get_mapping(&self, id: &ConceptId) -> Option<&MappingContract> {
        self.mappings.get(id)
    }

    pub fn all_mappings(&self) -> Vec<&MappingContract> {
        self.mappings.values().collect()
    }

    pub fn projection_count(&self) -> usize {
        self.projections.len()
    }

    pub fn add_projection(&mut self, projection: ProjectionContract) -> Result<(), String> {
        let id = projection.id().clone();
        if self.projections.contains_key(&id) {
            return Err(format!("Projection with ID {} already exists", id));
        }
        self.projections.insert(id, projection);
        Ok(())
    }

    pub fn has_projection(&self, id: &ConceptId) -> bool {
        self.projections.contains_key(id)
    }

    pub fn get_projection(&self, id: &ConceptId) -> Option<&ProjectionContract> {
        self.projections.get(id)
    }

    pub fn all_projections(&self) -> Vec<&ProjectionContract> {
        self.projections.values().collect()
    }

    /// Extend this graph with all nodes and policies from another graph.
    /// The operation is atomic: the existing graph is only modified if the entire
    /// merge succeeds, which prevents partial state when errors occur.
    pub fn extend(&mut self, other: Graph) -> Result<(), String> {
        let mut merged = self.clone();
        merged.extend_from_graph(other)?;
        *self = merged;
        Ok(())
    }

    fn extend_from_graph(&mut self, other: Graph) -> Result<(), String> {
        let Graph {
            entities,
            roles,
            resources,
            flows,
            relations,
            instances,
            entity_instances,
            policies,
            patterns,
            concept_changes,
            metrics,
            mappings,
            projections,
            declared_dimensions,
            declared_units,
            entity_roles,
            entity_contracts,
            enum_contracts,
            operation_bound_policy_names,
            config: _,
        } = other;

        for entity in entities.into_values() {
            self.add_entity(entity)?;
        }

        for role in roles.into_values() {
            self.add_role(role)?;
        }

        for resource in resources.into_values() {
            self.add_resource(resource)?;
        }

        for instance in instances.into_values() {
            self.add_instance(instance)?;
        }

        for entity_instance in entity_instances.into_values() {
            // The incoming contracts are installed below, so defer schema
            // validation until the complete atomic merge candidate exists.
            self.insert_entity_instance(entity_instance)?;
        }

        for flow in flows.into_values() {
            self.add_flow(flow)?;
        }

        for relation in relations.into_values() {
            self.add_relation_type(relation)?;
        }

        for pattern in patterns.into_values() {
            self.add_pattern(pattern)?;
        }

        for (entity_id, roles_for_entity) in entity_roles.into_iter() {
            for role_id in roles_for_entity {
                self.assign_role_to_entity(entity_id.clone(), role_id)?;
            }
        }

        self.entity_contracts.extend(entity_contracts);
        self.enum_contracts.extend(enum_contracts);
        self.operation_bound_policy_names
            .extend(operation_bound_policy_names);
        self.validate_entity_instances()
            .map_err(|errors| errors.join("; "))?;

        for policy in policies.into_values() {
            self.add_policy(policy)?;
        }

        for change in concept_changes.into_values() {
            self.add_concept_change(change)?;
        }

        for metric in metrics.into_values() {
            self.add_metric(metric)?;
        }

        for mapping in mappings.into_values() {
            self.add_mapping(mapping)?;
        }

        for projection in projections.into_values() {
            self.add_projection(projection)?;
        }

        for (id, dimension) in declared_dimensions {
            match self.declared_dimensions.get(&id) {
                Some(existing) if existing != &dimension => {
                    return Err(format!(
                        "Conflicting dimension '{}' already declared (existing namespace='{}'; new namespace='{}')",
                        dimension.name, existing.namespace, dimension.namespace
                    ));
                }
                _ => {
                    self.declared_dimensions.insert(id, dimension);
                }
            }
        }

        for (id, unit) in declared_units {
            match self.declared_units.get(&id) {
                Some(existing) if existing != &unit => {
                    return Err(format!(
                        "Conflicting unit '{}' already declared (existing: dimension={}, base_factor={}, base_unit={}; new: dimension={}, base_factor={}, base_unit={})",
                        unit.name,
                        existing.dimension,
                        existing.base_factor,
                        existing.base_unit,
                        unit.dimension,
                        unit.base_factor,
                        unit.base_unit
                    ));
                }
                _ => {
                    self.declared_units.insert(id, unit);
                }
            }
        }

        Ok(())
    }

    /// Validate the graph by evaluating all policies against it and
    /// collecting any violations produced. Returns a `ValidationResult`.
    pub fn validate(&self) -> ValidationResult {
        let mut all_violations: Vec<Violation> = Vec::new();
        let use_three_valued_logic = self.config.use_three_valued_logic;

        if let Err(errors) = self.validate_entity_instances() {
            all_violations.extend(
                errors
                    .into_iter()
                    .map(|error| Violation::new("entity_instance_schema", error, Severity::Error)),
            );
        }

        // Policies bound to an operation's `access policy_governed by`
        // clause are meant to be evaluated in that operation's typed
        // contract context (an input record field, a state precondition),
        // not against the bare graph, where their terms do not resolve and
        // evaluation returns UNKNOWN (limitation L9). `--application`/
        // `contract`/`envelope` check them in the right context instead.
        let mut evaluated = 0usize;
        for policy in self.policies.values() {
            if self.operation_bound_policy_names.contains(&policy.id) {
                continue;
            }
            evaluated += 1;
            match policy.evaluate_with_mode(self, use_three_valued_logic) {
                Ok(eval) => {
                    all_violations.extend(eval.violations);
                }
                Err(err) => {
                    // If a policy evaluation fails, produce an ERROR severity
                    // violation indicating evaluation failure so the user can
                    // see the issue.
                    let v = Violation::new(
                        &policy.name,
                        format!("Policy evaluation failed: {}", err),
                        Severity::Error,
                    );
                    all_violations.push(v);
                }
            }
        }

        ValidationResult::new(evaluated, all_violations)
    }
}