Skip to main content

wellfare_core/anatomy/
birth.rs

1//! The **birth transition**, the **Digital Birth Record**, and the **developmental accrual of agency** —
2//! the domain model of `docs/manuals/standards/init-draft-standards-wip-main/DigitalBirthRecord` (Timothy's
3//! draft standard), built on the correct primitive: **relational stewardship, not self-sovereignty.**
4//!
5//! ## Why this is *not* "self-sovereign" (the infant case falsifies it)
6//!
7//! An infant has no "sovereign self" to own or control anything — yet they are a full rights-bearing human.
8//! Their support is **stewardship via a permissive commons, defined *between* guardians** (plural, with
9//! distributed and differing roles: the medical decision-maker need not be the day-to-day carer). Personhood
10//! then is **not a switch that flips at birth** — it **accrues gradually and relationally** as the child
11//! develops (neurologically and otherwise), agency supports slowly yielding to the child's own say, toward
12//! the capacity to maintain **adult personhood — *if healthy***. For those who never reach independent adult
13//! agency, continued stewardship is **supported personhood, not a lesser status** (CRPD supported-, not
14//! substituted-, decision-making). "Self-sovereign identity" can model *none* of this — the infant, the
15//! gradient, or the lifelong-supported adult — which is exactly why it is the wrong, and harmful, model.
16//! Agency/personhood is a **developmental, relational fabric**, never an atomic sovereign property.
17//!
18//! ## What this module builds
19//!
20//! At birth the gestational [`MaternalFetalDyad`] resolves into a born person who **owns** a foundational,
21//! biometric-extended [`DigitalBirthRecord`] ("an inalienable digital prosthetic extension of a person"),
22//! held under a [`Guardianship`] **commons of [`Steward`]s** (default the biological parents, subject to
23//! official credentials), and carrying an [`AgencyStage`] on the developmental gradient. Biometrics are
24//! referenced **by class** ([`BiometricClass`]); the datum is `Sanctuary`-class, held in the person's data
25//! store and referenced, never inlined (data-minimisation).
26//!
27//! **What this is / isn't.** Domain machinery + the invariants, aligned to the standard's `br:` ontology
28//! (`hasGuardian`/`isGuardianOf`/`hasCredential`/`hasConsentFrom`). It does **not** encode the RDF `br:`
29//! vocabulary, biometric wire-formats, VC issuance, or wallet/`did:q42` integration (coordinate), and it
30//! does **not** settle the values/legal specifics — the stage boundaries, when adult status is recognised,
31//! the legal role definitions, guardianship-transfer policy — those are Timothy's / an expert's (§9.4).
32
33use serde::{Deserialize, Serialize};
34
35use super::dyad::{DyadInvalid, MaternalFetalDyad, Parentage, PrincipalRef};
36use super::scorecard::ForumClass;
37
38/// A **class** of biometric a birth record references — the record's *structure*, never the datum. The
39/// actual biometric (a DNA sequence, a blood type) is `Sanctuary`-class, held in the person's data store
40/// and referenced, not inlined here (data-minimisation).
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum BiometricClass {
44    /// DNA — also the evidentiary basis of biological parentage and ancestry use-cases.
45    Dna,
46    BloodType,
47    Fingerprint,
48    /// Neonatal footprint (a historical birth-record biometric).
49    Footprint,
50    Other(String),
51}
52
53/// The kind of official credential that establishes or overrides a stewardship relation (`br:hasCredential`).
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum GuardianshipCredential {
57    /// DNA / official attestation confirming a biological parent as steward.
58    ProofOfParentage,
59    /// An adoption order — assigns stewardship to adoptive parent(s).
60    AdoptionOrder,
61    /// A surrogacy legal-parentage order — assigns stewardship to the intended parent(s).
62    SurrogacyParentageOrder,
63    /// A court/official grant of guardianship to a non-parent (kinship carer, state guardian, …).
64    GuardianshipGrant,
65    Other(String),
66}
67
68/// A reference to a verifiable credential (`br:Credential` / `br:hasCredential`). Abstract here — the VC /
69/// identity layer resolves and verifies it.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct CredentialRef {
72    pub vc_id: String,
73    pub kind: GuardianshipCredential,
74}
75
76/// A responsibility a steward holds. Stewardship is **not one unitary "ownership"** — it is a *variety* of
77/// distinct responsibilities, which may be held by different stewards (a medical decision-maker who is not
78/// the day-to-day carer; a cultural/heritage steward; a financial trustee). Illustrative set — the
79/// authoritative roles are curation/legal (Timothy/§9.4).
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "snake_case")]
82pub enum StewardRole {
83    /// General guardianship (unspecified/full) — the default when roles are not split out.
84    Guardian,
85    /// Day-to-day care.
86    PrimaryCare,
87    /// Health decisions.
88    Medical,
89    /// Legal representation.
90    Legal,
91    /// Property / finances (in trust).
92    Financial,
93    Educational,
94    /// Cultural / heritage stewardship.
95    Cultural,
96    Other(String),
97}
98
99/// How a steward holds their role — the biological-parent default, or an official credential.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "snake_case")]
102pub enum StewardBasis {
103    /// The biological-parent default (guardians are by default the biological parents).
104    BiologicalDefault,
105    /// Established/assigned/overridden by an official credential (adoption, surrogacy order, grant).
106    Credentialed,
107}
108
109/// One steward in the guardianship commons — a guardian holding one or more [`StewardRole`]s. Stewardship
110/// is held **in trust, in the child's interest** — it is *never* ownership of the person.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112pub struct Steward {
113    pub principal: PrincipalRef,
114    pub roles: Vec<StewardRole>,
115    pub basis: StewardBasis,
116}
117
118/// Guardianship as a **permissive-commons stewardship** among [`Steward`]s — the correct model for an
119/// infant/child, and the illustration of why "self-sovereign" is wrong (an infant is not sovereign; it is
120/// *stewarded*, between guardians, in a commons). Not a single owner: a set of stewards holding distributed
121/// responsibilities, in the child's interest. By **default the biological parents**, **subject to official
122/// credentials** (`br:hasCredential`) that confirm, add, or override stewards.
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
124pub struct Guardianship {
125    /// The stewardship commons.
126    pub stewards: Vec<Steward>,
127    /// Official credentials bearing on stewardship (`br:hasCredential`).
128    pub credentials: Vec<CredentialRef>,
129}
130
131impl Guardianship {
132    /// The principals who steward the child (`br:isGuardianOf` → the subject).
133    pub fn guardians(&self) -> Vec<&PrincipalRef> {
134        self.stewards.iter().map(|s| &s.principal).collect()
135    }
136
137    /// Whether any steward holds their role by official credential (vs the biological default alone).
138    pub fn is_credentialed(&self) -> bool {
139        self.stewards
140            .iter()
141            .any(|s| s.basis == StewardBasis::Credentialed)
142            || !self.credentials.is_empty()
143    }
144
145    /// Stewards holding a particular responsibility — supports the "different roles held by different
146    /// guardians" reality (e.g. who is the medical decision-maker).
147    pub fn stewards_with(&self, role: &StewardRole) -> Vec<&Steward> {
148        self.stewards
149            .iter()
150            .filter(|s| s.roles.contains(role))
151            .collect()
152    }
153}
154
155/// Where a person is on the **developmental accrual of agency and personhood** — a *gradient*, not a binary
156/// "sovereign self" switch. Agency accrues gradually and relationally; the endpoint is the capacity to
157/// maintain adult personhood **if healthy**; continued stewardship for those who need it is
158/// [`SupportedAdult`] — **full personhood with supports, never a lesser status**.
159///
160/// The stage *boundaries* (and how they map to any legal age of majority / capacity assessment) are
161/// deliberately **not asserted** here — that is values/legal content (Timothy/§9.4). The type encodes the
162/// *shape* (a monotone gradient of self-determination) so downstream layers cannot model personhood as an
163/// on/off sovereign property.
164///
165/// [`SupportedAdult`]: AgencyStage::SupportedAdult
166#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
167#[serde(rename_all = "snake_case")]
168pub enum AgencyStage {
169    /// Newborn — the fourth trimester. Fully stewarded.
170    Neonate,
171    /// Infancy — fully stewarded via the guardianship commons.
172    Infant,
173    /// Childhood — developing agency, a growing say alongside stewardship.
174    Child,
175    /// Adolescence — substantial, evolving capacity (a large and increasing say).
176    Adolescent,
177    /// Adulthood — maintains personhood independently, if healthy.
178    Adult,
179    /// Adulthood with **supported** decision-making where needed — full personhood, with stewardship
180    /// supports. Not a diminished status; the CRPD "supported, not substituted" model.
181    SupportedAdult,
182}
183
184impl AgencyStage {
185    /// A coarse, monotone indication (0..=100) of the person's own self-determination at this stage — it
186    /// **increases** across the developmental gradient. Illustrative shape only (the authoritative model is
187    /// Timothy's/§9.4); its purpose is to make "agency is graduated, not binary" structural. `SupportedAdult`
188    /// is full self-determination *with supports* — not reduced.
189    pub fn self_determination(self) -> u8 {
190        match self {
191            AgencyStage::Neonate => 0,
192            AgencyStage::Infant => 10,
193            AgencyStage::Child => 40,
194            AgencyStage::Adolescent => 75,
195            AgencyStage::Adult => 100,
196            AgencyStage::SupportedAdult => 100,
197        }
198    }
199
200    /// Whether stewardship is still active at this stage (everything up to independent/ supported adulthood
201    /// carries stewardship; `SupportedAdult` carries *supports*, which are stewardship in service of the
202    /// person's own will).
203    pub fn stewardship_active(self) -> bool {
204        !matches!(self, AgencyStage::Adult)
205    }
206}
207
208/// A **Digital Birth Record** — the foundational, self-owned, biometric-extended record produced at birth.
209/// An *inalienable prosthetic extension of the person*: they own it; the guardianship commons stewards it
210/// (and the data store) as their agency develops.
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct DigitalBirthRecord {
213    /// The born person — the **subject who owns this record** (their own pairwise fabric, carried from the
214    /// emerging child; never collapsed into a guardian or parent).
215    pub subject: PrincipalRef,
216    /// Which biometrics are attached (structure only; data held Sanctuary-class in the person's store).
217    pub biometrics: Vec<BiometricClass>,
218    /// The parentage carried forward from gestation (genetic + social roles), the basis of the biological
219    /// default and of ancestry use-cases.
220    pub parentage: Parentage,
221    /// The stewardship commons (default biological parents, subject to official credentials).
222    pub guardianship: Guardianship,
223    /// The subject's stage on the developmental agency gradient (at birth, [`AgencyStage::Neonate`]).
224    pub agency_stage: AgencyStage,
225    /// The issuing/attesting authority's principal (`br:issuedBy`), if any. It *attests*; it does not own.
226    pub issued_by: Option<PrincipalRef>,
227    /// Date of birth as an ISO-8601 string, if recorded (kept as a string so this pure crate takes no date
228    /// dependency; the caller supplies it).
229    pub birth_date: Option<String>,
230}
231
232/// A reason a birth record is structurally invalid — a **rights** violation or an impossibility.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "snake_case")]
235pub enum BirthRecordInvalid {
236    /// The subject (the born person) is missing.
237    NoSubject,
238    /// The subject is **collapsed into a steward or parent** — the person is their own principal, never a
239    /// field of an adult's identity.
240    SubjectCollapsed,
241    /// No steward — a child is never left unstewarded (an infant is not self-sovereign).
242    NoSteward,
243}
244
245impl DigitalBirthRecord {
246    /// A birth record is **forum internum**, `Sanctuary`-class (biometrics + a person's foundational
247    /// record — the most sensitive class).
248    pub const fn forum_class(&self) -> ForumClass {
249        ForumClass::Internum
250    }
251    /// Sensitivity class.
252    pub const fn sensitivity_class(&self) -> &'static str {
253        "Sanctuary"
254    }
255
256    /// The effective guardians / stewards (`br:isGuardianOf` → this subject).
257    pub fn guardians(&self) -> Vec<&PrincipalRef> {
258        self.guardianship.guardians()
259    }
260
261    /// Enforce the rights invariants.
262    pub fn validate(&self) -> Result<(), BirthRecordInvalid> {
263        let subject = self.subject.did.trim();
264        if subject.is_empty() {
265            return Err(BirthRecordInvalid::NoSubject);
266        }
267        if self.guardianship.stewards.is_empty() {
268            return Err(BirthRecordInvalid::NoSteward);
269        }
270        // The subject is distinct from every steward and every known adult in the parentage.
271        let collapses_into_steward = self
272            .guardianship
273            .stewards
274            .iter()
275            .any(|s| s.principal.did.trim() == subject);
276        let collapses_into_parent = self
277            .parentage
278            .known_genetic_parents()
279            .into_iter()
280            .chain(self.parentage.intended_parents.iter())
281            .any(|p| p.did.trim() == subject);
282        if collapses_into_steward || collapses_into_parent {
283            return Err(BirthRecordInvalid::SubjectCollapsed);
284        }
285        Ok(())
286    }
287}
288
289impl MaternalFetalDyad {
290    /// Resolve the gestational dyad into a [`DigitalBirthRecord`] **at birth**. The emerging child becomes
291    /// the born **subject** (owner of the record) at [`AgencyStage::Neonate`]; the guardianship **commons**
292    /// defaults to the known biological parents (each a [`Steward`] via [`StewardBasis::BiologicalDefault`]),
293    /// **subject to** `credentials` + `credentialed_guardians` (an adoption/surrogacy order or a guardianship
294    /// grant — those become the stewards via [`StewardBasis::Credentialed`], overriding the biological
295    /// default). Each default steward is assigned the general [`StewardRole::Guardian`]; splitting roles
296    /// across different stewards is a later, legal/curation act. Only valid from a valid dyad.
297    pub fn give_birth(
298        &self,
299        biometrics: Vec<BiometricClass>,
300        credentials: Vec<CredentialRef>,
301        credentialed_guardians: Vec<PrincipalRef>,
302        issued_by: Option<PrincipalRef>,
303        birth_date: Option<String>,
304    ) -> Result<DigitalBirthRecord, DyadInvalid> {
305        self.validate()?;
306        let stewards: Vec<Steward> = if credentialed_guardians.is_empty() {
307            // Default: the known biological parents steward the child.
308            self.child
309                .parentage
310                .known_genetic_parents()
311                .into_iter()
312                .cloned()
313                .map(|principal| Steward {
314                    principal,
315                    roles: vec![StewardRole::Guardian],
316                    basis: StewardBasis::BiologicalDefault,
317                })
318                .collect()
319        } else {
320            // An official credential assigns/overrides the stewards (adoption, surrogacy order, grant).
321            credentialed_guardians
322                .into_iter()
323                .map(|principal| Steward {
324                    principal,
325                    roles: vec![StewardRole::Guardian],
326                    basis: StewardBasis::Credentialed,
327                })
328                .collect()
329        };
330        Ok(DigitalBirthRecord {
331            subject: PrincipalRef::new(self.child.pairwise_did.clone()),
332            biometrics,
333            parentage: self.child.parentage.clone(),
334            guardianship: Guardianship {
335                stewards,
336                credentials,
337            },
338            agency_stage: AgencyStage::Neonate,
339            issued_by,
340            birth_date,
341        })
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::super::dyad::InterfaceKind;
348    use super::super::dyad::{
349        EmergingChild, MaternalBody, Progenitor, RightsStage, SocialRightsThreshold,
350    };
351    use super::super::physiology::{PhysiologicalState, ReproductiveState, Trimester};
352    use super::*;
353
354    /// A dyad with two KNOWN biological parents (the common case).
355    fn dyad_two_known_parents() -> MaternalFetalDyad {
356        MaternalFetalDyad {
357            maternal: MaternalBody {
358                principal: PrincipalRef::new("did:wf:mother"),
359                state: PhysiologicalState::Reproductive(ReproductiveState::Pregnant(
360                    Trimester::Third,
361                )),
362            },
363            child: EmergingChild {
364                pairwise_did: "did:wf:child-1".into(),
365                parentage: Parentage {
366                    ovum_source: Progenitor::Known(PrincipalRef::new("did:wf:mother")),
367                    sperm_source: Progenitor::Known(PrincipalRef::new("did:wf:father")),
368                    intended_parents: vec![],
369                },
370                rights_stage: RightsStage::EmergingInGestation,
371            },
372            gestational_age_days: 38 * 7,
373            carnegie_stage: None,
374            interface: InterfaceKind::Placenta,
375            social_rights_threshold: SocialRightsThreshold::Undecided,
376        }
377    }
378
379    #[test]
380    fn birth_default_stewards_are_the_biological_parents_in_a_commons() {
381        let rec = dyad_two_known_parents()
382            .give_birth(
383                vec![BiometricClass::Dna, BiometricClass::BloodType],
384                vec![],
385                vec![],
386                None,
387                None,
388            )
389            .unwrap();
390        assert_eq!(rec.validate(), Ok(()));
391        // The born person owns their record; starts as a neonate on the agency gradient.
392        assert_eq!(rec.subject.did, "did:wf:child-1");
393        assert_eq!(rec.agency_stage, AgencyStage::Neonate);
394        // Guardianship is a COMMONS of the two biological-parent stewards (not one sovereign owner).
395        assert_eq!(rec.guardianship.stewards.len(), 2);
396        let guardian_dids: Vec<&str> = rec.guardians().iter().map(|g| g.did.as_str()).collect();
397        assert!(guardian_dids.contains(&"did:wf:mother"));
398        assert!(guardian_dids.contains(&"did:wf:father"));
399        assert!(
400            rec.guardianship
401                .stewards
402                .iter()
403                .all(|s| s.basis == StewardBasis::BiologicalDefault)
404        );
405        assert!(!rec.guardianship.is_credentialed());
406        assert_eq!(rec.forum_class(), ForumClass::Internum);
407    }
408
409    #[test]
410    fn an_official_credential_overrides_the_biological_default() {
411        // Surrogacy: the carrier gives birth, but a surrogacy parentage order assigns the intended parents.
412        let mut dyad = dyad_two_known_parents();
413        dyad.maternal.principal = PrincipalRef::new("did:wf:surrogate");
414        dyad.child.parentage = Parentage {
415            ovum_source: Progenitor::Donor,
416            sperm_source: Progenitor::Known(PrincipalRef::new("did:wf:genetic-father")),
417            intended_parents: vec![
418                PrincipalRef::new("did:wf:parent-a"),
419                PrincipalRef::new("did:wf:parent-b"),
420            ],
421        };
422        let rec = dyad
423            .give_birth(
424                vec![BiometricClass::Dna],
425                vec![CredentialRef {
426                    vc_id: "vc:surrogacy-order-1".into(),
427                    kind: GuardianshipCredential::SurrogacyParentageOrder,
428                }],
429                vec![
430                    PrincipalRef::new("did:wf:parent-a"),
431                    PrincipalRef::new("did:wf:parent-b"),
432                ],
433                Some(PrincipalRef::new("did:wf:registry")),
434                Some("2026-07-06".into()),
435            )
436            .unwrap();
437        assert_eq!(rec.validate(), Ok(()));
438        assert!(rec.guardianship.is_credentialed());
439        assert!(
440            rec.guardianship
441                .stewards
442                .iter()
443                .all(|s| s.basis == StewardBasis::Credentialed)
444        );
445        let guardian_dids: Vec<&str> = rec.guardians().iter().map(|g| g.did.as_str()).collect();
446        assert_eq!(guardian_dids, vec!["did:wf:parent-a", "did:wf:parent-b"]);
447        assert!(!guardian_dids.contains(&"did:wf:surrogate"));
448    }
449
450    #[test]
451    fn agency_is_a_gradient_not_a_binary_and_stewardship_yields_over_development() {
452        // Self-determination increases monotonically across the developmental gradient.
453        assert!(
454            AgencyStage::Neonate.self_determination() < AgencyStage::Child.self_determination()
455        );
456        assert!(
457            AgencyStage::Child.self_determination() < AgencyStage::Adolescent.self_determination()
458        );
459        assert!(
460            AgencyStage::Adolescent.self_determination() < AgencyStage::Adult.self_determination()
461        );
462        // A supported adult has FULL self-determination (with supports), not a reduced status.
463        assert_eq!(
464            AgencyStage::SupportedAdult.self_determination(),
465            AgencyStage::Adult.self_determination()
466        );
467        // Stewardship is active through development; an independent adult carries none; a supported adult
468        // carries supports (stewardship in service of the person's own will), so it stays "active".
469        assert!(AgencyStage::Neonate.stewardship_active());
470        assert!(!AgencyStage::Adult.stewardship_active());
471        assert!(AgencyStage::SupportedAdult.stewardship_active());
472    }
473
474    #[test]
475    fn roles_can_be_split_across_different_stewards() {
476        // The medical decision-maker need not be the day-to-day carer — the commons holds distributed roles.
477        let g = Guardianship {
478            stewards: vec![
479                Steward {
480                    principal: PrincipalRef::new("did:wf:carer"),
481                    roles: vec![StewardRole::PrimaryCare],
482                    basis: StewardBasis::BiologicalDefault,
483                },
484                Steward {
485                    principal: PrincipalRef::new("did:wf:medical-guardian"),
486                    roles: vec![StewardRole::Medical, StewardRole::Legal],
487                    basis: StewardBasis::Credentialed,
488                },
489            ],
490            credentials: vec![],
491        };
492        let medical = g.stewards_with(&StewardRole::Medical);
493        assert_eq!(medical.len(), 1);
494        assert_eq!(medical[0].principal.did, "did:wf:medical-guardian");
495        assert_eq!(
496            g.stewards_with(&StewardRole::PrimaryCare)[0].principal.did,
497            "did:wf:carer"
498        );
499    }
500
501    #[test]
502    fn a_child_is_never_left_unstewarded_or_collapsed_into_a_steward() {
503        // No known biological parent and no credentialed steward ⇒ no steward ⇒ invalid.
504        let mut dyad = dyad_two_known_parents();
505        dyad.child.parentage = Parentage {
506            ovum_source: Progenitor::Donor,
507            sperm_source: Progenitor::Unknown,
508            intended_parents: vec![],
509        };
510        let rec = dyad.give_birth(vec![], vec![], vec![], None, None).unwrap();
511        assert_eq!(rec.validate(), Err(BirthRecordInvalid::NoSteward));
512
513        // Subject collapsed into a steward ⇒ invalid.
514        let mut rec2 = dyad_two_known_parents()
515            .give_birth(vec![], vec![], vec![], None, None)
516            .unwrap();
517        rec2.subject = PrincipalRef::new("did:wf:mother");
518        assert_eq!(rec2.validate(), Err(BirthRecordInvalid::SubjectCollapsed));
519    }
520
521    #[test]
522    fn birth_requires_a_valid_dyad() {
523        let mut dyad = dyad_two_known_parents();
524        dyad.maternal.state = PhysiologicalState::Baseline;
525        assert_eq!(
526            dyad.give_birth(vec![], vec![], vec![], None, None)
527                .unwrap_err(),
528            DyadInvalid::NotPregnant
529        );
530    }
531
532    #[test]
533    fn serde_round_trips() {
534        let rec = dyad_two_known_parents()
535            .give_birth(vec![BiometricClass::Dna], vec![], vec![], None, None)
536            .unwrap();
537        let json = serde_json::to_string(&rec).unwrap();
538        let back: DigitalBirthRecord = serde_json::from_str(&json).unwrap();
539        assert_eq!(rec, back);
540    }
541}