Skip to main content

qualia_core_db/modalities/logic/
deontic.rs

1//! Deontic Logic extension for the Qualia Bytecode VM.
2//!
3//! Implements a defeasible deontic contract evaluator over a `&[NQuin]` slice.
4//! Conforms to the 42 MB Prolog Sentinel memory ceiling, the 48-byte Super-Quin
5//! invariant, and the zero-heap-allocation mandate (no `Vec`, `String`, or `Box`).
6//!
7//! # Opcodes
8//!
9//! Three raw `u8` constants define the deontic modality, packed into **bits 0–7** of
10//! the `predicate` field of every norm Quin:
11//!
12//! | Constant      | Value | SDL formula | Meaning                          |
13//! |---------------|-------|-------------|----------------------------------|
14//! | `OP_OBLIGATE` | 0x10  | O(φ)        | Party *must* perform action φ    |
15//! | `OP_PERMIT`   | 0x11  | P(φ)        | Party *may* perform action φ     |
16//! | `OP_FORBID`   | 0x12  | F(φ)=O(¬φ)  | Party *must not* perform action φ|
17//!
18//! # 48-byte Norm Quin Layout
19//!
20//! ```text
21//! ┌──────────┬──────────────────────────────────────────────────────────────────┐
22//! │ Field    │ Bit layout                                                       │
23//! ├──────────┼──────────────────────────────────────────────────────────────────┤
24//! │ subject  │ [63]=0 (rsvd)  │ [0..62] = FNV-1a hash of the bound party DID  │
25//! │ predicate│ [63]=DEFEATER  │ [8..62] = property-path hash (action/norm URI) │
26//! │          │                │ [0..7]  = deontic opcode (OP_OBLIGATE etc.)    │
27//! │ object   │ [63]=0 (rsvd)  │ [0..62] = FNV-1a hash of the action object    │
28//! │ context  │ [56..63] = sensitivity class (from NQuin::SENSITIVITY_*)   │
29//! │          │ [0..55]  = q_hash of the contract/graph DID                     │
30//! │ metadata │ [61..62] = PermissiveRoutingLane bits                           │
31//! │          │ [32..60] = Lamport logical clock                                │
32//! │          │ [0..31]  = expiry as truncated Unix-32 timestamp                │
33//! │ parity   │ XOR fold of subject ⊕ predicate ⊕ object ⊕ context (ECC check)  │
34//! └──────────┴──────────────────────────────────────────────────────────────────┘
35//! ```
36//!
37//! # Defeater Nodes — `q42:unless`
38//!
39//! A Quin with **bit 63 of `predicate` set** (`DEFEATER_BIT`) is not a primary norm;
40//! it is a `q42:unless` exception node that defeats any norm sharing the same
41//! (subject, context, property-path) fingerprint.  This supports non-monotonic,
42//! defeasible reasoning:
43//!
44//! > *Alice is forbidden from disclosing project data — **unless** she is speaking
45//! > to a certified auditor.*
46//!
47//! The evaluator performs a two-phase linear scan:
48//! 1. **Defeater harvest** — collect up to `MAX_DEFEATER_SLOTS` fingerprints into
49//!    a fixed `[u64; 64]` stack buffer (512 bytes, one cache-line group on Cortex-A78).
50//! 2. **Norm evaluation** — for each non-defeater Quin: check expiry, probe the
51//!    defeater buffer, emit a `DeonticVerdict` into the caller-supplied `out` slice.
52//!
53//! # Legal SHACL Blueprint
54//!
55//! ## Non-Disclosure Agreement (NDA)
56//!
57//! NDA between `did:web:alice.example` and `did:web:bob.example`, covering
58//! confidential project-X data, valid until 2028-01-01 (Unix epoch 1 830 297 600).
59//! Three Quins fully encode the agreement and its auditor exception:
60//!
61//! ```text
62//! // Quin 1 — Alice's confidentiality prohibition
63//! subject   = q_hash("did:web:alice.example")
64//! predicate = OP_FORBID as u64
65//!           | (q_hash("q42:disclose") << 8)           // property-path in [8..62]
66//! object    = q_hash("q42:data:project-x:confidential")
67//! context   = q_hash("did:web:nda:contract-001")      // contract graph
68//! metadata  = 1_830_297_600_u64                        // expiry in bits [0..31]
69//! parity    = subject ^ predicate ^ object ^ context   // ECC fold
70//!
71//! // Quin 2 — Bob's symmetric prohibition (identical structure, different subject)
72//! subject   = q_hash("did:web:bob.example")
73//! predicate = OP_FORBID as u64 | (q_hash("q42:disclose") << 8)
74//! object    = q_hash("q42:data:project-x:confidential")
75//! context   = q_hash("did:web:nda:contract-001")
76//! metadata  = 1_830_297_600_u64
77//! parity    = subject ^ predicate ^ object ^ context
78//!
79//! // Quin 3 — Defeater: Alice MAY disclose to a certified auditor (q42:unless)
80//! subject   = q_hash("did:web:alice.example")
81//! predicate = DEFEATER_BIT                             // bit 63 marks q42:unless
82//!           | OP_PERMIT as u64
83//!           | (q_hash("q42:disclose") << 8)           // same property-path as Quin 1
84//! object    = q_hash("q42:role:certified-auditor")    // excepted entity class
85//! context   = q_hash("did:web:nda:contract-001")      // same contract graph
86//! metadata  = 1_830_297_600_u64
87//! parity    = subject ^ predicate ^ object ^ context
88//! ```
89//!
90//! Quin 3 shares (subject, context, property-path) with Quin 1, so the evaluator
91//! marks Quin 1 as `DeonticStatus::Defeated` when an auditor invokes the exception.
92//!
93//! ## Guardianship Contract
94//!
95//! Ward: `did:web:ward.example`, Guardian: `did:web:guardian.example`.
96//! Guardianship expires at majority (2030-01-01, epoch 1 893 456 000):
97//!
98//! ```text
99//! // Quin 1 — Guardian obligated to act in the ward's best interest
100//! subject   = q_hash("did:web:guardian.example")
101//! predicate = OP_OBLIGATE as u64
102//!           | (q_hash("q42:actInBestInterest") << 8)
103//! object    = q_hash("did:web:ward.example")
104//! context   = q_hash("did:web:guardianship:contract-002")
105//! metadata  = 1_893_456_000_u64   // contract expires when ward reaches majority
106//! parity    = subject ^ predicate ^ object ^ context
107//!
108//! // Quin 2 — Temporal defeater: ward may self-determine after majority age
109//! subject   = q_hash("did:web:ward.example")
110//! predicate = DEFEATER_BIT
111//!           | OP_PERMIT as u64
112//!           | (q_hash("q42:actInBestInterest") << 8)  // defeats the same obligation path
113//! object    = q_hash("did:web:ward.example")
114//! context   = q_hash("did:web:guardianship:contract-002")
115//! metadata  = 1_893_456_000_u64   // carries same timestamp; expiry semantics applied
116//! parity    = subject ^ predicate ^ object ^ context
117//! ```
118//!
119//! After majority, `now_unix > 1_893_456_000` causes Quin 1 to emit
120//! `DeonticStatus::Expired`, and the defeater Quin 2 itself becomes moot —
121//! demonstrating how temporal bounds compose naturally with defeasibility in a
122//! single linear scan without branching stacks.
123//!
124//! # Edge-native 3-core CPU triad
125//!
126//! The two-phase design maps to the triad naturally:
127//! - **Core 0** — defeater harvest (Phase 1, read-only, highly prefetchable).
128//! - **Core 1** — norm evaluation (Phase 2, linear probe of the 512-byte buffer).
129//! - **Core 2** — verdict dispatch / downstream enforcement routing.
130//!
131//! Cache-line pressure is bounded: the `[u64; MAX_DEFEATER_SLOTS]` buffer fits in
132//! 8 × 64-byte cache lines; each `DeonticVerdict` is 64 bytes (one cache line).
133
134#[cfg(any(
135    not(target_arch = "wasm32"),
136    feature = "wasm-scientific",
137    feature = "wasm-full"
138))]
139use crate::modalities::logic::n3_parser::Term;
140use crate::q_hash;
141use crate::NQuin;
142
143// ─── Deontic Opcodes ─────────────────────────────────────────────────────────
144//
145// These u8 constants are packed into bits [0..7] of the `predicate` field of
146// every norm Quin.  Values 0x10–0x12 are chosen above the mini_parser opcode
147// range (0x00–0x04) to allow mixed Quin databases without collision.
148
149/// O(φ) — the subject party *must* perform the action.
150pub const OP_OBLIGATE: u8 = 0x10;
151
152/// P(φ) — the subject party *may* perform the action.
153pub const OP_PERMIT: u8 = 0x11;
154
155/// F(φ) = O(¬φ) — the subject party *must not* perform the action.
156pub const OP_FORBID: u8 = 0x12;
157
158// ─── SDL⁺ extension opcodes (deontic block 0x13–0x1F, per DEONTIC_LOGIC_PLAN §3) ──
159
160/// U(φ) — optionality / indifference: `¬O(φ) ∧ ¬F(φ)`. The system is indifferent;
161/// neither doing nor omitting φ is a violation. May be asserted or derived
162/// (see [`is_optional`]).
163pub const OP_OPTIONAL: u8 = 0x13;
164
165/// G(φ) — gratuitousness: `¬O(φ)`. The agent is free to omit φ (it may still be
166/// permitted or forbidden). May be asserted or derived (see [`is_gratuitous`]).
167pub const OP_GRATUITOUS: u8 = 0x14;
168
169/// O(q | p) — the head of a dyadic / conditional obligation: q is obligatory
170/// *given* condition p. Evaluation is fact-driven (see [`evaluate_conditional_obligation`]);
171/// contrary-to-duty is the special case p = "primary breached".
172pub const OP_CONDITIONAL: u8 = 0x15;
173
174/// Reserved for Phase 3 (STIT agency): `O[α stit φ]`. Declared here to fence the
175/// opcode so nothing else claims it before agency lands.
176pub const OP_STIT: u8 = 0x16;
177
178/// An *undercutting* defeater: combined with [`DEFEATER_BIT`] it invalidates the
179/// inference link `p ⇒ Oq` without asserting `¬Oq` (vs a *rebutting* defeater — a
180/// `DEFEATER_BIT` node with an O/P/F opcode — which asserts the contrary). The
181/// fingerprint match is identical (the opcode byte is masked out); only the
182/// classification in [`DefeatKind`] differs.
183pub const OP_UNDERCUT: u8 = 0x17;
184
185/// Bit 63 of `predicate`: marks a `q42:unless` defeater / exception node.
186/// When set the Quin is *not* a primary norm and defeats matching obligations.
187/// Canonical bit position lives in the FrameLayout ABI (single source of truth).
188pub use crate::frame_layout::DEFEATER_BIT;
189
190/// Stack capacity for defeater fingerprints per evaluation call.
191/// 64 slots × 8 bytes = 512 bytes — fits within a single L1 cache-line group.
192pub const MAX_DEFEATER_SLOTS: usize = 64;
193
194// ─── DeonticStatus ────────────────────────────────────────────────────────────
195
196/// The result of evaluating a single norm Quin against temporal bounds and defeaters.
197#[repr(u8)]
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
199pub enum DeonticStatus {
200    #[default]
201    /// Norm is temporally valid and has no active defeater.
202    Active = 0x00,
203    /// A matching `q42:unless` defeater node was found; obligation is overridden.
204    Defeated = 0x01,
205    /// Current timestamp exceeds the expiry embedded in `metadata[0..31]`.
206    Expired = 0x02,
207    /// The Quin's predicate carries an unrecognised opcode byte; skipped by caller.
208    Malformed = 0x03,
209    /// Norm is parsed and valid, but its effectivity window has not yet begun
210    /// (`now < effective_from`). Not yet binding. (Lifecycle, Phase 1.)
211    Pending = 0x04,
212    /// An in-force obligation whose action was not performed (or a prohibition that
213    /// was breached), per the supplied facts. Triggers CTD / sanction routing.
214    Violated = 0x05,
215    /// An in-force obligation that has been fulfilled per the supplied facts; the
216    /// specific duty terminates.
217    Discharged = 0x06,
218}
219
220/// How a norm came to be [`DeonticStatus::Defeated`] — Hart/Pollock's rebutting vs
221/// undercutting distinction. A *rebutting* defeater asserts the contrary conclusion
222/// (`DEFEATER_BIT` + an O/P/F opcode); an *undercutting* defeater ([`OP_UNDERCUT`])
223/// severs the rule's support without asserting the contrary.
224#[repr(u8)]
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
226pub enum DefeatKind {
227    #[default]
228    /// Not defeated.
229    None = 0x00,
230    /// Defeated by a contrary norm (rebutting).
231    Rebutting = 0x01,
232    /// Defeated by link-invalidation (undercutting).
233    Undercutting = 0x02,
234}
235
236// ─── DeonticVerdict ───────────────────────────────────────────────────────────
237
238/// A verdict emitted for one norm Quin.  Exactly 64 bytes — one cache line.
239///
240/// Layout: 48-byte norm Quin + 1-byte status + 1-byte opcode + 6-byte pad = 56 B
241/// aligned to 8, padded by the compiler to the nearest power-of-two boundary.
242#[repr(C, align(8))]
243#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
244pub struct DeonticVerdict {
245    /// The original norm Quin that was evaluated.
246    pub norm: NQuin,
247    /// Outcome of the evaluation.
248    pub status: DeonticStatus,
249    /// Deontic opcode extracted from `norm.predicate[0..7]`.
250    pub opcode: u8,
251    /// When `status == Defeated`, *how* it was defeated (rebutting vs undercutting);
252    /// `None` otherwise.
253    pub defeat_kind: DefeatKind,
254    _pad: [u8; 5],
255}
256
257// ─── DeonticError ─────────────────────────────────────────────────────────────
258
259#[derive(Debug, PartialEq)]
260pub enum DeonticError {
261    /// The caller-supplied `out` slice was exhausted before the scan completed.
262    OutputBufferFull,
263}
264
265// ─── Bit-field helpers ────────────────────────────────────────────────────────
266
267/// Extracts the deontic opcode from bits [0..7] of a `predicate` word.
268#[inline(always)]
269pub fn extract_deontic_opcode(predicate: u64) -> u8 {
270    (predicate & 0xFF) as u8
271}
272
273/// Extracts the 32-bit expiry from bits [0..31] of a `metadata` word.
274/// A zero value means "no expiry set" and is always treated as valid.
275#[inline(always)]
276pub fn extract_expiry_unix32(metadata: u64) -> u32 {
277    (metadata & 0xFFFF_FFFF) as u32
278}
279
280/// Produces the defeater-matching fingerprint for any Quin (norm or defeater).
281///
282/// Two Quins share a fingerprint iff they bind the same party (`subject`),
283/// the same contract graph (`context`), and the same property-path
284/// (`predicate[8..62]` — the portion above the opcode byte and below the
285/// defeater bit).  The opcode byte and defeater bit are masked out so that a
286/// `q42:unless` node correctly matches the norm it defeats.
287#[inline(always)]
288pub fn defeater_fingerprint(q: &NQuin) -> u64 {
289    // Strip defeater bit (63) and opcode byte (0..7); retain property-path (8..62).
290    let path_bits = q.predicate & 0x7FFF_FFFF_FFFF_FF00;
291    q.subject ^ q.context ^ path_bits
292}
293
294/// Harvest `q42:unless` defeater fingerprints from a contract slice (Phase 1 only).
295pub fn harvest_defeater_fingerprints(quins: &[NQuin], out: &mut [u64]) -> usize {
296    let mut count = 0usize;
297    for &q in quins {
298        if q.predicate & DEFEATER_BIT == 0 {
299            continue;
300        }
301        let expected_parity = q.subject ^ q.predicate ^ q.object ^ q.context;
302        if q.parity == expected_parity && count < out.len() {
303            out[count] = defeater_fingerprint(&q);
304            count += 1;
305        }
306    }
307    count
308}
309
310/// Returns `true` if the defeater buffer contains a fingerprint that matches `norm`.
311#[inline]
312pub fn norm_has_active_defeater(norm: &NQuin, defeaters: &[u64]) -> bool {
313    has_defeater(defeaters, norm)
314}
315
316#[inline]
317fn has_defeater(defeaters: &[u64], norm: &NQuin) -> bool {
318    let key = defeater_fingerprint(norm);
319    let mut i = 0;
320    while i < defeaters.len() {
321        if defeaters[i] == key {
322            return true;
323        }
324        i += 1;
325    }
326    false
327}
328
329/// Like [`has_defeater`], but returns *which kind* of defeater matched (rebutting vs
330/// undercutting), or [`DefeatKind::None`] if the norm is undefeated. `kinds[i]` is the
331/// kind of `defeaters[i]` (parallel arrays harvested together).
332#[inline]
333fn defeater_kind_for(defeaters: &[u64], kinds: &[DefeatKind], norm: &NQuin) -> DefeatKind {
334    let key = defeater_fingerprint(norm);
335    let mut i = 0;
336    while i < defeaters.len() {
337        if defeaters[i] == key {
338            return kinds[i];
339        }
340        i += 1;
341    }
342    DefeatKind::None
343}
344
345// ─── evaluate_deontic_contract ────────────────────────────────────────────────
346
347/// Evaluate a deontic contract encoded as a `&[NQuin]` slice.
348///
349/// ## Algorithm
350///
351/// **Phase 1 — Defeater harvest** (single forward pass, O(n)):
352/// Every Quin whose `predicate` has `DEFEATER_BIT` set is identified as a
353/// `q42:unless` defeater.  Its fingerprint is written into the fixed-capacity
354/// `[u64; MAX_DEFEATER_SLOTS]` stack buffer.  Excess defeaters beyond
355/// `MAX_DEFEATER_SLOTS` are silently dropped (contracts this large exceed the
356/// 42 MB Prolog Sentinel and are rejected at ingest time).
357///
358/// **Phase 2 — Norm evaluation** (single forward pass, O(n)):
359/// Every Quin whose `predicate[0..7]` ∈ {`OP_OBLIGATE`, `OP_PERMIT`, `OP_FORBID`}
360/// and whose `DEFEATER_BIT` is **clear** is a primary norm.  For each:
361/// 1. Temporal check: if `expiry != 0 && now_unix > expiry` → `Expired`.
362/// 2. Defeater probe: if `has_defeater(buffer, quin)` → `Defeated`.
363/// 3. Otherwise → `Active`.
364///
365/// Non-deontic Quins (opcode not in the set above) are skipped silently.
366///
367/// ## Constraints
368///
369/// - Zero heap allocation: all state lives in registers and the caller-supplied
370///   `out` slice.
371/// - Stack budget: `8 × MAX_DEFEATER_SLOTS` bytes (512 B) + frame overhead.
372/// - Deterministic O(n²) worst-case defeater probe, O(n) amortised for contracts
373///   with few exceptions (the common case in legal documents).
374///
375/// ## Parameters
376///
377/// * `quins`     — the deontic contract encoded as a Quin slice.
378/// * `now_unix`  — current time as a truncated 32-bit Unix timestamp.
379/// * `out`       — caller-supplied verdict buffer; must be `≥` the number of
380///                 norm Quins in `quins` to avoid `OutputBufferFull`.
381///
382/// ## Returns
383///
384/// `Ok(n)` where `n` is the number of verdicts written to `out[..n]`.
385pub fn evaluate_deontic_contract(
386    quins: &[NQuin],
387    now_unix: u32,
388    out: &mut [DeonticVerdict],
389) -> Result<usize, DeonticError> {
390    // ── Phase 1: harvest defeater fingerprints ─────────────────────────────────
391    //
392    // Stack-allocated; fits in < 1 KB, well within any thread stack.
393    let mut defeater_buf = [0u64; MAX_DEFEATER_SLOTS];
394    let mut kind_buf = [DefeatKind::Rebutting; MAX_DEFEATER_SLOTS];
395    let mut defeater_count = 0usize;
396
397    for &q in quins {
398        if q.predicate & DEFEATER_BIT != 0 {
399            // ECC Parity XOR fold check
400            let expected_parity = q.subject ^ q.predicate ^ q.object ^ q.context;
401            if q.parity == expected_parity {
402                if defeater_count < MAX_DEFEATER_SLOTS {
403                    defeater_buf[defeater_count] = defeater_fingerprint(&q);
404                    // OP_UNDERCUT severs the rule link; any other opcode rebuts.
405                    kind_buf[defeater_count] = if extract_deontic_opcode(q.predicate) == OP_UNDERCUT
406                    {
407                        DefeatKind::Undercutting
408                    } else {
409                        DefeatKind::Rebutting
410                    };
411                    defeater_count += 1;
412                }
413                // Excess defeaters are dropped; contracts this dense are rejected upstream.
414            }
415        }
416    }
417
418    let active_defeaters = &defeater_buf[..defeater_count];
419    let active_kinds = &kind_buf[..defeater_count];
420
421    // ── Phase 2: evaluate norm Quins ──────────────────────────────────────────
422    let mut verdict_count = 0usize;
423
424    for &q in quins {
425        // Defeater nodes are not norms; skip them in the second pass.
426        if q.predicate & DEFEATER_BIT != 0 {
427            continue;
428        }
429
430        let expected_parity = q.subject ^ q.predicate ^ q.object ^ q.context;
431        if q.parity != expected_parity {
432            if verdict_count >= out.len() {
433                return Err(DeonticError::OutputBufferFull);
434            }
435            out[verdict_count] = DeonticVerdict {
436                norm: q,
437                status: DeonticStatus::Malformed,
438                opcode: extract_deontic_opcode(q.predicate),
439                defeat_kind: DefeatKind::None,
440                _pad: [0u8; 5],
441            };
442            verdict_count += 1;
443            continue;
444        }
445
446        let opcode = extract_deontic_opcode(q.predicate);
447
448        let mut defeat_kind = DefeatKind::None;
449        let status = match opcode {
450            OP_OBLIGATE | OP_PERMIT | OP_FORBID => {
451                let expiry = extract_expiry_unix32(q.metadata);
452                if expiry != 0 && now_unix > expiry {
453                    DeonticStatus::Expired
454                } else {
455                    let k = defeater_kind_for(active_defeaters, active_kinds, &q);
456                    if k != DefeatKind::None {
457                        defeat_kind = k;
458                        DeonticStatus::Defeated
459                    } else {
460                        DeonticStatus::Active
461                    }
462                }
463            }
464            // Not a deontic Quin — skip silently (e.g. SHACL shape Quins coexist).
465            _ => continue,
466        };
467
468        if verdict_count >= out.len() {
469            return Err(DeonticError::OutputBufferFull);
470        }
471
472        out[verdict_count] = DeonticVerdict {
473            norm: q,
474            status,
475            opcode,
476            defeat_kind,
477            _pad: [0u8; 5],
478        };
479        verdict_count += 1;
480    }
481
482    Ok(verdict_count)
483}
484
485// ─── N3 → deontic norm bridge ───────────────────────────────────────────────
486
487#[cfg(any(
488    not(target_arch = "wasm32"),
489    feature = "wasm-scientific",
490    feature = "wasm-full"
491))]
492/// Resolve an N3 `Term` to its 60-bit URI hash (`Some`) or `None` for
493/// non-IRI terms (literals, variables, formulas). Feature-gated shim over
494/// `n3_parser::term_uri_hash` — unavailable on bare `wasm32` builds.
495pub fn term_uri_hash(term: &Term) -> Option<u64> {
496    crate::modalities::logic::n3_parser::term_uri_hash(term)
497}
498
499// Canonical `values:` deontic operators. The registry stores a compiled rule
500// (hashes only - the predicate IRI string is gone), so the deontic opcode is
501// recovered by matching the premise predicate hash against these. Both the full
502// IRI and the CURIE token are listed, because `@prefix` is not expanded on the
503const FORBID_HASHES: [u64; 2] = [
504    q_hash("https://ns.webcivics.net/values/forbids"),
505    q_hash("values:forbids"),
506];
507const PERMIT_HASHES: [u64; 2] = [
508    q_hash("https://ns.webcivics.net/values/permits"),
509    q_hash("values:permits"),
510];
511const OBLIGATE_HASHES: [u64; 4] = [
512    q_hash("https://ns.webcivics.net/values/requires"),
513    q_hash("values:requires"),
514    q_hash("https://ns.webcivics.net/values/obligates"),
515    q_hash("values:obligates"),
516];
517
518/// Classify a premise-predicate hash into a deontic opcode (+ defeater flag).
519///
520/// A `Defeater` (`^>`) rule is always a `q42:unless` permit-defeater. Otherwise a
521/// recognised `values:` operator picks the opcode; an unrecognised predicate
522/// falls back to the rule-type default (Strict/Linear => obligation, Defeasible =>
523/// permission), preserving behaviour for non-`values` contract predicates.
524fn opcode_from_predicate_hash(
525    pred_hash: u64,
526    rule_type: crate::modalities::logic::n3_parser::RuleType,
527) -> (u8, bool) {
528    use crate::modalities::logic::n3_parser::RuleType;
529    if matches!(rule_type, RuleType::Defeater) {
530        return (OP_PERMIT, true);
531    }
532    if FORBID_HASHES.contains(&pred_hash) {
533        return (OP_FORBID, false);
534    }
535    if PERMIT_HASHES.contains(&pred_hash) {
536        return (OP_PERMIT, false);
537    }
538    if OBLIGATE_HASHES.contains(&pred_hash) {
539        return (OP_OBLIGATE, false);
540    }
541    match rule_type {
542        RuleType::Strict | RuleType::Linear => (OP_OBLIGATE, false),
543        RuleType::Defeasible => (OP_PERMIT, false),
544        RuleType::Defeater => (OP_PERMIT, true),
545    }
546}
547
548/// Compile an N3 `Rule()` into a norm Quin (or defeater Quin for `^>` rules).
549///
550/// Maps premise triple → party / property / action; `rule_type` → opcode + defeater flag.
551pub fn compile_n3_rule_to_norm(
552    rule: &crate::modalities::logic::n3_compiler::CompiledRule,
553    contract_hash: u64,
554    expiry_unix32: u32,
555) -> Option<NQuin> {
556    // `triples` is a fixed `[_; 8]` array, so `.first()` is always `Some`; an
557    // empty rule must be rejected on `len`, not on `.first()`.
558    if rule.premise.len == 0 {
559        return None;
560    }
561    let premise = rule.premise.triples.first()?;
562    let party = premise.subject.as_u64();
563    let property_path = premise.predicate.as_u64();
564    let action_object = premise.object.as_u64();
565
566    // Recover the deontic opcode from the premise predicate hash (the compiled
567    // rule no longer carries the IRI string).
568    let (opcode, is_defeater) = opcode_from_predicate_hash(property_path, rule.rule_type);
569
570    Some(compile_norm_quin(
571        party,
572        opcode,
573        property_path,
574        action_object,
575        contract_hash,
576        expiry_unix32,
577        is_defeater,
578    ))
579}
580
581// ─── compile_norm_quin ────────────────────────────────────────────────────────
582
583/// Build a norm Quin from its logical components.
584///
585/// Convenience constructor that packs the deontic opcode and property-path hash
586/// into `predicate`, stores the contract DID in `context`, and sets the ECC
587/// parity to the XOR fold of the four semantic fields.
588///
589/// # Parameters
590/// * `party_did_hash`    — `q_hash` of the bound party's DID.
591/// * `opcode`            — `OP_OBLIGATE`, `OP_PERMIT`, or `OP_FORBID`.
592/// * `property_path_hash`— `q_hash` of the obligation/action URI.
593/// * `action_object_hash`— `q_hash` of the action's target entity/data.
594/// * `contract_hash`     — `q_hash` of the contract graph DID.
595/// * `expiry_unix32`     — 32-bit Unix timestamp for the norm's expiry (0 = no expiry).
596/// * `is_defeater`       — when `true`, sets `DEFEATER_BIT` making this a `q42:unless` node.
597#[inline]
598pub fn compile_norm_quin(
599    party_did_hash: u64,
600    opcode: u8,
601    property_path_hash: u64,
602    action_object_hash: u64,
603    contract_hash: u64,
604    expiry_unix32: u32,
605    is_defeater: bool,
606) -> NQuin {
607    let defeater_flag = if is_defeater { DEFEATER_BIT } else { 0u64 };
608    // Mask DEFEATER_BIT from the shifted path so only `is_defeater` controls bit 63.
609    let path_bits = (property_path_hash << 8) & !DEFEATER_BIT;
610    let predicate = defeater_flag | path_bits | (opcode as u64);
611    let metadata = expiry_unix32 as u64; // bits [0..31]; Lamport/routing bits left zero
612    let parity = party_did_hash ^ predicate ^ action_object_hash ^ contract_hash;
613
614    NQuin {
615        subject: party_did_hash,
616        predicate,
617        object: action_object_hash,
618        context: contract_hash,
619        metadata,
620        parity,
621    }
622}
623
624// ─── Contrary-to-duty (dyadic deontic) ──────────────────────────────────────────
625
626/// Contrary-to-duty obligation `O(reparation / breach)`: a *secondary* obligation
627/// that arises precisely because a *primary* obligation was breached (the
628/// remedy/reparation logic — Geneva/ICCPR remedy instruments). Returns `true` iff
629/// the CTD is satisfied: either the primary was NOT breached by the party (the
630/// CTD is not triggered), or it was breached AND the reparation has been fulfilled.
631///
632/// Facts convention: a breach is `(party, q42:breached, primary)`; a fulfilled
633/// reparation is `(party, q42:fulfilled, reparation)`. Zero-heap (linear scans).
634pub fn evaluate_contrary_to_duty(
635    facts: &[NQuin],
636    party: u64,
637    primary: u64,
638    reparation: u64,
639) -> bool {
640    // CTD is the dyadic obligation O(reparation | breached(primary)).
641    evaluate_conditional_obligation(facts, party, q_hash("q42:breached"), primary, reparation)
642}
643
644/// General dyadic / conditional obligation `O(obligation | condition)`: the obligation
645/// is binding only *given* the condition holds. Returns `true` iff the conditional is
646/// satisfied — either the condition does not hold (vacuously satisfied), or it holds
647/// AND the obligation has been fulfilled.
648///
649/// Facts convention: the condition holds iff `(party, condition_pred, condition_obj)` is
650/// present; the obligation is fulfilled iff `(party, q42:fulfilled, obligation_obj)` is.
651/// Contrary-to-duty is the special case `condition_pred = q42:breached`. Zero-heap.
652pub fn evaluate_conditional_obligation(
653    facts: &[NQuin],
654    party: u64,
655    condition_pred: u64,
656    condition_obj: u64,
657    obligation_obj: u64,
658) -> bool {
659    let triggered = facts
660        .iter()
661        .any(|q| q.subject == party && q.predicate == condition_pred && q.object == condition_obj);
662    if !triggered {
663        return true; // condition absent → conditional obligation not triggered
664    }
665    let fulfilled = q_hash("q42:fulfilled");
666    facts
667        .iter()
668        .any(|q| q.subject == party && q.predicate == fulfilled && q.object == obligation_obj)
669}
670
671// ─── Deontic lifecycle (Pending → Active → {Violated, Discharged, Defeated, Expired}) ─
672
673/// Compute the full lifecycle status of a single norm against an effectivity window,
674/// the current time, the harvested defeaters, and a fact slice.
675///
676/// Transition order (first match wins):
677/// 1. `effective_from != 0 && now < effective_from` → [`Pending`](DeonticStatus::Pending).
678/// 2. `expiry != 0 && now > expiry` → [`Expired`](DeonticStatus::Expired).
679/// 3. a matching defeater → [`Defeated`](DeonticStatus::Defeated).
680/// 4. in-force, then the facts decide:
681///    - `OP_OBLIGATE`: `(party, q42:fulfilled, action)` → `Discharged()`; else
682///      `(party, q42:breached, action)` → `Violated()`; else `Active()`.
683///    - `OP_FORBID`: `(party, q42:performed, action)` → `Violated()`; else `Active()`.
684///    - `OP_PERMIT`: always `Active()` (a liberty cannot be violated or discharged).
685///
686/// Zero-heap (linear scans). `active_defeaters` is the buffer from
687/// [`harvest_defeater_fingerprints`].
688pub fn norm_lifecycle_status(
689    norm: &NQuin,
690    now_unix: u32,
691    effective_from: u32,
692    active_defeaters: &[u64],
693    facts: &[NQuin],
694) -> DeonticStatus {
695    if effective_from != 0 && now_unix < effective_from {
696        return DeonticStatus::Pending;
697    }
698    let expiry = extract_expiry_unix32(norm.metadata);
699    if expiry != 0 && now_unix > expiry {
700        return DeonticStatus::Expired;
701    }
702    if has_defeater(active_defeaters, norm) {
703        return DeonticStatus::Defeated;
704    }
705    let party = norm.subject;
706    let action = norm.object;
707    let opcode = extract_deontic_opcode(norm.predicate);
708    let fact_present = |pred: u64| {
709        facts
710            .iter()
711            .any(|q| q.subject == party && q.predicate == pred && q.object == action)
712    };
713    match opcode {
714        OP_OBLIGATE => {
715            if fact_present(q_hash("q42:fulfilled")) {
716                DeonticStatus::Discharged
717            } else if fact_present(q_hash("q42:breached")) {
718                DeonticStatus::Violated
719            } else {
720                DeonticStatus::Active
721            }
722        }
723        OP_FORBID => {
724            if fact_present(q_hash("q42:performed")) {
725                DeonticStatus::Violated
726            } else {
727                DeonticStatus::Active
728            }
729        }
730        _ => DeonticStatus::Active, // OP_PERMIT and others: a liberty cannot be violated
731    }
732}
733
734// ─── Optionality (U) and Gratuitousness (G) — derived modalities ────────────────
735
736/// True iff action φ is **optional / indifferent** for `party`: `¬O(φ) ∧ ¬F(φ)` — no
737/// active (non-defeater) obligation and no prohibition over `(party, action)` in the
738/// norm slice. (An explicit `OP_OPTIONAL` assertion also counts.)
739pub fn is_optional(norms: &[NQuin], party: u64, action: u64) -> bool {
740    !has_active_norm(norms, party, action, OP_OBLIGATE)
741        && !has_active_norm(norms, party, action, OP_FORBID)
742}
743
744/// True iff action φ is **gratuitous** (non-obligatory) for `party`: `¬O(φ)` — no
745/// active obligation over `(party, action)` (it may still be permitted or forbidden).
746pub fn is_gratuitous(norms: &[NQuin], party: u64, action: u64) -> bool {
747    !has_active_norm(norms, party, action, OP_OBLIGATE)
748}
749
750/// Helper: is there a non-defeater norm with `opcode` binding `party` to `action`?
751/// Matches the explicit modality opcode (`OP_OPTIONAL`/`OP_GRATUITOUS` short-circuit).
752fn has_active_norm(norms: &[NQuin], party: u64, action: u64, opcode: u8) -> bool {
753    norms.iter().any(|q| {
754        q.predicate & DEFEATER_BIT == 0
755            && q.subject == party
756            && q.object == action
757            && extract_deontic_opcode(q.predicate) == opcode
758    })
759}
760
761// ─── Norm-conflict resolution (proportionality + human-rights priority) ──────────
762
763/// Do two deontic OPCODES conflict — an obligation/permission to do φ vs a prohibition of φ?
764pub fn opcodes_conflict(a: u8, b: u8) -> bool {
765    let permits = |op: u8| op == OP_OBLIGATE || op == OP_PERMIT;
766    (permits(a) && b == OP_FORBID) || (permits(b) && a == OP_FORBID)
767}
768
769/// Do two norms CONFLICT — same party (`subject`) over the same action (`object`), with
770/// deontically opposed opcodes? Active (non-defeater) norms only.
771pub fn norms_conflict(a: &NQuin, b: &NQuin) -> bool {
772    a.predicate & DEFEATER_BIT == 0
773        && b.predicate & DEFEATER_BIT == 0
774        && a.subject == b.subject
775        && a.object == b.object
776        && opcodes_conflict(
777            extract_deontic_opcode(a.predicate),
778            extract_deontic_opcode(b.predicate),
779        )
780}
781
782/// The outcome of resolving a norm conflict.
783#[derive(Debug, Clone, Copy, PartialEq, Eq)]
784pub enum NormResolution {
785    /// The first norm prevails.
786    FirstPrevails,
787    /// The second norm prevails.
788    SecondPrevails,
789    /// A genuine conflict — routed to human review (never auto-flattened).
790    RequiresHumanReview,
791}
792
793/// Resolve a norm conflict by, in strict order:
794///  1. **Non-derogable human-rights priority** — a norm grounded in a non-derogable instrument
795///     defeats a derogable one (never weaken a non-derogable principle).
796///  2. **Proportionality** — if neither/both are non-derogable, the norm whose action is
797///     *proportionate* (`legal_compose::proportionality_met`: marginal harm < advantage) prevails
798///     over a disproportionate one.
799///  3. Otherwise **human review** — a contested norm is never auto-flattened.
800///
801/// `a_proportionate`/`b_proportionate` are the proportionality verdicts (`None` = unmodelled).
802pub fn resolve_norm_conflict(
803    a_nonderogable: bool,
804    b_nonderogable: bool,
805    a_proportionate: Option<bool>,
806    b_proportionate: Option<bool>,
807) -> NormResolution {
808    match (a_nonderogable, b_nonderogable) {
809        (true, false) => return NormResolution::FirstPrevails,
810        (false, true) => return NormResolution::SecondPrevails,
811        _ => {}
812    }
813    match (a_proportionate, b_proportionate) {
814        (Some(true), Some(false)) => NormResolution::FirstPrevails,
815        (Some(false), Some(true)) => NormResolution::SecondPrevails,
816        _ => NormResolution::RequiresHumanReview,
817    }
818}
819
820// ─── Permissions as non-fungible cryptographic constraints ──────────────────────
821
822/// A collision-resistant (BLAKE3) fingerprint over a Quin's six fields — the cryptographic
823/// binding anchor. Changing any field changes the fingerprint.
824pub fn nquin_binding_hash(q: &NQuin) -> u64 {
825    let mut bytes = [0u8; 48];
826    bytes[0..8].copy_from_slice(&q.subject.to_le_bytes());
827    bytes[8..16].copy_from_slice(&q.predicate.to_le_bytes());
828    bytes[16..24].copy_from_slice(&q.object.to_le_bytes());
829    bytes[24..32].copy_from_slice(&q.context.to_le_bytes());
830    bytes[32..40].copy_from_slice(&q.metadata.to_le_bytes());
831    bytes[40..48].copy_from_slice(&q.parity.to_le_bytes());
832    let h = blake3::hash(&bytes);
833    u64::from_le_bytes(h.as_bytes()[..8].try_into().unwrap())
834}
835
836/// Compile a permission into a **non-fungible cryptographic constraint** bound to a *specific*
837/// target nquin: the constraint carries, in `context`, a BLAKE3 binding to `target`, so the
838/// permission cannot be detached and reused for a different nquin — it travels persistently with
839/// that exact one. The identity layer SIGNS this envelope (the engine never holds keys — see
840/// `meta_deontic::endorsement_credential`); this constructs the bound, verifiable constraint.
841pub fn compile_permission_constraint(action: u64, principal: u64, target: &NQuin) -> NQuin {
842    let binding = nquin_binding_hash(target);
843    let mut c = NQuin {
844        subject: principal,
845        predicate: OP_PERMIT as u64,
846        object: action,
847        context: binding,
848        metadata: 0,
849        parity: 0,
850    };
851    c.parity = c.subject ^ c.predicate ^ c.object ^ c.context;
852    c
853}
854
855/// Verify that a permission `constraint` is bound to `target` (the non-fungibility check): its
856/// `context` binding must match `target`'s current fingerprint. Tampering with `target`, or moving
857/// the constraint to a different nquin, breaks the binding.
858pub fn permission_binds_to(constraint: &NQuin, target: &NQuin) -> bool {
859    constraint.context == nquin_binding_hash(target)
860}
861
862// ─── Tests ────────────────────────────────────────────────────────────────────
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    #[test]
869    fn norm_conflict_detection_and_proportional_resolution() {
870        let party = q_hash("did:party");
871        let action = q_hash("act:disclose");
872        let mk = |op: u8| {
873            let mut q = NQuin {
874                subject: party,
875                predicate: op as u64,
876                object: action,
877                context: 0,
878                metadata: 0,
879                parity: 0,
880            };
881            q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
882            q
883        };
884        // Obligate-disclose vs Forbid-disclose for the same party/action → conflict.
885        assert!(norms_conflict(&mk(OP_OBLIGATE), &mk(OP_FORBID)));
886        assert!(opcodes_conflict(OP_PERMIT, OP_FORBID));
887        // Two obligations don't conflict; different actions don't.
888        assert!(!norms_conflict(&mk(OP_OBLIGATE), &mk(OP_OBLIGATE)));
889        let mut other = mk(OP_FORBID);
890        other.object = q_hash("act:other");
891        assert!(!norms_conflict(&mk(OP_OBLIGATE), &other));
892
893        // Resolution: non-derogable beats derogable.
894        assert_eq!(
895            resolve_norm_conflict(true, false, None, None),
896            NormResolution::FirstPrevails
897        );
898        assert_eq!(
899            resolve_norm_conflict(false, true, None, None),
900            NormResolution::SecondPrevails
901        );
902        // Neither non-derogable → proportionality decides.
903        assert_eq!(
904            resolve_norm_conflict(false, false, Some(true), Some(false)),
905            NormResolution::FirstPrevails
906        );
907        assert_eq!(
908            resolve_norm_conflict(false, false, Some(false), Some(true)),
909            NormResolution::SecondPrevails
910        );
911        // Both non-derogable, or proportionality unmodelled → human review.
912        assert_eq!(
913            resolve_norm_conflict(true, true, None, None),
914            NormResolution::RequiresHumanReview
915        );
916        assert_eq!(
917            resolve_norm_conflict(false, false, None, None),
918            NormResolution::RequiresHumanReview
919        );
920    }
921
922    #[test]
923    fn permission_is_non_fungibly_bound_to_its_nquin() {
924        let principal = q_hash("did:principal");
925        let action = q_hash("act:read");
926        let mut target = NQuin {
927            subject: q_hash("doc:42"),
928            predicate: q_hash("q42:hasContent"),
929            object: q_hash("blob:abc"),
930            context: 7,
931            metadata: 0,
932            parity: 0,
933        };
934        target.parity = target.subject ^ target.predicate ^ target.object ^ target.context;
935
936        let c = compile_permission_constraint(action, principal, &target);
937        assert!(
938            permission_binds_to(&c, &target),
939            "the permission binds to its target nquin"
940        );
941        assert_eq!(extract_deontic_opcode(c.predicate), OP_PERMIT);
942
943        // Tampering with the target breaks the binding (non-fungible / tamper-evident).
944        let mut tampered = target;
945        tampered.object ^= 0x1;
946        assert!(
947            !permission_binds_to(&c, &tampered),
948            "any edit to the target breaks the binding"
949        );
950
951        // The constraint cannot be reused for a DIFFERENT nquin.
952        let mut other = target;
953        other.subject = q_hash("doc:99");
954        other.parity = other.subject ^ other.predicate ^ other.object ^ other.context;
955        assert!(
956            !permission_binds_to(&c, &other),
957            "permission is not fungible across nquins"
958        );
959    }
960    use crate::q_hash;
961
962    #[test]
963    fn contrary_to_duty_requires_reparation_after_breach() {
964        let party = q_hash("did:web:acme");
965        let primary = q_hash("q42:protectData");
966        let reparation = q_hash("q42:notifyAndRemedy");
967        let mk = |s: u64, p: u64, o: u64| {
968            let mut q = NQuin {
969                subject: s,
970                predicate: p,
971                object: o,
972                context: 0,
973                metadata: 0,
974                parity: 0,
975            };
976            q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
977            q
978        };
979        // No breach → satisfied (CTD not triggered).
980        assert!(evaluate_contrary_to_duty(&[], party, primary, reparation));
981        // Breach without reparation → NOT satisfied.
982        let breach = [mk(party, q_hash("q42:breached"), primary)];
983        assert!(!evaluate_contrary_to_duty(
984            &breach, party, primary, reparation
985        ));
986        // Breach WITH reparation → satisfied.
987        let repaired = [
988            mk(party, q_hash("q42:breached"), primary),
989            mk(party, q_hash("q42:fulfilled"), reparation),
990        ];
991        assert!(evaluate_contrary_to_duty(
992            &repaired, party, primary, reparation
993        ));
994    }
995
996    /// Webizen values-credential smoke test (PLAN §11.3 / §17.1) — THE KEYSTONE.
997    ///
998    /// Proves a real values prohibition flows the live deontic lane:
999    ///   N3 `Rule` (ns.webcivics.net) → `compile_n3_rule_to_norm` → `evaluate_deontic_contract`
1000    ///   → `DeonticVerdict`  (this is exactly what the `NativeDeonticEval` opcode dispatches to).
1001    /// And that the engine's NATIVE defeasibility flips Active → Defeated when a `q42:unless`
1002    /// defeater is present. No `n3logic.rs::infer_logic_bindings` on this path.
1003    #[test]
1004    fn values_credential_deontic_smoke() {
1005        use crate::modalities::logic::n3_parser::{Formula, Rule, RuleType, Term, Triple};
1006
1007        // A values prohibition (UDHR Art 30 family) as a parsed-shape N3 rule:
1008        //   { values:Agent  values:forbids  values:DestructionOfRights }
1009        let prohibition = Rule {
1010            id: Some("UDHR-Art30-smoke"),
1011            rule_type: RuleType::Strict,
1012            weight: None,
1013            premise: Formula {
1014                triples: vec![Triple {
1015                    subject: Term::Uri("https://ns.webcivics.net/values/Agent"),
1016                    predicate: Term::Uri("https://ns.webcivics.net/values/forbids"),
1017                    object: Term::Uri("https://ns.webcivics.net/values/DestructionOfRights"),
1018                }],
1019            },
1020            conclusion: Formula { triples: vec![] },
1021        };
1022        let contract = q_hash("contract:udhr-smoke");
1023
1024        // ── values rule → norm Quin (the values→deontic bridge) ──
1025        let norm = compile_n3_rule_to_norm(
1026            &crate::modalities::logic::n3_compiler::compile_rule_to_zero_heap(&prohibition),
1027            contract,
1028            0,
1029        )
1030        .expect("a values prohibition must compile to a norm Quin");
1031        assert_eq!(
1032            extract_deontic_opcode(norm.predicate),
1033            OP_FORBID,
1034            "a `values:forbids` rule must compile to an OP_FORBID norm"
1035        );
1036
1037        // ── evaluate via the native deontic VM path → the prohibition is Active (live) ──
1038        let mut out = [DeonticVerdict::default(); 4];
1039        let n = evaluate_deontic_contract(&[norm], NOW, &mut out)
1040            .expect("deontic evaluation must succeed");
1041        assert_eq!(n, 1, "exactly one norm verdict expected");
1042        assert_eq!(
1043            out[0].status,
1044            DeonticStatus::Active,
1045            "the values prohibition holds (Active) — it is live in the engine, not bot-faked"
1046        );
1047        assert_eq!(out[0].opcode, OP_FORBID);
1048
1049        // ── native defeasibility: a `q42:unless` defeater on the same party+path+contract
1050        //    flips Active → Defeated ("forbidden ... UNLESS lawfully authorised"). ──
1051        let party = q_hash("https://ns.webcivics.net/values/Agent");
1052        let path = q_hash("https://ns.webcivics.net/values/forbids");
1053        let defeater = compile_norm_quin(
1054            party,
1055            OP_PERMIT,
1056            path,
1057            q_hash("https://ns.webcivics.net/values/lawfullyAuthorised"),
1058            contract,
1059            0,
1060            /* is_defeater = */ true,
1061        );
1062        let mut out2 = [DeonticVerdict::default(); 4];
1063        let n2 = evaluate_deontic_contract(&[norm, defeater], NOW, &mut out2)
1064            .expect("deontic evaluation with defeater must succeed");
1065        assert_eq!(
1066            n2, 1,
1067            "the defeater is not a primary norm; one verdict expected"
1068        );
1069        assert_eq!(
1070            out2[0].status,
1071            DeonticStatus::Defeated,
1072            "an `unless` defeater on the same party+path must defeat the prohibition"
1073        );
1074    }
1075
1076    fn alice() -> u64 {
1077        q_hash("did:web:alice.example")
1078    }
1079    fn bob() -> u64 {
1080        q_hash("did:web:bob.example")
1081    }
1082    fn nda() -> u64 {
1083        q_hash("did:web:nda:contract-001")
1084    }
1085    fn disclose_path() -> u64 {
1086        q_hash("q42:disclose")
1087    }
1088    fn conf_data() -> u64 {
1089        q_hash("q42:data:project-x:confidential")
1090    }
1091
1092    const NOW: u32 = 1_717_200_000; // ~2024-06-01 — well before NDA expiry
1093    const EXPIRY_NDA: u32 = 1_830_297_600; // 2028-01-01
1094
1095    fn nda_quins() -> [NQuin; 3] {
1096        [
1097            // Quin 0: Alice FORBID disclose (active)
1098            compile_norm_quin(
1099                alice(),
1100                OP_FORBID,
1101                disclose_path(),
1102                conf_data(),
1103                nda(),
1104                EXPIRY_NDA,
1105                false,
1106            ),
1107            // Quin 1: Bob FORBID disclose (active)
1108            compile_norm_quin(
1109                bob(),
1110                OP_FORBID,
1111                disclose_path(),
1112                conf_data(),
1113                nda(),
1114                EXPIRY_NDA,
1115                false,
1116            ),
1117            // Quin 2: q42:unless — Alice PERMIT disclose to auditors (defeater for Quin 0)
1118            compile_norm_quin(
1119                alice(),
1120                OP_PERMIT,
1121                disclose_path(),
1122                q_hash("q42:role:certified-auditor"),
1123                nda(),
1124                EXPIRY_NDA,
1125                true,
1126            ),
1127        ]
1128    }
1129
1130    #[test]
1131    fn nda_alice_is_defeated_bob_is_active() {
1132        let quins = nda_quins();
1133        let mut out = [DeonticVerdict {
1134            norm: NQuin::default(),
1135            status: DeonticStatus::Malformed,
1136            opcode: 0,
1137            defeat_kind: DefeatKind::None,
1138            _pad: [0u8; 5],
1139        }; 8];
1140
1141        let n = evaluate_deontic_contract(&quins, NOW, &mut out).unwrap();
1142
1143        // Two norm Quins (Alice + Bob); defeater is not a norm.
1144        assert_eq!(n, 2, "expected exactly two verdicts");
1145
1146        // Alice's prohibition should be defeated by Quin 2.
1147        let alice_verdict = out[..n].iter().find(|v| v.norm.subject == alice()).unwrap();
1148        assert_eq!(
1149            alice_verdict.status,
1150            DeonticStatus::Defeated,
1151            "Alice obligation should be defeated"
1152        );
1153        assert_eq!(alice_verdict.opcode, OP_FORBID);
1154
1155        // Bob has no defeater — should be active.
1156        let bob_verdict = out[..n].iter().find(|v| v.norm.subject == bob()).unwrap();
1157        assert_eq!(
1158            bob_verdict.status,
1159            DeonticStatus::Active,
1160            "Bob obligation should be active"
1161        );
1162    }
1163
1164    #[test]
1165    fn expired_norm_is_detected() {
1166        let past_expiry: u32 = 1_000_000; // Unix epoch far in the past
1167        let norm = compile_norm_quin(
1168            alice(),
1169            OP_OBLIGATE,
1170            disclose_path(),
1171            conf_data(),
1172            nda(),
1173            past_expiry,
1174            false,
1175        );
1176        let quins = [norm];
1177        let mut out = [DeonticVerdict {
1178            norm: NQuin::default(),
1179            status: DeonticStatus::Malformed,
1180            opcode: 0,
1181            defeat_kind: DefeatKind::None,
1182            _pad: [0u8; 5],
1183        }; 4];
1184
1185        let n = evaluate_deontic_contract(&quins, NOW, &mut out).unwrap();
1186        assert_eq!(n, 1);
1187        assert_eq!(out[0].status, DeonticStatus::Expired);
1188    }
1189
1190    #[test]
1191    fn no_expiry_zero_is_always_valid() {
1192        let norm = compile_norm_quin(
1193            alice(),
1194            OP_PERMIT,
1195            disclose_path(),
1196            conf_data(),
1197            nda(),
1198            0,
1199            false,
1200        );
1201        let quins = [norm];
1202        let mut out = [DeonticVerdict {
1203            norm: NQuin::default(),
1204            status: DeonticStatus::Malformed,
1205            opcode: 0,
1206            defeat_kind: DefeatKind::None,
1207            _pad: [0u8; 5],
1208        }; 4];
1209
1210        let n = evaluate_deontic_contract(&quins, u32::MAX, &mut out).unwrap();
1211        assert_eq!(n, 1);
1212        assert_eq!(
1213            out[0].status,
1214            DeonticStatus::Active,
1215            "zero expiry should never expire"
1216        );
1217    }
1218
1219    #[test]
1220    fn non_deontic_quins_are_skipped() {
1221        // Plain SHACL/data Quin with opcode 0x00 — should produce no verdicts.
1222        let plain = NQuin {
1223            subject: 1,
1224            predicate: 0x00,
1225            object: 2,
1226            context: 3,
1227            metadata: 0,
1228            parity: 0,
1229        };
1230        let mut out = [DeonticVerdict {
1231            norm: NQuin::default(),
1232            status: DeonticStatus::Malformed,
1233            opcode: 0,
1234            defeat_kind: DefeatKind::None,
1235            _pad: [0u8; 5],
1236        }; 4];
1237
1238        let n = evaluate_deontic_contract(&[plain], NOW, &mut out).unwrap();
1239        assert_eq!(n, 0, "non-deontic Quins must be silently skipped");
1240    }
1241
1242    #[test]
1243    fn output_buffer_full_returns_error() {
1244        let quins = nda_quins(); // 2 norm Quins
1245        let mut out = [DeonticVerdict {
1246            norm: NQuin::default(),
1247            status: DeonticStatus::Malformed,
1248            opcode: 0,
1249            defeat_kind: DefeatKind::None,
1250            _pad: [0u8; 5],
1251        }; 1]; // one slot — too small
1252
1253        assert_eq!(
1254            evaluate_deontic_contract(&quins, NOW, &mut out),
1255            Err(DeonticError::OutputBufferFull)
1256        );
1257    }
1258
1259    #[test]
1260    fn empty_slice_returns_zero_verdicts() {
1261        let mut out = [DeonticVerdict {
1262            norm: NQuin::default(),
1263            status: DeonticStatus::Malformed,
1264            opcode: 0,
1265            defeat_kind: DefeatKind::None,
1266            _pad: [0u8; 5],
1267        }; 4];
1268        let n = evaluate_deontic_contract(&[], NOW, &mut out).unwrap();
1269        assert_eq!(n, 0);
1270    }
1271
1272    #[test]
1273    fn guardianship_contract_temporal_expiry() {
1274        let guardian = q_hash("did:web:guardian.example");
1275        let ward = q_hash("did:web:ward.example");
1276        let contract = q_hash("did:web:guardianship:contract-002");
1277        let path = q_hash("q42:actInBestInterest");
1278        let majority_epoch: u32 = 1_893_456_000; // 2030-01-01
1279
1280        let obligation = compile_norm_quin(
1281            guardian,
1282            OP_OBLIGATE,
1283            path,
1284            ward,
1285            contract,
1286            majority_epoch,
1287            false,
1288        );
1289        let quins = [obligation];
1290
1291        let mut out = [DeonticVerdict {
1292            norm: NQuin::default(),
1293            status: DeonticStatus::Malformed,
1294            opcode: 0,
1295            defeat_kind: DefeatKind::None,
1296            _pad: [0u8; 5],
1297        }; 4];
1298
1299        // Before majority — obligation is active.
1300        let n = evaluate_deontic_contract(&quins, NOW, &mut out).unwrap();
1301        assert_eq!(n, 1);
1302        assert_eq!(out[0].status, DeonticStatus::Active);
1303
1304        // After majority — obligation has expired.
1305        let n = evaluate_deontic_contract(&quins, majority_epoch + 1, &mut out).unwrap();
1306        assert_eq!(n, 1);
1307        assert_eq!(out[0].status, DeonticStatus::Expired);
1308    }
1309
1310    #[test]
1311    fn opcode_constants_are_distinct_from_mini_parser_range() {
1312        // mini_parser uses 0x00–0x04; deontic opcodes must not collide.
1313        assert!(OP_OBLIGATE > 0x04);
1314        assert!(OP_PERMIT > 0x04);
1315        assert!(OP_FORBID > 0x04);
1316        assert_ne!(OP_OBLIGATE, OP_PERMIT);
1317        assert_ne!(OP_PERMIT, OP_FORBID);
1318        assert_ne!(OP_OBLIGATE, OP_FORBID);
1319    }
1320
1321    #[test]
1322    fn defeater_bit_is_msb() {
1323        assert_eq!(DEFEATER_BIT, 1u64 << 63);
1324    }
1325
1326    #[test]
1327    fn compile_norm_quin_parity_is_xor_fold() {
1328        let q = compile_norm_quin(
1329            alice(),
1330            OP_FORBID,
1331            disclose_path(),
1332            conf_data(),
1333            nda(),
1334            EXPIRY_NDA,
1335            false,
1336        );
1337        let expected = q.subject ^ q.predicate ^ q.object ^ q.context;
1338        assert_eq!(
1339            q.parity, expected,
1340            "parity must be XOR fold of semantic fields"
1341        );
1342    }
1343
1344    #[test]
1345    fn compile_n3_defeater_sets_defeater_bit() {
1346        use crate::modalities::logic::n3_parser::{Formula, Rule, RuleType, Triple};
1347        let rule = Rule {
1348            id: None,
1349            rule_type: RuleType::Defeater,
1350            weight: None,
1351            premise: Formula {
1352                triples: vec![Triple {
1353                    subject: Term::Uri("did:web:alice.example".into()),
1354                    predicate: Term::Uri("q42:disclose".into()),
1355                    object: Term::Uri("q42:role:certified-auditor".into()),
1356                }],
1357            },
1358            conclusion: Formula {
1359                triples: vec![Triple {
1360                    subject: Term::Uri("did:web:alice.example".into()),
1361                    predicate: Term::Uri("q42:disclose".into()),
1362                    object: Term::Uri("true".into()),
1363                }],
1364            },
1365        };
1366        let q = compile_n3_rule_to_norm(
1367            &crate::modalities::logic::n3_compiler::compile_rule_to_zero_heap(&rule),
1368            nda(),
1369            EXPIRY_NDA,
1370        )
1371        .unwrap();
1372        assert_ne!(q.predicate & DEFEATER_BIT, 0);
1373    }
1374
1375    #[test]
1376    fn compile_n3_defeasible_permit_rule() {
1377        use crate::modalities::logic::n3_parser::{Formula, Rule, RuleType, Triple};
1378        let rule = Rule {
1379            id: None,
1380            rule_type: RuleType::Defeasible,
1381            weight: None,
1382            premise: Formula {
1383                triples: vec![Triple {
1384                    subject: Term::Uri("did:web:bob.example".into()),
1385                    predicate: Term::Uri("q42:permitAccess".into()),
1386                    object: Term::Uri("q42:data:project-x".into()),
1387                }],
1388            },
1389            conclusion: Formula { triples: vec![] },
1390        };
1391        let q = compile_n3_rule_to_norm(
1392            &crate::modalities::logic::n3_compiler::compile_rule_to_zero_heap(&rule),
1393            nda(),
1394            0,
1395        )
1396        .unwrap();
1397        assert_eq!(extract_deontic_opcode(q.predicate), OP_PERMIT);
1398        assert_eq!(q.predicate & DEFEATER_BIT, 0);
1399    }
1400
1401    #[test]
1402    fn compile_n3_malformed_rule_returns_none() {
1403        use crate::modalities::logic::n3_parser::{Formula, Rule, RuleType};
1404        let rule = Rule {
1405            id: None,
1406            rule_type: RuleType::Strict,
1407            weight: None,
1408            premise: Formula { triples: vec![] },
1409            conclusion: Formula { triples: vec![] },
1410        };
1411        assert!(compile_n3_rule_to_norm(
1412            &crate::modalities::logic::n3_compiler::compile_rule_to_zero_heap(&rule),
1413            nda(),
1414            0
1415        )
1416        .is_none());
1417    }
1418
1419    // ─── Phase 1: SDL⁺ extensions (DEONTIC_LOGIC_PLAN §4) ───────────────────────
1420
1421    fn mkfact(s: u64, p: u64, o: u64) -> NQuin {
1422        let mut q = NQuin {
1423            subject: s,
1424            predicate: p,
1425            object: o,
1426            context: 0,
1427            metadata: 0,
1428            parity: 0,
1429        };
1430        q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
1431        q
1432    }
1433
1434    #[test]
1435    fn lifecycle_pending_active_discharged_violated() {
1436        let party = alice();
1437        let action = conf_data();
1438        let duty = compile_norm_quin(party, OP_OBLIGATE, disclose_path(), action, nda(), 0, false);
1439
1440        // effective_from in the future → Pending.
1441        assert_eq!(
1442            norm_lifecycle_status(&duty, NOW, NOW + 1000, &[], &[]),
1443            DeonticStatus::Pending
1444        );
1445        // in force, no facts → Active.
1446        assert_eq!(
1447            norm_lifecycle_status(&duty, NOW, 0, &[], &[]),
1448            DeonticStatus::Active
1449        );
1450        // fulfilled fact → Discharged.
1451        let fulfilled = [mkfact(party, q_hash("q42:fulfilled"), action)];
1452        assert_eq!(
1453            norm_lifecycle_status(&duty, NOW, 0, &[], &fulfilled),
1454            DeonticStatus::Discharged
1455        );
1456        // breached fact → Violated.
1457        let breached = [mkfact(party, q_hash("q42:breached"), action)];
1458        assert_eq!(
1459            norm_lifecycle_status(&duty, NOW, 0, &[], &breached),
1460            DeonticStatus::Violated
1461        );
1462    }
1463
1464    #[test]
1465    fn lifecycle_forbid_violated_by_performance() {
1466        let party = bob();
1467        let action = conf_data();
1468        let prohibition =
1469            compile_norm_quin(party, OP_FORBID, disclose_path(), action, nda(), 0, false);
1470        let performed = [mkfact(party, q_hash("q42:performed"), action)];
1471        assert_eq!(
1472            norm_lifecycle_status(&prohibition, NOW, 0, &[], &performed),
1473            DeonticStatus::Violated
1474        );
1475        assert_eq!(
1476            norm_lifecycle_status(&prohibition, NOW, 0, &[], &[]),
1477            DeonticStatus::Active
1478        );
1479    }
1480
1481    #[test]
1482    fn lifecycle_expiry_and_defeater_precedence() {
1483        let party = alice();
1484        let action = conf_data();
1485        let duty = compile_norm_quin(
1486            party,
1487            OP_OBLIGATE,
1488            disclose_path(),
1489            action,
1490            nda(),
1491            EXPIRY_NDA,
1492            false,
1493        );
1494        let fulfilled = [mkfact(party, q_hash("q42:fulfilled"), action)];
1495        // past expiry → Expired (temporal precedes facts).
1496        assert_eq!(
1497            norm_lifecycle_status(&duty, EXPIRY_NDA + 1, 0, &[], &fulfilled),
1498            DeonticStatus::Expired
1499        );
1500        // matching defeater → Defeated (precedes facts).
1501        let df = defeater_fingerprint(&duty);
1502        assert_eq!(
1503            norm_lifecycle_status(&duty, NOW, 0, &[df], &fulfilled),
1504            DeonticStatus::Defeated
1505        );
1506    }
1507
1508    #[test]
1509    fn optionality_and_gratuitousness() {
1510        let party = alice();
1511        let action = q_hash("q42:donate");
1512        // no norms → optional and gratuitous.
1513        assert!(is_optional(&[], party, action));
1514        assert!(is_gratuitous(&[], party, action));
1515        // obligation → neither.
1516        let oblig = compile_norm_quin(party, OP_OBLIGATE, disclose_path(), action, nda(), 0, false);
1517        assert!(!is_optional(&[oblig], party, action));
1518        assert!(!is_gratuitous(&[oblig], party, action));
1519        // permission alone → optional and gratuitous.
1520        let perm = compile_norm_quin(party, OP_PERMIT, disclose_path(), action, nda(), 0, false);
1521        assert!(is_optional(&[perm], party, action));
1522        assert!(is_gratuitous(&[perm], party, action));
1523        // prohibition → gratuitous (not obliged) but NOT optional (forbidden).
1524        let forbid = compile_norm_quin(party, OP_FORBID, disclose_path(), action, nda(), 0, false);
1525        assert!(!is_optional(&[forbid], party, action));
1526        assert!(is_gratuitous(&[forbid], party, action));
1527    }
1528
1529    #[test]
1530    fn undercutting_vs_rebutting_defeater_kind() {
1531        let party = alice();
1532        let action = conf_data();
1533        let duty = compile_norm_quin(party, OP_OBLIGATE, disclose_path(), action, nda(), 0, false);
1534        let mut out = [DeonticVerdict::default(); 4];
1535
1536        // Rebutting: DEFEATER_BIT + a contrary opcode (PERMIT) on the same path.
1537        let rebut = compile_norm_quin(
1538            party,
1539            OP_PERMIT,
1540            disclose_path(),
1541            q_hash("q42:exc"),
1542            nda(),
1543            0,
1544            true,
1545        );
1546        let n = evaluate_deontic_contract(&[duty, rebut], NOW, &mut out).unwrap();
1547        assert_eq!(n, 1);
1548        assert_eq!(out[0].status, DeonticStatus::Defeated);
1549        assert_eq!(out[0].defeat_kind, DefeatKind::Rebutting);
1550
1551        // Undercutting: DEFEATER_BIT + OP_UNDERCUT on the same path → link-invalidation.
1552        let undercut = compile_norm_quin(
1553            party,
1554            OP_UNDERCUT,
1555            disclose_path(),
1556            q_hash("q42:exc"),
1557            nda(),
1558            0,
1559            true,
1560        );
1561        let n = evaluate_deontic_contract(&[duty, undercut], NOW, &mut out).unwrap();
1562        assert_eq!(n, 1);
1563        assert_eq!(out[0].status, DeonticStatus::Defeated);
1564        assert_eq!(out[0].defeat_kind, DefeatKind::Undercutting);
1565    }
1566
1567    #[test]
1568    fn dyadic_conditional_obligation() {
1569        let party = alice();
1570        let condition = q_hash("q42:dataCollected");
1571        let obligation = q_hash("q42:obtainConsent");
1572        let cond_pred = q_hash("q42:holds");
1573        // condition absent → vacuously satisfied.
1574        assert!(evaluate_conditional_obligation(
1575            &[],
1576            party,
1577            cond_pred,
1578            condition,
1579            obligation
1580        ));
1581        // condition present, unfulfilled → not satisfied.
1582        let triggered = [mkfact(party, cond_pred, condition)];
1583        assert!(!evaluate_conditional_obligation(
1584            &triggered, party, cond_pred, condition, obligation
1585        ));
1586        // condition present, fulfilled → satisfied.
1587        let done = [
1588            mkfact(party, cond_pred, condition),
1589            mkfact(party, q_hash("q42:fulfilled"), obligation),
1590        ];
1591        assert!(evaluate_conditional_obligation(
1592            &done, party, cond_pred, condition, obligation
1593        ));
1594    }
1595}