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    Unknown,
23}
24
25/// Immutable UI-rendering disclaimer for any biological / physiological / thermodynamic
26/// analysis. Hardcoded verbatim from the audit spec (Systemic Biological Framework).
27pub 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.";
28
29/// Immutable UI-rendering disclaimer for any jural / deontic / rights analysis. Hardcoded
30/// verbatim from the audit spec (Systemic Jural & Legal Framework).
31pub 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.";
32
33/// Identifies if a Quin encodes a definitive claim that crosses Epistemic Boundaries.
34pub fn identify_degradation_vector(quin: &NQuin) -> DegradationVector {
35    let predicate = quin.predicate;
36
37    // Medical/Biological Vectors
38    if predicate == q_hash("q42:biochemicalPathway") || predicate == q_hash("q42:medicalDiagnosis")
39    {
40        return DegradationVector::BiochemicalPathway;
41    }
42    if predicate == q_hash("q42:thermodynamicState") || predicate == q_hash("q42:kineticSimulation")
43    {
44        return DegradationVector::ThermodynamicTracking;
45    }
46    if predicate == q_hash("q42:genomicAlignment") || predicate == q_hash("q42:sequenceProcessing")
47    {
48        return DegradationVector::GenomicPrivacy;
49    }
50
51    // Legal/Jural Vectors
52    if predicate == q_hash("q42:contractualClause") || predicate == q_hash("q42:legalVerdict") {
53        return DegradationVector::ContractualPower;
54    }
55    if predicate == q_hash("q42:proportionalityTest") || predicate == q_hash("q42:rightsConflict") {
56        return DegradationVector::ProportionalityTest;
57    }
58    if predicate == q_hash("q42:governancePolicy") || predicate == q_hash("q42:enforcementProtocol")
59    {
60        return DegradationVector::InteractionGovernance;
61    }
62
63    // Fiduciary Vectors
64    if predicate == q_hash("q42:financialFiduciary")
65        || predicate == q_hash("q42:investmentDirective")
66    {
67        return DegradationVector::FiduciaryAdvice;
68    }
69
70    DegradationVector::Unknown
71}
72
73/// The Linguistic Degradation Matrix.
74/// Hardcoded zero-heap degradation from definitive claims to Socratic/Probabilistic maps.
75pub fn degrade_claim_to_socratic(vector: DegradationVector) -> Option<SocraticDegradation> {
76    match vector {
77        DegradationVector::BiochemicalPathway => Some(SocraticDegradation {
78            probabilistic_map: "Mechanistic pathway exploration.",
79            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?",
80            immutable_disclaimer: BIO_DISCLAIMER,
81        }),
82        DegradationVector::ThermodynamicTracking => Some(SocraticDegradation {
83            probabilistic_map: "Thermodynamic / Energy Tracking.",
84            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?",
85            immutable_disclaimer: BIO_DISCLAIMER,
86        }),
87        DegradationVector::GenomicPrivacy => Some(SocraticDegradation {
88            probabilistic_map: "Genomic Privacy Check.",
89            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?",
90            immutable_disclaimer: BIO_DISCLAIMER,
91        }),
92        DegradationVector::ContractualPower => Some(SocraticDegradation {
93            probabilistic_map: "Contractual Power Dynamics.",
94            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?",
95            immutable_disclaimer: LEGAL_DISCLAIMER,
96        }),
97        DegradationVector::ProportionalityTest => Some(SocraticDegradation {
98            probabilistic_map: "Proportionality Testing.",
99            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?",
100            immutable_disclaimer: LEGAL_DISCLAIMER,
101        }),
102        DegradationVector::InteractionGovernance => Some(SocraticDegradation {
103            probabilistic_map: "Interaction Governance.",
104            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?",
105            immutable_disclaimer: LEGAL_DISCLAIMER,
106        }),
107        DegradationVector::FiduciaryAdvice => Some(SocraticDegradation {
108            probabilistic_map: "Mapping market thermodynamics.",
109            socratic_prompt: "Under what macro-economic phase shift does this asset distribution experience maximal catastrophic drawdown?",
110            immutable_disclaimer: "This system models economic thermodynamics. It does not provide certified fiduciary or investment advice.",
111        }),
112        DegradationVector::Unknown => None,
113    }
114}
115
116// ─── Guided Referral Triggers (acute physical harm / imminent legal jeopardy) ───────
117//
118// The Linguistic Degradation Matrix *softens* analytical claims into Socratic questions.
119// Some inputs cross a higher threshold: an acute physical-harm or imminent-legal-jeopardy
120// signal must NOT be merely softened — it must interrupt with an explicit, overriding
121// instruction to reach a human professional / emergency service *before* any analysis is
122// read. This is the hard liability gate the audit calls the "Guided Referral Trigger".
123
124/// The domain of an overriding referral.
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum ReferralDomain {
127    /// Acute physical harm / medical crisis → emergency services.
128    MedicalEmergency,
129    /// Imminent legal jeopardy (arrest, custody, hard deadline) → licensed counsel.
130    LegalJeopardy,
131}
132
133/// An overriding referral that must be surfaced verbatim, *ahead of* any analytical output.
134/// Zero-heap (`&'static str`).
135#[derive(Debug, Clone, Copy)]
136pub struct ReferralTrigger {
137    pub domain: ReferralDomain,
138    pub overriding_prompt: &'static str,
139    pub immutable_disclaimer: &'static str,
140}
141
142/// Overriding prompt for acute physical-harm / medical-crisis signals.
143pub 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.";
144
145/// Overriding prompt for imminent-legal-jeopardy signals.
146pub 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.";
147
148/// The minimum `metadata` severity byte (0-255, low byte) at which an otherwise-analytical
149/// degradation vector is escalated to an overriding referral. See [`detect_referral_by_severity`].
150pub const REFERRAL_SEVERITY_FLOOR: u8 = 0xC0; // 192/255 ≈ "high-liability risk threshold"
151
152/// Detect whether a claim Quin crosses an **overriding** referral threshold via an explicit
153/// high-liability predicate (acute harm / imminent jeopardy). Predicate-driven, like
154/// [`identify_degradation_vector`]. Returns `None` for ordinary analytical claims (those go
155/// through the Linguistic Degradation Matrix instead).
156pub fn detect_referral_trigger(quin: &NQuin) -> Option<ReferralTrigger> {
157    let p = quin.predicate;
158    if p == q_hash("q42:acutePhysicalHarm")
159        || p == q_hash("q42:medicalEmergency")
160        || p == q_hash("q42:selfHarmRisk")
161        || p == q_hash("q42:overdoseRisk")
162    {
163        return Some(ReferralTrigger {
164            domain: ReferralDomain::MedicalEmergency,
165            overriding_prompt: EMERGENCY_PROMPT,
166            immutable_disclaimer: BIO_DISCLAIMER,
167        });
168    }
169    if p == q_hash("q42:imminentLegalJeopardy")
170        || p == q_hash("q42:arrestRisk")
171        || p == q_hash("q42:custodialThreat")
172        || p == q_hash("q42:filingDeadlineImminent")
173    {
174        return Some(ReferralTrigger {
175            domain: ReferralDomain::LegalJeopardy,
176            overriding_prompt: LEGAL_JEOPARDY_PROMPT,
177            immutable_disclaimer: LEGAL_DISCLAIMER,
178        });
179    }
180    None
181}
182
183/// Severity-driven escalation: an analytical degradation `vector` whose claim Quin carries a
184/// `metadata` low-byte severity at or above [`REFERRAL_SEVERITY_FLOOR`] is escalated from a
185/// Socratic softening to an overriding referral (medical for bio/thermo/genomic vectors;
186/// legal for contractual/proportionality/governance/fiduciary). Below the floor → `None`
187/// (the caller uses the Linguistic Degradation Matrix as normal).
188pub fn detect_referral_by_severity(
189    vector: DegradationVector,
190    metadata: u64,
191) -> Option<ReferralTrigger> {
192    let severity = (metadata & 0xFF) as u8;
193    if severity < REFERRAL_SEVERITY_FLOOR {
194        return None;
195    }
196    match vector {
197        DegradationVector::BiochemicalPathway
198        | DegradationVector::ThermodynamicTracking
199        | DegradationVector::GenomicPrivacy => Some(ReferralTrigger {
200            domain: ReferralDomain::MedicalEmergency,
201            overriding_prompt: EMERGENCY_PROMPT,
202            immutable_disclaimer: BIO_DISCLAIMER,
203        }),
204        DegradationVector::ContractualPower
205        | DegradationVector::ProportionalityTest
206        | DegradationVector::InteractionGovernance
207        | DegradationVector::FiduciaryAdvice => Some(ReferralTrigger {
208            domain: ReferralDomain::LegalJeopardy,
209            overriding_prompt: LEGAL_JEOPARDY_PROMPT,
210            immutable_disclaimer: LEGAL_DISCLAIMER,
211        }),
212        DegradationVector::Unknown => None,
213    }
214}
215
216// ─── Structural refusal + nquin isolation (Semantic Shift) ──────────────────────────
217
218/// Structural refusal: predicates that assert a *definitive* state-classification — a medical
219/// diagnosis or a legal verdict — must **never** be instantiated as-is. The engine emits the
220/// mechanistic / dialectical degradation ([`degrade_claim_to_socratic`]) instead of a
221/// directive. Returns `true` iff `predicate` is a forbidden definitive classification.
222pub fn forbids_definitive_classification(predicate: u64) -> bool {
223    predicate == q_hash("q42:medicalDiagnosis")
224        || predicate == q_hash("q42:diseaseClassification")
225        || predicate == q_hash("q42:legalVerdict")
226        || predicate == q_hash("q42:guiltDetermination")
227}
228
229/// Nquin isolation guard: personal physiological / genomic data must be quarantined from
230/// public ontologies — processed as an abstract simulation, never aggregated or routed
231/// externally. Returns `true` iff the Quin carries content that must stay in a private
232/// subgraph (composes [`identify_degradation_vector`] plus explicit physiological predicates).
233pub fn requires_physiological_quarantine(quin: &NQuin) -> bool {
234    matches!(
235        identify_degradation_vector(quin),
236        DegradationVector::BiochemicalPathway | DegradationVector::GenomicPrivacy
237    ) || quin.predicate == q_hash("q42:physiologicalReading")
238        || quin.predicate == q_hash("q42:personalHealthRecord")
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    fn claim(predicate: &str, metadata: u64) -> NQuin {
246        let mut q = NQuin {
247            subject: q_hash("subj"),
248            predicate: q_hash(predicate),
249            object: 0,
250            context: 0,
251            metadata,
252            parity: 0,
253        };
254        q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
255        q
256    }
257
258    #[test]
259    fn degradation_matrix_softens_definitive_claims() {
260        // A medical-diagnosis claim degrades to a mechanistic Socratic map, never a directive.
261        let v = identify_degradation_vector(&claim("q42:medicalDiagnosis", 0));
262        assert_eq!(v, DegradationVector::BiochemicalPathway);
263        let d = degrade_claim_to_socratic(v).expect("medical claim degrades");
264        assert_eq!(d.immutable_disclaimer, BIO_DISCLAIMER);
265        assert!(d.socratic_prompt.contains("Have you considered"));
266        // A legal verdict degrades to the educational/jural map.
267        let lv = identify_degradation_vector(&claim("q42:legalVerdict", 0));
268        assert_eq!(lv, DegradationVector::ContractualPower);
269        assert_eq!(
270            degrade_claim_to_socratic(lv).unwrap().immutable_disclaimer,
271            LEGAL_DISCLAIMER
272        );
273        // An ordinary claim is untouched.
274        assert_eq!(
275            identify_degradation_vector(&claim("q42:hasColour", 0)),
276            DegradationVector::Unknown
277        );
278    }
279
280    #[test]
281    fn acute_harm_triggers_overriding_medical_referral() {
282        for p in [
283            "q42:acutePhysicalHarm",
284            "q42:medicalEmergency",
285            "q42:selfHarmRisk",
286            "q42:overdoseRisk",
287        ] {
288            let t =
289                detect_referral_trigger(&claim(p, 0)).expect("acute-harm predicate must trigger");
290            assert_eq!(t.domain, ReferralDomain::MedicalEmergency);
291            assert!(t.overriding_prompt.contains("emergency services"));
292        }
293        // A non-acute analytical claim does NOT trigger an overriding referral.
294        assert!(detect_referral_trigger(&claim("q42:medicalDiagnosis", 0)).is_none());
295    }
296
297    #[test]
298    fn imminent_jeopardy_triggers_overriding_legal_referral() {
299        for p in [
300            "q42:imminentLegalJeopardy",
301            "q42:arrestRisk",
302            "q42:custodialThreat",
303            "q42:filingDeadlineImminent",
304        ] {
305            let t = detect_referral_trigger(&claim(p, 0)).expect("jeopardy predicate must trigger");
306            assert_eq!(t.domain, ReferralDomain::LegalJeopardy);
307            assert!(t.overriding_prompt.contains("licensed lawyer"));
308        }
309    }
310
311    #[test]
312    fn severity_escalates_analytical_vectors_only_above_the_floor() {
313        // Below the floor: a high-but-not-critical biochemical claim stays analytical.
314        assert!(detect_referral_by_severity(DegradationVector::BiochemicalPathway, 0x80).is_none());
315        // At/above the floor: escalates to an overriding medical referral.
316        let t = detect_referral_by_severity(DegradationVector::BiochemicalPathway, 0xFF).unwrap();
317        assert_eq!(t.domain, ReferralDomain::MedicalEmergency);
318        // Legal-family vectors escalate to a legal referral.
319        let l = detect_referral_by_severity(
320            DegradationVector::ProportionalityTest,
321            REFERRAL_SEVERITY_FLOOR as u64,
322        )
323        .unwrap();
324        assert_eq!(l.domain, ReferralDomain::LegalJeopardy);
325        // Unknown never escalates.
326        assert!(detect_referral_by_severity(DegradationVector::Unknown, 0xFF).is_none());
327    }
328
329    #[test]
330    fn definitive_classifications_are_structurally_refused() {
331        assert!(forbids_definitive_classification(q_hash(
332            "q42:medicalDiagnosis"
333        )));
334        assert!(forbids_definitive_classification(q_hash(
335            "q42:legalVerdict"
336        )));
337        assert!(forbids_definitive_classification(q_hash(
338            "q42:guiltDetermination"
339        )));
340        // A mechanistic pathway predicate is allowed (it is the *permitted* mechanistic output).
341        assert!(!forbids_definitive_classification(q_hash(
342            "q42:biochemicalPathway"
343        )));
344    }
345
346    #[test]
347    fn physiological_data_is_quarantined_from_public_ontologies() {
348        assert!(requires_physiological_quarantine(&claim(
349            "q42:medicalDiagnosis",
350            0
351        )));
352        assert!(requires_physiological_quarantine(&claim(
353            "q42:genomicAlignment",
354            0
355        )));
356        assert!(requires_physiological_quarantine(&claim(
357            "q42:physiologicalReading",
358            0
359        )));
360        // A purely legal claim does not need physiological quarantine.
361        assert!(!requires_physiological_quarantine(&claim(
362            "q42:contractualClause",
363            0
364        )));
365    }
366}