Skip to main content

qualia_client_core/wellfair/api/
agency.rs

1//! Agency layer + wellbeing assessment
2
3use super::super::journal::JournalEntry;
4use qualia_cooperative_core::agency_delegation::{
5    agency_delegation_full_json, build_agency_delegation_envelope, delegation_permits,
6    parse_agency_delegation, AccessDecision, AccessRequest, AgencyDelegation, ConsentState,
7    Precedence,
8};
9use qualia_cooperative_core::agency_domain::agency_domain_taxonomy;
10use qualia_cooperative_core::taxonomy::Sphere;
11use qualia_cooperative_core::trigger::TriggerContext;
12use wellfare_core::assessment::{
13    assessment_summary, build_assessment_envelope, instrument, instrument_dto, instruments,
14    parse_assessment, score, AssessmentResult, InstrumentDto,
15};
16
17use super::*;
18
19impl WebizenHostApi {
20    // --- Agency layer: supported-agency delegations (ADR §7–§10; cooperative-core agency_*) -------
21    //
22    // A delegation binds a principal to their agent(s) for a *domain of agency* under an authority
23    // profile + values anchor, gated by an optional trigger and fail-closed ABAC. Persisted through
24    // the same signed journal path as other Restricted records (self-authored → commits; a proxy
25    // write would suspend into guardianship, T1.5). The **lossless** delegation JSON is stored as the
26    // record summary so the full object reconstructs on read; updates append a superseding version of
27    // the same delegation id (latest-wins projection in `list_agency_delegations`).
28
29    /// Persist a delegation (create or supersede). Returns the checkpointed journal entry.
30    /// A checkpoint error can occur after the journal write; callers must reconcile the
31    /// stored record before retrying rather than assume that no write occurred.
32    pub fn add_agency_delegation(
33        &mut self,
34        delegation: &AgencyDelegation,
35    ) -> Result<JournalEntry, String> {
36        let asserted = Self::now_unix() as u32;
37        let envelope = build_agency_delegation_envelope(
38            delegation,
39            &self.owner_did,
40            &self.author_did,
41            asserted,
42        );
43        let summary = agency_delegation_full_json(delegation);
44        self.submit_record_with_summary(
45            QAPP_COOPERATIVE,
46            envelope,
47            SOURCE_COOPERATIVE,
48            Some(summary),
49        )?;
50        self.finalize_batch().map_err(|e| {
51            format!("agency delegation journal write completed but checkpoint failed; reconcile before retrying: {e}")
52        })?;
53        self.list_journal_by_kind("agency_delegation", 1)?
54            .into_iter()
55            .next()
56            .ok_or_else(|| "agency delegation committed but journal empty".into())
57    }
58
59    /// Build and persist a new delegation from primitive fields (so the Tauri layer needs no
60    /// cooperative-core types). Validates the domain against the seeded taxonomy; an empty
61    /// `values_anchor` defaults to the UN-HR anchor (`urn:un:hr:udhr`). Returns the created record.
62    #[allow(clippy::too_many_arguments)]
63    pub fn create_agency_delegation(
64        &mut self,
65        principal_did: &str,
66        domain: &str,
67        values_anchor: &str,
68        agent_dids: Vec<String>,
69        precedence: &str,
70        consent: &str,
71    ) -> Result<AgencyDelegation, String> {
72        if agency_domain_taxonomy().get(domain).is_none() {
73            return Err(format!("unknown domain of agency: {domain}"));
74        }
75        let anchor = if values_anchor.trim().is_empty() {
76            "urn:un:hr:udhr"
77        } else {
78            values_anchor
79        };
80        let mut d = AgencyDelegation::new(principal_did, domain, anchor, Self::now_unix() as u32);
81        d.agent_dids = agent_dids
82            .into_iter()
83            .map(|s| s.trim().to_string())
84            .filter(|s| !s.is_empty())
85            .collect();
86        d.precedence = match precedence {
87            "secondary" => Precedence::Secondary,
88            "local_temporary" => Precedence::LocalTemporary,
89            _ => Precedence::Primary,
90        };
91        d.consent = agency_consent_from_str(consent).unwrap_or(ConsentState::Pending);
92        self.add_agency_delegation(&d)?;
93        Ok(d)
94    }
95
96    /// List the current delegations — latest version per delegation id (updates supersede).
97    ///
98    /// The journal is append-only and lists **newest-first**, so the first record seen for a given
99    /// logical delegation id is its latest version (append order == version order). This is robust
100    /// even when several versions share the same `asserted_time_unix` second.
101    pub fn list_agency_delegations(&self, limit: usize) -> Result<Vec<AgencyDelegation>, String> {
102        use std::collections::HashSet;
103        let entries = self.list_journal_by_kind("agency_delegation", limit)?;
104        let mut seen: HashSet<String> = HashSet::new();
105        let mut out: Vec<AgencyDelegation> = Vec::new();
106        for e in entries {
107            let Some(summary) = e.summary.as_deref() else {
108                continue;
109            };
110            let Some(d) = parse_agency_delegation(summary) else {
111                continue;
112            };
113            if seen.insert(d.id.clone()) {
114                out.push(d); // first-seen (newest-first order) == the latest version
115            }
116        }
117        out.sort_by(|a, b| {
118            a.valid_from_unix
119                .cmp(&b.valid_from_unix)
120                .then_with(|| a.id.cmp(&b.id))
121        });
122        Ok(out)
123    }
124
125    /// Fetch a single current delegation by its logical id.
126    pub fn get_agency_delegation(&self, delegation_id: &str) -> Result<AgencyDelegation, String> {
127        self.list_agency_delegations(512)?
128            .into_iter()
129            .find(|d| d.id == delegation_id)
130            .ok_or_else(|| format!("agency delegation '{delegation_id}' not found"))
131    }
132
133    /// Update the principal's consent state (grant / withdraw) — appends a superseding version.
134    pub fn set_agency_delegation_consent(
135        &mut self,
136        delegation_id: &str,
137        consent: ConsentState,
138    ) -> Result<JournalEntry, String> {
139        let mut d = self.get_agency_delegation(delegation_id)?;
140        d.consent = consent;
141        self.add_agency_delegation(&d)
142    }
143
144    /// Revoke a delegation — appends a superseding, revoked version (revocation is monotonic).
145    pub fn revoke_agency_delegation(
146        &mut self,
147        delegation_id: &str,
148    ) -> Result<JournalEntry, String> {
149        let mut d = self.get_agency_delegation(delegation_id)?;
150        d.revoked = true;
151        self.add_agency_delegation(&d)
152    }
153
154    /// The seeded domains of agency (id + label + description + consequential/selfhood flags), for a
155    /// delegation-creation picker. Category terms are excluded — only the 17 leaf domains.
156    pub fn list_agency_domains(&self) -> Vec<AgencyDomainInfo> {
157        let tax = agency_domain_taxonomy();
158        tax.all()
159            .iter()
160            .filter(|t| t.category.is_some())
161            .map(|t| AgencyDomainInfo {
162                id: t.id.clone(),
163                label: t.label.clone(),
164                category: t.category.clone(),
165                description: t.description.clone(),
166                consequential: t.attr("consequential") == Some("true"),
167                selfhood: t.sphere() == Sphere::Selfhood,
168            })
169            .collect()
170    }
171
172    /// Evaluate the fail-closed ABAC for a delegation against an access request built from the
173    /// delegation's own domain. `action` is `"read" | "write" | "decide"`. Uses a bare trigger
174    /// context (now only) — trigger-gated delegations therefore read as inactive here; supplying a
175    /// richer context (events/attestations) is a follow-up. Demonstrates the safety invariants:
176    /// selfhood default-deny, and consequential judgements requiring declared provenance + horizon.
177    pub fn evaluate_agency_access(
178        &self,
179        delegation_id: &str,
180        action: &str,
181        data_class: &str,
182    ) -> Result<AccessDecision, String> {
183        let d = self.get_agency_delegation(delegation_id)?;
184        let tax = agency_domain_taxonomy();
185        let sphere = match tax.get(&d.domain).map(|t| t.sphere()) {
186            Some(Sphere::Selfhood) => Sphere::Selfhood,
187            _ => Sphere::Personhood,
188        };
189        let request = AccessRequest {
190            domain: d.domain.clone(),
191            data_class: data_class.to_string(),
192            action: action.to_string(),
193            sphere,
194            jurisdiction: None,
195            provenance: None,
196        };
197        let ctx = TriggerContext::at(Self::now_unix() as u32);
198        Ok(delegation_permits(&d, &tax, &request, &ctx))
199    }
200
201    // --- Wellbeing self-assessment instruments (T2.2; PHQ-9 / GAD-7) ---------------------------
202    //
203    // A self-monitoring aid, not a diagnosis. Scoring is fail-closed in the domain layer; results
204    // persist as Restricted records through the signed journal (lossless summary → reconstructs).
205
206    /// The instruments this build ships (definitions: items, options, bands, disclaimer).
207    pub fn list_assessment_instruments(&self) -> Vec<InstrumentDto> {
208        instruments().into_iter().map(instrument_dto).collect()
209    }
210
211    /// Score `responses` against the given instrument and persist the result. Returns the scored
212    /// outcome (total, band, interpretation, any safety flags). Errors if the instrument is unknown
213    /// or the responses are the wrong count / out of range (fail-closed in `score`).
214    pub fn record_assessment(
215        &mut self,
216        instrument_id: &str,
217        responses: Vec<u8>,
218    ) -> Result<AssessmentResult, String> {
219        let inst = instrument(instrument_id)
220            .ok_or_else(|| format!("unknown assessment instrument: {instrument_id}"))?;
221        let now = Self::now_unix() as u32;
222        let result = score(inst, &responses, now)?;
223        let envelope = build_assessment_envelope(&result, &self.owner_did, &self.author_did, now);
224        let summary = assessment_summary(&result);
225        self.submit_record_with_summary(QAPP_WELLBEING, envelope, SOURCE_WELLBEING, Some(summary))?;
226        self.finalize_batch().ok();
227        Ok(result)
228    }
229
230    /// Past assessment results, newest-first, reconstructed from the journal.
231    pub fn list_assessments(&self, limit: usize) -> Result<Vec<AssessmentResult>, String> {
232        let entries = self.list_journal_by_kind("wellbeing_assessment", limit)?;
233        Ok(entries
234            .iter()
235            .filter_map(|e| e.summary.as_deref().and_then(parse_assessment))
236            .collect())
237    }
238}