Skip to main content

qualia_core_db/modalities/
jural.rs

1//! Hohfeldian jural relations (Phase 2, DEONTIC_LOGIC_PLAN §6).
2//!
3//! Wesley Newcomb Hohfeld decomposed the ambiguous word "right" into eight strict
4//! fundamental positions arranged as **correlatives** and **opposites**. This is the
5//! computational bridge for legal ontologies: a vague "right" becomes a precise position
6//! held by one agent *toward another*, with a **necessary correlative** the counterparty
7//! must hold. A Claim with no correlative Duty-bearer is therefore a *legible structural
8//! gap*, not silence ([`find_unmet_correlatives`]).
9//!
10//! First-order (rules of conduct):  Claim↔Duty,    Privilege↔No-Right
11//! Second-order (rules of control): Power↔Liability, Immunity↔Disability
12//! Opposites:  Claim/No-Right · Duty/Privilege · Power/Disability · Immunity/Liability
13//!
14//! ## NQuin encoding
15//! A jural relation "`holder` holds `position` over `content` toward `counterparty` in
16//! `frame`" packs as: `subject = holder`, `object = counterparty`, `context = frame`,
17//! `predicate = (content << 8) | position` (low byte = position opcode, bits [8..62] =
18//! content path — same convention as `deontic.rs`). Zero-heap throughout.
19
20use crate::agent::A_NATURAL_PERSON;
21use crate::NQuin;
22
23// ─── The eight positions (opcode block 0x30–0x37; distinct from deontic 0x10–0x1F
24//     and epistemic 0x20–0x26) ──────────────────────────────────────────────────
25pub const JURAL_CLAIM: u8 = 0x30;
26pub const JURAL_DUTY: u8 = 0x31;
27pub const JURAL_PRIVILEGE: u8 = 0x32;
28pub const JURAL_NO_RIGHT: u8 = 0x33;
29pub const JURAL_POWER: u8 = 0x34;
30pub const JURAL_LIABILITY: u8 = 0x35;
31pub const JURAL_IMMUNITY: u8 = 0x36;
32pub const JURAL_DISABILITY: u8 = 0x37;
33
34/// Content-path mask: bits [8..62] of the predicate (opcode byte + bit 63 excluded).
35const CONTENT_MASK: u64 = 0x7FFF_FFFF_FFFF_FF00;
36
37/// The **correlative** position the counterparty necessarily holds. If A holds `pos`
38/// toward B over content φ, then B holds `correlative(pos)` toward A over φ.
39pub const fn correlative(pos: u8) -> u8 {
40    match pos {
41        JURAL_CLAIM => JURAL_DUTY,
42        JURAL_DUTY => JURAL_CLAIM,
43        JURAL_PRIVILEGE => JURAL_NO_RIGHT,
44        JURAL_NO_RIGHT => JURAL_PRIVILEGE,
45        JURAL_POWER => JURAL_LIABILITY,
46        JURAL_LIABILITY => JURAL_POWER,
47        JURAL_IMMUNITY => JURAL_DISABILITY,
48        JURAL_DISABILITY => JURAL_IMMUNITY,
49        other => other,
50    }
51}
52
53/// The **jural opposite** (the position whose presence negates this one for the holder).
54pub const fn jural_opposite(pos: u8) -> u8 {
55    match pos {
56        JURAL_CLAIM => JURAL_NO_RIGHT,
57        JURAL_NO_RIGHT => JURAL_CLAIM,
58        JURAL_DUTY => JURAL_PRIVILEGE,
59        JURAL_PRIVILEGE => JURAL_DUTY,
60        JURAL_POWER => JURAL_DISABILITY,
61        JURAL_DISABILITY => JURAL_POWER,
62        JURAL_IMMUNITY => JURAL_LIABILITY,
63        JURAL_LIABILITY => JURAL_IMMUNITY,
64        other => other,
65    }
66}
67
68/// Is `pos` one of the eight jural positions?
69#[inline]
70pub const fn is_jural_position(pos: u8) -> bool {
71    matches!(
72        pos,
73        JURAL_CLAIM
74            | JURAL_DUTY
75            | JURAL_PRIVILEGE
76            | JURAL_NO_RIGHT
77            | JURAL_POWER
78            | JURAL_LIABILITY
79            | JURAL_IMMUNITY
80            | JURAL_DISABILITY
81    )
82}
83
84/// First-order positions are rules of *conduct*; second-order are rules of *control*.
85#[inline]
86pub const fn is_first_order(pos: u8) -> bool {
87    matches!(
88        pos,
89        JURAL_CLAIM | JURAL_DUTY | JURAL_PRIVILEGE | JURAL_NO_RIGHT
90    )
91}
92
93/// Readable name for a jural position.
94pub const fn position_name(pos: u8) -> Option<&'static str> {
95    Some(match pos {
96        JURAL_CLAIM => "Claim",
97        JURAL_DUTY => "Duty",
98        JURAL_PRIVILEGE => "Privilege",
99        JURAL_NO_RIGHT => "No-Right",
100        JURAL_POWER => "Power",
101        JURAL_LIABILITY => "Liability",
102        JURAL_IMMUNITY => "Immunity",
103        JURAL_DISABILITY => "Disability",
104        _ => return None,
105    })
106}
107
108#[inline]
109/// `?::jural_position`.
110pub const fn jural_position(predicate: u64) -> u8 {
111    (predicate & 0xFF) as u8
112}
113
114#[inline]
115/// `?::jural_content`.
116pub const fn jural_content(predicate: u64) -> u64 {
117    predicate & CONTENT_MASK
118}
119
120/// Build a jural-relation Quin: `holder` holds `position` over `content` toward
121/// `counterparty` within `frame`.
122pub fn compile_jural_quin(
123    holder: u64,
124    position: u8,
125    content_path: u64,
126    counterparty: u64,
127    frame: u64,
128) -> NQuin {
129    let predicate = ((content_path << 8) & CONTENT_MASK) | (position as u64);
130    let parity = holder ^ predicate ^ counterparty ^ frame;
131    NQuin {
132        subject: holder,
133        predicate,
134        object: counterparty,
135        context: frame,
136        metadata: 0,
137        parity,
138    }
139}
140
141/// The relation the counterparty NECESSARILY holds: swap holder/counterparty and map the
142/// position to its correlative, keeping the same content and frame.
143pub fn correlative_quin(rel: &NQuin) -> NQuin {
144    let pos = jural_position(rel.predicate);
145    let predicate = jural_content(rel.predicate) | (correlative(pos) as u64);
146    let holder = rel.object; // counterparty becomes holder of the correlative
147    let counterparty = rel.subject;
148    let frame = rel.context;
149    let parity = holder ^ predicate ^ counterparty ^ frame;
150    NQuin {
151        subject: holder,
152        predicate,
153        object: counterparty,
154        context: frame,
155        metadata: 0,
156        parity,
157    }
158}
159
160/// Does `graph` already contain the necessary correlative of `rel`?
161pub fn jural_correlativity_holds(rel: &NQuin, graph: &[NQuin]) -> bool {
162    let expected = correlative_quin(rel);
163    graph.iter().any(|q| {
164        q.subject == expected.subject
165            && q.object == expected.object
166            && q.predicate == expected.predicate
167            && q.context == expected.context
168    })
169}
170
171/// "Make the absence legible." For every jural relation whose correlative is NOT present
172/// in `rels`, emit the *expected* (missing) correlative into `out` — e.g. a Claim to a
173/// resource with no funded Duty-bearer surfaces the duty that ought to exist. Returns the
174/// count written. Zero-heap (caller-supplied `out`).
175pub fn find_unmet_correlatives(rels: &[NQuin], out: &mut [NQuin]) -> usize {
176    let mut n = 0usize;
177    for rel in rels {
178        if !is_jural_position(jural_position(rel.predicate)) {
179            continue;
180        }
181        if !jural_correlativity_holds(rel, rels) {
182            if n >= out.len() {
183                break;
184            }
185            out[n] = correlative_quin(rel);
186            n += 1;
187        }
188    }
189    n
190}
191
192/// Personhood **category-error** guard (composes `dl::check_subsumption_quin`): a benefit
193/// position (Claim / Privilege / Immunity) over a content that is exclusive to natural
194/// persons (e.g. `values:inherentDignity`) is a category error when the holder is **not**
195/// subsumed by `values:NaturalPerson` — i.e. a corporate/legal/artificial person asserting
196/// a human-only right. Returns `true` when the error fires.
197///
198/// * `holder_class` — the holder's declared `rdf:type` class hash (see `agent::agent_type`).
199/// * `content_is_np_exclusive` — whether the claimed content is natural-person-only.
200/// * `position` — the jural position asserted.
201/// * `tbox` — `rdfs:subClassOf` Quins for the subsumption check.
202pub fn personhood_category_error(
203    holder_class: u64,
204    content_is_np_exclusive: bool,
205    position: u8,
206    tbox: &[NQuin],
207) -> bool {
208    if !content_is_np_exclusive {
209        return false;
210    }
211    // Only benefit-holding positions over a human-only content can be a category error.
212    if !matches!(position, JURAL_CLAIM | JURAL_PRIVILEGE | JURAL_IMMUNITY) {
213        return false;
214    }
215    // Error iff the holder is NOT a NaturalPerson (nor a subclass of one).
216    !crate::modalities::dl::check_subsumption_quin(holder_class, A_NATURAL_PERSON, tbox)
217}
218
219// ─── Multi-party jural chains (A's Power over B's Duty to C) ─────────────────────────
220
221/// Second-order **control** positions (Power/Liability/Immunity/Disability) are the only ones
222/// that can govern — alter, or be immune to alteration of — another agent's relations.
223#[inline]
224pub const fn is_second_order(pos: u8) -> bool {
225    matches!(
226        pos,
227        JURAL_POWER | JURAL_LIABILITY | JURAL_IMMUNITY | JURAL_DISABILITY
228    )
229}
230
231/// A multi-party chain link: a second-order control relation `upstream` (held by A toward B)
232/// governs `downstream` (a relation held by B toward C). Valid iff `upstream` is a
233/// second-order position AND the pivot matches — A's counterparty (`upstream.object`) is the
234/// holder of the downstream relation (`downstream.subject`). Models "A has Power over B's
235/// Duty to C".
236pub fn jural_chain_links(upstream: &NQuin, downstream: &NQuin) -> bool {
237    is_second_order(jural_position(upstream.predicate))
238        && is_jural_position(jural_position(downstream.predicate))
239        && upstream.object == downstream.subject
240}
241
242/// The pivot party B of a valid chain link (`upstream.object == downstream.subject`), else `None`.
243pub fn jural_chain_pivot(upstream: &NQuin, downstream: &NQuin) -> Option<u64> {
244    if jural_chain_links(upstream, downstream) {
245        Some(upstream.object)
246    } else {
247        None
248    }
249}
250
251/// Confirm an ordered chain A→B→C→… is fully connected: every adjacent pair links. A single
252/// relation (or empty) is trivially valid. Zero-heap (slice windows, no allocation).
253pub fn jural_chain_valid(rels: &[NQuin]) -> bool {
254    rels.windows(2).all(|w| jural_chain_links(&w[0], &w[1]))
255}
256
257// ─── Rights-collision conflict resolution ───────────────────────────────────────────
258
259/// The outcome of resolving a collision between two jural relations.
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub enum CollisionResolution {
262    /// `a` prevails — it is grounded in a non-derogable human right and `b` is not.
263    FirstPrevails,
264    /// `b` prevails — it is grounded in a non-derogable human right and `a` is not.
265    SecondPrevails,
266    /// A genuine proportionality conflict (both, or neither, non-derogable). Never
267    /// auto-flattened — routed to human review per the Curation Directive.
268    RequiresHumanReview,
269    /// The inputs do not actually collide.
270    NoCollision,
271}
272
273/// Two jural relations **collide** iff the same holder is assigned a position and its jural
274/// *opposite* over the same content within the same frame (e.g. a Duty to φ and a Privilege
275/// not to do φ) — a direct contradiction in that holder's normative position.
276pub fn jural_collision(a: &NQuin, b: &NQuin) -> bool {
277    a.subject == b.subject
278        && a.context == b.context
279        && is_jural_position(jural_position(a.predicate))
280        && jural_content(a.predicate) == jural_content(b.predicate)
281        && jural_opposite(jural_position(a.predicate)) == jural_position(b.predicate)
282}
283
284/// Resolve a rights collision. `a_nonderogable` / `b_nonderogable` mark whether each relation
285/// is grounded in a **non-derogable** human-rights instrument (the ingest non-derogable-set).
286/// A non-derogable right defeats a derogable counterpart; two non-derogable (or two derogable)
287/// positions in genuine conflict are **never auto-flattened** — they route to human review.
288/// The engine proposes; the human disposes.
289pub fn resolve_collision(
290    a: &NQuin,
291    b: &NQuin,
292    a_nonderogable: bool,
293    b_nonderogable: bool,
294) -> CollisionResolution {
295    if !jural_collision(a, b) {
296        return CollisionResolution::NoCollision;
297    }
298    match (a_nonderogable, b_nonderogable) {
299        (true, false) => CollisionResolution::FirstPrevails,
300        (false, true) => CollisionResolution::SecondPrevails,
301        _ => CollisionResolution::RequiresHumanReview,
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use crate::q_hash;
309
310    #[test]
311    fn correlatives_are_involutive_and_paired() {
312        for &p in &[
313            JURAL_CLAIM,
314            JURAL_DUTY,
315            JURAL_PRIVILEGE,
316            JURAL_NO_RIGHT,
317            JURAL_POWER,
318            JURAL_LIABILITY,
319            JURAL_IMMUNITY,
320            JURAL_DISABILITY,
321        ] {
322            // correlative of correlative is the original (involution).
323            assert_eq!(correlative(correlative(p)), p, "{:?}", position_name(p));
324            assert_eq!(jural_opposite(jural_opposite(p)), p);
325            // correlative and opposite are themselves distinct from the position.
326            assert_ne!(correlative(p), p);
327            assert_ne!(jural_opposite(p), p);
328        }
329        assert_eq!(correlative(JURAL_CLAIM), JURAL_DUTY);
330        assert_eq!(correlative(JURAL_POWER), JURAL_LIABILITY);
331        assert_eq!(correlative(JURAL_IMMUNITY), JURAL_DISABILITY);
332        assert_eq!(jural_opposite(JURAL_CLAIM), JURAL_NO_RIGHT);
333    }
334
335    #[test]
336    fn claim_implies_correlative_duty() {
337        let (alice, bob, frame) = (q_hash("alice"), q_hash("bob"), q_hash("nda"));
338        let content = q_hash("q42:repayLoan");
339        // Alice holds a Claim toward Bob that he repay.
340        let claim = compile_jural_quin(alice, JURAL_CLAIM, content, bob, frame);
341        // The correlative is: Bob holds a Duty toward Alice to repay.
342        let duty = correlative_quin(&claim);
343        assert_eq!(jural_position(duty.predicate), JURAL_DUTY);
344        assert_eq!(duty.subject, bob);
345        assert_eq!(duty.object, alice);
346        assert_eq!(
347            jural_content(duty.predicate),
348            jural_content(claim.predicate)
349        );
350        assert_eq!(duty.context, frame);
351        // Parity is a valid XOR fold.
352        assert_eq!(
353            duty.parity,
354            duty.subject ^ duty.predicate ^ duty.object ^ duty.context
355        );
356    }
357
358    #[test]
359    fn correlativity_holds_when_duty_is_present() {
360        let (alice, bob, frame) = (q_hash("alice"), q_hash("bob"), q_hash("nda"));
361        let content = q_hash("q42:repayLoan");
362        let claim = compile_jural_quin(alice, JURAL_CLAIM, content, bob, frame);
363        let duty = correlative_quin(&claim);
364        // Graph with the duty present → correlativity holds.
365        assert!(jural_correlativity_holds(&claim, &[claim, duty]));
366        // Graph without it → does not hold.
367        assert!(!jural_correlativity_holds(&claim, &[claim]));
368    }
369
370    #[test]
371    fn unmet_correlative_duty_is_made_legible() {
372        let (alice, state, frame) = (q_hash("alice"), q_hash("state"), q_hash("icescr"));
373        let content = q_hash("q42:adequateHousing");
374        // Alice holds a Claim to housing toward the State — but no Duty is recorded.
375        let claim = compile_jural_quin(alice, JURAL_CLAIM, content, state, frame);
376        let mut out = [NQuin::default(); 4];
377        let n = find_unmet_correlatives(&[claim], &mut out);
378        assert_eq!(n, 1, "the missing duty must be surfaced");
379        assert_eq!(jural_position(out[0].predicate), JURAL_DUTY);
380        assert_eq!(
381            out[0].subject, state,
382            "the State is the would-be duty-bearer"
383        );
384        assert_eq!(out[0].object, alice);
385
386        // Once the duty exists, nothing is unmet.
387        let duty = correlative_quin(&claim);
388        assert_eq!(find_unmet_correlatives(&[claim, duty], &mut out), 0);
389    }
390
391    #[test]
392    fn corporate_person_claiming_human_only_right_is_category_error() {
393        // TBox: CorporatePerson ⊑ LegalPerson; NaturalPerson ⊑ Agent (disjoint branches).
394        let np = A_NATURAL_PERSON;
395        let legal = q_hash("https://ns.webcivics.net/values/LegalPerson");
396        let corp = q_hash("https://ns.webcivics.net/values/CorporatePerson");
397        let agent = q_hash("https://ns.webcivics.net/values/Agent");
398        let sub = q_hash("http://www.w3.org/2000/01/rdf-schema#subClassOf");
399        let e = |s: u64, o: u64| NQuin {
400            subject: s,
401            predicate: sub,
402            object: o,
403            context: 0,
404            metadata: 0,
405            parity: 0,
406        };
407        let tbox = [e(corp, legal), e(legal, agent), e(np, agent)];
408
409        // A CorporatePerson asserting a Claim to a human-only right → category error.
410        assert!(personhood_category_error(corp, true, JURAL_CLAIM, &tbox));
411        // A NaturalPerson asserting the same → fine.
412        assert!(!personhood_category_error(np, true, JURAL_CLAIM, &tbox));
413        // A CorporatePerson over a NON-exclusive content → not an error.
414        assert!(!personhood_category_error(corp, false, JURAL_CLAIM, &tbox));
415        // A Duty (burden, not benefit) borne by a CorporatePerson → never a category error.
416        assert!(!personhood_category_error(corp, true, JURAL_DUTY, &tbox));
417    }
418
419    #[test]
420    fn multi_party_chain_a_power_over_b_duty_to_c() {
421        let (a, b, c, frame) = (q_hash("A"), q_hash("B"), q_hash("C"), q_hash("frame"));
422        let content = q_hash("q42:performService");
423        // A holds a Power toward B; B holds a Duty toward C.
424        let a_power = compile_jural_quin(a, JURAL_POWER, content, b, frame);
425        let b_duty = compile_jural_quin(b, JURAL_DUTY, content, c, frame);
426        assert!(
427            jural_chain_links(&a_power, &b_duty),
428            "A's power over B governs B's duty to C"
429        );
430        assert_eq!(
431            jural_chain_pivot(&a_power, &b_duty),
432            Some(b),
433            "the pivot is B"
434        );
435        assert!(jural_chain_valid(&[a_power, b_duty]));
436
437        // A first-order Claim cannot be the governing upstream (not a control position).
438        let a_claim = compile_jural_quin(a, JURAL_CLAIM, content, b, frame);
439        assert!(!jural_chain_links(&a_claim, &b_duty));
440        // Broken pivot: B's duty is toward C, but the downstream is held by someone else.
441        let x_duty = compile_jural_quin(q_hash("X"), JURAL_DUTY, content, c, frame);
442        assert!(!jural_chain_links(&a_power, &x_duty));
443        assert_eq!(jural_chain_pivot(&a_power, &x_duty), None);
444    }
445
446    #[test]
447    fn colliding_rights_resolve_by_non_derogability_else_human_review() {
448        let (holder, cp, frame) = (q_hash("holder"), q_hash("counter"), q_hash("frame"));
449        let content = q_hash("q42:speak");
450        // Holder has a Duty to φ AND (from another source) a Privilege not to do φ — opposites.
451        let duty = compile_jural_quin(holder, JURAL_DUTY, content, cp, frame);
452        let privilege = compile_jural_quin(holder, JURAL_PRIVILEGE, content, cp, frame);
453        assert!(
454            jural_collision(&duty, &privilege),
455            "Duty vs Privilege over same content = collision"
456        );
457
458        // The non-derogable right prevails over the derogable one.
459        assert_eq!(
460            resolve_collision(&duty, &privilege, true, false),
461            CollisionResolution::FirstPrevails
462        );
463        assert_eq!(
464            resolve_collision(&duty, &privilege, false, true),
465            CollisionResolution::SecondPrevails
466        );
467        // Both (or neither) non-derogable → genuine proportionality conflict → human review, never flattened.
468        assert_eq!(
469            resolve_collision(&duty, &privilege, true, true),
470            CollisionResolution::RequiresHumanReview
471        );
472        assert_eq!(
473            resolve_collision(&duty, &privilege, false, false),
474            CollisionResolution::RequiresHumanReview
475        );
476
477        // No collision when positions are not opposites (Duty vs Duty).
478        let duty2 = compile_jural_quin(holder, JURAL_DUTY, content, cp, frame);
479        assert!(!jural_collision(&duty, &duty2));
480        assert_eq!(
481            resolve_collision(&duty, &duty2, true, false),
482            CollisionResolution::NoCollision
483        );
484    }
485}