kglite 0.16.15

Pure-Rust embedded Cypher knowledge graph engine with in-memory, mmap, and disk storage, and agent-facing schema introspection
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
//! The declared semantic layer: an `is_a` forest over type names plus
//! relationship semantics, persisted in `.kgl` metadata.
//!
//! **Annotations, not axioms.** The store never invents facts and never
//! changes what a query matches: it feeds `describe()`, provides defaults
//! for the rule-procedure validators, and (via the blueprint gate) turns
//! declarations into a load-time data-quality contract. In spirit this is
//! SKOS, not OWL — no entailment, no open-world semantics.
//!
//! Deliberately independent of `DirGraph::parent_types`: that map is a
//! *presentation* hierarchy (describe() tiering, `graph_scale`), this one is
//! *semantic* ("kind of"). `ProspectEstimate → Prospect` is ownership and
//! belongs there; `Licence is_a Licensable` belongs here. Neither is ever
//! derived from the other.
//!
//! Like `schema_from_value`, [`ontology_from_value`] is the one external
//! dialect chokepoint: Python dicts and C-ABI JSON both become a [`Value`]
//! before parsing, so every binding shares one grammar and one set of
//! messages. Canonical documents are JSON; YAML stays a Python-side
//! convenience.
//!
//! Grammar (all keys optional unless said otherwise):
//!
//! ```json
//! {
//!   "version": 1,
//!   "classes": {
//!     "Licensable": {"abstract": true, "description": "..."},
//!     "Licence":    {"is_a": "Licensable", "by": "kind", "description": "..."}
//!   },
//!   "relationships": {
//!     "HAS_OPERATOR": {
//!       "domain": "Licensable", "range": "Company",
//!       "required_properties": ["validFrom"],
//!       "property_types": {"validFrom": "date"},
//!       "inverse_name": "OPERATOR_OF",
//!       "cardinality": {"min": 0, "max": 1},
//!       "required": true, "transitive": false, "symmetric": false,
//!       "ancestry": false,
//!       "enforcement": "warn",
//!       "exempt": {"required_properties": ["PetregLicence"]},
//!       "description": "Operatorship over time"
//!     }
//!   }
//! }
//! ```
//!
//! Semantics the fields promise (and no more):
//! - `is_a` is a forest — one parent, no cycles, parent must be declared.
//! - `cardinality` / `required` describe **outgoing** edges of the domain
//!   type (the validators they feed — `cardinality_violation`,
//!   `missing_required_edge` — count outgoing only).
//! - `symmetric` lowers to `inverse_violation(rel, rel)`, which reports each
//!   asymmetric pair once per direction encountered.
//! - `transitive` and `ancestry` are the two readings of "this edge is a
//!   hierarchy", and they are mutually exclusive. `transitive` promises a
//!   **stored** closure and lowers to `transitivity_violation`, which flags
//!   every `a→b→c` without a stored `a→c`. `ancestry` promises nothing to
//!   audit: it records that the chain is meaningful and is walked with
//!   `*1..`, which is what a parent-pointer taxonomy (`STRAT_PARENT`,
//!   `wdt:P279`) actually is — declaring *that* `transitive` would report
//!   100% violations.
//! - `enforcement` is data for *callers* — the blueprint gate and
//!   `ontology_audit()` — never an engine write guarantee in this mode.
//! - `exempt` names, per check, source classes whose violations are counted
//!   *separately* (`ontology_audit`'s `exempted`) instead of against
//!   severity, so one legitimately-nonconforming source type cannot pin a
//!   whole rule at `advisory`. Accepted for [`EXEMPTABLE_CHECKS`] only.
//! - `by` names a discriminator property and is documentation only.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::datatypes::values::Value;

/// Schema-vocabulary scale boundary, enforced rather than documented: the
/// layer is for tens-to-hundreds of classes. Thousand-class taxonomies
/// (Wikidata P279) are *data* and belong in edges.
pub const MAX_ONTOLOGY_CLASSES: usize = 512;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct OntologyStore {
    #[serde(default = "default_version")]
    pub version: u32,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub classes: BTreeMap<String, ClassDecl>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub relationships: BTreeMap<String, RelationshipDecl>,
}

fn default_version() -> u32 {
    1
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ClassDecl {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_a: Option<String>,
    #[serde(
        rename = "abstract",
        default,
        skip_serializing_if = "std::ops::Not::not"
    )]
    pub is_abstract: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Documentation-only discriminator property name (unenforced).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub by: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct RelationshipDecl {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub range: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_properties: Vec<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub property_types: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inverse_name: Option<String>,
    /// Opt-in: audit `inverse_name` as a physical-pairing contract. Without
    /// it the name is a reading-direction alias only (describe()/agent
    /// metadata) and enrolls no check.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub inverse_enforced: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cardinality: Option<CardinalityDecl>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub required: bool,
    /// Opt-in **stored-closure** audit: `transitivity_violation` flags every
    /// `a→b→c` with no stored `a→c` edge. Correct only for graphs that
    /// materialize the closure; mutually exclusive with [`Self::ancestry`],
    /// which is what a parent-pointer taxonomy wants.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub transitive: bool,
    /// Annotation that ancestry along this relationship is meaningful and is
    /// walked with `*1..` — the parent-pointer taxonomy shape, whose closure
    /// is deliberately not stored. Reader-facing only (`describe()`, agent
    /// topics): it enrolls **no** check, which is the point — the stored-closure
    /// audit that [`Self::transitive`] enrolls would flag every edge of such
    /// a taxonomy. Declaring both is refused by [`OntologyStore::validate`].
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub ancestry: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub symmetric: bool,
    #[serde(default, skip_serializing_if = "Enforcement::is_default")]
    pub enforcement: Enforcement,
    /// Per-check severities (keys from [`CHECK_NAMES`]); unlisted checks
    /// fall back to `enforcement`.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub enforcement_overrides: BTreeMap<String, Enforcement>,
    /// Per-check source-class exemptions (keys from [`EXEMPTABLE_CHECKS`]).
    /// A violation whose edge source is one of the listed classes — or a
    /// declared descendant of one — is reported as `exempted` rather than
    /// counted against the check's severity.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub exempt: BTreeMap<String, Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl RelationshipDecl {
    /// The severity governing one check of this declaration.
    pub fn enforcement_for(&self, check: &str) -> Enforcement {
        self.enforcement_overrides
            .get(check)
            .copied()
            .unwrap_or(self.enforcement)
    }

    /// The base severity, plus any per-check overrides as `check=severity`.
    /// Both reader surfaces (`SHOW ONTOLOGY`, `describe()`) render this, so a
    /// declaration whose overrides raise a check above its base severity can
    /// never read as the bare base in one of them.
    pub(crate) fn enforcement_summary(&self) -> String {
        let base = self.enforcement.as_str().to_string();
        if self.enforcement_overrides.is_empty() {
            return base;
        }
        let overrides: Vec<String> = self
            .enforcement_overrides
            .iter()
            .map(|(check, sev)| format!("{check}={}", sev.as_str()))
            .collect();
        format!("{base}; {}", overrides.join(", "))
    }

    /// Source classes exempted from `check`; empty when none are.
    pub fn exempt_classes(&self, check: &str) -> &[String] {
        self.exempt.get(check).map(Vec::as_slice).unwrap_or(&[])
    }

    /// Declared exemptions as `check: [Class, …]`, `None` when there are
    /// none — the reader-surface companion to [`Self::enforcement_summary`],
    /// rendered by both `SHOW ONTOLOGY` and `describe()`.
    pub(crate) fn exempt_summary(&self) -> Option<String> {
        if self.exempt.is_empty() {
            return None;
        }
        Some(
            self.exempt
                .iter()
                .map(|(check, classes)| format!("{check}: [{}]", classes.join(", ")))
                .collect::<Vec<_>>()
                .join("; "),
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Enforcement {
    #[default]
    Advisory,
    Warn,
    Error,
}

impl Enforcement {
    fn is_default(&self) -> bool {
        *self == Enforcement::Advisory
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Enforcement::Advisory => "advisory",
            Enforcement::Warn => "warn",
            Enforcement::Error => "error",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct CardinalityDecl {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<u64>,
}

/// State of one materialized (managed) label — see
/// `dir_graph/ontology_apply.rs` for the invariant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ManagedLabelState {
    /// The engine is the bucket's only writer; it holds exactly the closure.
    Closed,
    /// Something outside the closure touched the bucket (manual SET, adopt,
    /// extend union). Correct, but closure-reliant optimizations stay off.
    Open,
}

impl ManagedLabelState {
    pub fn as_str(&self) -> &'static str {
        match self {
            ManagedLabelState::Closed => "closed",
            ManagedLabelState::Open => "open",
        }
    }
}

/// `skip_serializing_if` helper for the `Arc<OntologyStore>` field on
/// `DirGraph` (serde hands the function `&Arc<_>`, which method syntax
/// won't coerce in the derive).
pub fn arc_store_is_empty(store: &std::sync::Arc<OntologyStore>) -> bool {
    store.is_empty()
}

impl OntologyStore {
    pub fn is_empty(&self) -> bool {
        self.classes.is_empty() && self.relationships.is_empty()
    }

    /// Ancestor chain of `class`, nearest first. Empty for roots and for
    /// names the store does not declare. Bounded by the forest invariant
    /// (`validate` rejects cycles), with a defensive cap for stores built
    /// without it.
    pub fn ancestors(&self, class: &str) -> Vec<String> {
        let mut out = Vec::new();
        let mut current = class;
        while let Some(parent) = self.classes.get(current).and_then(|c| c.is_a.as_deref()) {
            if out.len() > self.classes.len() {
                break;
            }
            out.push(parent.to_string());
            current = parent;
        }
        out
    }

    /// Structural validation: the forest invariant, dangling `is_a`
    /// targets, and the class cap. Graph-aware checks (abstract vs live
    /// primary types) live in `DirGraph::define_ontology`, which has the
    /// graph.
    pub fn validate(&self) -> Result<(), String> {
        if self.classes.len() > MAX_ONTOLOGY_CLASSES {
            return Err(format!(
                "ontology declares {} classes; the layer is for schema-level vocabularies \
                 (max {MAX_ONTOLOGY_CLASSES}). Large taxonomies are data — model them as edges \
                 walked with `*1..` paths, declaring that relationship `ancestry: true`. Do not \
                 reach for `transitive: true` there: it audits a *stored* closure, so a \
                 parent-pointer taxonomy reports 100% violations.",
                self.classes.len()
            ));
        }
        for (name, decl) in &self.classes {
            if let Some(parent) = &decl.is_a {
                if !self.classes.contains_key(parent) {
                    return Err(format!(
                        "class '{name}': is_a target '{parent}' is not a declared class"
                    ));
                }
                if parent == name {
                    return Err(format!("class '{name}': is_a itself"));
                }
            }
        }
        // Cycle check: walk each chain; the forest has ≤ classes.len() edges,
        // so a longer walk is a cycle.
        for name in self.classes.keys() {
            let mut steps = 0usize;
            let mut current = name.as_str();
            while let Some(parent) = self.classes.get(current).and_then(|c| c.is_a.as_deref()) {
                steps += 1;
                if steps > self.classes.len() {
                    return Err(format!("class '{name}': is_a chain contains a cycle"));
                }
                current = parent;
            }
        }
        for (name, decl) in &self.relationships {
            for endpoint in [&decl.domain, &decl.range].into_iter().flatten() {
                if endpoint.is_empty() {
                    return Err(format!("relationship '{name}': empty endpoint name"));
                }
            }
            if decl.transitive && decl.ancestry {
                return Err(format!(
                    "relationship '{name}': 'transitive' and 'ancestry' are mutually exclusive. \
                     'transitive' audits a stored closure — transitivity_violation flags every \
                     a→b→c with no stored a→c edge. 'ancestry' annotates a parent-pointer \
                     taxonomy walked with `*1..` and enrolls no check. Declare one."
                ));
            }
            for (check, classes) in &decl.exempt {
                for class in classes {
                    if !self.classes.contains_key(class) {
                        return Err(format!(
                            "relationship '{name}': exempt['{check}'] names '{class}', which is \
                             not a declared class. An exemption widens over the declared is_a \
                             forest, so a name outside it would silently exempt nothing — \
                             declare the class (abstract or concrete) first."
                        ));
                    }
                }
            }
            if let Some(card) = &decl.cardinality {
                if let (Some(min), Some(max)) = (card.min, card.max) {
                    if min > max {
                        return Err(format!(
                            "relationship '{name}': cardinality min {min} > max {max}"
                        ));
                    }
                }
            }
        }
        Ok(())
    }
}

/// Parse the external dialect out of the shared [`Value`] data model — the
/// single chokepoint every binding routes through (see module doc). Unknown
/// keys are refused with a did-you-mean, the `define_schema` posture: a
/// declaration key the parser cannot place is never a harmless extra.
pub fn ontology_from_value(doc: &Value) -> Result<OntologyStore, String> {
    let map = as_map(doc).ok_or("ontology document must be a map")?;
    reject_unknown(map, &["version", "classes", "relationships"], "ontology")?;

    let mut store = OntologyStore {
        version: 1,
        ..Default::default()
    };
    if let Some(v) = map.get("version") {
        store.version = match v {
            Value::Int64(n) if *n >= 1 => *n as u32,
            _ => return Err("ontology 'version' must be a positive integer".to_string()),
        };
    }
    if let Some(classes) = map.get("classes") {
        let classes = as_map(classes).ok_or("ontology 'classes' must be a map")?;
        for (name, decl) in classes {
            store
                .classes
                .insert(name.to_string(), class_from_value(name, decl)?);
        }
    }
    if let Some(rels) = map.get("relationships") {
        let rels = as_map(rels).ok_or("ontology 'relationships' must be a map")?;
        for (name, decl) in rels {
            store
                .relationships
                .insert(name.to_string(), relationship_from_value(name, decl)?);
        }
    }
    store.validate()?;
    Ok(store)
}

/// [`ontology_from_value`] over a JSON document — the C ABI / file entry
/// point, routed through the same JSON→[`Value`] conversion every other
/// JSON-carrying surface uses.
pub fn ontology_from_json(json: &str) -> Result<OntologyStore, String> {
    let parsed: serde_json::Value =
        serde_json::from_str(json).map_err(|e| format!("ontology JSON parse: {e}"))?;
    let value = crate::param::json_value_to_kglite_value(&parsed);
    ontology_from_value(&value)
}

/// The closed accept-list for `property_types` values — every spelling
/// [`crate::graph::mutation::validation::value_matches_type`] resolves.
const PROPERTY_TYPE_NAMES: &[&str] = &[
    "string",
    "str",
    "integer",
    "int",
    "i64",
    "int64",
    "float",
    "double",
    "f64",
    "number",
    "float64",
    "boolean",
    "bool",
    "date",
    "datetime",
    "timestamp",
    "uniqueid",
    "point",
    "any",
];

/// Every declaration-driven check name (`DeclaredCheck::name` values) —
/// the accepted key set for the map form of `enforcement`.
pub const CHECK_NAMES: &[&str] = &[
    "domain",
    "range",
    "required",
    "required_properties",
    "property_types",
    "cardinality",
    "inverse",
    "symmetric",
    "transitive",
];

/// The checks a source-class exemption is well-defined for. Both flag one
/// edge, and the edge's source node carries exactly one domain-side class.
/// Every other check either **is** a domain-side class test (`domain`,
/// `range`, and the node-scoped `required` / `cardinality` — exempting a
/// class there disables the check for it outright) or flags a tuple of two
/// or three nodes with no single domain-side class (`inverse`, `symmetric`,
/// `transitive`).
pub const EXEMPTABLE_CHECKS: &[&str] = &["required_properties", "property_types"];

const CLASS_KEYS: &[&str] = &["is_a", "abstract", "description", "by"];
const REL_KEYS: &[&str] = &[
    "domain",
    "range",
    "required_properties",
    "property_types",
    "inverse_name",
    "inverse_enforced",
    "cardinality",
    "required",
    "transitive",
    "ancestry",
    "symmetric",
    "enforcement",
    "exempt",
    "description",
];

fn class_from_value(name: &str, value: &Value) -> Result<ClassDecl, String> {
    let map = as_map(value).ok_or_else(|| format!("class '{name}' must be a map"))?;
    reject_unknown(map, CLASS_KEYS, &format!("class '{name}'"))?;
    Ok(ClassDecl {
        is_a: opt_string(map, "is_a", name)?,
        is_abstract: opt_bool(map, "abstract", name)?,
        description: opt_string(map, "description", name)?,
        by: opt_string(map, "by", name)?,
    })
}

fn relationship_from_value(name: &str, value: &Value) -> Result<RelationshipDecl, String> {
    let map = as_map(value).ok_or_else(|| format!("relationship '{name}' must be a map"))?;
    reject_unknown(map, REL_KEYS, &format!("relationship '{name}'"))?;
    let severity = |s: &str| -> Result<Enforcement, String> {
        match s {
            "advisory" => Ok(Enforcement::Advisory),
            "warn" => Ok(Enforcement::Warn),
            "error" => Ok(Enforcement::Error),
            other => Err(format!(
                "relationship '{name}': enforcement '{other}' is not one of \
                 'advisory', 'warn', 'error'"
            )),
        }
    };
    let (enforcement, enforcement_overrides) = match map.get("enforcement") {
        None => (Enforcement::Advisory, BTreeMap::new()),
        Some(Value::String(s)) => (severity(s)?, BTreeMap::new()),
        // Map form: per-check severities; unlisted checks keep the
        // advisory base.
        Some(other) => match as_map(other) {
            Some(per_check) => {
                let mut overrides = BTreeMap::new();
                for (check, sv) in per_check {
                    if !CHECK_NAMES.contains(&check) {
                        return Err(format!(
                            "relationship '{name}': enforcement key '{check}' \
                             is not a check — use one of {CHECK_NAMES:?}"
                        ));
                    }
                    let Value::String(sv) = sv else {
                        return Err(format!(
                            "relationship '{name}': enforcement['{check}'] \
                             must be a severity string"
                        ));
                    };
                    overrides.insert(check.to_string(), severity(sv)?);
                }
                (Enforcement::Advisory, overrides)
            }
            None => {
                return Err(format!(
                    "relationship '{name}': 'enforcement' must be a severity \
                     string or a {{check: severity}} map"
                ))
            }
        },
    };
    let cardinality = match map.get("cardinality") {
        None => None,
        Some(v) => {
            let card = as_map(v)
                .ok_or_else(|| format!("relationship '{name}': 'cardinality' must be a map"))?;
            reject_unknown(
                card,
                &["min", "max"],
                &format!("relationship '{name}' cardinality"),
            )?;
            Some(CardinalityDecl {
                min: opt_u64(card, "min", name)?,
                max: opt_u64(card, "max", name)?,
            })
        }
    };
    let required_properties = match map.get("required_properties") {
        None => Vec::new(),
        Some(Value::List(items)) => items
            .iter()
            .map(|v| match v {
                Value::String(s) => Ok(s.clone()),
                _ => Err(format!(
                    "relationship '{name}': 'required_properties' entries must be strings"
                )),
            })
            .collect::<Result<_, _>>()?,
        Some(_) => {
            return Err(format!(
                "relationship '{name}': 'required_properties' must be a list"
            ))
        }
    };
    let property_types = match map.get("property_types") {
        None => BTreeMap::new(),
        Some(v) => {
            let types = as_map(v)
                .ok_or_else(|| format!("relationship '{name}': 'property_types' must be a map"))?;
            let mut out = BTreeMap::new();
            for (k, tv) in types {
                match tv {
                    Value::String(s) => {
                        // value_matches_type is permissive on unknown names,
                        // so a typo here would otherwise never fail anything.
                        if !PROPERTY_TYPE_NAMES.contains(&s.to_lowercase().as_str()) {
                            return Err(format!(
                                "relationship '{name}': 'property_types' entry \
                                 '{k}: {s}' names an unknown type — use one of \
                                 string, integer, float, boolean, date, \
                                 datetime, timestamp, point, any"
                            ));
                        }
                        out.insert(k.to_string(), s.clone());
                    }
                    _ => {
                        return Err(format!(
                            "relationship '{name}': 'property_types' values must be strings"
                        ))
                    }
                }
            }
            out
        }
    };
    let inverse_name = opt_string(map, "inverse_name", name)?;
    let inverse_enforced = opt_bool(map, "inverse_enforced", name)?;
    if inverse_enforced && inverse_name.is_none() {
        return Err(format!(
            "relationship '{name}': 'inverse_enforced' requires 'inverse_name'"
        ));
    }
    let exempt = exempt_from_value(name, map.get("exempt"))?;
    Ok(RelationshipDecl {
        domain: opt_string(map, "domain", name)?,
        range: opt_string(map, "range", name)?,
        required_properties,
        property_types,
        inverse_name,
        inverse_enforced,
        cardinality,
        required: opt_bool(map, "required", name)?,
        transitive: opt_bool(map, "transitive", name)?,
        ancestry: opt_bool(map, "ancestry", name)?,
        symmetric: opt_bool(map, "symmetric", name)?,
        enforcement,
        enforcement_overrides,
        exempt,
        description: opt_string(map, "description", name)?,
    })
}

/// `exempt: {check: [class, …]}`. The flat `exempt: [class, …]` form is
/// refused rather than spread across every check: an exemption that does
/// not name its check would silently apply where a source class is not what
/// the check tests, quietly weakening rules the declarer never considered.
fn exempt_from_value(
    name: &str,
    value: Option<&Value>,
) -> Result<BTreeMap<String, Vec<String>>, String> {
    let Some(value) = value else {
        return Ok(BTreeMap::new());
    };
    if matches!(value, Value::List(_)) {
        return Err(format!(
            "relationship '{name}': 'exempt' must be a {{check: [class, ...]}} map, not a list \
             — name the check each exemption applies to, e.g. \
             exempt: {{required_properties: ['PetregLicence']}}"
        ));
    }
    let per_check = as_map(value).ok_or_else(|| {
        format!("relationship '{name}': 'exempt' must be a {{check: [class, ...]}} map")
    })?;
    let mut out = BTreeMap::new();
    for (check, classes) in per_check {
        if !EXEMPTABLE_CHECKS.contains(&check) {
            return Err(exempt_check_refusal(name, check));
        }
        let Value::List(items) = classes else {
            return Err(format!(
                "relationship '{name}': exempt['{check}'] must be a list of class names"
            ));
        };
        let mut names = Vec::with_capacity(items.len());
        for item in items {
            match item {
                Value::String(s) if !s.is_empty() => names.push(s.clone()),
                Value::String(_) => {
                    return Err(format!(
                        "relationship '{name}': exempt['{check}'] has an empty class name"
                    ))
                }
                _ => {
                    return Err(format!(
                        "relationship '{name}': exempt['{check}'] entries must be strings"
                    ))
                }
            }
        }
        out.insert(check.to_string(), names);
    }
    Ok(out)
}

/// Why one check refuses exemption — the reason, not just the accept-list,
/// because "use required_properties instead" is not an answer to someone
/// who wants `domain` exempted.
fn exempt_check_refusal(name: &str, check: &str) -> String {
    let why = match check {
        "domain" | "range" | "required" | "cardinality" => {
            "that check already tests the domain-side class, so exempting a class would \
             disable it for that class outright"
        }
        "inverse" | "symmetric" | "transitive" => {
            "it flags a tuple of nodes rather than one edge, so there is no single \
             domain-side class to exempt"
        }
        _ => {
            let suggestion =
                crate::graph::mutation::validation::did_you_mean(check, EXEMPTABLE_CHECKS);
            return format!(
                "relationship '{name}': 'exempt' key '{check}' is not a check name.{suggestion} \
                 Exemption is accepted for {EXEMPTABLE_CHECKS:?} only."
            );
        }
    };
    format!(
        "relationship '{name}': 'exempt' does not accept check '{check}' — {why}. Exemption is \
         accepted for {EXEMPTABLE_CHECKS:?} only, where the exempted class is the edge's source \
         type."
    )
}

fn as_map(value: &Value) -> Option<&crate::datatypes::PropMap> {
    match value {
        Value::Map(map) => Some(map),
        _ => None,
    }
}

fn opt_string(
    map: &crate::datatypes::PropMap,
    key: &str,
    ctx: &str,
) -> Result<Option<String>, String> {
    match map.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) => Ok(Some(s.clone())),
        Some(_) => Err(format!("'{ctx}': '{key}' must be a string")),
    }
}

fn opt_bool(map: &crate::datatypes::PropMap, key: &str, ctx: &str) -> Result<bool, String> {
    match map.get(key) {
        None => Ok(false),
        Some(Value::Boolean(b)) => Ok(*b),
        Some(_) => Err(format!("'{ctx}': '{key}' must be a boolean")),
    }
}

fn opt_u64(map: &crate::datatypes::PropMap, key: &str, ctx: &str) -> Result<Option<u64>, String> {
    match map.get(key) {
        None => Ok(None),
        Some(Value::Int64(n)) if *n >= 0 => Ok(Some(*n as u64)),
        Some(_) => Err(format!(
            "relationship '{ctx}': cardinality '{key}' must be a non-negative integer"
        )),
    }
}

fn reject_unknown(
    map: &crate::datatypes::PropMap,
    accepted: &[&str],
    ctx: &str,
) -> Result<(), String> {
    for (key, _) in map {
        if accepted.contains(&key) {
            continue;
        }
        let suggestion = crate::graph::mutation::validation::did_you_mean(key, accepted);
        if !suggestion.is_empty() {
            return Err(format!("{ctx}: unknown key '{key}'.{suggestion}"));
        }
        let list = accepted
            .iter()
            .map(|k| format!("'{k}'"))
            .collect::<Vec<_>>()
            .join(", ");
        return Err(format!(
            "{ctx}: unknown key '{key}'. Accepted keys: {list}."
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(json: &str) -> Result<OntologyStore, String> {
        ontology_from_json(json)
    }

    #[test]
    fn round_trips_the_full_grammar() {
        let store = parse(
            r#"{"version": 1,
                "classes": {
                  "Licensable": {"abstract": true, "description": "d"},
                  "Licence": {"is_a": "Licensable", "by": "kind"}
                },
                "relationships": {
                  "HAS_OPERATOR": {
                    "domain": "Licensable", "range": "Company",
                    "required_properties": ["validFrom"],
                    "property_types": {"validFrom": "date"},
                    "inverse_name": "OPERATOR_OF",
                    "cardinality": {"min": 0, "max": 1},
                    "required": true, "transitive": false, "symmetric": false,
                    "ancestry": true,
                    "enforcement": "warn",
                    "exempt": {"required_properties": ["Licence"]},
                    "description": "op"
                  }
                }}"#,
        )
        .unwrap();
        assert!(store.classes["Licensable"].is_abstract);
        assert_eq!(store.classes["Licence"].is_a.as_deref(), Some("Licensable"));
        assert_eq!(store.ancestors("Licence"), vec!["Licensable"]);
        let rel = &store.relationships["HAS_OPERATOR"];
        assert_eq!(rel.enforcement, Enforcement::Warn);
        assert!(rel.ancestry && !rel.transitive);
        assert_eq!(rel.cardinality.unwrap().max, Some(1));
        assert_eq!(rel.exempt_classes("required_properties"), ["Licence"]);
        assert!(rel.exempt_classes("property_types").is_empty());
        assert_eq!(
            rel.exempt_summary().as_deref(),
            Some("required_properties: [Licence]")
        );
        // Serde round-trip (the FileMetadata path).
        let json = serde_json::to_string(&store).unwrap();
        let back: OntologyStore = serde_json::from_str(&json).unwrap();
        assert_eq!(back, store);
    }

    #[test]
    fn rejects_unknown_keys_with_suggestion() {
        let err = parse(r#"{"clases": {}}"#).unwrap_err();
        assert!(err.contains("classes"), "{err}");
        let err = parse(r#"{"classes": {"A": {"isa": "B"}}}"#).unwrap_err();
        assert!(err.contains("is_a"), "{err}");
        let err = parse(r#"{"relationships": {"R": {"enforcement": "fatal"}}}"#).unwrap_err();
        assert!(err.contains("advisory"), "{err}");
    }

    #[test]
    fn rejects_forest_violations() {
        let err = parse(r#"{"classes": {"A": {"is_a": "Missing"}}}"#).unwrap_err();
        assert!(err.contains("not a declared class"), "{err}");
        let err = parse(r#"{"classes": {"A": {"is_a": "B"}, "B": {"is_a": "A"}}}"#).unwrap_err();
        assert!(err.contains("cycle"), "{err}");
        let err = parse(r#"{"classes": {"A": {"is_a": "A"}}}"#).unwrap_err();
        assert!(err.contains("itself"), "{err}");
    }

    #[test]
    fn enforces_the_class_cap() {
        let classes: Vec<String> = (0..=MAX_ONTOLOGY_CLASSES)
            .map(|i| format!("\"C{i}\": {{}}"))
            .collect();
        let doc = format!("{{\"classes\": {{{}}}}}", classes.join(","));
        let err = parse(&doc).unwrap_err();
        assert!(err.contains("schema-level vocabularies"), "{err}");
        // The refusal used to recommend `transitive:` for exactly the shape
        // that check reports as 100% violating; it must steer to `ancestry:`
        // and say why `transitive` is not the answer.
        assert!(err.contains("`ancestry: true`"), "{err}");
        assert!(err.contains("stored"), "{err}");
    }

    #[test]
    fn transitive_and_ancestry_are_mutually_exclusive() {
        let err = parse(r#"{"relationships": {"P279": {"transitive": true, "ancestry": true}}}"#)
            .unwrap_err();
        assert!(err.contains("mutually exclusive"), "{err}");
        assert!(err.contains("stored closure"), "{err}");
        assert!(err.contains("*1.."), "{err}");
        // Either alone is accepted.
        for doc in [
            r#"{"relationships": {"P279": {"transitive": true}}}"#,
            r#"{"relationships": {"P279": {"ancestry": true}}}"#,
        ] {
            parse(doc).unwrap();
        }
    }

    #[test]
    fn ancestry_is_not_a_check_name() {
        // `ancestry` enrolls no check, so it is refused everywhere a check
        // name is expected — enforcement overrides and exempt alike.
        let err = parse(r#"{"relationships": {"R": {"enforcement": {"ancestry": "error"}}}}"#)
            .unwrap_err();
        assert!(err.contains("is not a check"), "{err}");
        let err = parse(
            r#"{"classes": {"A": {}},
                "relationships": {"R": {"exempt": {"ancestry": ["A"]}}}}"#,
        )
        .unwrap_err();
        assert!(err.contains("not a check name"), "{err}");
        assert!(!CHECK_NAMES.contains(&"ancestry"));
        assert!(!EXEMPTABLE_CHECKS.contains(&"ancestry"));
    }

    #[test]
    fn cardinality_min_over_max_rejected() {
        let err = parse(r#"{"relationships": {"R": {"cardinality": {"min": 2, "max": 1}}}}"#)
            .unwrap_err();
        assert!(err.contains("min 2 > max 1"), "{err}");
    }

    #[test]
    fn exempt_refuses_the_flat_form_and_unexemptable_checks() {
        let flat = parse(
            r#"{"classes": {"A": {}},
                "relationships": {"R": {"exempt": ["A"]}}}"#,
        )
        .unwrap_err();
        assert!(flat.contains("{check: [class, ...]}"), "{flat}");
        for (check, marker) in [
            ("domain", "already tests the domain-side class"),
            ("cardinality", "already tests the domain-side class"),
            ("transitive", "no single domain-side class"),
        ] {
            let err = parse(&format!(
                r#"{{"classes": {{"A": {{}}}},
                     "relationships": {{"R": {{"exempt": {{"{check}": ["A"]}}}}}}}}"#
            ))
            .unwrap_err();
            assert!(err.contains(marker), "{check}: {err}");
        }
        let typo = parse(
            r#"{"classes": {"A": {}},
                "relationships": {"R": {"exempt": {"required_propertys": ["A"]}}}}"#,
        )
        .unwrap_err();
        assert!(
            typo.contains("Did you mean 'required_properties'?"),
            "{typo}"
        );
    }

    #[test]
    fn exempt_class_must_be_declared() {
        let err = parse(
            r#"{"classes": {"A": {}},
                "relationships": {"R": {"exempt": {"property_types": ["Ghost"]}}}}"#,
        )
        .unwrap_err();
        assert!(err.contains("not a declared class"), "{err}");
    }

    #[test]
    fn empty_store_serializes_to_nothing_extra() {
        let store = OntologyStore::default();
        assert!(store.is_empty());
        assert_eq!(serde_json::to_string(&store).unwrap(), r#"{"version":0}"#);
    }
}