Skip to main content

qualia_core_db/modalities/
inference_guard.rs

1//! Graph-backed inference guard.
2//!
3//! This is the small, deterministic boundary between a generative backend and
4//! the semantic graph. It deliberately returns an action rather than emitting
5//! text: the caller owns rollback, UI copy, and any corrective prompt.
6
7use crate::modalities::epistemic::agent_knows;
8use crate::modalities::interaction_governance::{map_policy, Governance, PolicyMode};
9use crate::modalities::logic::deontic::{
10    harvest_defeater_fingerprints, norm_lifecycle_status, DeonticStatus, MAX_DEFEATER_SLOTS,
11};
12use crate::modalities::paraconsistent::route_paraconsistent;
13use crate::modalities::temporal_ltl::{evaluate_ltl_trace, LtlFormula};
14use crate::NQuin;
15
16/// Maximum graph facts that the browser guard admits in one pass. This keeps
17/// its two caller-owned scratch buffers below 25 KiB.
18pub const MAX_GUARD_GRAPH_QUINS: usize = 256;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum InferenceGuardAction {
22    Allow,
23    /// Do not use the unqualified result; the caller should retry with the
24    /// stated graph constraint in its prompt.
25    Steer,
26    /// Stop generation or roll back the current token stream.
27    Deny,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum InferenceGuardReason {
32    None,
33    DeonticViolation,
34    TemporalViolation,
35    MissingKnowledge,
36    ContradictoryGraph,
37    GraphCapacityExceeded,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct InferenceGuardVerdict {
42    pub action: InferenceGuardAction,
43    pub reason: InferenceGuardReason,
44    pub isolated_count: usize,
45}
46
47impl InferenceGuardVerdict {
48    const fn allow() -> Self {
49        Self {
50            action: InferenceGuardAction::Allow,
51            reason: InferenceGuardReason::None,
52            isolated_count: 0,
53        }
54    }
55}
56
57/// Evaluate graph logic before (or between tokens of) inference.
58///
59/// `non_derogable` is graph policy classification for the supplied norms. A
60/// violated non-derogable norm maps to `DenyRollback`; an ordinary violation
61/// maps to `Steer`, preserving the existing audit-first policy semantics.
62/// `required_claim == 0` and `temporal_invariant == 0` disable their respective
63/// checks, which lets callers compose only the logics relevant to a request.
64pub fn evaluate_inference_guard(
65    norms: &[NQuin],
66    facts: &[NQuin],
67    epistemic: &[NQuin],
68    trace: &[NQuin],
69    actor: u64,
70    required_claim: u64,
71    temporal_invariant: u64,
72    now_unix: u32,
73    non_derogable: bool,
74) -> InferenceGuardVerdict {
75    if facts.len() > MAX_GUARD_GRAPH_QUINS {
76        return InferenceGuardVerdict {
77            action: InferenceGuardAction::Steer,
78            reason: InferenceGuardReason::GraphCapacityExceeded,
79            isolated_count: 0,
80        };
81    }
82
83    // Temporal safety is a hard guard: a continuous invariant that has already
84    // failed cannot be repaired by an LLM completion.
85    if temporal_invariant != 0
86        && !evaluate_ltl_trace(trace, &LtlFormula::Globally(temporal_invariant))
87    {
88        return InferenceGuardVerdict {
89            action: InferenceGuardAction::Deny,
90            reason: InferenceGuardReason::TemporalViolation,
91            isolated_count: 0,
92        };
93    }
94
95    let mut defeaters = [0u64; MAX_DEFEATER_SLOTS];
96    let defeater_count = harvest_defeater_fingerprints(norms, &mut defeaters);
97    for norm in norms {
98        if norm_lifecycle_status(norm, now_unix, 0, &defeaters[..defeater_count], facts)
99            == DeonticStatus::Violated
100        {
101            let policy = map_policy(
102                DeonticStatus::Violated,
103                Governance {
104                    non_derogable,
105                    humanitarian: false,
106                    ambiguous: false,
107                },
108            );
109            return InferenceGuardVerdict {
110                action: if policy == PolicyMode::PreventiveBlock {
111                    InferenceGuardAction::Deny
112                } else {
113                    InferenceGuardAction::Steer
114                },
115                reason: InferenceGuardReason::DeonticViolation,
116                isolated_count: 0,
117            };
118        }
119    }
120
121    if required_claim != 0 && !agent_knows(epistemic, actor, required_claim) {
122        return InferenceGuardVerdict {
123            action: InferenceGuardAction::Steer,
124            reason: InferenceGuardReason::MissingKnowledge,
125            isolated_count: 0,
126        };
127    }
128
129    let mut consistent = [NQuin::default(); MAX_GUARD_GRAPH_QUINS];
130    let mut isolated = [NQuin::default(); MAX_GUARD_GRAPH_QUINS];
131    match route_paraconsistent(facts, &mut consistent, &mut isolated) {
132        Ok((_, isolated_count)) if isolated_count != 0 => InferenceGuardVerdict {
133            action: InferenceGuardAction::Steer,
134            reason: InferenceGuardReason::ContradictoryGraph,
135            isolated_count,
136        },
137        Ok(_) => InferenceGuardVerdict::allow(),
138        // Capacity was checked above, so an error is a conservative deferral.
139        Err(_) => InferenceGuardVerdict {
140            action: InferenceGuardAction::Steer,
141            reason: InferenceGuardReason::GraphCapacityExceeded,
142            isolated_count: 0,
143        },
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use crate::modalities::epistemic::{CERTAINTY_BIT_SHIFT, OP_KNOWS};
151    use crate::modalities::logic::deontic::OP_FORBID;
152    use crate::q_hash;
153
154    fn quin(subject: u64, predicate: u64, object: u64, context: u64) -> NQuin {
155        NQuin {
156            subject,
157            predicate,
158            object,
159            context,
160            metadata: 0,
161            parity: subject ^ predicate ^ object ^ context,
162        }
163    }
164
165    #[test]
166    fn non_derogable_prohibition_denies_inference() {
167        let actor = q_hash("did:demo:agent");
168        let action = q_hash("q42:publishSensitiveRecord");
169        let norm = quin(actor, OP_FORBID as u64, action, q_hash("q42:policy"));
170        let fact = quin(actor, q_hash("q42:performed"), action, q_hash("q42:policy"));
171        let verdict = evaluate_inference_guard(&[norm], &[fact], &[], &[], actor, 0, 0, 1, true);
172        assert_eq!(verdict.action, InferenceGuardAction::Deny);
173        assert_eq!(verdict.reason, InferenceGuardReason::DeonticViolation);
174    }
175
176    #[test]
177    fn missing_knowledge_steers_without_blocking() {
178        let actor = q_hash("did:demo:agent");
179        let claim = q_hash("q42:verifiedSource");
180        let verdict = evaluate_inference_guard(&[], &[], &[], &[], actor, claim, 0, 1, false);
181        assert_eq!(verdict.action, InferenceGuardAction::Steer);
182        assert_eq!(verdict.reason, InferenceGuardReason::MissingKnowledge);
183
184        let knowledge = quin(
185            actor,
186            OP_KNOWS as u64 | ((255u64) << CERTAINTY_BIT_SHIFT),
187            claim,
188            q_hash("q42:world"),
189        );
190        assert_eq!(
191            evaluate_inference_guard(&[], &[], &[knowledge], &[], actor, claim, 0, 1, false).action,
192            InferenceGuardAction::Allow
193        );
194    }
195
196    #[test]
197    fn failed_temporal_invariant_denies() {
198        let safe = q_hash("q42:safetyChecked");
199        let trace = [quin(1, safe, 0, 1), quin(1, q_hash("q42:unsafe"), 0, 1)];
200        let verdict = evaluate_inference_guard(&[], &[], &[], &trace, 0, 0, safe, 1, false);
201        assert_eq!(verdict.reason, InferenceGuardReason::TemporalViolation);
202        assert_eq!(verdict.action, InferenceGuardAction::Deny);
203    }
204
205    #[test]
206    fn contradiction_isolated_then_steered() {
207        let predicate = q_hash("q42:recordStatus");
208        let facts = [quin(1, predicate, 10, 9), quin(1, predicate, 11, 9)];
209        let verdict = evaluate_inference_guard(&[], &facts, &[], &[], 0, 0, 0, 1, false);
210        assert_eq!(verdict.action, InferenceGuardAction::Steer);
211        assert_eq!(verdict.reason, InferenceGuardReason::ContradictoryGraph);
212        assert_eq!(verdict.isolated_count, 1);
213    }
214}