Skip to main content

qualia_core_db/modalities/
epistemic_boundaries.rs

1use crate::{q_hash, NQuin};
2
3/// A zero-heap representation of a degraded claim.
4/// Ensures the engine outputs probabilistic analyses, dialectical maps, and Socratic questions
5/// instead of unauthorized legal/medical directives.
6#[derive(Debug, Clone, Copy)]
7pub struct SocraticDegradation {
8    pub probabilistic_map: &'static str,
9    pub socratic_prompt: &'static str,
10    pub immutable_disclaimer: &'static str,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum DegradationVector {
15    BiochemicalPathway,
16    ThermodynamicTracking,
17    GenomicPrivacy,
18    ContractualPower,
19    ProportionalityTest,
20    InteractionGovernance,
21    FiduciaryAdvice,
22    EthnobotanicalMedicinal,
23    TaxonomicClassification,
24    Unknown,
25}
26
27/// Immutable UI-rendering disclaimer for any biological / physiological / thermodynamic
28/// analysis. Hardcoded verbatim from the audit spec (Systemic Biological Framework).
29pub const BIO_DISCLAIMER: &str = "**Systemic Biological Analysis:** The outputs generated in this subgraph represent a mechanistic, probabilistic simulation of physiological and thermodynamic variables. They are constructed for educational ontology mapping and structural biological research. This system does not diagnose, treat, or prescribe. For definitive clinical applications, these findings should be presented to a certified medical practitioner.";
30
31/// Immutable UI-rendering disclaimer for traditional knowledge, ethnobotany, and species classification.
32pub const BIOSPHERE_TRADITIONAL_KNOWLEDGE_DISCLAIMER: &str = "**Biosphere & Ethnobotanical Knowledge:** Assertions regarding species classification, medicinal application, or ecological usage represent community and academic knowledge models. They do not constitute certified therapeutic guidance or definitive statutory taxonomy. Custodial knowledge is respected as relational heritage rather than open clinical endorsement.";
33
34/// Immutable UI-rendering disclaimer for any jural / deontic / rights analysis. Hardcoded
35/// verbatim from the audit spec (Systemic Jural & Legal Framework).
36pub const LEGAL_DISCLAIMER: &str = "**Informational/Educational Ontology:** This nquin subgraph represents a logical simulation of jural relations, deontic logic, and structural human rights frameworks. It is designed to empower individual agency through systemic education and dialectical mapping. This engine does not provide binding legal counsel, representation, or authoritative statutory interpretation. You are encouraged to seek licensed legal counsel for actionable fiduciary validation.";
37
38/// Identifies if a Quin encodes a definitive claim that crosses Epistemic Boundaries.
39pub fn identify_degradation_vector(quin: &NQuin) -> DegradationVector {
40    let predicate = quin.predicate;
41
42    // Medical/Biological Vectors
43    if predicate == q_hash("q42:biochemicalPathway") || predicate == q_hash("q42:medicalDiagnosis")
44    {
45        return DegradationVector::BiochemicalPathway;
46    }
47    if predicate == q_hash("q42:thermodynamicState") || predicate == q_hash("q42:kineticSimulation")
48    {
49        return DegradationVector::ThermodynamicTracking;
50    }
51    if predicate == q_hash("q42:genomicAlignment") || predicate == q_hash("q42:sequenceProcessing")
52    {
53        return DegradationVector::GenomicPrivacy;
54    }
55
56    // Legal/Jural Vectors
57    if predicate == q_hash("q42:contractualClause") || predicate == q_hash("q42:legalVerdict") {
58        return DegradationVector::ContractualPower;
59    }
60    if predicate == q_hash("q42:proportionalityTest") || predicate == q_hash("q42:rightsConflict") {
61        return DegradationVector::ProportionalityTest;
62    }
63    if predicate == q_hash("q42:governancePolicy") || predicate == q_hash("q42:enforcementProtocol")
64    {
65        return DegradationVector::InteractionGovernance;
66    }
67
68    // Fiduciary Vectors
69    if predicate == q_hash("q42:financialFiduciary")
70        || predicate == q_hash("q42:investmentDirective")
71    {
72        return DegradationVector::FiduciaryAdvice;
73    }
74
75    // Biosphere & Traditional Knowledge Vectors
76    if predicate == q_hash("q42:medicinalPlantUse")
77        || predicate == q_hash("q42:ethnobotanicalTherapy")
78        || predicate == q_hash("q42:bioactiveClaim")
79    {
80        return DegradationVector::EthnobotanicalMedicinal;
81    }
82    if predicate == q_hash("q42:definitiveTaxon")
83        || predicate == q_hash("q42:speciesIdentification")
84        || predicate == q_hash("q42:conservationStatusAsserted")
85    {
86        return DegradationVector::TaxonomicClassification;
87    }
88
89    DegradationVector::Unknown
90}
91
92/// The Linguistic Degradation Matrix.
93/// Hardcoded zero-heap degradation from definitive claims to Socratic/Probabilistic maps.
94pub fn degrade_claim_to_socratic(vector: DegradationVector) -> Option<SocraticDegradation> {
95    match vector {
96        DegradationVector::BiochemicalPathway => Some(SocraticDegradation {
97            probabilistic_map: "Mechanistic pathway exploration.",
98            socratic_prompt: "The provided variables map to a high-probability intersection with the metabolic pathway. Have you considered how localized environmental stressors or dietary inputs might influence this specific enzymatic response?",
99            immutable_disclaimer: BIO_DISCLAIMER,
100        }),
101        DegradationVector::ThermodynamicTracking => Some(SocraticDegradation {
102            probabilistic_map: "Thermodynamic / Energy Tracking.",
103            socratic_prompt: "This off-grid kinetic simulation indicates a potential deficit in localized caloric or hydration reserves under current thermal loads. What specific mitigation strategies are available to you within your current environmental constraints?",
104            immutable_disclaimer: BIO_DISCLAIMER,
105        }),
106        DegradationVector::GenomicPrivacy => Some(SocraticDegradation {
107            probabilistic_map: "Genomic Privacy Check.",
108            socratic_prompt: "This operation requires processing localized sequence alignments. Before executing, have you verified that your personal nquin graph is entirely isolated from external query routing to prevent unauthorized genetic aggregation?",
109            immutable_disclaimer: BIO_DISCLAIMER,
110        }),
111        DegradationVector::ContractualPower => Some(SocraticDegradation {
112            probabilistic_map: "Contractual Power Dynamics.",
113            socratic_prompt: "This contractual clause appears to grant Party A a *Power* while imposing a *Liability* on Party B. Have you considered how this imbalance interacts with standard tests for unconscionability or your fundamental rights under established human rights instruments?",
114            immutable_disclaimer: LEGAL_DISCLAIMER,
115        }),
116        DegradationVector::ProportionalityTest => Some(SocraticDegradation {
117            probabilistic_map: "Proportionality Testing.",
118            socratic_prompt: "The proposed action triggers a potential conflict between `[Duty X]` and `[Privilege Y]`. If applying a standard proportionality test, how would you weigh the advantages of this action against the systemic harms it might introduce?",
119            immutable_disclaimer: LEGAL_DISCLAIMER,
120        }),
121        DegradationVector::InteractionGovernance => Some(SocraticDegradation {
122            probabilistic_map: "Interaction Governance.",
123            socratic_prompt: "This decentralized governance policy suggests a strict duty-bearer enforcement protocol. Does this rigid structure allow for sufficient overriding rules in the event of a localized humanitarian emergency?",
124            immutable_disclaimer: LEGAL_DISCLAIMER,
125        }),
126        DegradationVector::FiduciaryAdvice => Some(SocraticDegradation {
127            probabilistic_map: "Mapping market thermodynamics.",
128            socratic_prompt: "Under what macro-economic phase shift does this asset distribution experience maximal catastrophic drawdown?",
129            immutable_disclaimer: "This system models economic thermodynamics. It does not provide certified fiduciary or investment advice.",
130        }),
131        DegradationVector::EthnobotanicalMedicinal => Some(SocraticDegradation {
132            probabilistic_map: "Ethnobotanical & Medicinal Plant Inquiry.",
133            socratic_prompt: "This record references traditional or phytotherapeutic usage. Have you cross-referenced these observations with authorized pharmacological databases and local custodial knowledge holders before drawing operational conclusions?",
134            immutable_disclaimer: BIOSPHERE_TRADITIONAL_KNOWLEDGE_DISCLAIMER,
135        }),
136        DegradationVector::TaxonomicClassification => Some(SocraticDegradation {
137            probabilistic_map: "Probabilistic Taxonomic Alignment.",
138            socratic_prompt: "The morphological or molecular markers indicate a likely match with this taxon. Have you verified diagnostic keys against verified museum vouchers or herbarium records to account for cryptic species boundaries?",
139            immutable_disclaimer: BIOSPHERE_TRADITIONAL_KNOWLEDGE_DISCLAIMER,
140        }),
141        DegradationVector::Unknown => None,
142    }
143}
144
145// ─── Guided Referral Triggers (acute physical harm / imminent legal jeopardy) ───────
146//
147// The Linguistic Degradation Matrix *softens* analytical claims into Socratic questions.
148// Some inputs cross a higher threshold: an acute physical-harm or imminent-legal-jeopardy
149// signal must NOT be merely softened — it must interrupt with an explicit, overriding
150// instruction to reach a human professional / emergency service *before* any analysis is
151// read. This is the hard liability gate the audit calls the "Guided Referral Trigger".
152
153/// The domain of an overriding referral.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum ReferralDomain {
156    /// Acute physical harm / medical crisis → emergency services.
157    MedicalEmergency,
158    /// Imminent legal jeopardy (arrest, custody, hard deadline) → licensed counsel.
159    LegalJeopardy,
160}
161
162/// An overriding referral that must be surfaced verbatim, *ahead of* any analytical output.
163/// Zero-heap (`&'static str`).
164#[derive(Debug, Clone, Copy)]
165pub struct ReferralTrigger {
166    pub domain: ReferralDomain,
167    pub overriding_prompt: &'static str,
168    pub immutable_disclaimer: &'static str,
169}
170
171/// Overriding prompt for acute physical-harm / medical-crisis signals.
172pub const EMERGENCY_PROMPT: &str = "\u{26A0} This appears to involve a risk of acute physical harm. This engine cannot help in an emergency and must not delay it. If you or someone else may be in danger, contact your local emergency services now (e.g. 000 in Australia, 911 in the US, 112 across the EU) or a crisis line. Any analysis below is educational only.";
173
174/// Overriding prompt for imminent-legal-jeopardy signals.
175pub const LEGAL_JEOPARDY_PROMPT: &str = "\u{26A0} This appears to involve imminent legal jeopardy (e.g. arrest, detention, or a hard filing deadline). This engine does not and cannot provide legal representation. Contact a licensed lawyer or your local legal-aid / community legal service before acting. Any analysis below is educational only.";
176
177/// The minimum `metadata` severity byte (0-255, low byte) at which an otherwise-analytical
178/// degradation vector is escalated to an overriding referral. See [`detect_referral_by_severity`].
179pub const REFERRAL_SEVERITY_FLOOR: u8 = 0xC0; // 192/255 ≈ "high-liability risk threshold"
180
181/// Detect whether a claim Quin crosses an **overriding** referral threshold via an explicit
182/// high-liability predicate (acute harm / imminent jeopardy). Predicate-driven, like
183/// [`identify_degradation_vector`]. Returns `None` for ordinary analytical claims (those go
184/// through the Linguistic Degradation Matrix instead).
185pub fn detect_referral_trigger(quin: &NQuin) -> Option<ReferralTrigger> {
186    let p = quin.predicate;
187    if p == q_hash("q42:acutePhysicalHarm")
188        || p == q_hash("q42:medicalEmergency")
189        || p == q_hash("q42:selfHarmRisk")
190        || p == q_hash("q42:overdoseRisk")
191    {
192        return Some(ReferralTrigger {
193            domain: ReferralDomain::MedicalEmergency,
194            overriding_prompt: EMERGENCY_PROMPT,
195            immutable_disclaimer: BIO_DISCLAIMER,
196        });
197    }
198    if p == q_hash("q42:imminentLegalJeopardy")
199        || p == q_hash("q42:arrestRisk")
200        || p == q_hash("q42:custodialThreat")
201        || p == q_hash("q42:filingDeadlineImminent")
202    {
203        return Some(ReferralTrigger {
204            domain: ReferralDomain::LegalJeopardy,
205            overriding_prompt: LEGAL_JEOPARDY_PROMPT,
206            immutable_disclaimer: LEGAL_DISCLAIMER,
207        });
208    }
209    None
210}
211
212/// Severity-driven escalation: an analytical degradation `vector` whose claim Quin carries a
213/// `metadata` low-byte severity at or above [`REFERRAL_SEVERITY_FLOOR`] is escalated from a
214/// Socratic softening to an overriding referral (medical for bio/thermo/genomic vectors;
215/// legal for contractual/proportionality/governance/fiduciary). Below the floor → `None`
216/// (the caller uses the Linguistic Degradation Matrix as normal).
217pub fn detect_referral_by_severity(
218    vector: DegradationVector,
219    metadata: u64,
220) -> Option<ReferralTrigger> {
221    let severity = (metadata & 0xFF) as u8;
222    if severity < REFERRAL_SEVERITY_FLOOR {
223        return None;
224    }
225    match vector {
226        DegradationVector::BiochemicalPathway
227        | DegradationVector::ThermodynamicTracking
228        | DegradationVector::GenomicPrivacy
229        | DegradationVector::EthnobotanicalMedicinal => Some(ReferralTrigger {
230            domain: ReferralDomain::MedicalEmergency,
231            overriding_prompt: EMERGENCY_PROMPT,
232            immutable_disclaimer: BIO_DISCLAIMER,
233        }),
234        DegradationVector::ContractualPower
235        | DegradationVector::ProportionalityTest
236        | DegradationVector::InteractionGovernance
237        | DegradationVector::FiduciaryAdvice => Some(ReferralTrigger {
238            domain: ReferralDomain::LegalJeopardy,
239            overriding_prompt: LEGAL_JEOPARDY_PROMPT,
240            immutable_disclaimer: LEGAL_DISCLAIMER,
241        }),
242        DegradationVector::TaxonomicClassification | DegradationVector::Unknown => None,
243    }
244}
245
246// ─── Structural refusal + nquin isolation (Semantic Shift) ──────────────────────────
247
248/// Structural refusal: predicates that assert a *definitive* state-classification — a medical
249/// diagnosis, legal verdict, or definitive biological taxon — must **never** be instantiated as-is.
250/// The engine emits the mechanistic / dialectical degradation ([`degrade_claim_to_socratic`]) instead of a
251/// directive. Returns `true` iff `predicate` is a forbidden definitive classification.
252pub fn forbids_definitive_classification(predicate: u64) -> bool {
253    predicate == q_hash("q42:medicalDiagnosis")
254        || predicate == q_hash("q42:diseaseClassification")
255        || predicate == q_hash("q42:legalVerdict")
256        || predicate == q_hash("q42:guiltDetermination")
257        || predicate == q_hash("q42:definitiveTaxon")
258        || predicate == q_hash("q42:ethnobotanicalTherapy")
259}
260
261/// Biosphere custodial guard: traditional knowledge and sensitive endangered species records
262/// must be protected from uncurated public scrape aggregation without custodial consent.
263pub fn requires_biosphere_custodial_quarantine(quin: &NQuin) -> bool {
264    matches!(
265        identify_degradation_vector(quin),
266        DegradationVector::EthnobotanicalMedicinal
267    ) || quin.predicate == q_hash("q42:sensitiveSpeciesExactLocation")
268        || quin.predicate == q_hash("q42:sacredSiteBoundary")
269}
270
271/// Nquin isolation guard: personal physiological / genomic data must be quarantined from
272/// public ontologies — processed as an abstract simulation, never aggregated or routed
273/// externally. Returns `true` iff the Quin carries content that must stay in a private
274/// subgraph (composes [`identify_degradation_vector`] plus explicit physiological predicates).
275pub fn requires_physiological_quarantine(quin: &NQuin) -> bool {
276    matches!(
277        identify_degradation_vector(quin),
278        DegradationVector::BiochemicalPathway | DegradationVector::GenomicPrivacy
279    ) || quin.predicate == q_hash("q42:physiologicalReading")
280        || quin.predicate == q_hash("q42:personalHealthRecord")
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    fn claim(predicate: &str, metadata: u64) -> NQuin {
288        let mut q = NQuin {
289            subject: q_hash("subj"),
290            predicate: q_hash(predicate),
291            object: 0,
292            context: 0,
293            metadata,
294            parity: 0,
295        };
296        q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
297        q
298    }
299
300    #[test]
301    fn degradation_matrix_softens_definitive_claims() {
302        // A medical-diagnosis claim degrades to a mechanistic Socratic map, never a directive.
303        let v = identify_degradation_vector(&claim("q42:medicalDiagnosis", 0));
304        assert_eq!(v, DegradationVector::BiochemicalPathway);
305        let d = degrade_claim_to_socratic(v).expect("medical claim degrades");
306        assert_eq!(d.immutable_disclaimer, BIO_DISCLAIMER);
307        assert!(d.socratic_prompt.contains("Have you considered"));
308        // A legal verdict degrades to the educational/jural map.
309        let lv = identify_degradation_vector(&claim("q42:legalVerdict", 0));
310        assert_eq!(lv, DegradationVector::ContractualPower);
311        assert_eq!(
312            degrade_claim_to_socratic(lv).unwrap().immutable_disclaimer,
313            LEGAL_DISCLAIMER
314        );
315        // An ordinary claim is untouched.
316        assert_eq!(
317            identify_degradation_vector(&claim("q42:hasColour", 0)),
318            DegradationVector::Unknown
319        );
320    }
321
322    #[test]
323    fn acute_harm_triggers_overriding_medical_referral() {
324        for p in [
325            "q42:acutePhysicalHarm",
326            "q42:medicalEmergency",
327            "q42:selfHarmRisk",
328            "q42:overdoseRisk",
329        ] {
330            let t =
331                detect_referral_trigger(&claim(p, 0)).expect("acute-harm predicate must trigger");
332            assert_eq!(t.domain, ReferralDomain::MedicalEmergency);
333            assert!(t.overriding_prompt.contains("emergency services"));
334        }
335        // A non-acute analytical claim does NOT trigger an overriding referral.
336        assert!(detect_referral_trigger(&claim("q42:medicalDiagnosis", 0)).is_none());
337    }
338
339    #[test]
340    fn imminent_jeopardy_triggers_overriding_legal_referral() {
341        for p in [
342            "q42:imminentLegalJeopardy",
343            "q42:arrestRisk",
344            "q42:custodialThreat",
345            "q42:filingDeadlineImminent",
346        ] {
347            let t = detect_referral_trigger(&claim(p, 0)).expect("jeopardy predicate must trigger");
348            assert_eq!(t.domain, ReferralDomain::LegalJeopardy);
349            assert!(t.overriding_prompt.contains("licensed lawyer"));
350        }
351    }
352
353    #[test]
354    fn severity_escalates_analytical_vectors_only_above_the_floor() {
355        // Below the floor: a high-but-not-critical biochemical claim stays analytical.
356        assert!(detect_referral_by_severity(DegradationVector::BiochemicalPathway, 0x80).is_none());
357        // At/above the floor: escalates to an overriding medical referral.
358        let t = detect_referral_by_severity(DegradationVector::BiochemicalPathway, 0xFF).unwrap();
359        assert_eq!(t.domain, ReferralDomain::MedicalEmergency);
360        // Legal-family vectors escalate to a legal referral.
361        let l = detect_referral_by_severity(
362            DegradationVector::ProportionalityTest,
363            REFERRAL_SEVERITY_FLOOR as u64,
364        )
365        .unwrap();
366        assert_eq!(l.domain, ReferralDomain::LegalJeopardy);
367        // Unknown never escalates.
368        assert!(detect_referral_by_severity(DegradationVector::Unknown, 0xFF).is_none());
369    }
370
371    #[test]
372    fn definitive_classifications_are_structurally_refused() {
373        assert!(forbids_definitive_classification(q_hash(
374            "q42:medicalDiagnosis"
375        )));
376        assert!(forbids_definitive_classification(q_hash(
377            "q42:legalVerdict"
378        )));
379        assert!(forbids_definitive_classification(q_hash(
380            "q42:guiltDetermination"
381        )));
382        // A mechanistic pathway predicate is allowed (it is the *permitted* mechanistic output).
383        assert!(!forbids_definitive_classification(q_hash(
384            "q42:biochemicalPathway"
385        )));
386    }
387
388    #[test]
389    fn physiological_data_is_quarantined_from_public_ontologies() {
390        assert!(requires_physiological_quarantine(&claim(
391            "q42:medicalDiagnosis",
392            0
393        )));
394        assert!(requires_physiological_quarantine(&claim(
395            "q42:genomicAlignment",
396            0
397        )));
398        assert!(requires_physiological_quarantine(&claim(
399            "q42:physiologicalReading",
400            0
401        )));
402        // A purely legal claim does not need physiological quarantine.
403        assert!(!requires_physiological_quarantine(&claim(
404            "q42:contractualClause",
405            0
406        )));
407    }
408}