Skip to main content

qualia_core_db/modalities/
epistemic_ontology.rs

1//! Epistemic Ontology Substrate: Open English WordNet (OEWN) & CILI Integration
2//!
3//! Provides zero-heap, ontologically grounded epistemic stances for QualiaDB assertions,
4//! sessions, and reasoning frames. Replaces ad-hoc string enums with formal RDF synsets
5//! from Open English WordNet (OEWN 2025-plus) and the Collaborative Interlingual Index (CILI).
6//!
7//! Architectural Invariants:
8//! - Tier-1 zero-heap evaluator loops: Caller supplies fixed-size `&mut [T]` output buffers.
9//! - 60-bit token space: All synset and CILI tokens fit into the 60-bit payload of `NQuin`.
10//! - Hierarchical subsumption: Integrates with `modalities::dl::check_subsumption_quin`
11//!   to resolve hypernym/hyponym trees (e.g. conjecture ⊑ hypothesis).
12
13use crate::modalities::dl::check_subsumption_quin;
14use crate::{q_hash, NQuin};
15
16// ─── Epistemic Predicates ────────────────────────────────────────────────────
17
18/// `q42:hasEpistemicStance` — Links an assertion, statement, or session to a synset stance.
19pub const PRED_EPISTEMIC_STANCE: u64 = q_hash("q42:hasEpistemicStance");
20
21/// `q42:hasWordNetSynset` — Links a concept to an explicit OEWN synset URI.
22pub const PRED_WORDNET_SYNSET: u64 = q_hash("q42:hasWordNetSynset");
23
24/// `q42:hasCiliConcept` — Links a stance to a language-independent CILI concept ID.
25pub const PRED_CILI_CONCEPT: u64 = q_hash("q42:hasCiliConcept");
26
27/// `rdfs:subClassOf` — Standard subsumption / hypernym relationship.
28pub const PRED_SUB_CLASS_OF: u64 = q_hash("http://www.w3.org/2000/01/rdf-schema#subClassOf");
29
30/// `wn:hypernym` — WordNet lexical hypernym relation.
31pub const PRED_WN_HYPERNYM: u64 = q_hash("https://en-wordnet.oed.com/schema/hypernym");
32
33// ─── Canonical OEWN 2025-plus Synsets (60-bit token masked) ───────────────────
34
35/// `synset-fact-noun-1`: Empirical observation, objective reality, ground truth.
36pub const SYNSET_FACT: u64 =
37    q_hash("https://en-wordnet.oed.com/id/synset-fact-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
38
39/// `synset-observation-noun-1`: Sensory datum, empirical field observation.
40pub const SYNSET_OBSERVATION: u64 =
41    q_hash("https://en-wordnet.oed.com/id/synset-observation-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
42
43/// `synset-hypothesis-noun-1`: Tentative proposition, testable scientific supposition.
44pub const SYNSET_HYPOTHESIS: u64 =
45    q_hash("https://en-wordnet.oed.com/id/synset-hypothesis-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
46
47/// `synset-conjecture-noun-1`: Mathematical/logical conjecture, speculation without proof.
48pub const SYNSET_CONJECTURE: u64 =
49    q_hash("https://en-wordnet.oed.com/id/synset-conjecture-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
50
51/// `synset-simulation-noun-1`: Computational representation, physical digital twin model.
52pub const SYNSET_SIMULATION: u64 =
53    q_hash("https://en-wordnet.oed.com/id/synset-simulation-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
54
55/// `synset-fiction-noun-1`: Speculative narrative, literary worldbuilding, fictional world.
56pub const SYNSET_FICTION: u64 =
57    q_hash("https://en-wordnet.oed.com/id/synset-fiction-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
58
59/// `synset-civics-noun-1`: Social commons, participatory governance, civic duty.
60pub const SYNSET_CIVICS: u64 =
61    q_hash("https://en-wordnet.oed.com/id/synset-civics-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
62
63/// `synset-counterfactual_conditional-noun-1`: Thought experiment, counter-to-fact inquiry.
64pub const SYNSET_COUNTERFACTUAL: u64 =
65    q_hash("https://en-wordnet.oed.com/id/synset-counterfactual_conditional-noun-1")
66        & 0x0FFF_FFFF_FFFF_FFFF;
67
68/// `synset-belief-noun-1`: Doxastic belief without definitive proof.
69pub const SYNSET_BELIEF: u64 =
70    q_hash("https://en-wordnet.oed.com/id/synset-belief-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
71
72/// `synset-knowledge-noun-1`: Justified, verified true belief / confirmed knowledge.
73pub const SYNSET_KNOWLEDGE: u64 =
74    q_hash("https://en-wordnet.oed.com/id/synset-knowledge-noun-1") & 0x0FFF_FFFF_FFFF_FFFF;
75
76// ─── Collaborative Interlingual Index (CILI) Concepts ────────────────────────
77
78/// CILI i68339: Language-independent fact concept.
79pub const CILI_FACT: u64 = q_hash("http://globalwordnet.org/ili/i68339") & 0x0FFF_FFFF_FFFF_FFFF;
80
81/// CILI i68341: Language-independent hypothesis concept.
82pub const CILI_HYPOTHESIS: u64 =
83    q_hash("http://globalwordnet.org/ili/i68341") & 0x0FFF_FFFF_FFFF_FFFF;
84
85/// CILI i68345: Language-independent conjecture concept.
86pub const CILI_CONJECTURE: u64 =
87    q_hash("http://globalwordnet.org/ili/i68345") & 0x0FFF_FFFF_FFFF_FFFF;
88
89/// CILI i68212: Language-independent simulation concept.
90pub const CILI_SIMULATION: u64 =
91    q_hash("http://globalwordnet.org/ili/i68212") & 0x0FFF_FFFF_FFFF_FFFF;
92
93/// CILI i71201: Language-independent fiction concept.
94pub const CILI_FICTION: u64 = q_hash("http://globalwordnet.org/ili/i71201") & 0x0FFF_FFFF_FFFF_FFFF;
95
96/// CILI i69420: Language-independent civics concept.
97pub const CILI_CIVICS: u64 = q_hash("http://globalwordnet.org/ili/i69420") & 0x0FFF_FFFF_FFFF_FFFF;
98
99/// CILI i70110: Language-independent observation concept.
100pub const CILI_OBSERVATION: u64 =
101    q_hash("http://globalwordnet.org/ili/i70110") & 0x0FFF_FFFF_FFFF_FFFF;
102
103// ─── Data Structures ─────────────────────────────────────────────────────────
104
105/// Zero-copy representation of an evaluated epistemic stance.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107#[repr(C)]
108pub struct EpistemicStanceRecord {
109    pub subject: u64,      // Entity, statement, or session DID hash
110    pub synset_hash: u64,  // 60-bit WordNet Synset token
111    pub cili_hash: u64,    // 60-bit language-independent CILI concept token
112    pub confidence: u16,   // Epistemic certainty / confidence weight (0..65535)
113    pub is_subsumed: bool, // Satisfies requested target category via hypernym DAG
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum EpistemicOntologyError {
118    BufferOverflow,
119    InvalidQuinEncoding,
120    UnresolvedConcept,
121}
122
123// ─── Core Functions ──────────────────────────────────────────────────────────
124
125/// Synthesizes a valid zero-allocation `NQuin` encoding an epistemic stance assertion.
126///
127/// Layout:
128/// - `subject`: Target entity/claim DID hash
129/// - `predicate`: `PRED_EPISTEMIC_STANCE`
130/// - `object`: 60-bit synset hash token
131/// - `context`: World or scenario context DID hash
132/// - `metadata`: bits 0..15 contain `confidence`
133/// - `parity`: XOR fold of subject ^ predicate ^ object ^ context
134#[inline]
135pub fn compile_epistemic_stance_quin(
136    claim_subject: u64,
137    synset_hash: u64,
138    context_hash: u64,
139    confidence: u16,
140) -> NQuin {
141    let clean_object = synset_hash & 0x0FFF_FFFF_FFFF_FFFF;
142    let metadata = confidence as u64;
143    let parity = claim_subject ^ PRED_EPISTEMIC_STANCE ^ clean_object ^ context_hash;
144
145    NQuin {
146        subject: claim_subject,
147        predicate: PRED_EPISTEMIC_STANCE,
148        object: clean_object,
149        context: context_hash,
150        metadata,
151        parity,
152    }
153}
154
155/// Resolves the canonical CILI concept identifier for a known OEWN synset token.
156/// Pure, deterministic, zero-heap mapping.
157#[inline]
158pub const fn synset_to_cili(synset_hash: u64) -> u64 {
159    let clean = synset_hash & 0x0FFF_FFFF_FFFF_FFFF;
160    if clean == SYNSET_FACT {
161        CILI_FACT
162    } else if clean == SYNSET_HYPOTHESIS {
163        CILI_HYPOTHESIS
164    } else if clean == SYNSET_CONJECTURE {
165        CILI_CONJECTURE
166    } else if clean == SYNSET_SIMULATION {
167        CILI_SIMULATION
168    } else if clean == SYNSET_FICTION {
169        CILI_FICTION
170    } else if clean == SYNSET_CIVICS {
171        CILI_CIVICS
172    } else if clean == SYNSET_OBSERVATION {
173        CILI_OBSERVATION
174    } else {
175        // Unknown or custom synset — retains identity hash
176        clean
177    }
178}
179
180/// Parses an epistemic mode string (e.g. legacy descriptors or configs) into its canonical OEWN synset token.
181/// Completely zero-heap matching over static string slices.
182#[inline]
183pub fn parse_epistemic_mode_to_synset(mode_str: &str) -> Option<u64> {
184    match mode_str.trim().to_ascii_lowercase().as_str() {
185        "fiction" | "speculative" | "narrative" => Some(SYNSET_FICTION),
186        "non-fiction" | "nonfiction" | "fact" | "empirical" | "ground-truth" => Some(SYNSET_FACT),
187        "observation" | "field-observation" | "sensory" => Some(SYNSET_OBSERVATION),
188        "simulation" | "digital-twin" | "model" => Some(SYNSET_SIMULATION),
189        "hypothesis" | "tentative" => Some(SYNSET_HYPOTHESIS),
190        "conjecture" | "unproven" => Some(SYNSET_CONJECTURE),
191        "counterfactual" | "thought-experiment" => Some(SYNSET_COUNTERFACTUAL),
192        "civics" | "civic" | "commons" | "normative" => Some(SYNSET_CIVICS),
193        "belief" | "doxastic" => Some(SYNSET_BELIEF),
194        "knowledge" | "epistemic" => Some(SYNSET_KNOWLEDGE),
195        _ => None,
196    }
197}
198
199/// Maps a canonical synset token to its primary English canonical display label.
200#[inline]
201pub fn synset_to_canonical_label(synset_hash: u64) -> &'static str {
202    let clean = synset_hash & 0x0FFF_FFFF_FFFF_FFFF;
203    if clean == SYNSET_FACT {
204        "fact"
205    } else if clean == SYNSET_OBSERVATION {
206        "observation"
207    } else if clean == SYNSET_HYPOTHESIS {
208        "hypothesis"
209    } else if clean == SYNSET_CONJECTURE {
210        "conjecture"
211    } else if clean == SYNSET_SIMULATION {
212        "simulation"
213    } else if clean == SYNSET_FICTION {
214        "fiction"
215    } else if clean == SYNSET_CIVICS {
216        "civics"
217    } else if clean == SYNSET_COUNTERFACTUAL {
218        "counterfactual"
219    } else if clean == SYNSET_BELIEF {
220        "belief"
221    } else if clean == SYNSET_KNOWLEDGE {
222        "knowledge"
223    } else {
224        "custom"
225    }
226}
227
228/// Resolves a localized lemma for a given CILI concept token.
229/// Supports English ("en"), Spanish ("es"), French ("fr"), and German ("de").
230/// Completely zero-heap, compile-time static lookup.
231#[inline]
232pub fn lookup_epistemic_lemma(cili_hash: u64, lang_code: &str) -> Option<&'static str> {
233    let clean = cili_hash & 0x0FFF_FFFF_FFFF_FFFF;
234    match lang_code {
235        "es" => {
236            if clean == CILI_FACT {
237                Some("hecho")
238            } else if clean == CILI_HYPOTHESIS {
239                Some("hipótesis")
240            } else if clean == CILI_CONJECTURE {
241                Some("conjetura")
242            } else if clean == CILI_SIMULATION {
243                Some("simulación")
244            } else if clean == CILI_FICTION {
245                Some("ficción")
246            } else if clean == CILI_CIVICS {
247                Some("cívica")
248            } else if clean == CILI_OBSERVATION {
249                Some("observación")
250            } else {
251                None
252            }
253        }
254        "fr" => {
255            if clean == CILI_FACT {
256                Some("fait")
257            } else if clean == CILI_HYPOTHESIS {
258                Some("hypothèse")
259            } else if clean == CILI_CONJECTURE {
260                Some("conjecture")
261            } else if clean == CILI_SIMULATION {
262                Some("simulation")
263            } else if clean == CILI_FICTION {
264                Some("fiction")
265            } else if clean == CILI_CIVICS {
266                Some("civisme")
267            } else if clean == CILI_OBSERVATION {
268                Some("observation")
269            } else {
270                None
271            }
272        }
273        "de" => {
274            if clean == CILI_FACT {
275                Some("Tatsache")
276            } else if clean == CILI_HYPOTHESIS {
277                Some("Hypothese")
278            } else if clean == CILI_CONJECTURE {
279                Some("Vermutung")
280            } else if clean == CILI_SIMULATION {
281                Some("Simulation")
282            } else if clean == CILI_FICTION {
283                Some("Fiktion")
284            } else if clean == CILI_CIVICS {
285                Some("Gemeinschaftswesen")
286            } else if clean == CILI_OBSERVATION {
287                Some("Beobachtung")
288            } else {
289                None
290            }
291        }
292        _ => {
293            // Default "en"
294            if clean == CILI_FACT {
295                Some("fact")
296            } else if clean == CILI_HYPOTHESIS {
297                Some("hypothesis")
298            } else if clean == CILI_CONJECTURE {
299                Some("conjecture")
300            } else if clean == CILI_SIMULATION {
301                Some("simulation")
302            } else if clean == CILI_FICTION {
303                Some("fiction")
304            } else if clean == CILI_CIVICS {
305                Some("civics")
306            } else if clean == CILI_OBSERVATION {
307                Some("observation")
308            } else {
309                None
310            }
311        }
312    }
313}
314
315/// Verifies whether an active stance synset matches or is subsumed by an expected category synset.
316///
317/// Utilizes `modalities::dl::check_subsumption_quin` to traverse hypernym / `rdfs:subClassOf`
318/// edges in the provided `tbox` slice in $O(V+E)$ time with zero allocations.
319pub fn is_epistemic_subsumed(active_synset: u64, expected_synset: u64, tbox: &[NQuin]) -> bool {
320    let clean_active = active_synset & 0x0FFF_FFFF_FFFF_FFFF;
321    let clean_expected = expected_synset & 0x0FFF_FFFF_FFFF_FFFF;
322
323    if clean_active == clean_expected {
324        return true;
325    }
326
327    // Direct OEWN built-in subsumption fallback for base axioms without external TBox
328    if clean_active == SYNSET_CONJECTURE && clean_expected == SYNSET_HYPOTHESIS {
329        return true;
330    }
331    if clean_active == SYNSET_OBSERVATION && clean_expected == SYNSET_FACT {
332        return true;
333    }
334    if clean_active == SYNSET_COUNTERFACTUAL && clean_expected == SYNSET_HYPOTHESIS {
335        return true;
336    }
337
338    // Traverse caller-provided TBox via Description Logic zero-heap transitive closure
339    check_subsumption_quin(clean_active, clean_expected, tbox)
340}
341
342/// Evaluates a slice of input `NQuin` statements against an expected epistemic stance.
343///
344/// Output is written to the caller-supplied `out` slice with zero heap allocations.
345/// Returns the number of matched records.
346pub fn evaluate_epistemic_stances(
347    quins: &[NQuin],
348    expected_synset: u64, // 0 = accept any epistemic stance
349    tbox: &[NQuin],       // WordNet hypernym / ontology subsumption edges
350    out: &mut [EpistemicStanceRecord],
351) -> Result<usize, EpistemicOntologyError> {
352    let mut written = 0;
353
354    for quin in quins {
355        if quin.predicate != PRED_EPISTEMIC_STANCE {
356            continue;
357        }
358
359        let synset_token = quin.object & 0x0FFF_FFFF_FFFF_FFFF;
360        let confidence = (quin.metadata & 0xFFFF) as u16;
361
362        let subsumed = if expected_synset == 0 {
363            true
364        } else {
365            is_epistemic_subsumed(synset_token, expected_synset, tbox)
366        };
367
368        if expected_synset == 0 || subsumed {
369            if written >= out.len() {
370                return Err(EpistemicOntologyError::BufferOverflow);
371            }
372
373            out[written] = EpistemicStanceRecord {
374                subject: quin.subject,
375                synset_hash: synset_token,
376                cili_hash: synset_to_cili(synset_token),
377                confidence,
378                is_subsumed: subsumed,
379            };
380            written += 1;
381        }
382    }
383
384    Ok(written)
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    #[test]
392    fn test_compile_and_exact_match() {
393        let claim_id = q_hash("did:q42:claim:water_balance_2026");
394        let context_id = q_hash("did:q42:context:scientific_trial");
395
396        let quin = compile_epistemic_stance_quin(claim_id, SYNSET_HYPOTHESIS, context_id, 45000);
397        assert_eq!(quin.subject, claim_id);
398        assert_eq!(quin.predicate, PRED_EPISTEMIC_STANCE);
399        assert_eq!(quin.object, SYNSET_HYPOTHESIS);
400        assert_eq!(quin.metadata & 0xFFFF, 45000);
401
402        let mut out = [EpistemicStanceRecord {
403            subject: 0,
404            synset_hash: 0,
405            cili_hash: 0,
406            confidence: 0,
407            is_subsumed: false,
408        }; 4];
409
410        let quins = [quin];
411        let count = evaluate_epistemic_stances(&quins, SYNSET_HYPOTHESIS, &[], &mut out).unwrap();
412        assert_eq!(count, 1);
413        assert_eq!(out[0].subject, claim_id);
414        assert_eq!(out[0].synset_hash, SYNSET_HYPOTHESIS);
415        assert_eq!(out[0].cili_hash, CILI_HYPOTHESIS);
416        assert_eq!(out[0].confidence, 45000);
417        assert!(out[0].is_subsumed);
418    }
419
420    #[test]
421    fn test_built_in_subsumption_conjecture_to_hypothesis() {
422        let claim_id = q_hash("did:q42:conjecture:riemann_hypothesis");
423        let context_id = q_hash("did:q42:context:math_corpus");
424
425        let quin = compile_epistemic_stance_quin(claim_id, SYNSET_CONJECTURE, context_id, 65000);
426        let mut out = [EpistemicStanceRecord {
427            subject: 0,
428            synset_hash: 0,
429            cili_hash: 0,
430            confidence: 0,
431            is_subsumed: false,
432        }; 4];
433
434        // Query expects generic HYPOTHESIS: conjecture should be accepted via subsumption
435        let count = evaluate_epistemic_stances(&[quin], SYNSET_HYPOTHESIS, &[], &mut out).unwrap();
436        assert_eq!(count, 1);
437        assert_eq!(out[0].synset_hash, SYNSET_CONJECTURE);
438        assert_eq!(out[0].cili_hash, CILI_CONJECTURE);
439        assert!(out[0].is_subsumed);
440    }
441
442    #[test]
443    fn test_tbox_hypernym_subsumption() {
444        let custom_synset =
445            q_hash("https://en-wordnet.oed.com/id/synset-working_hypothesis-noun-1")
446                & 0x0FFF_FFFF_FFFF_FFFF;
447        let claim_id = q_hash("did:q42:claim:thermal_dissipation_rate");
448        let context_id = q_hash("did:q42:context:field_lab");
449
450        let quin = compile_epistemic_stance_quin(claim_id, custom_synset, context_id, 50000);
451
452        // Define TBox edge: working_hypothesis rdfs:subClassOf hypothesis
453        let tbox_edge = NQuin {
454            subject: custom_synset,
455            predicate: PRED_SUB_CLASS_OF,
456            object: SYNSET_HYPOTHESIS,
457            context: 0,
458            metadata: 0,
459            parity: custom_synset ^ PRED_SUB_CLASS_OF ^ SYNSET_HYPOTHESIS ^ 0,
460        };
461
462        let mut out = [EpistemicStanceRecord {
463            subject: 0,
464            synset_hash: 0,
465            cili_hash: 0,
466            confidence: 0,
467            is_subsumed: false,
468        }; 2];
469
470        let count =
471            evaluate_epistemic_stances(&[quin], SYNSET_HYPOTHESIS, &[tbox_edge], &mut out).unwrap();
472        assert_eq!(count, 1);
473        assert_eq!(out[0].synset_hash, custom_synset);
474        assert!(out[0].is_subsumed);
475    }
476
477    #[test]
478    fn test_mismatched_stance_filtered_out() {
479        let claim_id = q_hash("did:q42:story:desert_odyssey");
480        let context_id = q_hash("did:q42:context:fictional_arc");
481
482        // Stance is FICTION
483        let quin = compile_epistemic_stance_quin(claim_id, SYNSET_FICTION, context_id, 65535);
484
485        let mut out = [EpistemicStanceRecord {
486            subject: 0,
487            synset_hash: 0,
488            cili_hash: 0,
489            confidence: 0,
490            is_subsumed: false,
491        }; 2];
492
493        // Query expects empirical FACT — fiction should be filtered out
494        let count = evaluate_epistemic_stances(&[quin], SYNSET_FACT, &[], &mut out).unwrap();
495        assert_eq!(count, 0);
496    }
497
498    #[test]
499    fn test_cili_multilingual_mapping() {
500        assert_eq!(synset_to_cili(SYNSET_FACT), CILI_FACT);
501        assert_eq!(synset_to_cili(SYNSET_HYPOTHESIS), CILI_HYPOTHESIS);
502        assert_eq!(synset_to_cili(SYNSET_SIMULATION), CILI_SIMULATION);
503        assert_eq!(synset_to_cili(SYNSET_FICTION), CILI_FICTION);
504        assert_eq!(synset_to_cili(SYNSET_CIVICS), CILI_CIVICS);
505    }
506}