aprender-contracts 0.70.1

Papers to Math to Contracts in Code — YAML contract parsing, validation, scaffold generation, and Kani harness codegen for provable Rust kernels
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
//! ONT-001 §4.1 — Σ, the ontology's own declaration (ONT-2b, PMAT-3471).
//!
//! Σ lives in `contracts/ontology.yaml` and declares what the corpus is allowed to say: the `concepts`, the `roles`
//! (with `domain`/`range`), the `symbols` a `formal:` expression may use, the `worlds`, the `agents`, the
//! `entity_types` and the `extractors` that read them, and the keys the ontology deliberately cannot express
//! (`not_expressible`).
//!
//! **Six ways Σ itself is malformed, all exit 3** (`error:`, never `reject:` — the corpus is not at fault):
//!
//! 1. an `entity_types` entry naming no extractor, or naming one `extractors[]` does not declare;
//! 2. a Σ key no declared reader claims — an anchor nothing reads is decoration, the defect ONT-1 refused;
//! 3. a `not_expressible` entry without a `reader`;
//! 4. an `extractors[]` entry without a `reader`;
//! 5. an `entity_types` entry named `entity` — the reserved name: entity classes live at `<ONT_BASE>entity/<type>`
//!    (#4160), so that type's property predicates `<ONT_BASE>entity/<key>` would share the classes' namespace;
//! 6. an `entity_type_target_class` key that no `entity_types` entry declares;
//! 7. an `implemented: true` entity type with neither a class nor an explicit `~` in `entity_type_target_class`
//!    (v4.16 D-T1: the map is cross-checked against `entity_types`, never a hand-kept list nothing reads back).
//!
//! A `reader` is a DECLARED NAME carried beside `implemented: true|false`, not a path that must resolve today
//! (plan v2 ruling 3): §4.1 gives `entity_types[{name, extractor, implemented}]` and ONT-4c marks four of them
//! `implemented: true` later, so a Σ that could only name built extractors could not be written at all in this row.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde::Deserialize;

/// Σ as `contracts/ontology.yaml` carries it.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Sigma {
    pub schema: String,
    #[serde(default)]
    pub concepts: BTreeMap<String, Concept>,
    #[serde(default)]
    pub roles: BTreeMap<String, Role>,
    #[serde(default)]
    pub symbols: Vec<Symbol>,
    #[serde(default)]
    pub worlds: BTreeMap<String, World>,
    #[serde(default)]
    pub agents: Vec<String>,
    #[serde(default)]
    pub entity_types: Vec<EntityTypeDecl>,
    #[serde(default)]
    pub extractors: Vec<ExtractorDecl>,
    #[serde(default)]
    pub not_expressible: Vec<NotExpressible>,
    /// ONT-4d (R-19): the subsumption hierarchy, `sub ⊑ sup` between declared concepts. Acyclic (a cycle is
    /// exit 3); shapes declared on `sup` apply to every instance of `sub`, through the type closure
    /// `extract::all` materializes.
    #[serde(default)]
    pub subsumes: Vec<Subsumes>,
    /// v4.16 D-T1 (qd4c4): `entity.type` → the class a shape with no `targetClass` targets
    /// (`shapes.rs::default_target`). An `entity.type` absent here gives such a shape no target: malformed, exit 3.
    /// A `~` value is an EXPLICIT no-default: the type is covered, and every shape on it names its own class.
    #[serde(default)]
    pub entity_type_target_class: BTreeMap<String, Option<String>>,
    /// v4.16 D5b (qd4c3): the `##` headings of an `llm-context` file that satisfy each role
    /// (`Purpose`, `Rules`, `Commands`, `Layout`) — `extract:llm-context` emits `llm:<role>Section` per match.
    #[serde(default)]
    pub llm_context_role_synonyms: BTreeMap<String, Vec<String>>,
    /// Which reader claims each Σ key. The anti-decoration rule: a key nobody reads is refused (exit 3).
    #[serde(default)]
    pub readers: BTreeMap<String, String>,
    /// The CONTRACT schema's own block, carried here because Σ is a contract too.
    ///
    /// `pv validate` REQUIRES `metadata.{version, description}` on a contract, and this file is a contract —
    /// so a corpus that keeps ONE `contracts/ontology.yaml` for both readers had `pv validate` at rc 0 and
    /// `pv lint --gate sigma` at exit 3 over the same bytes (measured on apex 2026-09-19, `pv 0.68.1`:
    /// ``unknown field `metadata` … at line 26``). One binary contradicting itself about one key is not a
    /// corpus defect, so the schema admits the block.
    ///
    /// Σ does not INTERPRET it: the value is opaque YAML, no Σ rule reads a field of it, and `readers` must
    /// still claim the key like every other — the anti-decoration rule is not weakened, it is answered
    /// ("the contract schema reads it, not Σ").
    #[serde(default)]
    pub metadata: Option<serde_yaml::Value>,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Concept {
    pub doc: String,
}

/// A binary relation the corpus may use in `relations:`. `domain`/`range` name concepts.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Role {
    pub domain: String,
    pub range: String,
    #[serde(default)]
    pub symmetric: bool,
    #[serde(default)]
    pub acyclic: bool,
    #[serde(default)]
    pub doc: String,
}

/// One token a `formal:` expression may carry.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Symbol {
    pub name: String,
    pub kind: SymbolKind,
    #[serde(default)]
    pub doc: String,
}

#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SymbolKind {
    Operator,
    Function,
    Predicate,
    Constant,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct World {
    pub doc: String,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct EntityTypeDecl {
    pub name: String,
    /// The extractor that reads this entity type. Must name an `extractors[]` entry.
    #[serde(default)]
    pub extractor: String,
    pub implemented: bool,
    /// ONT-4f: the vocabulary `extract:json` reads a SNAPSHOT entity type with — the GitHub entities under
    /// `evidence/github/<name>/`. Absent for every other type. `root_class` must be `ont:<a declared concept>`,
    /// because the type closure (R-19) reaches only Σ concepts; `version` names the snapshot's own field that
    /// the ref's `@<version>` slot must equal.
    #[serde(default)]
    pub vocabulary: Option<EntityVocabulary>,
}

/// ONT-4f: a snapshot entity type's vocabulary (`prefix:key` predicates, one root class, one version field).
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct EntityVocabulary {
    pub prefix: String,
    pub root_class: String,
    pub version: String,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct ExtractorDecl {
    pub name: String,
    /// A declared name, with `implemented` saying whether it exists yet (plan v2 ruling 3).
    #[serde(default)]
    pub reader: String,
    pub implemented: bool,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct NotExpressible {
    pub key: String,
    #[serde(default)]
    pub reader: String,
}

/// One subsumption edge: every instance of `sub` is an instance of `sup` (ONT-4d, R-19).
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Subsumes {
    pub sub: String,
    pub sup: String,
}

/// Σ is malformed. Every variant is exit 3 (`error:`): the corpus is not at fault, the declaration is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SigmaError {
    /// `contracts/ontology.yaml` did not parse.
    Parse(String),
    /// An `entity_types` entry names no extractor, or names one `extractors[]` does not declare.
    EntityTypeWithoutExtractor {
        entity_type: String,
        extractor: String,
    },
    /// A Σ key that no `readers` entry claims.
    KeyWithoutReader { key: String },
    /// A `not_expressible` entry without a `reader`.
    NotExpressibleWithoutReader { key: String },
    /// An `extractors[]` entry without a `reader`.
    ExtractorWithoutReader { extractor: String },
    /// ONT-4d: a `subsumes` edge names a concept `concepts` does not declare.
    SubsumesUndeclared { concept: String },
    /// ONT-4d (R-19): `subsumes` is cyclic. `path` walks the cycle and repeats its first concept at the end.
    SubsumesCycle { path: Vec<String> },
    /// ONT-4f: an entity type's `vocabulary` is incomplete, or its `root_class` is not a declared `ont:` concept.
    VocabularyMalformed { entity_type: String, why: String },
    /// An `entity_types` entry named [`RESERVED_ENTITY_TYPE`].
    ReservedEntityType { entity_type: String },
    /// An `entity_type_target_class` key that no `entity_types` entry declares.
    TargetClassForUndeclaredType { entity_type: String },
    /// An `implemented: true` entity type with neither a class nor an explicit `~` in `entity_type_target_class`.
    ImplementedTypeWithoutTargetClass { entity_type: String },
}

/// The one entity-type name Σ refuses. A contract of type `t` is an instance of `<ONT_BASE>entity/<t>` and carries
/// its properties as `<ONT_BASE><t>/<key>` (`extract::pv_contract::{entity_class, entity_predicate}`); for
/// `t = entity` the predicate `entity/study` IS the class of every `study` contract (quorum PMAT-4160, agy lane 1).
pub const RESERVED_ENTITY_TYPE: &str = "entity";

impl fmt::Display for SigmaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parse(e) => write!(f, "ontology.yaml: {e}"),
            Self::EntityTypeWithoutExtractor {
                entity_type,
                extractor,
            } => {
                if extractor.is_empty() {
                    write!(f, "entity_type `{entity_type}` names no extractor")
                } else {
                    write!(
                        f,
                        "entity_type `{entity_type}` names extractor `{extractor}`, which extractors[] does not declare"
                    )
                }
            }
            Self::KeyWithoutReader { key } => {
                write!(
                    f,
                    "Σ key `{key}` has no reader — a key nothing reads is decoration"
                )
            }
            Self::ReservedEntityType { entity_type } => write!(
                f,
                "entity_type `{entity_type}` is reserved — `<ONT_BASE>entity/` holds the entity classes, so its properties would collide with them"
            ),
            Self::NotExpressibleWithoutReader { key } => {
                write!(f, "not_expressible `{key}` has no reader")
            }
            Self::ExtractorWithoutReader { extractor } => {
                write!(f, "extractor `{extractor}` has no reader")
            }
            Self::SubsumesUndeclared { concept } => {
                write!(
                    f,
                    "subsumes names concept `{concept}`, which concepts does not declare"
                )
            }
            Self::SubsumesCycle { path } => write!(f, "subsumes cycle {}", path.join(" -> ")),
            Self::VocabularyMalformed { entity_type, why } => {
                write!(
                    f,
                    "entity_type `{entity_type}` vocabulary is malformed: {why}"
                )
            }
            Self::TargetClassForUndeclaredType { entity_type } => write!(
                f,
                "entity_type_target_class key `{entity_type}` names no declared entity_type"
            ),
            Self::ImplementedTypeWithoutTargetClass { entity_type } => write!(
                f,
                "implemented entity_type `{entity_type}` has neither a class nor an explicit `~` in entity_type_target_class"
            ),
        }
    }
}

impl std::error::Error for SigmaError {}

/// ONT-4d: depth-first search from `n` for a cycle through `path`, the concepts currently on the stack. A cycle
/// is returned as the path that closes it, its first concept repeated at the end. `done` holds concepts
/// fully explored, which cannot be on a cycle not yet found, so each concept is searched once. Recursion
/// depth is bounded by the number of concepts.
fn find_cycle<'a>(
    n: &'a str,
    edges: &BTreeMap<&'a str, BTreeSet<&'a str>>,
    path: &mut Vec<&'a str>,
    done: &mut BTreeSet<&'a str>,
) -> Option<Vec<String>> {
    if let Some(at) = path.iter().position(|p| *p == n) {
        let mut cycle: Vec<String> = path[at..].iter().map(|s| (*s).to_string()).collect();
        cycle.push(n.to_string());
        return Some(cycle);
    }
    if done.contains(n) {
        return None;
    }
    path.push(n);
    for &m in edges.get(n).into_iter().flatten() {
        if let Some(c) = find_cycle(m, edges, path, done) {
            return Some(c);
        }
    }
    path.pop();
    done.insert(n);
    None
}

/// The Σ keys that must be claimed by a reader when they are present and non-empty.
pub const READABLE_KEYS: [&str; 12] = [
    "concepts",
    "roles",
    "symbols",
    "worlds",
    "agents",
    "entity_types",
    "extractors",
    "not_expressible",
    "subsumes",
    "entity_type_target_class",
    "llm_context_role_synonyms",
    // The contract schema owns this one; Σ only carries it (see `Sigma::metadata`).
    "metadata",
];

impl Sigma {
    /// Parse Σ. Does NOT check integrity — [`Sigma::check_integrity`] does that, so a caller can report a parse
    /// failure and a malformed declaration differently.
    pub fn from_yaml(yaml: &str) -> Result<Self, SigmaError> {
        serde_yaml::from_str(yaml).map_err(|e| SigmaError::Parse(e.to_string()))
    }

    /// The malformed-Σ classes: ONT-2b's four in the order the row lists them, then the target-class map (v4.16 D-T1).
    ///
    /// # Errors
    /// [`SigmaError`] — every variant is exit 3, because a malformed declaration is not the corpus's fault.
    pub fn check_integrity(&self) -> Result<(), SigmaError> {
        self.check_entity_types()?;
        self.check_vocabularies()?;
        self.check_readers()?;
        self.check_not_expressible()?;
        self.check_extractors()?;
        self.check_subsumes()?;
        self.check_target_classes()
    }

    /// ONT-4d: every `subsumes` edge names declared concepts, and the hierarchy is acyclic (R-19). A cycle is
    /// reported as the path that closes it, first concept repeated at the end.
    fn check_subsumes(&self) -> Result<(), SigmaError> {
        if let Some(c) = self
            .subsumes
            .iter()
            .flat_map(|e| [&e.sub, &e.sup])
            .find(|c| !self.concepts.contains_key(c.as_str()))
        {
            return Err(SigmaError::SubsumesUndeclared { concept: c.clone() });
        }
        let edges = self.subsumption_edges();
        let mut done: BTreeSet<&str> = BTreeSet::new();
        for &root in edges.keys() {
            if let Some(path) = find_cycle(root, &edges, &mut Vec::new(), &mut done) {
                return Err(SigmaError::SubsumesCycle { path });
            }
        }
        Ok(())
    }

    /// `sub → {sup}` as declared.
    fn subsumption_edges(&self) -> BTreeMap<&str, BTreeSet<&str>> {
        let mut edges: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
        for e in &self.subsumes {
            edges
                .entry(e.sub.as_str())
                .or_default()
                .insert(e.sup.as_str());
        }
        edges
    }

    /// ONT-4d: every STRICT super-concept of `concept` (the transitive closure of `subsumes`, R-19). Terminates on
    /// a cyclic Σ too, though [`Sigma::check_integrity`] refuses one first.
    #[must_use]
    pub fn supers(&self, concept: &str) -> BTreeSet<String> {
        let edges = self.subsumption_edges();
        let mut out = BTreeSet::new();
        let mut stack: Vec<&str> = edges
            .get(concept)
            .map(|s| s.iter().copied().collect())
            .unwrap_or_default();
        while let Some(c) = stack.pop() {
            if c != concept && out.insert(c.to_string()) {
                stack.extend(edges.get(c).into_iter().flatten().copied());
            }
        }
        out
    }

    /// ONT-4d: every STRICT sub-concept of `concept`.
    #[must_use]
    pub fn subs(&self, concept: &str) -> BTreeSet<String> {
        self.concepts
            .keys()
            .filter(|c| c.as_str() != concept && self.supers(c).contains(concept))
            .cloned()
            .collect()
    }

    /// ONT-4f: a vocabulary names a non-empty prefix and version, and a root class `ont:<concept>` for a concept
    /// Σ declares — a root class the closure cannot reach types nodes no Σ shape can inherit onto.
    fn check_vocabularies(&self) -> Result<(), SigmaError> {
        for et in &self.entity_types {
            let Some(v) = &et.vocabulary else { continue };
            let bad = |why: String| SigmaError::VocabularyMalformed {
                entity_type: et.name.clone(),
                why,
            };
            if v.prefix.trim().is_empty() {
                return Err(bad("empty `prefix`".into()));
            }
            if v.version.trim().is_empty() {
                return Err(bad("empty `version`".into()));
            }
            if !v
                .root_class
                .strip_prefix("ont:")
                .is_some_and(|c| self.concepts.contains_key(c))
            {
                return Err(bad(format!(
                    "root_class `{}` is not `ont:<a concept Σ declares>`",
                    v.root_class
                )));
            }
        }
        Ok(())
    }

    /// Class 1: every `entity_types` entry names an extractor `extractors[]` declares.
    fn check_entity_types(&self) -> Result<(), SigmaError> {
        if let Some(et) = self
            .entity_types
            .iter()
            .find(|et| et.name == RESERVED_ENTITY_TYPE)
        {
            return Err(SigmaError::ReservedEntityType {
                entity_type: et.name.clone(),
            });
        }
        let declared: BTreeSet<&str> = self.extractors.iter().map(|e| e.name.as_str()).collect();
        match self
            .entity_types
            .iter()
            .find(|et| et.extractor.is_empty() || !declared.contains(et.extractor.as_str()))
        {
            None => Ok(()),
            Some(et) => Err(SigmaError::EntityTypeWithoutExtractor {
                entity_type: et.name.clone(),
                extractor: et.extractor.clone(),
            }),
        }
    }

    /// Class 2: every POPULATED Σ key is claimed by a non-empty `readers` entry.
    fn check_readers(&self) -> Result<(), SigmaError> {
        match self
            .populated_keys()
            .into_iter()
            .find(|key| self.readers.get(*key).is_none_or(|r| r.trim().is_empty()))
        {
            None => Ok(()),
            Some(key) => Err(SigmaError::KeyWithoutReader {
                key: key.to_string(),
            }),
        }
    }

    /// Class 3: every `not_expressible` entry names the reader that would have to change first.
    fn check_not_expressible(&self) -> Result<(), SigmaError> {
        match self
            .not_expressible
            .iter()
            .find(|ne| ne.reader.trim().is_empty())
        {
            None => Ok(()),
            Some(ne) => Err(SigmaError::NotExpressibleWithoutReader {
                key: ne.key.clone(),
            }),
        }
    }

    /// Class 4: every `extractors[]` entry names a reader.
    fn check_extractors(&self) -> Result<(), SigmaError> {
        match self
            .extractors
            .iter()
            .find(|ex| ex.reader.trim().is_empty())
        {
            None => Ok(()),
            Some(ex) => Err(SigmaError::ExtractorWithoutReader {
                extractor: ex.name.clone(),
            }),
        }
    }

    /// Classes 6 and 7: `entity_type_target_class` against `entity_types`, both ways. A key no type declares is a
    /// target nothing can reach; an implemented type the map does not mention is a shape default nobody decided.
    fn check_target_classes(&self) -> Result<(), SigmaError> {
        if let Some(key) = self
            .entity_type_target_class
            .keys()
            .find(|k| !self.declares_entity_type(k))
        {
            return Err(SigmaError::TargetClassForUndeclaredType {
                entity_type: key.clone(),
            });
        }
        match self
            .entity_types
            .iter()
            .find(|et| et.implemented && !self.entity_type_target_class.contains_key(&et.name))
        {
            None => Ok(()),
            Some(et) => Err(SigmaError::ImplementedTypeWithoutTargetClass {
                entity_type: et.name.clone(),
            }),
        }
    }

    /// Which Σ keys are present and non-empty — the set `readers` must cover.
    #[must_use]
    pub fn populated_keys(&self) -> BTreeSet<&'static str> {
        let mut keys = BTreeSet::new();
        if !self.concepts.is_empty() {
            keys.insert("concepts");
        }
        if !self.roles.is_empty() {
            keys.insert("roles");
        }
        if !self.symbols.is_empty() {
            keys.insert("symbols");
        }
        if !self.worlds.is_empty() {
            keys.insert("worlds");
        }
        if !self.agents.is_empty() {
            keys.insert("agents");
        }
        if !self.entity_types.is_empty() {
            keys.insert("entity_types");
        }
        if !self.extractors.is_empty() {
            keys.insert("extractors");
        }
        if !self.not_expressible.is_empty() {
            keys.insert("not_expressible");
        }
        if !self.subsumes.is_empty() {
            keys.insert("subsumes");
        }
        if !self.entity_type_target_class.is_empty() {
            keys.insert("entity_type_target_class");
        }
        if !self.llm_context_role_synonyms.is_empty() {
            keys.insert("llm_context_role_synonyms");
        }
        if self.metadata.is_some() {
            keys.insert("metadata");
        }
        keys
    }

    #[must_use]
    pub fn declares_role(&self, name: &str) -> bool {
        self.roles.contains_key(name)
    }

    #[must_use]
    pub fn declares_entity_type(&self, name: &str) -> bool {
        self.entity_types.iter().any(|e| e.name == name)
    }

    #[must_use]
    pub fn declares_symbol(&self, token: &str) -> bool {
        self.symbols.iter().any(|s| s.name == token)
    }
}

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

    /// A Σ small enough to read, with every key populated and claimed.
    fn good() -> &'static str {
        r#"
schema: ont-sigma-v1
concepts:
  Contract: {doc: "a pv contract file"}
  Code: {doc: "a Rust item"}
roles:
  binds: {domain: Contract, range: Code, acyclic: false, doc: "a contract binds a symbol"}
symbols:
  - {name: "∀", kind: operator}
  - {name: isFinite, kind: predicate}
worlds:
  default: {doc: "the tree as committed"}
agents: [pv]
entity_types:
  - {name: pv-contract, extractor: pv_contract, implemented: false}
extractors:
  - {name: pv_contract, reader: ontology/extract/pv_contract.rs, implemented: false}
not_expressible:
  - {key: taste, reader: ontology/sigma.rs}
readers:
  concepts: ontology/sigma.rs
  roles: lint/sigma_gate.rs
  symbols: lint/sigma_symbols.rs
  worlds: ontology/sigma.rs
  agents: ontology/sigma.rs
  entity_types: lint/sigma_gate.rs
  extractors: ontology/sigma.rs
  not_expressible: ontology/sigma.rs
"#
    }

    /// `good()` with `pv-contract` implemented and the map claimed, so each test is one edit to the map.
    fn with_map(map: &str) -> Result<(), SigmaError> {
        let y = good()
            .replace(
                "  - {name: pv-contract, extractor: pv_contract, implemented: false}",
                "  - {name: pv-contract, extractor: pv_contract, implemented: true}",
            )
            .replace(
                "readers:\n",
                &format!("{map}readers:\n  entity_type_target_class: ontology/shapes.rs\n"),
            );
        Sigma::from_yaml(&y).expect("parses").check_integrity()
    }

    #[test]
    fn an_implemented_type_is_covered_by_a_class_or_an_explicit_tilde() {
        assert_eq!(
            with_map("entity_type_target_class:\n  pv-contract: ont:Contract\n"),
            Ok(())
        );
        assert_eq!(
            with_map("entity_type_target_class:\n  pv-contract: ~\n"),
            Ok(())
        );
    }

    #[test]
    fn an_implemented_type_the_map_does_not_mention_is_malformed_named() {
        let e = with_map("").unwrap_err();
        assert_eq!(
            e,
            SigmaError::ImplementedTypeWithoutTargetClass {
                entity_type: "pv-contract".into()
            }
        );
        assert!(e.to_string().contains("`pv-contract`"), "{e}");
    }

    #[test]
    fn a_map_key_no_entity_type_declares_is_malformed_named() {
        let e = with_map("entity_type_target_class:\n  pv-contract: ont:Contract\n  ghost: g:G\n")
            .unwrap_err();
        assert_eq!(
            e,
            SigmaError::TargetClassForUndeclaredType {
                entity_type: "ghost".into()
            }
        );
    }

    /// The repo's own Σ is held to it: every implemented type is covered, and every key is a declared type.
    #[test]
    fn the_repo_sigma_map_covers_every_implemented_type_and_names_no_ghost() {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../contracts/ontology.yaml");
        let s =
            Sigma::from_yaml(&std::fs::read_to_string(path).expect("read Σ")).expect("Σ parses");
        assert_eq!(s.check_integrity(), Ok(()));
    }

    #[test]
    fn a_well_formed_sigma_parses_and_passes_integrity() {
        let s = Sigma::from_yaml(good()).expect("Σ parses");
        assert_eq!(s.schema, "ont-sigma-v1");
        assert_eq!(s.roles["binds"].domain, "Contract");
        assert!(s.check_integrity().is_ok(), "{:?}", s.check_integrity());
    }

    /// Σ is a CONTRACT, and `pv validate` requires `metadata.{version, description}` on a contract. Before this
    /// the Σ schema refused the block outright, so one file could not satisfy both readers: apex measured
    /// `pv validate` rc 0 and `pv lint --gate sigma` exit 3 over the same `contracts/ontology.yaml`
    /// (2026-09-19, pv 0.68.1). The block parses, is opaque to every Σ rule, and still has to be claimed.
    #[test]
    fn sigma_carries_the_contract_schemas_own_metadata_block_and_reads_nothing_of_it() {
        let y = good().replace(
            "readers:\n",
            "metadata:\n  version: 1.0.0\n  description: \"apex's entity-type registry\"\n  references:\n    - 'APEX-001 §5 row EV-19'\nreaders:\n  metadata: schema/types.rs (the contract schema, not Σ)\n",
        );
        let s = Sigma::from_yaml(&y).expect("Σ with metadata parses");
        assert!(s.metadata.is_some());
        assert!(s.check_integrity().is_ok(), "{:?}", s.check_integrity());
        // Opaque: no Σ rule reads a field of it, and the rest of Σ is unchanged by its presence.
        let without = Sigma::from_yaml(good()).expect("Σ parses");
        assert_eq!(s.concepts, without.concepts);
        assert_eq!(s.entity_types, without.entity_types);
    }

    /// …and the anti-decoration rule is answered, not weakened: an unclaimed `metadata:` is still refused.
    #[test]
    fn an_unclaimed_metadata_block_is_refused_like_every_other_key() {
        let y = good().replace(
            "readers:\n",
            "metadata:\n  version: 1.0.0\n  description: d\nreaders:\n",
        );
        let s = Sigma::from_yaml(&y).expect("Σ parses");
        match s.check_integrity() {
            Err(SigmaError::KeyWithoutReader { key }) => assert_eq!(key, "metadata"),
            other => panic!("an unclaimed metadata: must be refused, got {other:?}"),
        }
    }

    #[test]
    fn an_entity_type_naming_no_extractor_is_malformed() {
        let y = good().replace(
            "  - {name: pv-contract, extractor: pv_contract, implemented: false}",
            "  - {name: pv-contract, extractor: \"\", implemented: false}",
        );
        let s = Sigma::from_yaml(&y).expect("parses");
        assert_eq!(
            s.check_integrity(),
            Err(SigmaError::EntityTypeWithoutExtractor {
                entity_type: "pv-contract".into(),
                extractor: String::new()
            })
        );
    }

    #[test]
    fn an_entity_type_named_entity_is_reserved() {
        let y = good().replace(
            "  - {name: pv-contract, extractor: pv_contract, implemented: false}",
            "  - {name: pv-contract, extractor: pv_contract, implemented: false}\n  - {name: entity, extractor: pv_contract, implemented: false}",
        );
        let s = Sigma::from_yaml(&y).expect("parses");
        let err = s.check_integrity().expect_err("`entity` is reserved");
        assert_eq!(
            err,
            SigmaError::ReservedEntityType {
                entity_type: "entity".into()
            }
        );
        assert!(err.to_string().contains("reserved"), "{err}");
        // The collision the rule exists for, so the rule and its reason cannot drift apart.
        use crate::ontology::extract::pv_contract::{entity_class, entity_predicate};
        assert_eq!(
            entity_predicate(RESERVED_ENTITY_TYPE, "study"),
            entity_class("study")
        );
        // A name merely containing it is not the reserved name.
        let ok = good().replace("{name: pv-contract,", "{name: entity-ish,");
        assert_eq!(
            Sigma::from_yaml(&ok).expect("parses").check_integrity(),
            Ok(())
        );
    }

    #[test]
    fn an_entity_type_naming_an_undeclared_extractor_is_malformed() {
        let y = good().replace("extractor: pv_contract,", "extractor: ghost,");
        let s = Sigma::from_yaml(&y).expect("parses");
        assert_eq!(
            s.check_integrity(),
            Err(SigmaError::EntityTypeWithoutExtractor {
                entity_type: "pv-contract".into(),
                extractor: "ghost".into()
            })
        );
    }

    #[test]
    fn a_sigma_key_with_no_reader_is_malformed() {
        let y = good().replace("  symbols: lint/sigma_symbols.rs\n", "");
        let s = Sigma::from_yaml(&y).expect("parses");
        assert_eq!(
            s.check_integrity(),
            Err(SigmaError::KeyWithoutReader {
                key: "symbols".into()
            })
        );
    }

    #[test]
    fn an_extractor_without_a_reader_is_malformed() {
        let y = good().replace(
            "  - {name: pv_contract, reader: ontology/extract/pv_contract.rs, implemented: false}",
            "  - {name: pv_contract, reader: \"\", implemented: false}",
        );
        let s = Sigma::from_yaml(&y).expect("parses");
        assert_eq!(
            s.check_integrity(),
            Err(SigmaError::ExtractorWithoutReader {
                extractor: "pv_contract".into()
            })
        );
    }

    #[test]
    fn a_not_expressible_without_a_reader_is_malformed() {
        let y = good().replace(
            "  - {key: taste, reader: ontology/sigma.rs}",
            "  - {key: taste, reader: \"\"}",
        );
        let s = Sigma::from_yaml(&y).expect("parses");
        assert_eq!(
            s.check_integrity(),
            Err(SigmaError::NotExpressibleWithoutReader {
                key: "taste".into()
            })
        );
    }

    #[test]
    fn an_empty_key_needs_no_reader() {
        // `populated_keys` is what `readers` must cover: a key Σ does not use is not decoration.
        let y = good()
            .replace("agents: [pv]", "agents: []")
            .replace("  agents: ontology/sigma.rs\n", "");
        let s = Sigma::from_yaml(&y).expect("parses");
        assert!(!s.populated_keys().contains("agents"));
        assert!(s.check_integrity().is_ok(), "{:?}", s.check_integrity());
    }

    #[test]
    fn lookups_answer_only_for_what_sigma_declares() {
        let s = Sigma::from_yaml(good()).expect("parses");
        assert!(s.declares_role("binds"));
        assert!(!s.declares_role("refines"), "undeclared role");
        assert!(s.declares_entity_type("pv-contract"));
        assert!(!s.declares_entity_type("csv"), "undeclared entity type");
        assert!(s.declares_symbol("∀"));
        assert!(s.declares_symbol("isFinite"));
        assert!(!s.declares_symbol("⊗"), "undeclared symbol");
    }

    #[test]
    fn an_unknown_key_is_refused_by_the_parser() {
        let y = format!("{}\nsurprise: 1\n", good());
        assert!(matches!(Sigma::from_yaml(&y), Err(SigmaError::Parse(_))));
    }

    #[test]
    fn the_repo_sigma_parses_and_is_well_formed() {
        let path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contracts/ontology.yaml");
        let text = std::fs::read_to_string(&path).expect("contracts/ontology.yaml is readable");
        let s = Sigma::from_yaml(&text).expect("the repo's Σ parses");
        assert!(s.check_integrity().is_ok(), "{:?}", s.check_integrity());
        assert!(!s.entity_types.is_empty(), "Σ declares entity types");
        assert!(!s.extractors.is_empty(), "Σ declares extractors");
        assert!(
            s.symbols.len() >= 20,
            "Σ declares the corpus's operator vocabulary, got {}",
            s.symbols.len()
        );
    }

    // ---- ONT-4d (R-19): subsumes ------------------------------------------------------------------------

    fn with_subsumes(edges: &[(&str, &str)]) -> Sigma {
        let mut s = Sigma::from_yaml(good()).expect("Σ parses");
        s.concepts.insert(
            "Kernel".into(),
            Concept {
                doc: "a kernel contract".into(),
            },
        );
        s.subsumes = edges
            .iter()
            .map(|(a, b)| Subsumes {
                sub: (*a).into(),
                sup: (*b).into(),
            })
            .collect();
        s.readers
            .insert("subsumes".into(), "ontology/sigma.rs".into());
        s
    }

    #[test]
    fn ont4d_supers_and_subs_are_the_strict_transitive_closure() {
        let s = with_subsumes(&[("Kernel", "Code"), ("Code", "Contract")]);
        assert!(s.check_integrity().is_ok(), "{:?}", s.check_integrity());
        assert_eq!(
            s.supers("Kernel").into_iter().collect::<Vec<_>>(),
            vec!["Code", "Contract"]
        );
        assert!(
            s.supers("Contract").is_empty(),
            "the top has no strict super"
        );
        assert_eq!(
            s.subs("Contract").into_iter().collect::<Vec<_>>(),
            vec!["Code", "Kernel"]
        );
        assert!(
            !s.supers("Code").contains("Code"),
            "strict: a concept is never its own super"
        );
    }

    #[test]
    fn ont4d_a_cycle_is_refused_naming_the_closing_path() {
        let s = with_subsumes(&[
            ("Kernel", "Code"),
            ("Code", "Contract"),
            ("Contract", "Kernel"),
        ]);
        match s.check_integrity() {
            Err(SigmaError::SubsumesCycle { path }) => {
                assert_eq!(path.first(), path.last(), "the path closes: {path:?}");
                assert_eq!(
                    path.len(),
                    4,
                    "three edges, first concept repeated: {path:?}"
                );
                assert!(SigmaError::SubsumesCycle { path: path.clone() }
                    .to_string()
                    .starts_with("subsumes cycle "));
            }
            other => panic!("a cycle is exit 3: {other:?}"),
        }
        // A self-edge is the shortest cycle.
        assert!(matches!(
            with_subsumes(&[("Code", "Code")]).check_integrity(),
            Err(SigmaError::SubsumesCycle { .. })
        ));
        // supers() terminates on a cyclic Σ (check_integrity refuses it first, but a caller must not hang).
        let cyc = with_subsumes(&[("Kernel", "Code"), ("Code", "Kernel")]);
        assert_eq!(
            cyc.supers("Kernel").into_iter().collect::<Vec<_>>(),
            vec!["Code"]
        );
    }

    #[test]
    fn ont4d_a_diamond_is_not_a_cycle() {
        let mut s = with_subsumes(&[
            ("Kernel", "Code"),
            ("Kernel", "Contract"),
            ("Code", "Contract"),
        ]);
        s.concepts
            .insert("Other".into(), Concept { doc: "x".into() });
        assert!(
            s.check_integrity().is_ok(),
            "two paths to one super is a DAG: {:?}",
            s.check_integrity()
        );
    }

    #[test]
    fn ont4d_an_edge_over_an_undeclared_concept_is_refused() {
        let s = with_subsumes(&[("Kernel", "Ghost")]);
        assert!(matches!(
            s.check_integrity(),
            Err(SigmaError::SubsumesUndeclared { concept }) if concept == "Ghost"
        ));
    }

    #[test]
    fn ont4d_subsumes_needs_a_reader_like_every_key() {
        let mut s = with_subsumes(&[("Kernel", "Code")]);
        s.readers.remove("subsumes");
        assert!(
            matches!(s.check_integrity(), Err(SigmaError::KeyWithoutReader { key }) if key == "subsumes")
        );
    }

    fn with_vocabulary(root_class: &str, version: &str) -> Sigma {
        let yaml = good().replace(
            "  - {name: pv-contract, extractor: pv_contract, implemented: false}\n",
            &format!(
                "  - {{name: pv-contract, extractor: pv_contract, implemented: false}}\n  - {{name: repo, extractor: pv_contract, implemented: false, vocabulary: {{prefix: repo, root_class: \"{root_class}\", version: \"{version}\"}}}}\n"
            ),
        );
        Sigma::from_yaml(&yaml).expect("Σ with a vocabulary parses")
    }

    #[test]
    fn ont4f_a_vocabulary_over_a_declared_concept_is_well_formed() {
        let s = with_vocabulary("ont:Code", "sha");
        let v = s.entity_types[1].vocabulary.as_ref().expect("vocabulary");
        assert_eq!((v.prefix.as_str(), v.version.as_str()), ("repo", "sha"));
        assert!(s.check_integrity().is_ok(), "{:?}", s.check_integrity());
    }

    #[test]
    fn ont4f_a_vocabulary_whose_root_class_the_closure_cannot_reach_is_refused() {
        for bad in ["ont:Ghost", "repo:Repo", ""] {
            let s = with_vocabulary(bad, "sha");
            let err = s.check_integrity().expect_err(bad);
            assert!(
                matches!(&err, SigmaError::VocabularyMalformed { entity_type, .. } if entity_type == "repo"),
                "{err}"
            );
        }
        let err = with_vocabulary("ont:Code", " ")
            .check_integrity()
            .unwrap_err();
        assert!(err.to_string().contains("empty `version`"), "{err}");
    }
}