Skip to main content

wellfare_core/
guardianship.rs

1//! Guardianship approval escrow — M-of-N co-signature for proxy actions.
2//!
3//! **Supported agency, not warden control.** When an agent acting *on behalf of* a principal
4//! (a proxy / supporter) writes a protected record, the write does not auto-commit. It is held
5//! in escrow as a [`GuardianshipProposal`]; designated guardians co-sign with immutable
6//! [`GuardianshipVote`] records. The current status is a **derived projection** over the votes
7//! (latest vote per guardian) — replay-safe, so duplicated / reordered / replayed co-signatures
8//! never change the outcome. On reaching the approval threshold the *actual* escrowed record
9//! commits through the normal signed vault path.
10//!
11//! The escrow protects the **principal** from an ill-considered or erring supporter — a
12//! co-guardian objection halts the escrow (a protective veto). That guards the principal's
13//! agency against a rogue proxy; it is not a warden overriding the principal, who is not the
14//! actor here.
15//!
16//! Merge discipline mirrors the rest of `wellfare-core`: proposals and votes are immutable
17//! append-only records merged by stable id; status is *derived*, never a mutated field.
18
19use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::record::{
23    EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
24};
25
26/// A proxy write held pending M-of-N guardian co-signature.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct GuardianshipProposal {
29    pub id: String,
30    /// The principal on whose behalf the proxy acted (the escrowed record's owner).
31    pub principal_did: String,
32    /// The agent that proposed the write (the proxy / supporter).
33    pub proxy_did: String,
34    /// Number of distinct guardian approvals required to ratify (always ≥ 1).
35    pub threshold: u8,
36    /// Journal kind of the escrowed record (for the tray label / filtering).
37    pub escrowed_kind: String,
38    /// The escrowed [`RecordEnvelope`], serialized — committed verbatim on ratification.
39    pub escrowed_envelope_json: String,
40    /// The escrowed record's UI summary, re-attached on commit.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub escrowed_summary: Option<String>,
43    /// Human-readable reason the write needs co-signature.
44    pub reason: String,
45    pub created_unix: u32,
46    /// High-resolution instant (T71 bridge). Preferred over `created_unix`
47    /// when present; the u32 field is kept for backward-compatible deserialization.
48    #[serde(skip_serializing_if = "Option::is_none", default)]
49    pub created_instant: Option<InstantBridge>,
50}
51
52impl GuardianshipProposal {
53    #[allow(clippy::too_many_arguments)]
54    /// Creates a new instance.
55    pub fn new(
56        principal_did: impl Into<String>,
57        proxy_did: impl Into<String>,
58        threshold: u8,
59        escrowed: &RecordEnvelope,
60        escrowed_summary: Option<String>,
61        reason: impl Into<String>,
62        created_unix: u32,
63    ) -> Self {
64        let escrowed_kind = crate::conditions::journal_kind_for_record_id(&escrowed.id).to_string();
65        Self {
66            id: Uuid::new_v4().to_string(),
67            principal_did: principal_did.into(),
68            proxy_did: proxy_did.into(),
69            threshold: threshold.max(1),
70            escrowed_kind,
71            escrowed_envelope_json: serde_json::to_string(escrowed).unwrap_or_default(),
72            escrowed_summary,
73            reason: reason.into(),
74            created_unix,
75            created_instant: Some(InstantBridge::from_coarse(created_unix)),
76        }
77    }
78
79    /// Resolve the created instant, preferring the high-resolution
80    /// `InstantBridge` field when present (T71 bridge).
81    pub fn created_at(&self) -> InstantBridge {
82        self.created_instant
83            .unwrap_or_else(|| InstantBridge::from_coarse(self.created_unix))
84    }
85
86    /// Deserialize the escrowed envelope (committed verbatim on ratification).
87    pub fn escrowed_envelope(&self) -> Option<RecordEnvelope> {
88        serde_json::from_str(&self.escrowed_envelope_json).ok()
89    }
90
91    /// The escrowed record id — the stable key used for idempotent commit-on-ratify.
92    pub fn escrowed_record_id(&self) -> Option<String> {
93        self.escrowed_envelope().map(|e| e.id)
94    }
95}
96
97/// A guardian's immutable co-signature (approve) or objection (deny) on a proposal.
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99pub struct GuardianshipVote {
100    pub id: String,
101    pub proposal_id: String,
102    pub guardian_did: String,
103    pub approve: bool,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub reason: Option<String>,
106    pub voted_unix: u32,
107    /// High-resolution instant (T71 bridge). Preferred over `voted_unix`
108    /// when present; the u32 field is kept for backward-compatible deserialization.
109    #[serde(skip_serializing_if = "Option::is_none", default)]
110    pub voted_instant: Option<InstantBridge>,
111}
112
113impl GuardianshipVote {
114    /// Creates a new instance.
115    pub fn new(
116        proposal_id: impl Into<String>,
117        guardian_did: impl Into<String>,
118        approve: bool,
119        reason: Option<String>,
120        voted_unix: u32,
121    ) -> Self {
122        Self {
123            id: Uuid::new_v4().to_string(),
124            proposal_id: proposal_id.into(),
125            guardian_did: guardian_did.into(),
126            approve,
127            reason,
128            voted_unix,
129            voted_instant: Some(InstantBridge::from_coarse(voted_unix)),
130        }
131    }
132
133    /// Resolve the voted instant, preferring the high-resolution
134    /// `InstantBridge` field when present (T71 bridge).
135    pub fn voted_at(&self) -> InstantBridge {
136        self.voted_instant
137            .unwrap_or_else(|| InstantBridge::from_coarse(self.voted_unix))
138    }
139}
140
141/// Terminal / in-flight state of a proposal.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
143#[serde(rename_all = "snake_case")]
144pub enum ProposalState {
145    Pending,
146    Ratified,
147    Denied,
148}
149
150/// Derived status of a proposal — a pure projection over the votes, never a stored field.
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152pub struct ProposalStatus {
153    pub state: ProposalState,
154    pub approvals: u8,
155    pub threshold: u8,
156    /// Set when a guardian objection halted the escrow.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub denied_by: Option<String>,
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub denial_reason: Option<String>,
161}
162
163/// Derive the status of a proposal from its votes.
164///
165/// Replay-safe: only the **latest vote per guardian** counts (by `voted_unix`, later-seen wins on
166/// tie), so duplicated or reordered co-signatures converge to the same result. A guardian's latest
167/// vote being an objection halts the escrow (protective veto); otherwise the proposal ratifies once
168/// `approvals ≥ threshold`.
169pub fn derive_status(
170    proposal: &GuardianshipProposal,
171    votes: &[GuardianshipVote],
172) -> ProposalStatus {
173    // Latest vote per guardian for this proposal.
174    let mut latest: Vec<&GuardianshipVote> = Vec::new();
175    for v in votes.iter().filter(|v| v.proposal_id == proposal.id) {
176        if let Some(slot) = latest.iter_mut().find(|s| s.guardian_did == v.guardian_did) {
177            if v.voted_unix >= slot.voted_unix {
178                *slot = v;
179            }
180        } else {
181            latest.push(v);
182        }
183    }
184
185    let approvals = latest.iter().filter(|v| v.approve).count() as u8;
186
187    // A standing objection halts the escrow.
188    if let Some(deny) = latest.iter().find(|v| !v.approve) {
189        return ProposalStatus {
190            state: ProposalState::Denied,
191            approvals,
192            threshold: proposal.threshold,
193            denied_by: Some(deny.guardian_did.clone()),
194            denial_reason: deny.reason.clone(),
195        };
196    }
197
198    let state = if approvals >= proposal.threshold {
199        ProposalState::Ratified
200    } else {
201        ProposalState::Pending
202    };
203    ProposalStatus {
204        state,
205        approvals,
206        threshold: proposal.threshold,
207        denied_by: None,
208        denial_reason: None,
209    }
210}
211
212///  record ID.
213pub fn proposal_record_id(uuid: &str) -> String {
214    format!("urn:wellfair:guardianship_proposal:{uuid}")
215}
216
217///  record ID.
218pub fn vote_record_id(uuid: &str) -> String {
219    format!("urn:wellfair:guardianship_vote:{uuid}")
220}
221
222/// Governance envelope for a proposal/vote record.
223///
224/// `proxy_did` is intentionally `None`: these governance records must not themselves be proxy
225/// actions, or writing them would recurse back into the escrow. They inherit the escrowed
226/// record's sensitivity so the Sanctuary projection guards them identically.
227fn governance_envelope(
228    id: &str,
229    owner_did: &str,
230    author_did: &str,
231    sensitivity: SensitivityClass,
232    asserted_unix: u32,
233) -> RecordEnvelope {
234    RecordEnvelope {
235        id: id.to_string(),
236        owner_did: owner_did.to_string(),
237        author_did: author_did.to_string(),
238        proxy_did: None,
239        epistemic_status: EpistemicStatus::Asserted,
240        evidence_type: EvidenceType::SelfReported,
241        sensitivity,
242        asserted_time_unix: asserted_unix,
243        asserted_instant: None,
244        valid_time_start_unix: Some(asserted_unix),
245        valid_time_start_instant: None,
246        valid_time_end_unix: None,
247        valid_time_end_instant: None,
248        predecessor_id: None,
249        blob_hash: None,
250        tombstone: false,
251    }
252}
253
254/// Builds the  envelope.
255pub fn build_proposal_envelope(
256    proposal: &GuardianshipProposal,
257    owner_did: &str,
258    author_did: &str,
259    asserted_unix: u32,
260) -> RecordEnvelope {
261    let sensitivity = proposal
262        .escrowed_envelope()
263        .map(|e| e.sensitivity)
264        .unwrap_or(SensitivityClass::Restricted);
265    let id = proposal_record_id(&proposal.id);
266    governance_envelope(&id, owner_did, author_did, sensitivity, asserted_unix)
267}
268
269/// Builds the  envelope.
270pub fn build_vote_envelope(
271    vote: &GuardianshipVote,
272    owner_did: &str,
273    author_did: &str,
274    asserted_unix: u32,
275) -> RecordEnvelope {
276    let id = vote_record_id(&vote.id);
277    governance_envelope(
278        &id,
279        owner_did,
280        author_did,
281        SensitivityClass::Restricted,
282        asserted_unix,
283    )
284}
285
286///  summary.
287pub fn proposal_summary(proposal: &GuardianshipProposal) -> String {
288    serde_json::to_string(proposal).unwrap_or_default()
289}
290
291///  summary.
292pub fn vote_summary(vote: &GuardianshipVote) -> String {
293    serde_json::to_string(vote).unwrap_or_default()
294}
295
296///  summary.
297pub fn parse_proposal_summary(summary: &str) -> Option<GuardianshipProposal> {
298    serde_json::from_str(summary).ok()
299}
300
301///  summary.
302pub fn parse_vote_summary(summary: &str) -> Option<GuardianshipVote> {
303    serde_json::from_str(summary).ok()
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    fn escrowed(owner: &str, proxy: &str) -> RecordEnvelope {
311        RecordEnvelope {
312            id: "urn:wellfair:condition:e1".into(),
313            owner_did: owner.into(),
314            author_did: proxy.into(),
315            proxy_did: Some(proxy.into()),
316            epistemic_status: EpistemicStatus::Asserted,
317            evidence_type: EvidenceType::SelfReported,
318            sensitivity: SensitivityClass::Restricted,
319            asserted_time_unix: 1_700_000_000,
320            asserted_instant: None,
321            valid_time_start_unix: Some(1_700_000_000),
322            valid_time_start_instant: None,
323            valid_time_end_unix: None,
324            valid_time_end_instant: None,
325            predecessor_id: None,
326            blob_hash: None,
327            tombstone: false,
328        }
329    }
330
331    fn proposal() -> GuardianshipProposal {
332        let env = escrowed("did:wf:principal", "did:wf:proxy");
333        GuardianshipProposal::new(
334            "did:wf:principal",
335            "did:wf:proxy",
336            2,
337            &env,
338            Some("{\"label\":\"Asthma\"}".into()),
339            "Proxy write on protected record",
340            1_700_000_000,
341        )
342    }
343
344    #[test]
345    fn new_proposal_infers_kind_and_escrows_envelope() {
346        let p = proposal();
347        assert_eq!(p.escrowed_kind, "condition");
348        assert_eq!(p.threshold, 2);
349        let env = p.escrowed_envelope().unwrap();
350        assert_eq!(env.id, "urn:wellfair:condition:e1");
351        assert_eq!(
352            p.escrowed_record_id().as_deref(),
353            Some("urn:wellfair:condition:e1")
354        );
355    }
356
357    #[test]
358    fn threshold_is_floored_to_one() {
359        let env = escrowed("o", "p");
360        let p = GuardianshipProposal::new("o", "p", 0, &env, None, "r", 1);
361        assert_eq!(p.threshold, 1);
362    }
363
364    #[test]
365    fn pending_until_threshold_reached() {
366        let p = proposal();
367        let votes = vec![GuardianshipVote::new(&p.id, "did:wf:g1", true, None, 10)];
368        let s = derive_status(&p, &votes);
369        assert_eq!(s.state, ProposalState::Pending);
370        assert_eq!(s.approvals, 1);
371        assert_eq!(s.threshold, 2);
372    }
373
374    #[test]
375    fn ratifies_at_threshold_with_distinct_guardians() {
376        let p = proposal();
377        let votes = vec![
378            GuardianshipVote::new(&p.id, "did:wf:g1", true, None, 10),
379            GuardianshipVote::new(&p.id, "did:wf:g2", true, None, 11),
380        ];
381        let s = derive_status(&p, &votes);
382        assert_eq!(s.state, ProposalState::Ratified);
383        assert_eq!(s.approvals, 2);
384    }
385
386    #[test]
387    fn duplicate_and_replayed_votes_do_not_inflate_approvals() {
388        let p = proposal();
389        // g1 votes three times (duplicate + replay); still one distinct approval → never ratifies.
390        let votes = vec![
391            GuardianshipVote::new(&p.id, "did:wf:g1", true, None, 10),
392            GuardianshipVote::new(&p.id, "did:wf:g1", true, None, 12),
393            GuardianshipVote::new(&p.id, "did:wf:g1", true, None, 11),
394        ];
395        let s = derive_status(&p, &votes);
396        assert_eq!(s.approvals, 1);
397        assert_eq!(s.state, ProposalState::Pending);
398    }
399
400    #[test]
401    fn guardian_may_change_mind_latest_vote_wins() {
402        let p = proposal();
403        // g1 approves then later objects; the standing objection halts.
404        let votes = vec![
405            GuardianshipVote::new(&p.id, "did:wf:g1", true, None, 10),
406            GuardianshipVote::new(&p.id, "did:wf:g2", true, None, 10),
407            GuardianshipVote::new(&p.id, "did:wf:g1", false, Some("reconsidered".into()), 20),
408        ];
409        let s = derive_status(&p, &votes);
410        assert_eq!(s.state, ProposalState::Denied);
411        assert_eq!(s.denied_by.as_deref(), Some("did:wf:g1"));
412        assert_eq!(s.denial_reason.as_deref(), Some("reconsidered"));
413    }
414
415    #[test]
416    fn objection_halts_even_past_threshold() {
417        let p = proposal();
418        // Two approvals would ratify, but a third guardian objects → protective veto.
419        let votes = vec![
420            GuardianshipVote::new(&p.id, "did:wf:g1", true, None, 10),
421            GuardianshipVote::new(&p.id, "did:wf:g2", true, None, 11),
422            GuardianshipVote::new(
423                &p.id,
424                "did:wf:g3",
425                false,
426                Some("not in her interest".into()),
427                12,
428            ),
429        ];
430        let s = derive_status(&p, &votes);
431        assert_eq!(s.state, ProposalState::Denied);
432    }
433
434    #[test]
435    fn votes_for_other_proposals_are_ignored() {
436        let p = proposal();
437        let votes = vec![
438            GuardianshipVote::new("other-proposal", "did:wf:g1", true, None, 10),
439            GuardianshipVote::new("other-proposal", "did:wf:g2", true, None, 11),
440        ];
441        let s = derive_status(&p, &votes);
442        assert_eq!(s.approvals, 0);
443        assert_eq!(s.state, ProposalState::Pending);
444    }
445
446    #[test]
447    fn summary_round_trips() {
448        let p = proposal();
449        let parsed = parse_proposal_summary(&proposal_summary(&p)).unwrap();
450        assert_eq!(parsed, p);
451
452        let v = GuardianshipVote::new(&p.id, "did:wf:g1", true, Some("ok".into()), 10);
453        let pv = parse_vote_summary(&vote_summary(&v)).unwrap();
454        assert_eq!(pv, v);
455    }
456
457    #[test]
458    fn proposal_envelope_inherits_escrowed_sensitivity_and_is_not_proxy() {
459        let p = proposal();
460        let env = build_proposal_envelope(&p, "did:wf:principal", "did:wf:proxy", 1_700_000_000);
461        assert!(env.id.contains(":guardianship_proposal:"));
462        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
463        assert!(
464            env.proxy_did.is_none(),
465            "governance records must not recurse into escrow"
466        );
467    }
468}