1use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::record::{
23 EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
24};
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct GuardianshipProposal {
29 pub id: String,
30 pub principal_did: String,
32 pub proxy_did: String,
34 pub threshold: u8,
36 pub escrowed_kind: String,
38 pub escrowed_envelope_json: String,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub escrowed_summary: Option<String>,
43 pub reason: String,
45 pub created_unix: u32,
46 #[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 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 pub fn created_at(&self) -> InstantBridge {
82 self.created_instant
83 .unwrap_or_else(|| InstantBridge::from_coarse(self.created_unix))
84 }
85
86 pub fn escrowed_envelope(&self) -> Option<RecordEnvelope> {
88 serde_json::from_str(&self.escrowed_envelope_json).ok()
89 }
90
91 pub fn escrowed_record_id(&self) -> Option<String> {
93 self.escrowed_envelope().map(|e| e.id)
94 }
95}
96
97#[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 #[serde(skip_serializing_if = "Option::is_none", default)]
110 pub voted_instant: Option<InstantBridge>,
111}
112
113impl GuardianshipVote {
114 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 pub fn voted_at(&self) -> InstantBridge {
136 self.voted_instant
137 .unwrap_or_else(|| InstantBridge::from_coarse(self.voted_unix))
138 }
139}
140
141#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152pub struct ProposalStatus {
153 pub state: ProposalState,
154 pub approvals: u8,
155 pub threshold: u8,
156 #[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
163pub fn derive_status(
170 proposal: &GuardianshipProposal,
171 votes: &[GuardianshipVote],
172) -> ProposalStatus {
173 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 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
212pub fn proposal_record_id(uuid: &str) -> String {
214 format!("urn:wellfair:guardianship_proposal:{uuid}")
215}
216
217pub fn vote_record_id(uuid: &str) -> String {
219 format!("urn:wellfair:guardianship_vote:{uuid}")
220}
221
222fn 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
254pub 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
269pub 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
286pub fn proposal_summary(proposal: &GuardianshipProposal) -> String {
288 serde_json::to_string(proposal).unwrap_or_default()
289}
290
291pub fn vote_summary(vote: &GuardianshipVote) -> String {
293 serde_json::to_string(vote).unwrap_or_default()
294}
295
296pub fn parse_proposal_summary(summary: &str) -> Option<GuardianshipProposal> {
298 serde_json::from_str(summary).ok()
299}
300
301pub 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 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 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 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}