Skip to main content

qualia_core_db/
deontic_logic.rs

1//! Deontic logic engine — ODRL-based policy evaluation for credential-gated subgraph access.
2//!
3//! The policy hierarchy maps agent Verifiable Credentials to `SubgraphLayer` access rights.
4//! Policy evaluation is:
5//!   1. Extract `VcAttributes` from the agent's NQuin slice (credential claims).
6//!   2. Evaluate against the `SubgraphPolicy` for the requested layer.
7//!   3. If the policy passes, call `KeyVault::generate_layer_key()` and return it.
8//!
9//! The `deontic_logic` module is intentionally free of heap allocation in evaluation paths
10//! — all structures fit in fixed-size arrays.
11
12#[cfg(not(target_arch = "wasm32"))]
13use crate::key_vault::{KeyVault, SubgraphKey, SubgraphLayer};
14use crate::q_hash;
15
16// ── VC role IRI hashes ────────────────────────────────────────────────────────
17
18/// Compile-time hashes of canonical ODRL/Qualia role IRIs used in VC claims.
19pub mod vc_roles {
20    use crate::q_hash;
21
22    /// Any authenticated principal — no further VC attributes required.
23    pub const AUTHENTICATED: u64 = q_hash("urn:qualia:role:authenticated");
24    /// Professional context (e.g., organisation employee with NDA).
25    pub const PROFESSIONAL: u64 = q_hash("urn:qualia:role:professional");
26    /// Legal practitioner with privileged access to legal subgraph.
27    pub const LEGAL_PRACTITIONER: u64 = q_hash("urn:qualia:role:legal-practitioner");
28    /// Registered medical professional.
29    pub const MEDICAL_PROFESSIONAL: u64 = q_hash("urn:qualia:role:medical-professional");
30    /// Fiduciary duty holder (financial advisor, trustee, etc.).
31    pub const FIDUCIARY: u64 = q_hash("urn:qualia:role:fiduciary");
32    /// Qualia node operator — administrative role.
33    pub const NODE_OPERATOR: u64 = q_hash("urn:qualia:role:node-operator");
34}
35
36/// Predicate hash for VC role claims (`urn:qualia:vc:hasRole`).
37const P_HAS_ROLE: u64 = q_hash("urn:qualia:vc:hasRole");
38/// Predicate hash for VC clearance level (`urn:qualia:vc:clearanceLevel`).
39const P_CLEARANCE_LEVEL: u64 = q_hash("urn:qualia:vc:clearanceLevel");
40/// Predicate hash for VC issuer (`urn:qualia:vc:issuedBy`).
41const P_ISSUED_BY: u64 = q_hash("urn:qualia:vc:issuedBy");
42
43/// Maximum number of roles stored in `VcAttributes`.
44const MAX_ROLES: usize = 8;
45
46/// Parsed Verifiable Credential attributes for a single agent.
47///
48/// Extracted from the agent's NQuin slice via `VcAttributes::from_quins()`.
49#[derive(Debug, Clone, Copy)]
50pub struct VcAttributes {
51    pub did_hash: u64,
52    pub roles: [u64; MAX_ROLES],
53    pub role_count: u8,
54    /// Numeric clearance level (0=public … 4=fiduciary). Sourced from `vc:clearanceLevel`.
55    pub clearance_level: u8,
56    /// Hash of the VC issuer's DID — must be in the trusted-issuer set.
57    pub credential_issuer: u64,
58}
59
60impl VcAttributes {
61    /// Create a minimal `VcAttributes` for `did_hash` with no claims.
62    pub fn unauthenticated(did_hash: u64) -> Self {
63        Self {
64            did_hash,
65            roles: [0; MAX_ROLES],
66            role_count: 0,
67            clearance_level: 0,
68            credential_issuer: 0,
69        }
70    }
71
72    /// Parse VC claims for `agent_did` from a slice of NQuins.
73    ///
74    /// Scans for quins where `subject == agent_did` and predicate is one of
75    /// `P_HAS_ROLE`, `P_CLEARANCE_LEVEL`, or `P_ISSUED_BY`.
76    pub fn from_quins(agent_did: u64, quins: &[crate::NQuin]) -> Self {
77        let mut attrs = Self::unauthenticated(agent_did);
78        for q in quins {
79            if q.subject != agent_did {
80                continue;
81            }
82            if q.predicate == P_HAS_ROLE && (attrs.role_count as usize) < MAX_ROLES {
83                attrs.roles[attrs.role_count as usize] = q.object;
84                attrs.role_count += 1;
85            } else if q.predicate == P_CLEARANCE_LEVEL {
86                attrs.clearance_level = (q.object & 0x0F) as u8;
87            } else if q.predicate == P_ISSUED_BY {
88                attrs.credential_issuer = q.object;
89            }
90        }
91        attrs
92    }
93
94    /// Returns `true` if this VC includes `role_hash` in its role claims.
95    #[inline]
96    pub fn has_role(self, role_hash: u64) -> bool {
97        self.roles[..self.role_count as usize].contains(&role_hash)
98    }
99}
100
101#[cfg(not(target_arch = "wasm32"))]
102/// The result of a deontic policy evaluation for subgraph key release.
103#[derive(Debug)]
104pub enum DeonticResult {
105    /// Policy passed — the derived `SubgraphKey` can be released to the agent.
106    KeyRelease(SubgraphKey),
107    /// Policy denied. The key is not returned.
108    AccessDenied {
109        layer: SubgraphLayer,
110        reason: &'static str,
111    },
112}
113
114#[cfg(not(target_arch = "wasm32"))]
115impl DeonticResult {
116    /// `true` when permitted.
117    pub fn is_permitted(&self) -> bool {
118        matches!(self, Self::KeyRelease(_))
119    }
120}
121
122/// Evaluate an agent's VCs against the ODRL policy for `layer` and, if permitted,
123/// return the derived `SubgraphKey`.
124///
125/// # Policy table
126///
127/// | Layer        | Minimum clearance | Accepted roles                         |
128/// |-------------|-------------------|-----------------------------------------|
129/// | Public      | 0 (any)           | (none required)                         |
130/// | Professional| 1                 | `role:professional`, `role:node-operator` |
131/// | Legal       | 2                 | `role:legal-practitioner`               |
132/// | Medical     | 3                 | `role:medical-professional`             |
133/// | Fiduciary   | 4                 | `role:fiduciary`                        |
134///
135/// Clearance level OR role match is sufficient; both are not required.
136///
137/// # Trusted issuers
138/// The `trusted_issuers` slice lists DID hashes of credential issuers the node
139/// accepts.  An empty slice disables issuer-trust enforcement (dev mode only).
140#[cfg(not(target_arch = "wasm32"))]
141pub fn evaluate_vc_for_subgraph_key_release(
142    vault: &KeyVault,
143    vc: &VcAttributes,
144    layer: SubgraphLayer,
145    trusted_issuers: &[u64],
146) -> DeonticResult {
147    // 1. Issuer trust check (skip if no trusted issuers configured).
148    if !trusted_issuers.is_empty() && !trusted_issuers.contains(&vc.credential_issuer) {
149        return DeonticResult::AccessDenied {
150            layer,
151            reason: "credential issuer not in trusted-issuer set",
152        };
153    }
154
155    // 2. Layer-specific policy.
156    let policy_passed = match layer {
157        SubgraphLayer::Public => true,
158
159        SubgraphLayer::Professional => {
160            vc.clearance_level >= 1
161                || vc.has_role(vc_roles::PROFESSIONAL)
162                || vc.has_role(vc_roles::NODE_OPERATOR)
163        }
164
165        SubgraphLayer::Legal => {
166            vc.clearance_level >= 2 || vc.has_role(vc_roles::LEGAL_PRACTITIONER)
167        }
168
169        SubgraphLayer::Medical => {
170            vc.clearance_level >= 3 || vc.has_role(vc_roles::MEDICAL_PROFESSIONAL)
171        }
172
173        SubgraphLayer::Fiduciary => vc.clearance_level >= 4 || vc.has_role(vc_roles::FIDUCIARY),
174    };
175
176    if policy_passed {
177        DeonticResult::KeyRelease(vault.generate_layer_key(layer))
178    } else {
179        DeonticResult::AccessDenied {
180            layer,
181            reason: "insufficient VC clearance or role",
182        }
183    }
184}
185
186/// Convenience: evaluate which layers the agent can access and write the permitted
187/// keys into `out`, in ascending layer order.
188///
189/// Zero-heap: writes at most `out.len().min(5)` `(SubgraphLayer, SubgraphKey)` entries
190/// (one per layer) into the caller-supplied slice and returns the count written.
191/// `SubgraphKey` is move-only (it zeroizes on drop), so `out` is a slice of `Option<…>`;
192/// written entries are `Some`. This function is not on a hot path.
193#[cfg(not(target_arch = "wasm32"))]
194pub fn evaluate_accessible_layers(
195    vault: &KeyVault,
196    vc: &VcAttributes,
197    trusted_issuers: &[u64],
198    out: &mut [Option<(SubgraphLayer, SubgraphKey)>],
199) -> usize {
200    let layers = [
201        SubgraphLayer::Public,
202        SubgraphLayer::Professional,
203        SubgraphLayer::Legal,
204        SubgraphLayer::Medical,
205        SubgraphLayer::Fiduciary,
206    ];
207    let mut n = 0usize;
208    for layer in layers {
209        if let DeonticResult::KeyRelease(key) =
210            evaluate_vc_for_subgraph_key_release(vault, vc, layer, trusted_issuers)
211        {
212            if n >= out.len() {
213                break;
214            }
215            out[n] = Some((layer, key));
216            n += 1;
217        }
218    }
219    n
220}
221
222/// Build the NQuins that record a VC credential claim for an agent, for insertion
223/// into the daemon graph.
224///
225/// Each `role_hash` becomes a `P_HAS_ROLE` quin in `CONTEXT`.
226/// `clearance` and `issuer_did` emit one quin each.
227pub fn write_vc_claim_quins(
228    agent_did: u64,
229    roles: &[u64],
230    clearance: u8,
231    issuer_did: u64,
232    ts: u64,
233) -> [crate::NQuin; 3] {
234    const VC_CONTEXT: u64 = q_hash("urn:qualia:context:vc");
235
236    let role_hash = if roles.is_empty() {
237        vc_roles::AUTHENTICATED
238    } else {
239        roles[0]
240    };
241
242    [
243        crate::NQuin {
244            subject: agent_did,
245            predicate: P_HAS_ROLE,
246            object: role_hash,
247            context: VC_CONTEXT,
248            metadata: ts & 0xFFFF_FFFF,
249            parity: agent_did ^ P_HAS_ROLE ^ role_hash ^ VC_CONTEXT,
250        },
251        crate::NQuin {
252            subject: agent_did,
253            predicate: P_CLEARANCE_LEVEL,
254            object: clearance as u64,
255            context: VC_CONTEXT,
256            metadata: ts & 0xFFFF_FFFF,
257            parity: agent_did ^ P_CLEARANCE_LEVEL ^ (clearance as u64) ^ VC_CONTEXT,
258        },
259        crate::NQuin {
260            subject: agent_did,
261            predicate: P_ISSUED_BY,
262            object: issuer_did,
263            context: VC_CONTEXT,
264            metadata: ts & 0xFFFF_FFFF,
265            parity: agent_did ^ P_ISSUED_BY ^ issuer_did ^ VC_CONTEXT,
266        },
267    ]
268}
269
270pub use crate::modalities::logic::deontic::{DEFEATER_BIT, OP_FORBID, OP_OBLIGATE, OP_PERMIT};
271use crate::modalities::logic::n3_compiler::CompiledRule;
272use crate::modalities::logic::n3_parser::RuleType;
273
274/// Compile an N3 rule into a norm Quin (or a defeater Quin if rule_type is Defeater).
275///
276/// Mapping:
277///   premise.triples\[0\].subject  → party_did_hash  (who is bound)
278///   premise.triples\[0\].predicate → property_path_hash  (what action/property)
279///   premise.triples\[0\].object   → action_object_hash  (target entity)
280///   rule.rule_type              → opcode + is_defeater flag
281///   conclusion.triples\[0\].subject → contract context hash
282///
283/// Returns None if the rule does not have the expected triple structure.
284pub fn compile_n3_rule_to_norm(
285    rule: &CompiledRule,
286    contract_hash: u64,
287    expiry_unix32: u32,
288) -> Option<crate::NQuin> {
289    if rule.premise.len == 0 || rule.conclusion.len == 0 {
290        return None;
291    }
292
293    let premise_triple = &rule.premise.triples[0];
294    let conclusion_triple = &rule.conclusion.triples[0];
295
296    let party_did_hash = premise_triple.subject.as_u64();
297    let property_path_hash = premise_triple.predicate.as_u64();
298    let action_object_hash = premise_triple.object.as_u64();
299
300    let mapped_contract_hash = if contract_hash == 0 {
301        conclusion_triple.subject.as_u64()
302    } else {
303        contract_hash
304    };
305
306    let mut opcode = OP_PERMIT;
307    let mut is_defeater = false;
308
309    let p_hash = property_path_hash;
310
311    let is_obligate = [
312        crate::q_hash("q42:obligate"),
313        crate::q_hash("q42:must"),
314        crate::q_hash("q42:shall"),
315    ]
316    .contains(&p_hash);
317    let is_permit = [
318        crate::q_hash("q42:permit"),
319        crate::q_hash("q42:may"),
320        crate::q_hash("q42:can"),
321    ]
322    .contains(&p_hash);
323    let is_forbid = [
324        crate::q_hash("q42:forbid"),
325        crate::q_hash("q42:not"),
326        crate::q_hash("q42:prohibit"),
327    ]
328    .contains(&p_hash);
329
330    match rule.rule_type {
331        RuleType::Strict => {
332            if is_obligate {
333                opcode = OP_OBLIGATE;
334            }
335        }
336        RuleType::Defeasible => {
337            if is_permit {
338                opcode = OP_PERMIT;
339            } else if is_forbid {
340                opcode = OP_FORBID;
341            }
342        }
343        RuleType::Defeater => {
344            opcode = OP_PERMIT;
345            is_defeater = true;
346        }
347        RuleType::Linear => {
348            if is_obligate {
349                opcode = OP_OBLIGATE;
350            }
351        }
352    }
353
354    let mut quin = crate::NQuin::default();
355    quin.subject = party_did_hash;
356
357    // Predicate: opcode in lower 8 bits, property hash shifted left 8 bits (masked to 55 bits), and DEFEATER_BIT if needed
358    let mut predicate_packed =
359        ((property_path_hash & 0x007F_FFFF_FFFF_FFFF) << 8) | (opcode as u64);
360    if is_defeater {
361        predicate_packed |= DEFEATER_BIT;
362    }
363    quin.predicate = predicate_packed;
364
365    quin.object = action_object_hash;
366    quin.context = mapped_contract_hash;
367    quin.metadata = expiry_unix32 as u64;
368    quin.parity = quin.subject ^ quin.predicate ^ quin.object ^ quin.context;
369
370    Some(quin)
371}
372
373use crate::governance::webizen::agreement::{AgreementDID, AgreementState};
374use crate::modalities::logic::n3_parser::{
375    Rule as N3Rule, StackRule as N3StackRule, Term as N3Term,
376};
377
378fn hash_n3_term(term: &N3Term<'_>) -> u64 {
379    match term {
380        N3Term::Uri(s) | N3Term::Variable(s) | N3Term::Literal(s) | N3Term::Formula(s) => {
381            crate::q_hash(s)
382        }
383    }
384}
385
386/// Compile an uncompiled/borrowed N3 AST `Rule` directly into a norm Quin.
387pub fn compile_n3_ast_rule_to_norm(
388    rule: &N3Rule<'_>,
389    contract_hash: u64,
390    expiry_unix32: u32,
391) -> Option<crate::NQuin> {
392    if rule.premise.triples.is_empty() || rule.conclusion.triples.is_empty() {
393        return None;
394    }
395    let p_triple = &rule.premise.triples[0];
396    let c_triple = &rule.conclusion.triples[0];
397
398    let party_did_hash = hash_n3_term(&p_triple.subject);
399    let property_path_hash = hash_n3_term(&p_triple.predicate);
400    let action_object_hash = hash_n3_term(&p_triple.object);
401    let mapped_contract_hash = if contract_hash == 0 {
402        hash_n3_term(&c_triple.subject)
403    } else {
404        contract_hash
405    };
406
407    let p_str = match p_triple.predicate {
408        N3Term::Uri(s) | N3Term::Variable(s) | N3Term::Literal(s) | N3Term::Formula(s) => {
409            s.to_ascii_lowercase()
410        }
411    };
412
413    let is_obligate =
414        p_str.contains("obligate") || p_str.contains("must") || p_str.contains("shall");
415    let is_permit = p_str.contains("permit") || p_str.contains("may") || p_str.contains("can");
416    let is_forbid = p_str.contains("forbid") || p_str.contains("not") || p_str.contains("prohibit");
417
418    let mut opcode = OP_PERMIT;
419    let mut is_defeater = false;
420
421    match rule.rule_type {
422        RuleType::Strict => {
423            opcode = if is_obligate { OP_OBLIGATE } else { OP_PERMIT };
424        }
425        RuleType::Defeasible => {
426            if is_forbid {
427                opcode = OP_FORBID;
428            } else if is_permit {
429                opcode = OP_PERMIT;
430            }
431        }
432        RuleType::Defeater => {
433            opcode = OP_PERMIT;
434            is_defeater = true;
435        }
436        RuleType::Linear => {
437            opcode = if is_obligate { OP_OBLIGATE } else { OP_PERMIT };
438        }
439    }
440
441    let mut predicate_packed =
442        ((property_path_hash & 0x007F_FFFF_FFFF_FFFF) << 8) | (opcode as u64);
443    if is_defeater {
444        predicate_packed |= DEFEATER_BIT;
445    }
446
447    let parity = party_did_hash ^ predicate_packed ^ action_object_hash ^ mapped_contract_hash;
448
449    Some(crate::NQuin {
450        subject: party_did_hash,
451        predicate: predicate_packed,
452        object: action_object_hash,
453        context: mapped_contract_hash,
454        metadata: expiry_unix32 as u64,
455        parity,
456    })
457}
458
459/// Compile a zero-allocation `StackRule` directly into a norm Quin.
460pub fn compile_stack_rule_to_norm(
461    rule: &N3StackRule<'_>,
462    contract_hash: u64,
463    expiry_unix32: u32,
464) -> Option<crate::NQuin> {
465    if rule.premise.len == 0 || rule.conclusion.len == 0 {
466        return None;
467    }
468    let p_triple = &rule.premise.triples[0];
469    let c_triple = &rule.conclusion.triples[0];
470
471    let party_did_hash = hash_n3_term(&p_triple.subject);
472    let property_path_hash = hash_n3_term(&p_triple.predicate);
473    let action_object_hash = hash_n3_term(&p_triple.object);
474    let mapped_contract_hash = if contract_hash == 0 {
475        hash_n3_term(&c_triple.subject)
476    } else {
477        contract_hash
478    };
479
480    let p_str = match p_triple.predicate {
481        N3Term::Uri(s) | N3Term::Variable(s) | N3Term::Literal(s) | N3Term::Formula(s) => {
482            s.to_ascii_lowercase()
483        }
484    };
485
486    let is_obligate =
487        p_str.contains("obligate") || p_str.contains("must") || p_str.contains("shall");
488    let is_permit = p_str.contains("permit") || p_str.contains("may") || p_str.contains("can");
489    let is_forbid = p_str.contains("forbid") || p_str.contains("not") || p_str.contains("prohibit");
490
491    let mut opcode = OP_PERMIT;
492    let mut is_defeater = false;
493
494    match rule.rule_type {
495        RuleType::Strict => {
496            opcode = if is_obligate { OP_OBLIGATE } else { OP_PERMIT };
497        }
498        RuleType::Defeasible => {
499            if is_forbid {
500                opcode = OP_FORBID;
501            } else if is_permit {
502                opcode = OP_PERMIT;
503            }
504        }
505        RuleType::Defeater => {
506            opcode = OP_PERMIT;
507            is_defeater = true;
508        }
509        RuleType::Linear => {
510            opcode = if is_obligate { OP_OBLIGATE } else { OP_PERMIT };
511        }
512    }
513
514    let mut predicate_packed =
515        ((property_path_hash & 0x007F_FFFF_FFFF_FFFF) << 8) | (opcode as u64);
516    if is_defeater {
517        predicate_packed |= DEFEATER_BIT;
518    }
519
520    let parity = party_did_hash ^ predicate_packed ^ action_object_hash ^ mapped_contract_hash;
521
522    Some(crate::NQuin {
523        subject: party_did_hash,
524        predicate: predicate_packed,
525        object: action_object_hash,
526        context: mapped_contract_hash,
527        metadata: expiry_unix32 as u64,
528        parity,
529    })
530}
531
532/// Compile a ratified `AgreementDID` into authorized deontic norm Quins.
533pub fn compile_agreement_to_deontic_norms(
534    agreement: &AgreementDID,
535    expiry_unix32: u32,
536    out: &mut [crate::NQuin],
537) -> usize {
538    if agreement.current_state != AgreementState::Ratified || out.is_empty() {
539        return 0;
540    }
541    let mut written = 0;
542    let has_domain_scope = crate::q_hash("q42:hasDomainScope");
543
544    for i in 0..agreement.num_agents as usize {
545        if written >= out.len() {
546            break;
547        }
548        let agent = agreement.agents[i];
549        let predicate = ((has_domain_scope & 0x007F_FFFF_FFFF_FFFF) << 8) | (OP_PERMIT as u64);
550        let object = agreement.domain_id;
551        let context = agreement.agreement_id;
552        let metadata = (expiry_unix32 as u64) | 0x4000_0000_0000_0002;
553        let parity = agent ^ predicate ^ object ^ context;
554
555        out[written] = crate::NQuin {
556            subject: agent,
557            predicate,
558            object,
559            context,
560            metadata,
561            parity,
562        };
563        written += 1;
564    }
565    written
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571
572    fn test_vault() -> KeyVault {
573        let tmp = tempfile::tempdir().expect("tmpdir");
574        KeyVault::load_or_generate(tmp.path().to_str().unwrap()).expect("vault")
575    }
576
577    const ISSUER: u64 = 0x1550_0000_0000_CAFE;
578    const AGENT: u64 = 0xA6E4_7777_0000_0001;
579
580    fn vc_with_role(role: u64, clearance: u8) -> VcAttributes {
581        let mut vc = VcAttributes::unauthenticated(AGENT);
582        vc.roles[0] = role;
583        vc.role_count = 1;
584        vc.clearance_level = clearance;
585        vc.credential_issuer = ISSUER;
586        vc
587    }
588
589    #[test]
590    fn public_layer_always_accessible() {
591        let vault = test_vault();
592        let vc = VcAttributes::unauthenticated(AGENT);
593        let result = evaluate_vc_for_subgraph_key_release(&vault, &vc, SubgraphLayer::Public, &[]);
594        assert!(result.is_permitted());
595    }
596
597    #[test]
598    fn professional_layer_requires_role_or_clearance() {
599        let vault = test_vault();
600
601        // No role, no clearance → deny.
602        let no_vc = VcAttributes::unauthenticated(AGENT);
603        assert!(!evaluate_vc_for_subgraph_key_release(
604            &vault,
605            &no_vc,
606            SubgraphLayer::Professional,
607            &[]
608        )
609        .is_permitted());
610
611        // Professional role → permit.
612        let pro = vc_with_role(vc_roles::PROFESSIONAL, 0);
613        assert!(evaluate_vc_for_subgraph_key_release(
614            &vault,
615            &pro,
616            SubgraphLayer::Professional,
617            &[]
618        )
619        .is_permitted());
620
621        // Clearance 1 → permit.
622        let cleared = vc_with_role(0, 1);
623        assert!(evaluate_vc_for_subgraph_key_release(
624            &vault,
625            &cleared,
626            SubgraphLayer::Professional,
627            &[]
628        )
629        .is_permitted());
630    }
631
632    #[test]
633    fn medical_layer_requires_role_or_clearance_3() {
634        let vault = test_vault();
635
636        let low = vc_with_role(vc_roles::PROFESSIONAL, 0);
637        assert!(
638            !evaluate_vc_for_subgraph_key_release(&vault, &low, SubgraphLayer::Medical, &[])
639                .is_permitted()
640        );
641
642        let med_role = vc_with_role(vc_roles::MEDICAL_PROFESSIONAL, 0);
643        assert!(evaluate_vc_for_subgraph_key_release(
644            &vault,
645            &med_role,
646            SubgraphLayer::Medical,
647            &[]
648        )
649        .is_permitted());
650
651        let cleared = vc_with_role(0, 3);
652        assert!(evaluate_vc_for_subgraph_key_release(
653            &vault,
654            &cleared,
655            SubgraphLayer::Medical,
656            &[]
657        )
658        .is_permitted());
659    }
660
661    #[test]
662    fn fiduciary_layer_strictest() {
663        let vault = test_vault();
664
665        let med = vc_with_role(vc_roles::MEDICAL_PROFESSIONAL, 3);
666        assert!(
667            !evaluate_vc_for_subgraph_key_release(&vault, &med, SubgraphLayer::Fiduciary, &[])
668                .is_permitted()
669        );
670
671        let fid = vc_with_role(vc_roles::FIDUCIARY, 0);
672        assert!(
673            evaluate_vc_for_subgraph_key_release(&vault, &fid, SubgraphLayer::Fiduciary, &[])
674                .is_permitted()
675        );
676    }
677
678    #[test]
679    fn trusted_issuer_check_blocks_unknown_issuer() {
680        let vault = test_vault();
681        let trusted = [ISSUER];
682
683        let mut vc = vc_with_role(vc_roles::FIDUCIARY, 4);
684        vc.credential_issuer = 0xBAD_CAFE; // wrong issuer
685        assert!(!evaluate_vc_for_subgraph_key_release(
686            &vault,
687            &vc,
688            SubgraphLayer::Fiduciary,
689            &trusted
690        )
691        .is_permitted());
692
693        vc.credential_issuer = ISSUER; // correct issuer
694        assert!(evaluate_vc_for_subgraph_key_release(
695            &vault,
696            &vc,
697            SubgraphLayer::Fiduciary,
698            &trusted
699        )
700        .is_permitted());
701    }
702
703    #[test]
704    fn evaluate_accessible_layers_returns_permitted_set() {
705        let vault = test_vault();
706        // clearance 2 → Public + Professional + Legal, not Medical or Fiduciary.
707        let vc = vc_with_role(0, 2);
708        let mut out: [Option<(SubgraphLayer, SubgraphKey)>; 5] = [None, None, None, None, None];
709        let count = evaluate_accessible_layers(&vault, &vc, &[], &mut out);
710        assert_eq!(count, 3);
711        let layers = [
712            out[0].as_ref().unwrap().0,
713            out[1].as_ref().unwrap().0,
714            out[2].as_ref().unwrap().0,
715        ];
716        assert_eq!(
717            layers,
718            [
719                SubgraphLayer::Public,
720                SubgraphLayer::Professional,
721                SubgraphLayer::Legal
722            ]
723        );
724    }
725
726    #[test]
727    fn vc_attributes_from_quins_extracts_role_and_clearance() {
728        let quins = write_vc_claim_quins(AGENT, &[vc_roles::MEDICAL_PROFESSIONAL], 3, ISSUER, 1000);
729        let attrs = VcAttributes::from_quins(AGENT, &quins);
730        assert_eq!(attrs.role_count, 1);
731        assert!(attrs.has_role(vc_roles::MEDICAL_PROFESSIONAL));
732        assert_eq!(attrs.clearance_level, 3);
733        assert_eq!(attrs.credential_issuer, ISSUER);
734    }
735
736    #[test]
737    fn test_child_medical_data_egress_violation() {
738        use crate::mini_parser::{OP_END, OP_EVAL_PERMIT};
739        use crate::webizen_bytecode::{execute_program, GuardianshipContext, VmError};
740
741        let child_did = crate::q_hash("did:q42:child");
742        let medical_data = crate::q_hash("MedicalData");
743        let share_data = crate::q_hash("q42:shareData");
744
745        let mut intent_quin = crate::NQuin::default();
746        intent_quin.subject = child_did;
747        intent_quin.predicate = share_data;
748        intent_quin.object = medical_data;
749
750        let db = [intent_quin];
751        let mut prog = [0u8; 1024];
752        // Program just has OP_EVAL_PERMIT then OP_END
753        prog[0] = OP_EVAL_PERMIT;
754        prog[1] = OP_END;
755
756        let mut out = [crate::NQuin::default(); 10];
757
758        let context = GuardianshipContext {
759            principal_did: child_did,
760            guardian_did: None, // No active guardian signature
761        };
762
763        let result = execute_program(&prog, &db, &mut out, Some(&context));
764        assert_eq!(result, Err(VmError::HaltViolation));
765    }
766
767    #[test]
768    fn test_compile_n3_rule_to_norm() {
769        use crate::modalities::logic::n3_parser::RuleType;
770
771        use crate::modalities::logic::n3_compiler::{
772            CompiledFormula, CompiledTerm, CompiledTriple,
773        };
774        let make_rule = |rt: RuleType, pred: &str| -> CompiledRule {
775            let mut premise_triples = [CompiledTriple {
776                subject: CompiledTerm::Uri(0),
777                predicate: CompiledTerm::Uri(0),
778                object: CompiledTerm::Uri(0),
779            }; 8];
780            premise_triples[0] = CompiledTriple {
781                subject: CompiledTerm::Uri(crate::q_hash("did:party")),
782                predicate: CompiledTerm::Uri(crate::q_hash(pred)),
783                object: CompiledTerm::Uri(crate::q_hash("did:target")),
784            };
785            let mut conclusion_triples = [CompiledTriple {
786                subject: CompiledTerm::Uri(0),
787                predicate: CompiledTerm::Uri(0),
788                object: CompiledTerm::Uri(0),
789            }; 8];
790            conclusion_triples[0] = CompiledTriple {
791                subject: CompiledTerm::Uri(crate::q_hash("urn:contract")),
792                predicate: CompiledTerm::Uri(crate::q_hash("q42:boundBy")),
793                object: CompiledTerm::Uri(crate::q_hash("did:party")),
794            };
795            CompiledRule {
796                id_hash: None,
797                rule_type: rt,
798                weight: None,
799                premise: CompiledFormula {
800                    triples: premise_triples,
801                    len: 1,
802                },
803                conclusion: CompiledFormula {
804                    triples: conclusion_triples,
805                    len: 1,
806                },
807            }
808        };
809
810        let contract_hash = 12345;
811
812        // 1. Defeater
813        let defeater_rule = make_rule(RuleType::Defeater, "q42:permit");
814        let q = compile_n3_rule_to_norm(&defeater_rule, contract_hash, 0).unwrap();
815        assert_eq!(
816            q.predicate & 0xFF,
817            crate::modalities::logic::deontic::OP_PERMIT as u64
818        );
819        assert_ne!(
820            q.predicate & crate::modalities::logic::deontic::DEFEATER_BIT,
821            0
822        );
823
824        // 2. Defeasible Permit
825        let permit_rule = make_rule(RuleType::Defeasible, "q42:permit");
826        let q2 = compile_n3_rule_to_norm(&permit_rule, contract_hash, 0).unwrap();
827        assert_eq!(
828            q2.predicate & 0xFF,
829            crate::modalities::logic::deontic::OP_PERMIT as u64
830        );
831        assert_eq!(
832            q2.predicate & crate::modalities::logic::deontic::DEFEATER_BIT,
833            0
834        );
835
836        // 3. Strict Obligate
837        let obligate_rule = make_rule(RuleType::Strict, "q42:obligate");
838        let q3 = compile_n3_rule_to_norm(&obligate_rule, contract_hash, 0).unwrap();
839        assert_eq!(
840            q3.predicate & 0xFF,
841            crate::modalities::logic::deontic::OP_OBLIGATE as u64
842        );
843        assert_eq!(
844            q3.predicate & crate::modalities::logic::deontic::DEFEATER_BIT,
845            0
846        );
847
848        // 4. Malformed
849        let mut malformed = make_rule(RuleType::Strict, "q42:obligate");
850        malformed.premise.len = 0;
851        assert!(compile_n3_rule_to_norm(&malformed, contract_hash, 0).is_none());
852    }
853
854    #[test]
855    fn test_compile_n3_ast_and_stack_rules_and_agreements() {
856        use crate::modalities::logic::n3_parser::{
857            Formula, Rule as N3Rule, StackFormula, StackRule as N3StackRule, Term as N3Term,
858            Triple as N3Triple,
859        };
860
861        let t1 = N3Triple {
862            subject: N3Term::Uri("did:agent:alice"),
863            predicate: N3Term::Uri("q42:mayEnter"),
864            object: N3Term::Uri("zone:park"),
865        };
866        let t2 = N3Triple {
867            subject: N3Term::Uri("urn:contract:sanctuary"),
868            predicate: N3Term::Uri("q42:appliesTo"),
869            object: N3Term::Uri("zone:park"),
870        };
871
872        // AST Defeater rule
873        let ast_defeater = N3Rule {
874            id: Some("r1"),
875            rule_type: RuleType::Defeater,
876            weight: None,
877            premise: Formula { triples: vec![t1] },
878            conclusion: Formula { triples: vec![t2] },
879        };
880        let norm1 = compile_n3_ast_rule_to_norm(&ast_defeater, 0, 1000).expect("ast norm compiles");
881        assert_eq!(norm1.predicate & 0xFF, OP_PERMIT as u64);
882        assert_ne!(norm1.predicate & DEFEATER_BIT, 0);
883
884        // Stack strict obligate rule
885        let mut s_premise = StackFormula::new();
886        s_premise.triples[0] = N3Triple {
887            subject: N3Term::Uri("did:agent:bob"),
888            predicate: N3Term::Uri("q42:mustPayFee"),
889            object: N3Term::Literal("10"),
890        };
891        s_premise.len = 1;
892        let mut s_conclusion = StackFormula::new();
893        s_conclusion.triples[0] = t2;
894        s_conclusion.len = 1;
895
896        let stack_rule = N3StackRule {
897            id: None,
898            rule_type: RuleType::Strict,
899            weight: None,
900            premise: s_premise,
901            conclusion: s_conclusion,
902        };
903        let norm2 = compile_stack_rule_to_norm(&stack_rule, 0, 2000).expect("stack norm compiles");
904        assert_eq!(norm2.predicate & 0xFF, OP_OBLIGATE as u64);
905        assert_eq!(norm2.predicate & DEFEATER_BIT, 0);
906
907        // AgreementDID compile to deontic norms
908        let mut agreement = AgreementDID {
909            agreement_id: 0x9999,
910            principal: 0x1111,
911            agents: [0x2222, 0x3333, 0, 0, 0, 0, 0, 0],
912            num_agents: 2,
913            domain_id: 0x4444,
914            threshold: 2,
915            current_state: AgreementState::Ratified,
916        };
917        let mut agreement_norms = [crate::NQuin::default(); 4];
918        let count = compile_agreement_to_deontic_norms(&agreement, 3000, &mut agreement_norms);
919        assert_eq!(count, 2);
920        assert_eq!(agreement_norms[0].subject, 0x2222);
921        assert_eq!(agreement_norms[0].predicate & 0xFF, OP_PERMIT as u64);
922        assert_eq!(agreement_norms[1].subject, 0x3333);
923
924        agreement.current_state = AgreementState::Proposed;
925        assert_eq!(
926            compile_agreement_to_deontic_norms(&agreement, 3000, &mut agreement_norms),
927            0
928        );
929    }
930}