Skip to main content

qualia_cooperative_core/
agency_delegation.rs

1//! `AgencyDelegation` — the integrating record for **supported agency** (ADR §7–§10).
2//!
3//! Binds a principal to their agent(s) for a *domain of agency*, under an [`AuthorityProfile`]
4//! (modality × trigger × accountability), gated by a [`Trigger`], anchored to a shared-values
5//! credential (default UN-HR / UNCRC), scoped by ABAC attributes + jurisdiction + precedence
6//! (the backpacker case: family Primary, a local housemate LocalTemporary), with validity,
7//! consent, revocation, an evidence-chain reference, and — for the child-maturation case — a
8//! monotonic developmental transfer schedule.
9//!
10//! [`delegation_permits`] is the fail-closed ABAC evaluator. Two invariants are load-bearing:
11//! **selfhood is never delegated by default** (a Selfhood-sphere request is denied unless the
12//! delegation carries an explicit selfhood grant), and **consequential-domain judgements require
13//! declared provenance + an epistemic horizon**.
14
15use serde::{Deserialize, Serialize};
16use uuid::Uuid;
17
18use crate::record::{EpistemicStatus, EvidenceType, RecordEnvelope, SensitivityClass};
19
20use crate::agency_domain::is_consequential;
21use crate::authority_type::AuthorityProfile;
22use crate::provenance::JudgementProvenance;
23use crate::taxonomy::{Sphere, Taxonomy, TermId};
24use crate::trigger::{evaluate as evaluate_trigger, Trigger, TriggerContext};
25
26/// Precedence among agents/delegations. The backpacker case: family back home is `Primary`, a
27/// local housemate who can help in an emergency is `LocalTemporary`.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
29#[serde(rename_all = "snake_case")]
30pub enum Precedence {
31    #[default]
32    Primary,
33    Secondary,
34    LocalTemporary,
35}
36
37/// Consent state of the principal. Fail-closed: `Pending` is not effective.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
39#[serde(rename_all = "snake_case")]
40pub enum ConsentState {
41    #[default]
42    Pending,
43    Granted,
44    Withdrawn,
45    /// The delegation's origination doesn't require the principal's consent (e.g. adjudicated).
46    NotRequired,
47}
48
49impl ConsentState {
50    fn is_effective(self) -> bool {
51        matches!(self, ConsentState::Granted | ConsentState::NotRequired)
52    }
53}
54
55/// Control stage of a domain under a developmental (child-maturation) transfer. Monotonic:
56/// authority only ever flows toward the principal (ADR §7.2).
57#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
58#[serde(rename_all = "snake_case")]
59pub enum ControlStage {
60    GuardianSole,
61    CoSigned,
62    PrincipalSole,
63}
64
65/// One monotonic transfer step: at `trigger` (age milestone / capacity attestation / the child's
66/// declarative claim), `domain` advances to `to_stage`.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct TransferStage {
69    pub domain: TermId,
70    pub to_stage: ControlStage,
71    pub trigger: Trigger,
72}
73
74/// A supported-agency delegation.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct AgencyDelegation {
77    pub id: String,
78    pub principal_did: String,
79    pub agent_dids: Vec<String>,
80    /// The domain of agency this delegation covers (an `agency_domain` term id).
81    pub domain: TermId,
82    #[serde(default)]
83    pub authority: AuthorityProfile,
84    /// When the authority activates. `None` = active whenever consent + validity hold.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub trigger: Option<Trigger>,
87    /// Shared-values credential anchor (a credential/instrument id). REQUIRED (ADR decision;
88    /// default UN-HR / UNCRC), so no delegation is values-unanchored.
89    pub values_anchor: String,
90    /// ABAC scope attributes, e.g. ("data_class","medication"), ("action","read"),
91    /// ("purpose","emergency-care"), ("selfhood_grant","explicit").
92    #[serde(default)]
93    pub scope: Vec<(String, String)>,
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub jurisdiction: Option<TermId>,
96    #[serde(default)]
97    pub precedence: Precedence,
98    pub valid_from_unix: u32,
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub valid_to_unix: Option<u32>,
101    #[serde(default)]
102    pub consent: ConsentState,
103    #[serde(default)]
104    pub revoked: bool,
105    /// Evidence-chain reference (a provenance / receipt record id).
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub evidence_ref: Option<String>,
108    /// Developmental transfer schedule (empty unless a developmental/scaffolding delegation).
109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
110    pub transfer_schedule: Vec<TransferStage>,
111}
112
113impl AgencyDelegation {
114    /// Creates a new instance.
115    pub fn new(
116        principal_did: impl Into<String>,
117        domain: impl Into<TermId>,
118        values_anchor: impl Into<String>,
119        valid_from_unix: u32,
120    ) -> Self {
121        Self {
122            id: Uuid::new_v4().to_string(),
123            principal_did: principal_did.into(),
124            agent_dids: Vec::new(),
125            domain: domain.into(),
126            authority: AuthorityProfile::default(),
127            trigger: None,
128            values_anchor: values_anchor.into(),
129            scope: Vec::new(),
130            jurisdiction: None,
131            precedence: Precedence::Primary,
132            valid_from_unix,
133            valid_to_unix: None,
134            consent: ConsentState::Pending,
135            revoked: false,
136            evidence_ref: None,
137            transfer_schedule: Vec::new(),
138        }
139    }
140
141    fn scope_has(&self, key: &str, value: &str) -> bool {
142        self.scope.iter().any(|(k, v)| k == key && v == value)
143    }
144}
145
146/// `agency-delegation-record` ID.
147pub fn agency_delegation_record_id(uuid: &str) -> String {
148    format!("urn:qualia:agency-delegation:{uuid}")
149}
150
151/// Builds agency-delegation-envelope.
152pub fn build_agency_delegation_envelope(
153    delegation: &AgencyDelegation,
154    owner_did: &str,
155    author_did: &str,
156    asserted_unix: u32,
157) -> RecordEnvelope {
158    RecordEnvelope {
159        id: agency_delegation_record_id(&delegation.id),
160        owner_did: owner_did.to_string(),
161        author_did: author_did.to_string(),
162        proxy_did: None,
163        epistemic_status: EpistemicStatus::Asserted,
164        evidence_type: EvidenceType::SelfReported,
165        sensitivity: SensitivityClass::Restricted,
166        asserted_time_unix: asserted_unix,
167        asserted_instant: None,
168        valid_time_start_unix: Some(delegation.valid_from_unix),
169        valid_time_start_instant: None,
170        valid_time_end_unix: delegation.valid_to_unix,
171        valid_time_end_instant: None,
172        predecessor_id: None,
173        blob_hash: None,
174        tombstone: false,
175    }
176}
177
178/// Agency-delegation summary.
179pub fn agency_delegation_summary(delegation: &AgencyDelegation) -> String {
180    serde_json::json!({
181        "id": delegation.id,
182        "principal_did": delegation.principal_did,
183        "agent_dids": delegation.agent_dids,
184        "domain": delegation.domain,
185        "precedence": delegation.precedence,
186        "consent": delegation.consent,
187        "revoked": delegation.revoked,
188        "jurisdiction": delegation.jurisdiction,
189    })
190    .to_string()
191}
192
193/// The **lossless** JSON of a delegation — every field. Stored as the journal record's summary so
194/// the full delegation (authority, trigger, scope, transfer schedule, …) reconstructs on read; the
195/// lossy [`agency_delegation_summary`] is for compact projections only.
196pub fn agency_delegation_full_json(delegation: &AgencyDelegation) -> String {
197    serde_json::to_string(delegation).unwrap_or_default()
198}
199
200/// Reconstruct a delegation from its lossless JSON (as stored by [`agency_delegation_full_json`]).
201pub fn parse_agency_delegation(json: &str) -> Option<AgencyDelegation> {
202    serde_json::from_str(json).ok()
203}
204
205// ---------------------------------------------------------------------------
206// ABAC evaluation
207// ---------------------------------------------------------------------------
208
209/// A request to act under a delegation. `provenance` carries the declared judgement provenance
210/// (required for consequential-domain judgements).
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct AccessRequest {
213    pub domain: TermId,
214    #[serde(default)]
215    pub data_class: String,
216    /// "read" | "write" | "decide" — write/decide are *judgements* for the consequential rule.
217    pub action: String,
218    #[serde(default)]
219    pub sphere: Sphere,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub jurisdiction: Option<TermId>,
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub provenance: Option<JudgementProvenance>,
224}
225
226impl AccessRequest {
227    fn is_judgement(&self) -> bool {
228        matches!(self.action.as_str(), "write" | "decide")
229    }
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "snake_case")]
234pub enum AccessDecision {
235    Permit,
236    Deny(String),
237}
238
239impl AccessDecision {
240    /// `true` when permit.
241    pub fn is_permit(&self) -> bool {
242        matches!(self, AccessDecision::Permit)
243    }
244}
245
246/// Fail-closed, bounded, deterministic ABAC. Order matters: revocation → consent → validity →
247/// trigger → domain → **selfhood default-deny** → **consequential-provenance** → jurisdiction.
248pub fn delegation_permits(
249    delegation: &AgencyDelegation,
250    domains: &Taxonomy,
251    request: &AccessRequest,
252    ctx: &TriggerContext,
253) -> AccessDecision {
254    if delegation.revoked {
255        return AccessDecision::Deny("delegation revoked".into());
256    }
257    if !delegation.consent.is_effective() {
258        return AccessDecision::Deny(format!("consent not effective ({:?})", delegation.consent));
259    }
260    if ctx.now_unix < delegation.valid_from_unix {
261        return AccessDecision::Deny("delegation not yet valid".into());
262    }
263    if let Some(end) = delegation.valid_to_unix {
264        if ctx.now_unix > end {
265            return AccessDecision::Deny("delegation expired".into());
266        }
267    }
268    if let Some(trigger) = &delegation.trigger {
269        if !evaluate_trigger(trigger, ctx) {
270            return AccessDecision::Deny("delegation trigger is not active".into());
271        }
272    }
273    if request.domain != delegation.domain {
274        return AccessDecision::Deny(format!(
275            "delegation does not cover domain '{}'",
276            request.domain
277        ));
278    }
279    // Selfhood is never delegated by default. A selfhood-sphere request is denied unless the
280    // delegation carries an explicit selfhood grant (ADR §7 invariant).
281    if request.sphere == Sphere::Selfhood && !delegation.scope_has("selfhood_grant", "explicit") {
282        return AccessDecision::Deny(
283            "selfhood is not delegable without an explicit selfhood grant".into(),
284        );
285    }
286    // Consequential-domain judgements require declared provenance + an epistemic horizon.
287    if request.is_judgement() && is_consequential(domains, &request.domain) {
288        match &request.provenance {
289            Some(p) if p.epistemic_horizon.is_some() => {}
290            _ => return AccessDecision::Deny(
291                "consequential judgement requires declared provenance with an epistemic horizon"
292                    .into(),
293            ),
294        }
295    }
296    // Jurisdiction, if both are specified, must match (the backpacker case: a LocalTemporary
297    // delegation in the foreign jurisdiction permits foreign-jurisdiction requests).
298    if let (Some(dj), Some(rj)) = (&delegation.jurisdiction, &request.jurisdiction) {
299        if dj != rj {
300            return AccessDecision::Deny("jurisdiction mismatch".into());
301        }
302    }
303    AccessDecision::Permit
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use crate::agency_domain::{agency_domain_taxonomy, ids as dom};
310    use crate::provenance::{AgentRef, JudgementProvenance};
311    use crate::trigger::{Attestation, Trigger, TriggerContext};
312
313    fn ctx(now: u32) -> TriggerContext {
314        TriggerContext::at(now)
315    }
316
317    fn granted(domain: &str) -> AgencyDelegation {
318        let mut d = AgencyDelegation::new("did:wf:alice", domain, "urn:un:hr:udhr", 100);
319        d.consent = ConsentState::Granted;
320        d
321    }
322
323    fn read_req(domain: &str) -> AccessRequest {
324        AccessRequest {
325            domain: domain.into(),
326            data_class: "x".into(),
327            action: "read".into(),
328            sphere: Sphere::Personhood,
329            jurisdiction: None,
330            provenance: None,
331        }
332    }
333
334    #[test]
335    fn permits_within_scope_when_valid_and_consented() {
336        let tax = agency_domain_taxonomy();
337        let d = granted(dom::PERSONAL_WELFARE);
338        assert!(
339            delegation_permits(&d, &tax, &read_req(dom::PERSONAL_WELFARE), &ctx(200)).is_permit()
340        );
341    }
342
343    #[test]
344    fn denies_revoked_pending_withdrawn_expired_and_not_yet_valid() {
345        let tax = agency_domain_taxonomy();
346        let base = granted(dom::PERSONAL_WELFARE);
347        let req = read_req(dom::PERSONAL_WELFARE);
348
349        let mut revoked = base.clone();
350        revoked.revoked = true;
351        assert!(!delegation_permits(&revoked, &tax, &req, &ctx(200)).is_permit());
352
353        let mut pending = base.clone();
354        pending.consent = ConsentState::Pending;
355        assert!(!delegation_permits(&pending, &tax, &req, &ctx(200)).is_permit());
356
357        let mut withdrawn = base.clone();
358        withdrawn.consent = ConsentState::Withdrawn;
359        assert!(!delegation_permits(&withdrawn, &tax, &req, &ctx(200)).is_permit());
360
361        let mut expiring = base.clone();
362        expiring.valid_to_unix = Some(150);
363        assert!(!delegation_permits(&expiring, &tax, &req, &ctx(200)).is_permit());
364
365        // now < valid_from (100)
366        assert!(!delegation_permits(&base, &tax, &req, &ctx(50)).is_permit());
367    }
368
369    #[test]
370    fn wrong_domain_is_denied() {
371        let tax = agency_domain_taxonomy();
372        let d = granted(dom::FINANCIAL);
373        assert!(!delegation_permits(&d, &tax, &read_req(dom::MEDICAL), &ctx(200)).is_permit());
374    }
375
376    #[test]
377    fn trigger_gates_activation() {
378        let tax = agency_domain_taxonomy();
379        let mut d = granted(dom::MEDICAL);
380        // Crisis: needs an ER-admission event AND 2 signed physician attestations.
381        d.trigger = Some(Trigger::All(vec![
382            Trigger::VerifiableEvent {
383                event_id: "er".into(),
384            },
385            Trigger::HumanConsensus {
386                required_capacity: Some("physician".into()),
387                m: 2,
388                n: 5,
389            },
390        ]));
391        // A read on a consequential domain still needs the trigger active.
392        let req = read_req(dom::MEDICAL);
393
394        // Trigger inactive → deny.
395        assert!(!delegation_permits(&d, &tax, &req, &ctx(200)).is_permit());
396
397        // Trigger satisfied → the read is permitted (read is not a judgement, so no provenance needed).
398        let active = ctx(200)
399            .with_event("er")
400            .with_attestation(Attestation::signed("physician"))
401            .with_attestation(Attestation::signed("physician"));
402        assert!(delegation_permits(&d, &tax, &req, &active).is_permit());
403    }
404
405    #[test]
406    fn selfhood_is_denied_without_explicit_grant() {
407        let tax = agency_domain_taxonomy();
408        let d = granted(dom::REPRODUCTIVE_BIOMETRIC_GENETIC);
409        let mut req = read_req(dom::REPRODUCTIVE_BIOMETRIC_GENETIC);
410        req.sphere = Sphere::Selfhood;
411        // Default-deny.
412        assert!(!delegation_permits(&d, &tax, &req, &ctx(200)).is_permit());
413
414        // Only an explicit selfhood grant permits it.
415        let mut explicit = d.clone();
416        explicit
417            .scope
418            .push(("selfhood_grant".into(), "explicit".into()));
419        assert!(delegation_permits(&explicit, &tax, &req, &ctx(200)).is_permit());
420    }
421
422    #[test]
423    fn consequential_judgement_requires_provenance_with_horizon() {
424        let tax = agency_domain_taxonomy();
425        let d = granted(dom::MEDICAL);
426        let mut decide = read_req(dom::MEDICAL);
427        decide.action = "decide".into();
428
429        // A consequential judgement with no provenance is denied.
430        assert!(!delegation_permits(&d, &tax, &decide, &ctx(200)).is_permit());
431
432        // Provenance without a horizon is still denied.
433        let mut no_horizon = decide.clone();
434        no_horizon.provenance = Some(JudgementProvenance::new(AgentRef::natural_person("did:dr")));
435        assert!(!delegation_permits(&d, &tax, &no_horizon, &ctx(200)).is_permit());
436
437        // Provenance WITH a horizon is permitted.
438        let mut with_horizon = decide.clone();
439        with_horizon.provenance = Some(
440            JudgementProvenance::new(AgentRef::natural_person("did:dr")).with_horizon("merkle:abc"),
441        );
442        assert!(delegation_permits(&d, &tax, &with_horizon, &ctx(200)).is_permit());
443    }
444
445    #[test]
446    fn jurisdiction_mismatch_denied_but_local_temporary_matches_its_own() {
447        let tax = agency_domain_taxonomy();
448        let mut d = granted(dom::MEDICAL);
449        d.jurisdiction = Some("urn:jur:au-vic".into());
450        let mut req = read_req(dom::MEDICAL);
451        req.jurisdiction = Some("urn:jur:th".into());
452        assert!(!delegation_permits(&d, &tax, &req, &ctx(200)).is_permit());
453
454        // A LocalTemporary delegation in the foreign jurisdiction permits foreign requests.
455        let mut local = granted(dom::MEDICAL);
456        local.precedence = Precedence::LocalTemporary;
457        local.jurisdiction = Some("urn:jur:th".into());
458        assert!(delegation_permits(&local, &tax, &req, &ctx(200)).is_permit());
459    }
460
461    #[test]
462    fn envelope_kind_and_summary_round_trip() {
463        let d = granted(dom::FINANCIAL);
464        let env = build_agency_delegation_envelope(&d, "did:wf:alice", "did:wf:alice", 100);
465        assert!(env.id.contains(":agency-delegation:"));
466        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
467        let summary = agency_delegation_summary(&d);
468        assert!(summary.contains(dom::FINANCIAL));
469    }
470
471    #[test]
472    fn full_json_round_trips_losslessly() {
473        // The full-JSON form (stored as the journal summary) must reconstruct every field, not the
474        // lossy projection.
475        let mut d = granted(dom::MEDICAL);
476        d.agent_dids = vec!["did:wf:carer".into()];
477        d.scope = vec![("data_class".into(), "medication".into())];
478        d.trigger = Some(Trigger::TemporalWindow {
479            from_unix: 10,
480            to_unix: Some(20),
481        });
482        d.transfer_schedule = vec![TransferStage {
483            domain: dom::MEDICAL.into(),
484            to_stage: ControlStage::CoSigned,
485            trigger: Trigger::TemporalWindow {
486                from_unix: 1_000,
487                to_unix: None,
488            },
489        }];
490        let json = agency_delegation_full_json(&d);
491        let back = parse_agency_delegation(&json).expect("reconstructs");
492        assert_eq!(d, back);
493        // The lossy summary, by contrast, drops fields like the trigger and scope.
494        assert!(!agency_delegation_summary(&d).contains("temporal_window"));
495    }
496
497    #[test]
498    fn developmental_transfer_stages_are_ordered_and_serde_round_trip() {
499        let mut d = granted(dom::COMMUNICATION);
500        d.transfer_schedule = vec![
501            TransferStage {
502                domain: dom::COMMUNICATION.into(),
503                to_stage: ControlStage::CoSigned,
504                trigger: Trigger::TemporalWindow {
505                    from_unix: 1_000,
506                    to_unix: None,
507                },
508            },
509            TransferStage {
510                domain: dom::COMMUNICATION.into(),
511                to_stage: ControlStage::PrincipalSole,
512                trigger: Trigger::TemporalWindow {
513                    from_unix: 2_000,
514                    to_unix: None,
515                },
516            },
517        ];
518        // Monotonic toward principal autonomy.
519        assert!(d.transfer_schedule[0].to_stage < d.transfer_schedule[1].to_stage);
520        let json = serde_json::to_string(&d).unwrap();
521        let back: AgencyDelegation = serde_json::from_str(&json).unwrap();
522        assert_eq!(d, back);
523    }
524}