Skip to main content

qualia_core_db/modalities/logic/
n3_compiler.rs

1//! N3Logic → SHACL → Sentinel Bytecode compiler (CogAI symbolic layer).
2//!
3//! The LLM emits N3 assertions on the cold path; this module validates them against
4//! compiled SHACL shapes from [`crate::modalities::logic::shacl`] and lowers surviving rules to
5//! [`SlgOpcode`] sequences for the Core-1 Webizen VM. Hot-path execution uses only
6//! fixed caller-supplied buffers.
7
8use crate::modalities::logic::n3_parser::{Formula, Rule, RuleType, Term, Triple};
9use crate::modalities::logic::shacl::{
10    CompiledShape, ShaclCompiler, ShaclConstraint, ShaclSeverity,
11};
12use crate::q_hash;
13use crate::webizen::{execute_vm_frame, SlgArena, SlgOpcode, VmFrame};
14use crate::NQuin;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum CompiledTerm {
18    Uri(u64),
19    Variable(u64),
20    Literal(u64),
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct CompiledTriple {
25    pub subject: CompiledTerm,
26    pub predicate: CompiledTerm,
27    pub object: CompiledTerm,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct CompiledFormula {
32    pub triples: [CompiledTriple; 8],
33    pub len: usize,
34}
35
36impl Default for CompiledFormula {
37    /// An empty formula: 8 zeroed triple slots, `len` 0.
38    fn default() -> Self {
39        Self {
40            triples: [CompiledTriple {
41                subject: CompiledTerm::Uri(0),
42                predicate: CompiledTerm::Uri(0),
43                object: CompiledTerm::Uri(0),
44            }; 8],
45            len: 0,
46        }
47    }
48}
49
50#[derive(Debug, Clone, PartialEq)]
51pub struct CompiledRule {
52    pub id_hash: Option<u64>,
53    pub rule_type: RuleType,
54    pub weight: Option<f32>,
55    pub premise: CompiledFormula,
56    pub conclusion: CompiledFormula,
57}
58
59impl CompiledTerm {
60    /// The term's hash payload regardless of variant — callers
61    /// distinguishing roles must check `is_variable` first.
62    pub fn as_u64(&self) -> u64 {
63        match self {
64            CompiledTerm::Uri(h) => *h,
65            CompiledTerm::Variable(h) => *h,
66            CompiledTerm::Literal(h) => *h,
67        }
68    }
69
70    /// True when the term is a rule variable (unifiable slot) rather
71    /// than a URI or literal.
72    pub fn is_variable(&self) -> bool {
73        matches!(self, CompiledTerm::Variable(_))
74    }
75}
76
77/// Hash-lower a parsed N3 `Term` to a `CompiledTerm`, preserving the
78/// variable/literal/URI distinction. Variables hash their name; an
79/// unhashable non-variable falls back to `q_hash("?")`.
80pub fn compile_term(term: &Term<'_>) -> CompiledTerm {
81    let hash =
82        crate::modalities::logic::n3_parser::term_uri_hash(term).unwrap_or_else(|| match term {
83            Term::Variable(name) => q_hash(name),
84            _ => q_hash("?"),
85        });
86    match term {
87        Term::Variable(_) => CompiledTerm::Variable(hash),
88        Term::Literal(_) => CompiledTerm::Literal(hash),
89        _ => CompiledTerm::Uri(hash),
90    }
91}
92
93/// Compile a parsed triple — each of subject/predicate/object lowered
94/// via [`compile_term`].
95pub fn compile_triple(triple: &Triple<'_>) -> CompiledTriple {
96    CompiledTriple {
97        subject: compile_term(&triple.subject),
98        predicate: compile_term(&triple.predicate),
99        object: compile_term(&triple.object),
100    }
101}
102
103/// Compile a formula into the fixed 8-triple `CompiledFormula` buffer;
104/// triples beyond the cap are silently truncated.
105pub fn compile_formula(formula: &Formula<'_>) -> CompiledFormula {
106    let mut comp = CompiledFormula::default();
107    for (i, t) in formula.triples.iter().enumerate().take(8) {
108        comp.triples[i] = compile_triple(t);
109        comp.len += 1;
110    }
111    comp
112}
113
114/// Compile an entire parsed N3 rule (id, arrow type, weight, premise,
115/// conclusion) into the zero-heap `CompiledRule` form.
116pub fn compile_rule_to_zero_heap(rule: &Rule<'_>) -> CompiledRule {
117    CompiledRule {
118        id_hash: rule.id.map(q_hash),
119        rule_type: rule.rule_type,
120        weight: rule.weight,
121        premise: compile_formula(&rule.premise),
122        conclusion: compile_formula(&rule.conclusion),
123    }
124}
125
126pub const MAX_COMPILED_OPCODES: usize = 256;
127pub const MAX_COMPILED_QUINS: usize = 64;
128pub const MAX_INTENT_SCOPE_SLOTS: usize = 16;
129pub const MAX_CONTEXT_NAMESPACE_SLOTS: usize = 16;
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
132pub enum N3OutputMode {
133    FreeText,
134    N3Assertions,
135    GraphMutation,
136    SummarizeOnly,
137}
138
139impl Default for N3OutputMode {
140    /// `FreeText` — the least restrictive output mode.
141    fn default() -> Self {
142        Self::FreeText
143    }
144}
145
146#[derive(Debug, PartialEq, Eq)]
147pub enum N3CompileError {
148    EmptyRule,
149    MalformedTriple,
150    UnsupportedRuleType,
151    ShapeViolation,
152    OpcodeBufferFull,
153    QuinBufferFull,
154    SentinelMemoryOverflow,
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum SentinelError {
159    MemoryOverflow,
160}
161
162#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
163pub struct N3CompiledProgram {
164    pub opcode_count: usize,
165    pub quin_count: usize,
166}
167
168#[repr(C)]
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub struct AgentIntentFrame {
171    pub intent_predicate: u64,
172    pub principal_did_hash: u64,
173    pub mcp_intent_frame_hash: u64,
174    pub ilp_offer_micro_cents: u64,
175    pub scope_count: u8,
176    pub context_namespace_count: u8,
177    pub requires_network: bool,
178    pub output_mode: N3OutputMode,
179    pub clearance_ceiling: u8,
180    pub max_sentinel_depth: u8,
181    pub graph_scope: [u64; MAX_INTENT_SCOPE_SLOTS],
182    pub context_namespaces: [u64; MAX_CONTEXT_NAMESPACE_SLOTS],
183}
184
185/// Strict term hashing for shape validation: URIs and literals hash
186/// their payload, formulas use the dedicated `q_hash_formula`, and
187/// variables are `MalformedTriple` — a shape-gated conclusion cannot
188/// contain unbound variables.
189fn term_hash(term: &Term<'_>) -> Result<u64, N3CompileError> {
190    match term {
191        Term::Uri(uri) => Ok(q_hash(uri)),
192        Term::Literal(lit) => Ok(q_hash(lit)),
193        Term::Formula(s) => Ok(crate::modalities::logic::n3_parser::q_hash_formula(s)),
194        Term::Variable(_) => Err(N3CompileError::MalformedTriple),
195    }
196}
197
198/// Pack a compiled triple into an `NQuin` under `context`, computing the
199/// XOR-fold parity. Never fails at present — the `Result` preserves the
200/// signature for future checks.
201pub fn triple_to_quin(triple: &CompiledTriple, context: u64) -> Result<NQuin, N3CompileError> {
202    let mut quin = NQuin::default();
203    quin.subject = triple.subject.as_u64();
204    quin.predicate = triple.predicate.as_u64();
205    quin.object = triple.object.as_u64();
206    quin.context = context;
207    quin.parity = quin.subject ^ quin.predicate ^ quin.object ^ quin.context;
208    Ok(quin)
209}
210
211/// Borrow the formula's first triple; `MalformedTriple` when `len` is
212/// 0 (multi-triple bodies keep only the head per the compiler's current
213/// limitation).
214fn first_triple<'a>(
215    f: &'a crate::modalities::logic::n3_compiler::CompiledFormula,
216) -> Result<&'a crate::modalities::logic::n3_compiler::CompiledTriple, N3CompileError> {
217    f.triples.first().ok_or(N3CompileError::MalformedTriple)
218}
219
220/// Returns true when every conclusion triple property path matches a compiled SHACL shape.
221pub fn validate_rule_against_shapes(
222    rule: &Rule<'_>,
223    shapes: &[&CompiledShape],
224) -> Result<(), N3CompileError> {
225    if shapes.is_empty() {
226        return Ok(());
227    }
228    let conclusion = rule
229        .conclusion
230        .triples
231        .first()
232        .ok_or(N3CompileError::MalformedTriple)?;
233    let property_hash = term_hash(&conclusion.predicate)?;
234    let mut matched = false;
235    for shape in shapes {
236        if q_hash(&shape.property_path) == property_hash {
237            matched = true;
238            if let Term::Literal(lit) = &conclusion.object {
239                if let Ok(value) = lit.parse::<f64>() {
240                    if !shape.evaluate_numeric(value) {
241                        return Err(N3CompileError::ShapeViolation);
242                    }
243                }
244            }
245        }
246    }
247    if matched {
248        Ok(())
249    } else {
250        Err(N3CompileError::ShapeViolation)
251    }
252}
253
254/// Append one opcode to the caller buffer via `count`;
255/// `OpcodeBufferFull` when `out` is exhausted — compile fails closed
256/// rather than truncating a program.
257fn push_opcode(
258    out: &mut [SlgOpcode],
259    count: &mut usize,
260    opcode: SlgOpcode,
261) -> Result<(), N3CompileError> {
262    if *count >= out.len() {
263        return Err(N3CompileError::OpcodeBufferFull);
264    }
265    out[*count] = opcode;
266    *count += 1;
267    Ok(())
268}
269
270/// Lower one N3 rule into Sentinel opcodes (reuses SHACL terminal semantics).
271pub fn compile_rule_to_opcodes(
272    rule: &CompiledRule,
273    out: &mut [SlgOpcode],
274) -> Result<usize, N3CompileError> {
275    let mut count = 0usize;
276    match rule.rule_type {
277        RuleType::Strict => {
278            push_opcode(out, &mut count, SlgOpcode::Unify)?;
279            push_opcode(out, &mut count, SlgOpcode::Call)?;
280            push_opcode(out, &mut count, SlgOpcode::Halt)?;
281        }
282        RuleType::Defeasible => {
283            push_opcode(out, &mut count, SlgOpcode::CheckDefeaters)?;
284            push_opcode(out, &mut count, SlgOpcode::Unify)?;
285            push_opcode(out, &mut count, SlgOpcode::Call)?;
286            push_opcode(out, &mut count, SlgOpcode::WarnOnly)?;
287        }
288        RuleType::Defeater => {
289            push_opcode(out, &mut count, SlgOpcode::NativeUnless)?;
290            push_opcode(out, &mut count, SlgOpcode::Halt)?;
291        }
292        RuleType::Linear => {
293            push_opcode(out, &mut count, SlgOpcode::NativeLinearConsume)?;
294            push_opcode(out, &mut count, SlgOpcode::Unify)?;
295            push_opcode(out, &mut count, SlgOpcode::Call)?;
296            push_opcode(out, &mut count, SlgOpcode::Halt)?;
297        }
298    }
299    Ok(count)
300}
301
302/// Emit a compiled rule as `NQuin`(s): deontic-lowerable rules produce a
303/// single norm quin via `compile_n3_rule_to_norm`; other rules fall back
304/// to one fact quin per formula head triple. `QuinBufferFull` when `out`
305/// can't hold the result.
306pub fn compile_rule_to_quin(
307    rule: &CompiledRule,
308    contract_hash: u64,
309    out: &mut [NQuin],
310) -> Result<usize, N3CompileError> {
311    if let Some(norm) =
312        crate::modalities::logic::deontic::compile_n3_rule_to_norm(rule, contract_hash, 0)
313    {
314        if out.is_empty() {
315            return Err(N3CompileError::QuinBufferFull);
316        }
317        out[0] = norm;
318        return Ok(1);
319    }
320
321    let mut count = 0usize;
322    let triples = [&rule.premise, &rule.conclusion];
323    for formula in triples {
324        if let Ok(triple) = first_triple(formula) {
325            if count >= out.len() {
326                return Err(N3CompileError::QuinBufferFull);
327            }
328            out[count] = triple_to_quin(triple, contract_hash)?;
329            count += 1;
330        }
331    }
332    if count == 0 {
333        return Err(N3CompileError::EmptyRule);
334    }
335    Ok(count)
336}
337
338/// SHACL-gated batch compile: validate each rule, then emit opcodes into a fixed buffer.
339pub fn compile_rules_with_shacl_gate(
340    rules: &[Rule<'_>],
341    shapes: &[&CompiledShape],
342    opcodes_out: &mut [SlgOpcode],
343    quins_out: &mut [NQuin],
344    contract_hash: u64,
345) -> Result<N3CompiledProgram, N3CompileError> {
346    let mut opcode_offset = 0usize;
347    let mut quin_offset = 0usize;
348
349    for rule in rules {
350        // SHACL firewall: validate each rule against the routed shapes BEFORE compiling.
351        // `compile_term` hashes literals away ("12" -> u64), so a numeric range check is
352        // only possible here, on the Rule. Fail closed on any violation. Validation reads
353        // the existing Rule (no allocation); the compile step below is stack-only, so the
354        // gate itself remains zero-heap.
355        validate_rule_against_shapes(rule, shapes)?;
356
357        let compiled = compile_rule_to_zero_heap(rule);
358
359        let written = compile_rule_to_opcodes(&compiled, &mut opcodes_out[opcode_offset..])?;
360        opcode_offset += written;
361
362        let quins_written =
363            compile_rule_to_quin(&compiled, contract_hash, &mut quins_out[quin_offset..])?;
364        quin_offset += quins_written;
365    }
366
367    Ok(N3CompiledProgram {
368        opcode_count: opcode_offset,
369        quin_count: quin_offset,
370    })
371}
372
373/// Execute compiled opcodes inside the 42 MB `SlgArena` without heap growth in the eval loop.
374pub fn execute_compiled_program(
375    arena: &mut SlgArena,
376    opcodes: &[SlgOpcode],
377    frame: &mut VmFrame,
378    max_depth: u8,
379) -> Result<Option<NQuin>, SentinelError> {
380    if opcodes.len() > max_depth as usize {
381        return Err(SentinelError::MemoryOverflow);
382    }
383    Ok(execute_vm_frame(arena, opcodes, frame))
384}
385
386/// Build a default health-observation SHACL gate for LLM-emitted N3 (cold path helper).
387pub fn default_observation_shape() -> CompiledShape {
388    ShaclCompiler::new().compile_class(
389        "fhir:Observation",
390        "health:restingHeartRate",
391        ShaclConstraint::MinInclusive(20.0),
392        ShaclSeverity::Violation,
393    )
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use crate::modalities::logic::n3_parser::{Formula, Rule, RuleType, Triple};
400
401    fn sample_strict_rule() -> Rule<'static> {
402        Rule {
403            id: Some("hr-observation".into()),
404            rule_type: RuleType::Strict,
405            weight: None,
406            premise: Formula {
407                triples: vec![Triple {
408                    subject: Term::Uri("ex:Patient1".into()),
409                    predicate: Term::Uri("health:restingHeartRate".into()),
410                    object: Term::Literal("72".into()),
411                }],
412            },
413            conclusion: Formula {
414                triples: vec![Triple {
415                    subject: Term::Uri("ex:Patient1".into()),
416                    predicate: Term::Uri("health:restingHeartRate".into()),
417                    object: Term::Literal("72".into()),
418                }],
419            },
420        }
421    }
422
423    #[test]
424    fn compiles_strict_rule_to_opcodes() {
425        let mut opcodes = [SlgOpcode::Call; MAX_COMPILED_OPCODES];
426        let count =
427            compile_rule_to_opcodes(
428                &crate::modalities::logic::n3_compiler::compile_rule_to_zero_heap(
429                    &sample_strict_rule(),
430                ),
431                &mut opcodes,
432            )
433            .unwrap();
434        assert_eq!(count, 3);
435        assert_eq!(opcodes[0], SlgOpcode::Unify);
436        assert_eq!(opcodes[1], SlgOpcode::Call);
437        assert_eq!(opcodes[2], SlgOpcode::Halt);
438    }
439
440    #[test]
441    fn shacl_gate_rejects_out_of_range_numeric() {
442        let mut rule = sample_strict_rule();
443        rule.conclusion.triples[0].object = Term::Literal("12".into());
444        let shape = default_observation_shape();
445        let shapes = [&shape];
446        assert_eq!(
447            validate_rule_against_shapes(&rule, &shapes),
448            Err(N3CompileError::ShapeViolation)
449        );
450    }
451
452    #[test]
453    fn zero_heap_compile_rules_with_shacl_gate() {
454        // Build inputs OUTSIDE the measured region: parser-owned `Rule`s carry heap Vecs;
455        // this test asserts the GATE ITSELF allocates nothing (validate + stack compile).
456        let rules = [sample_strict_rule()];
457        let shape = default_observation_shape();
458        let shapes = [&shape];
459        let mut opcodes = [SlgOpcode::Call; MAX_COMPILED_OPCODES];
460        let mut quins = [NQuin::default(); MAX_COMPILED_QUINS];
461
462        let _profiler = dhat::Profiler::builder().testing().build();
463        let result = compile_rules_with_shacl_gate(
464            &rules,
465            &shapes,
466            &mut opcodes,
467            &mut quins,
468            q_hash("did:test:contract"),
469        );
470        assert!(result.is_ok());
471        assert!(result.unwrap().opcode_count > 0);
472
473        let stats = dhat::HeapStats::get();
474        assert_eq!(
475            stats.curr_blocks, 0,
476            "compile_rules_with_shacl_gate must not allocate"
477        );
478        assert_eq!(stats.curr_bytes, 0);
479    }
480}