pr4xis 0.23.1

Prove your domain is correct — ontology-driven rule enforcement with category theory, logical composition, and runtime state machines
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
//! Kind-parameterised structural axioms — replaces the per-primitive-trait
//! families (`NoCycles<TaxonomyDef>`, `NoCycles<MereologyDef>`, …) with a
//! single family per structural property that filters a `Category`'s
//! morphisms by its typed relation kind.
//!
//! # Why typed, not stringly typed (#163)
//!
//! Each OnKind axiom is parameterised over a `Category` `C` and compares
//! against a typed instance of `<C::Morphism as Arrow>::Kind`. No
//! `kind_name: &'static str`, no separate filter predicate — the kind
//! value itself is the filter. Framework-neutral: each ontology
//! instantiates with its own local kind enum (e.g. `FooRelationKind`),
//! or with an imported shared kind type (e.g. a Relations-ontology
//! concept), without core committing to any specific relations ontology.
//!
//! Per Gruber (1993) *KAS* 5: "ontology = formally-named relations" —
//! typed entities, not string conventions.
//! Per Smith et al. (2005) OBO-RO: every relation is a canonical named
//! type. Encoding that as a compile-time-checked `Kind` value matches
//! the literature.
//!
//! # Rationale (issue #152, #163)
//!
//! The axioms *are properties of relations*, not type-level distinctions.
//! Forcing each axiom into a separate trait family (`TaxonomyDef` vs
//! `MereologyDef`) is a category error — that's #152. Forcing the
//! relation-identity through a `&'static str` parameter is a separate
//! category error — that's #163. Both resolve in this module: one axiom
//! type per structural property, filtered by typed kind value.
//!
//! Sources for the structural properties themselves:
//! - Tarski (1941) *Calculus of Relations* — the axiom names and their
//!   algebraic definitions
//! - Russell & Whitehead *Principia Mathematica* (1910–13) §§30–35 — binary
//!   relations and their structural properties
//! - Smith et al. (2005) OBO Relation Ontology — which properties attach
//!   to which relation types canonically

use std::collections::HashSet;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;

use crate::category::{Arrow, Category};
use crate::logic::axiom::Axiom;
use crate::logic::proof::{SimpleCounterexample, SimpleProof, Verdict};
use crate::ontology::meta::{Citation, Label, OntologyName};

type KindOf<C> = <<C as Category>::Morphism as Arrow>::Kind;

/// Collect (from, to) pairs from the category's morphisms whose kind
/// equals `kind`.
fn kinded_pairs<C>(kind: KindOf<C>) -> Vec<(C::Object, C::Object)>
where
    C: Category,
    C::Object: Clone,
    C::Morphism: Arrow<Object = C::Object>,
    KindOf<C>: PartialEq,
{
    C::morphisms()
        .into_iter()
        .filter(|m| m.kind() == kind)
        .map(|m| (m.source(), m.target()))
        .collect()
}

/// A cycle on `kind` exists iff the category's **materialized closed**
/// morphism set carries a self-edge `e --kind--> e` for some object `e`.
///
/// This is a closure-membership query, not a re-derived reachability walk:
/// `ontology!` already materialises the per-kind transitive closure into
/// `morphisms()` (Floyd–Warshall at macro expansion), so a cyclic kind path
/// `e ⇒ … ⇒ e` has already been composed down to the self-edge `(e, e, kind)`.
/// We read it off the same closed set via [`Category::morphisms_from`] and
/// test for a self-target — never an adjacency map + BFS standing in for the
/// closure the macro emits.
fn has_kinded_self_edge<C>(kind: KindOf<C>) -> bool
where
    C: Category,
    C::Object: Clone + Eq + Hash,
    C::Morphism: Arrow<Object = C::Object>,
    KindOf<C>: PartialEq + Copy,
{
    // The objects to probe are exactly the endpoints of `kind`-edges in the
    // closed set; nothing else can host a `kind`-self-edge.
    let mut objects: HashSet<C::Object> = HashSet::new();
    for (from, to) in kinded_pairs::<C>(kind) {
        objects.insert(from);
        objects.insert(to);
    }
    objects.into_iter().any(|e| {
        // The relational image of `e` under `kind` in the closed set —
        // a closure query, read off `morphisms_from`, not re-walked.
        C::morphisms_from(&e)
            .into_iter()
            .any(|m| m.kind() == kind && m.target() == e)
    })
}

/// Build the `name()` override for an OnKind axiom, projecting the typed
/// kind via `Debug` into an identifier like `"NoCyclesOnKind[Subsumption]"`.
/// Kinds are enum-like, so their Debug output is their variant name —
/// exactly the identifier the Lemon registry wants.
fn name_with_kind<K: Debug>(axiom_name: &'static str, kind: &K) -> OntologyName {
    OntologyName::new(format!("{axiom_name}[{kind:?}]"))
}

/// Build the `description()` override for an OnKind axiom.
fn description_with_kind<K: Debug>(axiom_name: &'static str, kind: &K) -> Label {
    Label::new(format!("{axiom_name} applied to edges of kind {kind:?}"))
}

// ---------------------------------------------------------------------------
// NoCyclesOnKind — filter a category's edges by kind; verify the resulting
// graph has no cycles (DAG). Applies canonically to Subsumption and Parthood.
// Source: Guarino (2009); Casati & Varzi (1999); Tarski (1941).
// ---------------------------------------------------------------------------

pub struct NoCyclesOnKind<C: Category>
where
    C::Morphism: Arrow,
{
    kind: KindOf<C>,
    _marker: PhantomData<C>,
}

impl<C: Category> NoCyclesOnKind<C>
where
    C::Morphism: Arrow,
{
    pub fn new(kind: KindOf<C>) -> Self {
        Self {
            kind,
            _marker: PhantomData,
        }
    }
}

impl<C> Axiom for NoCyclesOnKind<C>
where
    C: Category,
    C::Object: Clone + Eq + Hash,
    C::Morphism: Arrow<Object = C::Object>,
    KindOf<C>: PartialEq,
{
    fn verify(&self) -> Verdict {
        // No cycle on this kind ⇔ no `e --kind--> e` self-edge survives in the
        // materialized closed morphism set (the macro composed any cyclic path
        // down to such a self-edge). A closure-membership read, not a BFS.
        if has_kinded_self_edge::<C>(self.kind) {
            Err(Box::new(SimpleCounterexample::new(self.meta())))
        } else {
            Ok(Box::new(SimpleProof::new(self.meta())))
        }
    }

    fn name(&self) -> OntologyName {
        name_with_kind("NoCyclesOnKind", &self.kind)
    }

    fn description(&self) -> Label {
        description_with_kind("NoCyclesOnKind", &self.kind)
    }

    fn citation(&self) -> Citation {
        Citation::parse_static(
            "Guarino (2009); Casati & Varzi (1999); Tarski (1941) Calculus of Relations",
        )
    }
}

// ---------------------------------------------------------------------------
// AntisymmetricOnKind — if (A, B) is an edge and A ≠ B, then (B, A) is not.
// Applies canonically to Subsumption (if A is-a B then B is not a A).
// Source: Guarino (2009); Tarski (1941); Mac Lane (1971) partial orders.
// ---------------------------------------------------------------------------

pub struct AntisymmetricOnKind<C: Category>
where
    C::Morphism: Arrow,
{
    kind: KindOf<C>,
    _marker: PhantomData<C>,
}

impl<C: Category> AntisymmetricOnKind<C>
where
    C::Morphism: Arrow,
{
    pub fn new(kind: KindOf<C>) -> Self {
        Self {
            kind,
            _marker: PhantomData,
        }
    }
}

impl<C> Axiom for AntisymmetricOnKind<C>
where
    C: Category,
    C::Object: Clone + Eq + Hash,
    C::Morphism: Arrow<Object = C::Object>,
    KindOf<C>: PartialEq,
{
    fn verify(&self) -> Verdict {
        let pairs = kinded_pairs::<C>(self.kind);
        let set: HashSet<(C::Object, C::Object)> = pairs.iter().cloned().collect();
        if pairs
            .iter()
            .all(|(a, b)| a == b || !set.contains(&(b.clone(), a.clone())))
        {
            Ok(Box::new(SimpleProof::new(self.meta())))
        } else {
            Err(Box::new(SimpleCounterexample::new(self.meta())))
        }
    }

    fn name(&self) -> OntologyName {
        name_with_kind("AntisymmetricOnKind", &self.kind)
    }

    fn description(&self) -> Label {
        description_with_kind("AntisymmetricOnKind", &self.kind)
    }

    fn citation(&self) -> Citation {
        Citation::parse_static("Guarino (2009); Tarski (1941); Mac Lane (1971) partial orders")
    }
}

// ---------------------------------------------------------------------------
// AsymmetricOnKind — no symmetric pair at all (stronger than antisymmetric:
// also excludes self-loops). Applies canonically to Causation.
// Source: Lewis (1973) Causation; Reichenbach (1956); Tarski (1941).
// ---------------------------------------------------------------------------

pub struct AsymmetricOnKind<C: Category>
where
    C::Morphism: Arrow,
{
    kind: KindOf<C>,
    _marker: PhantomData<C>,
}

impl<C: Category> AsymmetricOnKind<C>
where
    C::Morphism: Arrow,
{
    pub fn new(kind: KindOf<C>) -> Self {
        Self {
            kind,
            _marker: PhantomData,
        }
    }
}

impl<C> Axiom for AsymmetricOnKind<C>
where
    C: Category,
    C::Object: Clone + Eq + Hash,
    C::Morphism: Arrow<Object = C::Object>,
    KindOf<C>: PartialEq,
{
    fn verify(&self) -> Verdict {
        let pairs = kinded_pairs::<C>(self.kind);
        let set: HashSet<(C::Object, C::Object)> = pairs.iter().cloned().collect();
        if pairs
            .iter()
            .all(|(a, b)| a != b && !set.contains(&(b.clone(), a.clone())))
        {
            Ok(Box::new(SimpleProof::new(self.meta())))
        } else {
            Err(Box::new(SimpleCounterexample::new(self.meta())))
        }
    }

    fn name(&self) -> OntologyName {
        name_with_kind("AsymmetricOnKind", &self.kind)
    }

    fn description(&self) -> Label {
        description_with_kind("AsymmetricOnKind", &self.kind)
    }

    fn citation(&self) -> Citation {
        Citation::parse_static(
            "Lewis (1973) Causation; Reichenbach (1956) Direction of Time; Tarski (1941)",
        )
    }
}

// ---------------------------------------------------------------------------
// SymmetricOnKind — every edge's reverse is also an edge. Applies canonically
// to Opposition and Equivalence.
// Source: Aristotle *Peri Hermeneias* Square of Opposition; Saussure (1916);
// Cruse (1986) *Lexical Semantics*; Tarski (1941).
// ---------------------------------------------------------------------------

pub struct SymmetricOnKind<C: Category>
where
    C::Morphism: Arrow,
{
    kind: KindOf<C>,
    _marker: PhantomData<C>,
}

impl<C: Category> SymmetricOnKind<C>
where
    C::Morphism: Arrow,
{
    pub fn new(kind: KindOf<C>) -> Self {
        Self {
            kind,
            _marker: PhantomData,
        }
    }
}

impl<C> Axiom for SymmetricOnKind<C>
where
    C: Category,
    C::Object: Clone + Eq + Hash,
    C::Morphism: Arrow<Object = C::Object>,
    KindOf<C>: PartialEq,
{
    fn verify(&self) -> Verdict {
        let pairs = kinded_pairs::<C>(self.kind);
        let set: HashSet<(C::Object, C::Object)> = pairs.iter().cloned().collect();
        if pairs
            .iter()
            .all(|(a, b)| set.contains(&(b.clone(), a.clone())))
        {
            Ok(Box::new(SimpleProof::new(self.meta())))
        } else {
            Err(Box::new(SimpleCounterexample::new(self.meta())))
        }
    }

    fn name(&self) -> OntologyName {
        name_with_kind("SymmetricOnKind", &self.kind)
    }

    fn description(&self) -> Label {
        description_with_kind("SymmetricOnKind", &self.kind)
    }

    fn citation(&self) -> Citation {
        Citation::parse_static(
            "Aristotle Peri Hermeneias; Saussure (1916); Cruse (1986) Lexical Semantics; Tarski (1941)",
        )
    }
}

// ---------------------------------------------------------------------------
// IrreflexiveOnKind — no entity is its own image under the relation.
// Applies canonically to Opposition and Causation.
// Source: Aristotle Peri Hermeneias; Lewis (1973); Tarski (1941).
// ---------------------------------------------------------------------------

pub struct IrreflexiveOnKind<C: Category>
where
    C::Morphism: Arrow,
{
    kind: KindOf<C>,
    _marker: PhantomData<C>,
}

impl<C: Category> IrreflexiveOnKind<C>
where
    C::Morphism: Arrow,
{
    pub fn new(kind: KindOf<C>) -> Self {
        Self {
            kind,
            _marker: PhantomData,
        }
    }
}

impl<C> Axiom for IrreflexiveOnKind<C>
where
    C: Category,
    C::Object: Clone + Eq,
    C::Morphism: Arrow<Object = C::Object>,
    KindOf<C>: PartialEq,
{
    fn verify(&self) -> Verdict {
        if C::morphisms()
            .into_iter()
            .filter(|m| m.kind() == self.kind)
            .all(|m| m.source() != m.target())
        {
            Ok(Box::new(SimpleProof::new(self.meta())))
        } else {
            Err(Box::new(SimpleCounterexample::new(self.meta())))
        }
    }

    fn name(&self) -> OntologyName {
        name_with_kind("IrreflexiveOnKind", &self.kind)
    }

    fn description(&self) -> Label {
        description_with_kind("IrreflexiveOnKind", &self.kind)
    }

    fn citation(&self) -> Citation {
        Citation::parse_static("Aristotle Peri Hermeneias; Lewis (1973); Tarski (1941)")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::category::{Concept, FinitelyGenerated};

    // A tiny test category with kinded morphisms.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    enum TestObj {
        A,
        B,
        C,
    }

    impl Concept for TestObj {}
    impl FinitelyGenerated for TestObj {
        fn variants() -> Vec<Self> {
            vec![TestObj::A, TestObj::B, TestObj::C]
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    enum TestKind {
        Identity,
        Subsumption,
        Opposition,
        Causation,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
    struct TestMorph {
        from: TestObj,
        to: TestObj,
        kind: TestKind,
    }

    impl Arrow for TestMorph {
        type Object = TestObj;
        type Kind = TestKind;
        fn source(&self) -> TestObj {
            self.from
        }
        fn target(&self) -> TestObj {
            self.to
        }
        fn kind(&self) -> TestKind {
            self.kind
        }
    }

    struct TestCat;
    impl Category for TestCat {
        type Object = TestObj;
        type Morphism = TestMorph;
        fn identity(obj: &TestObj) -> TestMorph {
            TestMorph {
                from: *obj,
                to: *obj,
                kind: TestKind::Identity,
            }
        }
        fn compose(f: &TestMorph, g: &TestMorph) -> Option<TestMorph> {
            if f.to != g.from {
                return None;
            }
            Some(TestMorph {
                from: f.from,
                to: g.to,
                kind: TestKind::Identity,
            })
        }
        fn morphisms() -> Vec<TestMorph> {
            vec![
                // Identities
                TestMorph {
                    from: TestObj::A,
                    to: TestObj::A,
                    kind: TestKind::Identity,
                },
                TestMorph {
                    from: TestObj::B,
                    to: TestObj::B,
                    kind: TestKind::Identity,
                },
                TestMorph {
                    from: TestObj::C,
                    to: TestObj::C,
                    kind: TestKind::Identity,
                },
                // Subsumption chain: A ⊑ B ⊑ C (DAG, antisymmetric)
                TestMorph {
                    from: TestObj::A,
                    to: TestObj::B,
                    kind: TestKind::Subsumption,
                },
                TestMorph {
                    from: TestObj::B,
                    to: TestObj::C,
                    kind: TestKind::Subsumption,
                },
                // Opposition pair: A ↔ B (symmetric, irreflexive)
                TestMorph {
                    from: TestObj::A,
                    to: TestObj::B,
                    kind: TestKind::Opposition,
                },
                TestMorph {
                    from: TestObj::B,
                    to: TestObj::A,
                    kind: TestKind::Opposition,
                },
                // Causation: A → B (asymmetric, irreflexive)
                TestMorph {
                    from: TestObj::A,
                    to: TestObj::B,
                    kind: TestKind::Causation,
                },
            ]
        }
    }

    /// A category whose `Subsumption` edges form a cycle A ⊑ B ⊑ A. Its
    /// `morphisms()` is the **materialized closed** set — exactly what the
    /// `ontology!` macro emits: the closure of the cyclic kind has composed
    /// the path down to the self-edges `(A, A, Subsumption)` / `(B, B,
    /// Subsumption)`. `NoCyclesOnKind` reads those self-edges off the closure
    /// rather than re-walking adjacency, so this is the refutation witness.
    struct CyclicSubsumptionCat;
    impl Category for CyclicSubsumptionCat {
        type Object = TestObj;
        type Morphism = TestMorph;
        fn identity(obj: &TestObj) -> TestMorph {
            TestMorph {
                from: *obj,
                to: *obj,
                kind: TestKind::Identity,
            }
        }
        fn compose(f: &TestMorph, g: &TestMorph) -> Option<TestMorph> {
            if f.to != g.from {
                return None;
            }
            Some(TestMorph {
                from: f.from,
                to: g.to,
                kind: TestKind::Subsumption,
            })
        }
        fn morphisms() -> Vec<TestMorph> {
            let sub = |from, to| TestMorph {
                from,
                to,
                kind: TestKind::Subsumption,
            };
            vec![
                // Identities.
                TestMorph {
                    from: TestObj::A,
                    to: TestObj::A,
                    kind: TestKind::Identity,
                },
                TestMorph {
                    from: TestObj::B,
                    to: TestObj::B,
                    kind: TestKind::Identity,
                },
                // Direct cyclic Subsumption edges A ⊑ B, B ⊑ A …
                sub(TestObj::A, TestObj::B),
                sub(TestObj::B, TestObj::A),
                // … and the transitive-closure self-edges the macro materializes
                // for a cyclic transitive kind.
                sub(TestObj::A, TestObj::A),
                sub(TestObj::B, TestObj::B),
            ]
        }
    }

    /// Pattern-match helpers — the ontological test shape. The claim IS
    /// the Axiom; the test bridges the Verdict to Rust's panic-based test
    /// harness. No `.is_ok()`/`.is_err()` bool shortcuts (see
    /// `feedback_core_no_bool_api`).
    fn expect_proves<A: Axiom>(axiom: A) {
        match axiom.verify() {
            Ok(_) => {}
            Err(c) => panic!("expected proof but got counterexample: {}", c.meta().name),
        }
    }

    fn expect_refutes<A: Axiom>(axiom: A) {
        match axiom.verify() {
            Err(_) => {}
            Ok(p) => panic!("expected counterexample but got proof: {}", p.meta().name),
        }
    }

    #[test]
    fn no_cycles_holds_on_subsumption() {
        expect_proves(NoCyclesOnKind::<TestCat>::new(TestKind::Subsumption));
    }

    #[test]
    fn no_cycles_refutes_on_cyclic_subsumption() {
        // The cyclic kind's closure carries `(A, A, Subsumption)` — the axiom
        // reads that materialized self-edge and refutes, no BFS needed.
        expect_refutes(NoCyclesOnKind::<CyclicSubsumptionCat>::new(
            TestKind::Subsumption,
        ));
    }

    #[test]
    fn antisymmetric_holds_on_subsumption() {
        expect_proves(AntisymmetricOnKind::<TestCat>::new(TestKind::Subsumption));
    }

    #[test]
    fn symmetric_holds_on_opposition() {
        expect_proves(SymmetricOnKind::<TestCat>::new(TestKind::Opposition));
    }

    #[test]
    fn irreflexive_holds_on_opposition() {
        expect_proves(IrreflexiveOnKind::<TestCat>::new(TestKind::Opposition));
    }

    #[test]
    fn asymmetric_holds_on_causation() {
        expect_proves(AsymmetricOnKind::<TestCat>::new(TestKind::Causation));
    }

    #[test]
    fn symmetric_fails_on_causation() {
        // Causation has (A, B) but not (B, A) — symmetric must refute.
        expect_refutes(SymmetricOnKind::<TestCat>::new(TestKind::Causation));
    }

    #[test]
    fn meta_carries_kind_identifier() {
        let ax = NoCyclesOnKind::<TestCat>::new(TestKind::Subsumption);
        assert_eq!(ax.meta().name.as_str(), "NoCyclesOnKind[Subsumption]");
        assert!(!ax.meta().citation.as_str().is_empty());
    }
}