Skip to main content

qualia_core_db/modalities/logic/owl/
mod.rs

1//! OWL support for QualiaDB.
2//!
3//! Two distinct concerns, one per submodule, plus the disjoint domain boundary
4//! guard (`D = D_living ⊔ D_artifact`, Playbook v4 §6.2.2):
5//!
6//! - [`shacl_convert`] — *vocabulary lowering*: parse OWL (RadLex/DICOM healthcare
7//!   ontologies in RDF/XML, Turtle, or N3) and emit `sh:NodeShape` graphs for the
8//!   Webizen Sentinel, preserving the agency invariant (a `q42:Principal` may *have*
9//!   `q42:Thing` possessions but is never itself a Thing).
10//! - [`materialize`] — *reasoning*: OWL 2 RL forward-chaining entailment closure
11//!   over NQuin-style triples (zero-heap, datalog-style fixpoint), with disjointness
12//!   contradiction isolation and property-chain unrolling.
13//! - **Disjoint Domain Partition (`D = D_living ⊔ D_artifact`):** Because W3C OWL 2
14//!   Direct Semantics defines `owl:Thing` as the universal domain of all individuals
15//!   admitted into an OWL interpretation, nodes in `D_living` (`self:HumanBeing`,
16//!   `values:NaturalPerson`, `idf:NaturalAgent`, `idf:LivingFloraFauna`) are evaluated
17//!   strictly under `N3Logic` / `living-SHACL` and rejected at the evaluator routing
18//!   boundary if routed into the OWL 2 artifact reasoner.
19//!
20//! The public surface of both submodules is re-exported here so the historical
21//! module path `crate::modalities::logic::owl::*` is preserved.
22
23pub mod materialize;
24pub mod shacl_convert;
25
26pub use materialize::*;
27pub use shacl_convert::*;
28
29// ── Disjoint Domain Partition (D = D_living ⊔ D_artifact, §6.2.2) ────────────
30
31pub const OWL_THING: u64 = crate::q_hash("http://www.w3.org/2002/07/owl#Thing");
32pub const OWL_THING_CURIE: u64 = crate::q_hash("owl:Thing");
33
34pub const SELF_HUMAN_BEING: u64 = crate::q_hash("https://ns.webcivics.net/selfhood#HumanBeing");
35pub const SELF_HUMAN_BEING_CURIE: u64 = crate::q_hash("self:HumanBeing");
36pub const VALUES_NATURAL_PERSON: u64 =
37    crate::q_hash("https://ns.webcivics.net/values#NaturalPerson");
38pub const VALUES_NATURAL_PERSON_CURIE: u64 = crate::q_hash("values:NaturalPerson");
39pub const IDF_NATURAL_AGENT: u64 = crate::q_hash("urn:qualia:idf:NaturalAgent");
40pub const IDF_NATURAL_AGENT_CURIE: u64 = crate::q_hash("idf:NaturalAgent");
41pub const IDF_LIVING_FLORA_FAUNA: u64 = crate::q_hash("urn:qualia:idf:LivingFloraFauna");
42pub const IDF_LIVING_FLORA_FAUNA_CURIE: u64 = crate::q_hash("idf:LivingFloraFauna");
43
44/// Partition of the semantic domain `D = D_living ⊔ D_artifact`.
45#[repr(u8)]
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum DomainPartition {
48    /// Living beings (`self:HumanBeing`, `values:NaturalPerson`, `idf:NaturalAgent`,
49    /// `idf:LivingFloraFauna`) — evaluated strictly under `N3Logic` + `living-SHACL`.
50    Living = 1,
51    /// Artifacts, instruments, and structural vocabularies — eligible for OWL 2 RL.
52    Artifact = 2,
53}
54
55/// Routing boundary rejection when `D_living` nodes or `owl:Thing` subsumptions
56/// are routed into the OWL 2 artifact reasoner.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum OwlDomainBoundaryError {
59    LivingEntityRoutedToOwlArtifactReasoner { subject: u64, living_class: u64 },
60    LivingClassSubsumedUnderOwlThing { living_class: u64 },
61    LivingSameAsMergeForbidden { left: u64, right: u64 },
62}
63
64/// True iff `class_hash` names a `D_living` class (`self:HumanBeing`,
65/// `values:NaturalPerson`, `idf:NaturalAgent`, or `idf:LivingFloraFauna`).
66#[inline]
67pub const fn is_living_domain_class(class_hash: u64) -> bool {
68    class_hash == SELF_HUMAN_BEING
69        || class_hash == SELF_HUMAN_BEING_CURIE
70        || class_hash == VALUES_NATURAL_PERSON
71        || class_hash == VALUES_NATURAL_PERSON_CURIE
72        || class_hash == IDF_NATURAL_AGENT
73        || class_hash == IDF_NATURAL_AGENT_CURIE
74        || class_hash == IDF_LIVING_FLORA_FAUNA
75        || class_hash == IDF_LIVING_FLORA_FAUNA_CURIE
76}
77
78#[inline]
79const fn is_owl_thing(class_hash: u64) -> bool {
80    class_hash == OWL_THING || class_hash == OWL_THING_CURIE
81}
82
83/// Enforce `D = D_living ⊔ D_artifact` before running the OWL 2 RL artifact reasoner.
84///
85/// Rejects any triple graph that:
86/// 1. Types an individual as a member of `D_living` inside an OWL 2 reasoning batch;
87/// 2. Declares a `D_living` class as `rdfs:subClassOf` or `owl:equivalentClass` of `owl:Thing`;
88/// 3. Applies `owl:sameAs` to a `D_living` class or individual.
89pub fn enforce_disjoint_artifact_domain(
90    triples: &[RdfTriple],
91) -> Result<DomainPartition, OwlDomainBoundaryError> {
92    let mut i = 0usize;
93    while i < triples.len() {
94        let t = triples[i];
95        if (t.p == RDF_TYPE || t.p == crate::q_hash("rdf:type") || t.p == crate::q_hash("a"))
96            && is_living_domain_class(t.o)
97        {
98            return Err(
99                OwlDomainBoundaryError::LivingEntityRoutedToOwlArtifactReasoner {
100                    subject: t.s,
101                    living_class: t.o,
102                },
103            );
104        }
105        if (t.p == RDFS_SUBCLASS_OF
106            || t.p == OWL_EQUIVALENT_CLASS
107            || t.p == crate::q_hash("rdfs:subClassOf")
108            || t.p == crate::q_hash("owl:equivalentClass"))
109            && ((is_living_domain_class(t.s) && is_owl_thing(t.o))
110                || (is_owl_thing(t.s) && is_living_domain_class(t.o)))
111        {
112            let living_class = if is_living_domain_class(t.s) {
113                t.s
114            } else {
115                t.o
116            };
117            return Err(OwlDomainBoundaryError::LivingClassSubsumedUnderOwlThing { living_class });
118        }
119        if (t.p == OWL_SAME_AS || t.p == crate::q_hash("owl:sameAs"))
120            && (is_living_domain_class(t.s) || is_living_domain_class(t.o))
121        {
122            return Err(OwlDomainBoundaryError::LivingSameAsMergeForbidden {
123                left: t.s,
124                right: t.o,
125            });
126        }
127        i += 1;
128    }
129    Ok(DomainPartition::Artifact)
130}
131
132#[cfg(test)]
133mod domain_partition_tests {
134    use super::*;
135
136    #[test]
137    fn owl_reasoner_boundary_rejects_d_living_classes() {
138        for living in [
139            SELF_HUMAN_BEING,
140            SELF_HUMAN_BEING_CURIE,
141            VALUES_NATURAL_PERSON,
142            VALUES_NATURAL_PERSON_CURIE,
143            IDF_NATURAL_AGENT,
144            IDF_NATURAL_AGENT_CURIE,
145            IDF_LIVING_FLORA_FAUNA,
146            IDF_LIVING_FLORA_FAUNA_CURIE,
147        ] {
148            let triples = [RdfTriple::new(crate::q_hash("urn:agent:alice"), RDF_TYPE, living)];
149            assert_eq!(
150                enforce_disjoint_artifact_domain(&triples),
151                Err(
152                    OwlDomainBoundaryError::LivingEntityRoutedToOwlArtifactReasoner {
153                        subject: crate::q_hash("urn:agent:alice"),
154                        living_class: living,
155                    }
156                )
157            );
158        }
159    }
160
161    #[test]
162    fn owl_reasoner_boundary_rejects_living_subclass_of_owl_thing() {
163        let triples = [RdfTriple::new(IDF_NATURAL_AGENT, RDFS_SUBCLASS_OF, OWL_THING)];
164        assert_eq!(
165            enforce_disjoint_artifact_domain(&triples),
166            Err(OwlDomainBoundaryError::LivingClassSubsumedUnderOwlThing {
167                living_class: IDF_NATURAL_AGENT,
168            })
169        );
170    }
171
172    #[test]
173    fn owl_reasoner_boundary_admits_pure_artifact_triples() {
174        let triples = [RdfTriple::new(
175            crate::q_hash("urn:device:sensor1"),
176            RDF_TYPE,
177            crate::q_hash("urn:qualia:idf:MachineDevice"),
178        )];
179        assert_eq!(
180            enforce_disjoint_artifact_domain(&triples),
181            Ok(DomainPartition::Artifact)
182        );
183    }
184}