Skip to main content

qualia_core_db/modalities/
n3_deontic_bridge.rs

1//! N3 Defeasible/Defeater & AgreementDID -> Deontic/Epistemic Quin Compiler (Task G & C2).
2//!
3//! Fully zero-allocation (Tier-1 Zero-Heap). Bridges N3 rules and ratified AgreementDID
4//! structure Quins into parity-valid deontic and epistemic NQuins (<450 lines).
5
6use crate::governance::webizen::agreement::AgreementDID;
7use crate::modalities::epistemic::{CERTAINTY_BIT_SHIFT, OP_BELIEVES};
8use crate::modalities::logic::deontic::{
9    evaluate_deontic_contract, DeonticError, DeonticVerdict, DEFEATER_BIT,
10    OP_FORBID, OP_OBLIGATE, OP_PERMIT,
11};
12#[cfg(test)]
13use crate::governance::webizen::agreement::AgreementState;
14#[cfg(test)]
15use crate::modalities::epistemic::{EpistemicStatus, EpistemicVerdict, OP_KNOWS};
16#[cfg(test)]
17use crate::modalities::logic::deontic::DeonticStatus;
18use crate::modalities::logic::n3_parser::{Rule, RuleType, StackRule, Term};
19use crate::q_hash;
20use crate::NQuin;
21
22pub const HAS_GUARDIAN: u64 = q_hash("q42:hasGuardian");
23pub const HAS_DOMAIN_SCOPE: u64 = q_hash("q42:hasDomainScope");
24pub const REQUIRES_CONSENSUS: u64 = q_hash("q42:requiresConsensus");
25pub const BILATERAL_MICROCOMMONS_LANE: u64 = 0x4000_0000_0000_0002;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum BridgeError {
29    BufferOverflow,
30    UnratifiedConsensusThreshold,
31    ExpiredAgreement,
32    MalformedRule,
33    MissingStructureQuin,
34    DeonticEvaluationError,
35    EpistemicEvaluationError,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq)]
39pub struct N3RuleDescriptor {
40    pub rule_type: RuleType,
41    pub party_did_hash: u64,
42    pub property_path_hash: u64,
43    pub action_object_hash: u64,
44    pub contract_hash: u64,
45    pub weight: Option<f32>,
46    pub expiry_unix32: u32,
47}
48
49#[inline(always)]
50fn hash_term(term: &Term<'_>) -> u64 {
51    match term {
52        Term::Uri(s) | Term::Variable(s) | Term::Literal(s) | Term::Formula(s) => q_hash(s),
53    }
54}
55
56impl N3RuleDescriptor {
57    pub fn from_ast_rule(rule: &Rule<'_>, default_contract_hash: u64, default_expiry: u32) -> Result<Self, BridgeError> {
58        if rule.premise.triples.is_empty() || rule.conclusion.triples.is_empty() { return Err(BridgeError::MalformedRule); }
59        let (p, c) = (&rule.premise.triples[0], &rule.conclusion.triples[0]);
60        let contract_hash = if default_contract_hash != 0 { default_contract_hash } else { hash_term(&c.subject) };
61        Ok(Self {
62            rule_type: rule.rule_type,
63            party_did_hash: hash_term(&p.subject),
64            property_path_hash: hash_term(&p.predicate),
65            action_object_hash: hash_term(&p.object),
66            contract_hash,
67            weight: rule.weight,
68            expiry_unix32: default_expiry,
69        })
70    }
71
72    pub fn from_stack_rule(rule: &StackRule<'_>, default_contract_hash: u64, default_expiry: u32) -> Result<Self, BridgeError> {
73        if rule.premise.len == 0 || rule.conclusion.len == 0 { return Err(BridgeError::MalformedRule); }
74        let (p, c) = (&rule.premise.triples[0], &rule.conclusion.triples[0]);
75        let contract_hash = if default_contract_hash != 0 { default_contract_hash } else { hash_term(&c.subject) };
76        Ok(Self {
77            rule_type: rule.rule_type,
78            party_did_hash: hash_term(&p.subject),
79            property_path_hash: hash_term(&p.predicate),
80            action_object_hash: hash_term(&p.object),
81            contract_hash,
82            weight: rule.weight,
83            expiry_unix32: default_expiry,
84        })
85    }
86}
87
88#[inline]
89pub fn parse_deontic_modality(p_hash: u64, rule_type: RuleType) -> (u8, bool) {
90    if rule_type == RuleType::Defeater { return (OP_PERMIT, true); }
91    let is_forbid = [q_hash("q42:forbid"), q_hash("q42:not"), q_hash("q42:prohibit")].contains(&p_hash);
92    let is_permit = [q_hash("q42:permit"), q_hash("q42:may"), q_hash("q42:can")].contains(&p_hash);
93    let opcode = if is_forbid { OP_FORBID } else if is_permit { OP_PERMIT } else { OP_OBLIGATE };
94    (opcode, false)
95}
96
97pub fn compile_descriptor_to_deontic_norm(desc: &N3RuleDescriptor) -> NQuin {
98    let (opcode, is_defeater) = parse_deontic_modality(desc.property_path_hash, desc.rule_type);
99    let mut pred = ((desc.property_path_hash & 0x007F_FFFF_FFFF_FFFF) << 8) | (opcode as u64);
100    if is_defeater || desc.rule_type == RuleType::Defeater { pred |= DEFEATER_BIT; }
101    let parity = desc.party_did_hash ^ pred ^ desc.action_object_hash ^ desc.contract_hash;
102    NQuin {
103        subject: desc.party_did_hash,
104        predicate: pred,
105        object: desc.action_object_hash,
106        context: desc.contract_hash,
107        metadata: desc.expiry_unix32 as u64,
108        parity,
109    }
110}
111
112pub fn compile_descriptor_to_epistemic_quin(desc: &N3RuleDescriptor, opcode: u8) -> NQuin {
113    let certainty = match desc.weight {
114        Some(w) => (w.clamp(0.0, 1.0) * 255.0).round() as u8,
115        None => if opcode == OP_BELIEVES { 200 } else { 255 },
116    };
117    let pred = (opcode as u64) | ((certainty as u64) << CERTAINTY_BIT_SHIFT);
118    let parity = desc.party_did_hash ^ pred ^ desc.action_object_hash ^ desc.contract_hash;
119    NQuin {
120        subject: desc.party_did_hash,
121        predicate: pred,
122        object: desc.action_object_hash,
123        context: desc.contract_hash,
124        metadata: (desc.expiry_unix32 as u64) | (certainty as u64),
125        parity,
126    }
127}
128
129pub fn compile_agreement_structure_quins_to_deontic_norms(
130    structure_quins: &[NQuin],
131    collected_signatures: u8,
132    current_epoch: u32,
133    expiry_epoch: u32,
134    out: &mut [NQuin],
135) -> Result<usize, BridgeError> {
136    if expiry_epoch != 0 && current_epoch > expiry_epoch { return Err(BridgeError::ExpiredAgreement); }
137    let (mut agreement_id, mut domain_id, mut threshold) = (0u64, 0u64, 0u8);
138    let mut agents = [0u64; 8];
139    let (mut num_agents, mut has_consensus) = (0usize, false);
140
141    for q in structure_quins {
142        if q.predicate == HAS_GUARDIAN {
143            agreement_id = q.context;
144            if q.object != 0 && num_agents < 8 && !agents[..num_agents].contains(&q.object) {
145                agents[num_agents] = q.object;
146                num_agents += 1;
147            }
148        } else if q.predicate == HAS_DOMAIN_SCOPE {
149            if agreement_id == 0 { agreement_id = q.subject; }
150            domain_id = q.object;
151        } else if q.predicate == REQUIRES_CONSENSUS {
152            if agreement_id == 0 { agreement_id = q.subject; }
153            if domain_id == 0 { domain_id = q.context; }
154            threshold = q.object as u8;
155            has_consensus = true;
156        }
157    }
158    if !has_consensus || threshold == 0 { return Err(BridgeError::MissingStructureQuin); }
159    if collected_signatures < threshold { return Err(BridgeError::UnratifiedConsensusThreshold); }
160    if out.len() < num_agents { return Err(BridgeError::BufferOverflow); }
161
162    for i in 0..num_agents {
163        let agent = agents[i];
164        let predicate = ((HAS_DOMAIN_SCOPE & 0x007F_FFFF_FFFF_FFFF) << 8) | (OP_OBLIGATE as u64);
165        let parity = agent ^ predicate ^ domain_id ^ agreement_id;
166        out[i] = NQuin {
167            subject: agent,
168            predicate,
169            object: domain_id,
170            context: agreement_id,
171            metadata: (expiry_epoch as u64) | BILATERAL_MICROCOMMONS_LANE,
172            parity,
173        };
174    }
175    Ok(num_agents)
176}
177
178pub fn compile_agreement_did_to_deontic_norms(
179    agreement: &AgreementDID,
180    collected_signatures: u8,
181    current_epoch: u32,
182    expiry_epoch: u32,
183    out: &mut [NQuin],
184) -> Result<usize, BridgeError> {
185    if expiry_epoch != 0 && current_epoch > expiry_epoch { return Err(BridgeError::ExpiredAgreement); }
186    if collected_signatures < agreement.threshold { return Err(BridgeError::UnratifiedConsensusThreshold); }
187    let n = agreement.num_agents as usize;
188    if out.len() < n { return Err(BridgeError::BufferOverflow); }
189    for i in 0..n {
190        let agent = agreement.agents[i];
191        let predicate = ((HAS_DOMAIN_SCOPE & 0x007F_FFFF_FFFF_FFFF) << 8) | (OP_OBLIGATE as u64);
192        let parity = agent ^ predicate ^ agreement.domain_id ^ agreement.agreement_id;
193        out[i] = NQuin {
194            subject: agent,
195            predicate,
196            object: agreement.domain_id,
197            context: agreement.agreement_id,
198            metadata: (expiry_epoch as u64) | BILATERAL_MICROCOMMONS_LANE,
199            parity,
200        };
201    }
202    Ok(n)
203}
204
205#[inline]
206pub fn evaluate_deontic_frame(quins: &[NQuin], now_unix: u32, out: &mut [DeonticVerdict]) -> Result<usize, DeonticError> {
207    evaluate_deontic_contract(quins, now_unix, out)
208}
209
210pub fn compile_and_evaluate_n3_deontic_norms(
211    descriptors: &[N3RuleDescriptor],
212    agreement_structure_quins: &[NQuin],
213    collected_signatures: u8,
214    current_epoch: u32,
215    expiry_epoch: u32,
216    quin_buf: &mut [NQuin],
217    out_verdicts: &mut [DeonticVerdict],
218) -> Result<usize, BridgeError> {
219    if quin_buf.len() < descriptors.len() { return Err(BridgeError::BufferOverflow); }
220    let mut written = 0usize;
221    for d in descriptors {
222        quin_buf[written] = compile_descriptor_to_deontic_norm(d);
223        written += 1;
224    }
225    if !agreement_structure_quins.is_empty() {
226        let n_agr = compile_agreement_structure_quins_to_deontic_norms(
227            agreement_structure_quins,
228            collected_signatures,
229            current_epoch,
230            expiry_epoch,
231            &mut quin_buf[written..],
232        )?;
233        written += n_agr;
234    }
235    evaluate_deontic_frame(&quin_buf[..written], current_epoch, out_verdicts)
236        .map_err(|_| BridgeError::DeonticEvaluationError)
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use crate::modalities::epistemic::evaluate_epistemic_frame;
243    use crate::modalities::logic::deontic::DefeatKind;
244    use crate::modalities::logic::n3_parser::{Formula, StackFormula, Triple};
245
246    const PARTY_ALICE: u64 = 0xA11C_E000_0000_0001;
247    const PARTY_BOB: u64 = 0xB0B0_0000_0000_0002;
248    const PRED_DISCLOSE: u64 = q_hash("q42:disclose");
249    const OBJ_PROJECT_X: u64 = q_hash("q42:projectX");
250    const OBJ_AUDITOR: u64 = q_hash("q42:auditor");
251    const CONTRACT_NDA: u64 = 0xCDA0_0000_0000_0001;
252
253    fn sample_agreement(state: AgreementState, threshold: u8, num_agents: u8) -> AgreementDID {
254        AgreementDID {
255            agreement_id: 0x8888,
256            principal: 0x1111,
257            agents: [PARTY_ALICE, PARTY_BOB, 0, 0, 0, 0, 0, 0],
258            num_agents,
259            domain_id: 0x9999,
260            threshold,
261            current_state: state,
262        }
263    }
264
265    #[test]
266    fn test_defeasible_obligation_active_and_defeated_by_defeater() {
267        let defeasible_rule = N3RuleDescriptor {
268            rule_type: RuleType::Defeasible,
269            party_did_hash: PARTY_ALICE,
270            property_path_hash: PRED_DISCLOSE,
271            action_object_hash: OBJ_PROJECT_X,
272            contract_hash: CONTRACT_NDA,
273            weight: None,
274            expiry_unix32: 5000,
275        };
276        let mut quins = [NQuin::default(); 8];
277        let mut verdicts = [DeonticVerdict::default(); 8];
278
279        let count = compile_and_evaluate_n3_deontic_norms(
280            &[defeasible_rule], &[], 0, 1000, 5000, &mut quins, &mut verdicts,
281        ).expect("eval alone");
282        assert_eq!(count, 1);
283        assert_eq!(verdicts[0].status, DeonticStatus::Active);
284        assert_eq!(verdicts[0].opcode, OP_OBLIGATE);
285        assert_eq!(verdicts[0].defeat_kind, DefeatKind::None);
286
287        let defeater_rule = N3RuleDescriptor {
288            rule_type: RuleType::Defeater,
289            party_did_hash: PARTY_ALICE,
290            property_path_hash: PRED_DISCLOSE,
291            action_object_hash: OBJ_AUDITOR,
292            contract_hash: CONTRACT_NDA,
293            weight: None,
294            expiry_unix32: 5000,
295        };
296        let count2 = compile_and_evaluate_n3_deontic_norms(
297            &[defeasible_rule, defeater_rule], &[], 0, 1000, 5000, &mut quins, &mut verdicts,
298        ).expect("eval with defeater");
299        assert_eq!(count2, 1);
300        assert_eq!(verdicts[0].status, DeonticStatus::Defeated);
301        assert_eq!(verdicts[0].defeat_kind, DefeatKind::Rebutting);
302    }
303
304    #[test]
305    fn test_ratified_agreement_compiles_to_deontic_obligations() {
306        let agreement = sample_agreement(AgreementState::Ratified, 2, 2);
307        let structure_quins = agreement.compile_to_super_quins();
308        let mut quins = [NQuin::default(); 16];
309        let mut verdicts = [DeonticVerdict::default(); 8];
310
311        let count = compile_and_evaluate_n3_deontic_norms(
312            &[], &structure_quins, 2, 1000, 5000, &mut quins, &mut verdicts,
313        ).expect("compile agreement norms");
314        assert_eq!(count, 2);
315        assert_eq!(verdicts[0].status, DeonticStatus::Active);
316        assert_eq!(verdicts[0].opcode, OP_OBLIGATE);
317        assert_eq!(verdicts[0].norm.subject, PARTY_ALICE);
318        assert_eq!(verdicts[1].status, DeonticStatus::Active);
319        assert_eq!(verdicts[1].opcode, OP_OBLIGATE);
320        assert_eq!(verdicts[1].norm.subject, PARTY_BOB);
321    }
322
323    #[test]
324    fn test_negative_unratified_consensus_fails_closed() {
325        let agreement = sample_agreement(AgreementState::Ratified, 2, 2);
326        let structure_quins = agreement.compile_to_super_quins();
327        let mut out = [NQuin::default(); 4];
328        let err = compile_agreement_structure_quins_to_deontic_norms(
329            &structure_quins, 1, 1000, 5000, &mut out,
330        ).unwrap_err();
331        assert_eq!(err, BridgeError::UnratifiedConsensusThreshold);
332        let err_did = compile_agreement_did_to_deontic_norms(&agreement, 1, 1000, 5000, &mut out).unwrap_err();
333        assert_eq!(err_did, BridgeError::UnratifiedConsensusThreshold);
334    }
335
336    #[test]
337    fn test_negative_expired_epoch_fails_closed() {
338        let agreement = sample_agreement(AgreementState::Ratified, 1, 1);
339        let structure_quins = agreement.compile_to_super_quins();
340        let mut out = [NQuin::default(); 4];
341        let err = compile_agreement_structure_quins_to_deontic_norms(
342            &structure_quins, 1, 6000, 5000, &mut out,
343        ).unwrap_err();
344        assert_eq!(err, BridgeError::ExpiredAgreement);
345    }
346
347    #[test]
348    fn test_negative_buffer_overflow_fails_closed_without_partial_write() {
349        let agreement = sample_agreement(AgreementState::Ratified, 1, 2);
350        let structure_quins = agreement.compile_to_super_quins();
351        let mut out = [NQuin { subject: 0xDEAD_BEEF, predicate: 0, object: 0, context: 0, metadata: 0, parity: 0 }; 1];
352        let err = compile_agreement_structure_quins_to_deontic_norms(
353            &structure_quins, 1, 1000, 5000, &mut out,
354        ).unwrap_err();
355        assert_eq!(err, BridgeError::BufferOverflow);
356        assert_eq!(out[0].subject, 0xDEAD_BEEF);
357    }
358
359    #[test]
360    fn test_epistemic_compilation_and_evaluation() {
361        let known_rule = N3RuleDescriptor {
362            rule_type: RuleType::Strict,
363            party_did_hash: PARTY_ALICE,
364            property_path_hash: q_hash("q42:knows"),
365            action_object_hash: OBJ_PROJECT_X,
366            contract_hash: CONTRACT_NDA,
367            weight: Some(0.95),
368            expiry_unix32: 5000,
369        };
370        let uncertain_rule = N3RuleDescriptor {
371            rule_type: RuleType::Defeasible,
372            party_did_hash: PARTY_BOB,
373            property_path_hash: q_hash("q42:believes"),
374            action_object_hash: OBJ_PROJECT_X,
375            contract_hash: CONTRACT_NDA,
376            weight: Some(0.20),
377            expiry_unix32: 5000,
378        };
379        let q1 = compile_descriptor_to_epistemic_quin(&known_rule, OP_KNOWS);
380        let q2 = compile_descriptor_to_epistemic_quin(&uncertain_rule, OP_BELIEVES);
381        let mut verdicts = [EpistemicVerdict { claim: NQuin::default(), status: EpistemicStatus::Skipped, certainty: 0 }; 4];
382        let count = evaluate_epistemic_frame(&[q1, q2], 0, 0, &mut verdicts).expect("epistemic eval");
383        assert_eq!(count, 2);
384        assert_eq!(verdicts[0].status, EpistemicStatus::Active);
385        assert_eq!(verdicts[0].certainty, 242);
386        assert_eq!(verdicts[1].status, EpistemicStatus::Uncertain);
387        assert_eq!(verdicts[1].certainty, 51);
388    }
389
390    #[test]
391    fn test_ast_and_stack_rule_conversion() {
392        let mut s_premise = StackFormula::new();
393        s_premise.triples[0] = Triple {
394            subject: Term::Uri("did:web:alice"),
395            predicate: Term::Uri("q42:mustDeliver"),
396            object: Term::Uri("item:package"),
397        };
398        s_premise.len = 1;
399        let mut s_conclusion = StackFormula::new();
400        s_conclusion.triples[0] = Triple {
401            subject: Term::Uri("urn:contract:shipping"),
402            predicate: Term::Uri("q42:scope"),
403            object: Term::Uri("item:package"),
404        };
405        s_conclusion.len = 1;
406        let stack_rule = StackRule {
407            id: Some("sr-1"),
408            rule_type: RuleType::Strict,
409            weight: Some(1.0),
410            premise: s_premise,
411            conclusion: s_conclusion,
412        };
413
414        let desc = N3RuleDescriptor::from_stack_rule(&stack_rule, 0, 1000).expect("from stack rule");
415        assert_eq!(desc.party_did_hash, q_hash("did:web:alice"));
416        assert_eq!(desc.property_path_hash, q_hash("q42:mustDeliver"));
417        assert_eq!(desc.action_object_hash, q_hash("item:package"));
418        assert_eq!(desc.contract_hash, q_hash("urn:contract:shipping"));
419
420        let quin = compile_descriptor_to_deontic_norm(&desc);
421        assert_eq!(quin.subject, q_hash("did:web:alice"));
422        assert_eq!(quin.predicate & 0xFF, OP_OBLIGATE as u64);
423        assert_eq!(quin.predicate & DEFEATER_BIT, 0);
424
425        let empty_ast = Rule {
426            id: None,
427            rule_type: RuleType::Strict,
428            weight: None,
429            premise: Formula { triples: vec![] },
430            conclusion: Formula { triples: vec![] },
431        };
432        assert_eq!(N3RuleDescriptor::from_ast_rule(&empty_ast, 0, 0), Err(BridgeError::MalformedRule));
433    }
434}