wellfare_core/anatomy/dyad.rs
1//! P2 — the **maternal–fetal dyad** *domain* model (plan of record §3.3, §8), built on the **science**.
2//!
3//! Gestation modelled as the plan insists: **two coupled bodies, not one body with an organ.** But the
4//! rights structure has to follow biology, not a default family shape (Timothy, 2026-07-06):
5//!
6//! - **The emerging entity has two genetic origins.** Fertilization requires an ovum **and** a sperm — an
7//! ovum alone is not a new life — so there are two [`Progenitor`]s. Either may be **unknown**, a person
8//! who does not know, or a **donor**.
9//! - **Genetic ≠ gestational ≠ social ≠ guardian.** Surrogacy and gamete donation make these genuinely
10//! different parties (the ovum source, the sperm source, the gestational carrier, and any intended
11//! parents can all be distinct). Conflating them is the error this model avoids.
12//! - **The steward/guardian during gestation is the gestational mother.** She carries; she is the
13//! data-subject; guardianship of the emerging entity is hers ([`MaternalFetalDyad::guardian`]).
14//! - **Social/legal personhood accrues at or after *birth*** ([`RightsStage`]) — the exact threshold (at
15//! birth, or after the fourth trimester) is a **deferred values decision** ([`SocialRightsThreshold`],
16//! §9.4). During gestation the emerging entity is *stewarded* in guardianship; it is **not** modelled as a
17//! competing legal person, so the gestational mother's autonomy over her own body and data stays paramount.
18//!
19//! **What this module is, and isn't.** It builds the rights-and-structure machinery and encodes the
20//! invariants in the type system + [`MaternalFetalDyad::validate`]. It does **not** author cross-body
21//! physiological *correlation content* (that is clinician/midwife-gated, §9.3), and it does **not** settle
22//! the values calls (the social-rights threshold, when guardianship transfers) — those are Timothy's (§9.4).
23//! Everything it *does* emit is an [`EpistemicStatus::Hypothesis`] proposal, never a determination.
24//!
25//! This is the pure **domain/rights** model; the *visual* dyad (mesh placement) is the separate,
26//! geometry-gated `anatomy_dyad.rs` in the client layer — they compose (this = *who/what*, that = *where*).
27//!
28//! [`EpistemicStatus::Hypothesis`]: crate::record::EpistemicStatus::Hypothesis
29
30use serde::{Deserialize, Serialize};
31
32use super::physiology::{PhysiologicalState, ReproductiveState, Trimester};
33use super::scorecard::ForumClass;
34
35/// A reference to a rights-bearing **principal** by identifier — a DID, kept as an *identifier* and never
36/// treated as an identity (a DID identifies; identity is a probabilistic fabric that must not collapse onto
37/// one identifier). Abstract here — the identity/guardianship layer resolves it.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct PrincipalRef {
40 /// A pairwise/contextual DID identifier. Not an identity, not a legal name.
41 pub did: String,
42}
43
44impl PrincipalRef {
45 /// Creates a new instance.
46 pub fn new(did: impl Into<String>) -> Self {
47 Self { did: did.into() }
48 }
49 fn is_empty(&self) -> bool {
50 self.did.trim().is_empty()
51 }
52}
53
54/// A genetic **progenitor** — one gamete source. There are two per emerging entity (ovum + sperm). A
55/// progenitor may be a known principal, a donor (identity withheld/pseudonymous by arrangement — possibly
56/// resolvable later for the child's right to know their origins, a governance policy not asserted here), or
57/// simply unknown/unrecorded (a father may not be known, or not know).
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum Progenitor {
61 Known(PrincipalRef),
62 Donor,
63 Unknown,
64}
65
66impl Progenitor {
67 /// The known principal, if this progenitor is a known party.
68 pub fn known(&self) -> Option<&PrincipalRef> {
69 match self {
70 Progenitor::Known(p) => Some(p),
71 _ => None,
72 }
73 }
74}
75
76/// The distinct biological + social roles around the emerging child — modelled on the science, not on a
77/// presumed family shape. Genetic (the two [`Progenitor`]s), and social (declared [`intended_parents`]).
78/// The *gestational* role lives on [`MaternalBody`] (she carries), and *guardianship* during gestation is
79/// hers ([`MaternalFetalDyad::guardian`]).
80///
81/// [`intended_parents`]: Parentage::intended_parents
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct Parentage {
84 /// The ovum (egg) genetic source. May be the gestational mother, an egg donor, or unknown.
85 pub ovum_source: Progenitor,
86 /// The sperm genetic source. Required for a new life; may be a donor, unknown, or a person unaware.
87 pub sperm_source: Progenitor,
88 /// Intended / social parent(s), if declared (e.g. a surrogacy arrangement). Social roles, distinct from
89 /// genetics and from who carries.
90 #[serde(default)]
91 pub intended_parents: Vec<PrincipalRef>,
92}
93
94impl Parentage {
95 /// The **known genetic** parents — the ovum + sperm sources that are known principals. This is the
96 /// *biological* default for guardianship at birth (a donor / unknown contributes no principal).
97 pub fn known_genetic_parents(&self) -> Vec<&PrincipalRef> {
98 let mut v = Vec::new();
99 if let Some(p) = self.ovum_source.known() {
100 v.push(p);
101 }
102 if let Some(p) = self.sperm_source.known() {
103 v.push(p);
104 }
105 v
106 }
107
108 /// The **known** adult principals involved (genetic + intended) — the parties an emerging child must
109 /// never be collapsed into. Donors/unknowns contribute no principal here.
110 fn known_adults(&self) -> Vec<&PrincipalRef> {
111 let mut v = self.known_genetic_parents();
112 v.extend(self.intended_parents.iter());
113 v
114 }
115}
116
117/// Where the emerging entity is on the path to social/legal personhood.
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "snake_case")]
120pub enum RightsStage {
121 /// Before birth — an entity-in-formation, **stewarded in guardianship** by the gestational mother. Not
122 /// yet a full social/legal person (so it is not a competing legal person to the mother).
123 EmergingInGestation,
124 /// Born — social/legal personhood accrues (the exact threshold is [`SocialRightsThreshold`]).
125 Born,
126}
127
128/// The **deferred values decision**: when a born child's social/legal rights are recognised as accruing.
129/// Timothy flagged uncertainty (at birth, or after the fourth trimester); the model carries the choice, it
130/// does not assert one. Whatever the threshold, personhood is **never withheld beyond it** and never
131/// applied *during* gestation (which would subordinate the gestational mother's autonomy).
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
133#[serde(rename_all = "snake_case")]
134pub enum SocialRightsThreshold {
135 AtBirth,
136 AfterFourthTrimester,
137 /// Undecided — Timothy's values call (§9.4).
138 Undecided,
139}
140
141/// The developing child: an emerging entity indexed on the `t` (gestational-age) axis. Its identifier
142/// fabric is **pairwise, uncorrelated, and never collapsed** into any adult's record.
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144pub struct EmergingChild {
145 /// **One** pairwise identifier, for this relationship/context only — there is deliberately no single
146 /// "the child's identity". Correlation-by-default is the surveillance on-ramp this refuses.
147 pub pairwise_did: String,
148 /// The science-based origin: two genetic progenitors + any declared social parents.
149 pub parentage: Parentage,
150 /// The rights stage (in gestation this is [`RightsStage::EmergingInGestation`]).
151 pub rights_stage: RightsStage,
152}
153
154/// The maternal–fetal interface coupling the two bodies.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
156#[serde(rename_all = "snake_case")]
157pub enum InterfaceKind {
158 /// The placenta — the HRA reference organ we already compile (`placenta-full-term`).
159 Placenta,
160}
161
162/// The mother in the dyad: the **gestational** mother — the data-subject who carries, and the emerging
163/// child's **guardian during gestation**. Her whole-body model is in a pregnant [`PhysiologicalState`].
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
165pub struct MaternalBody {
166 /// The gestational mother's principal reference (she is also the guardian during gestation).
167 pub principal: PrincipalRef,
168 /// Expected `Reproductive(Pregnant(_))` — [`MaternalFetalDyad::validate`] enforces it.
169 pub state: PhysiologicalState,
170}
171
172/// The dyad: two coupled principals joined by the interface. **Sanctuary-class, forum-internum** data.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174pub struct MaternalFetalDyad {
175 pub maternal: MaternalBody,
176 pub child: EmergingChild,
177 /// Gestational age in days. **Convention is the caller's to state**: clinical gestational age is from
178 /// the last menstrual period (LMP); the Carnegie/embryology assets are indexed *postfertilization*
179 /// (~14 days earlier). Precise stage↔age↔trimester alignment is clinical content (§9), not asserted.
180 pub gestational_age_days: u32,
181 pub carnegie_stage: Option<u32>,
182 pub interface: InterfaceKind,
183 /// The (deferred) values setting for when a born child's social rights accrue.
184 pub social_rights_threshold: SocialRightsThreshold,
185}
186
187/// A reason a dyad is structurally invalid — a **rights** violation or an impossibility.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "snake_case")]
190pub enum DyadInvalid {
191 /// The maternal state is not a pregnant state — a gestational dyad exists only in pregnancy.
192 NotPregnant,
193 /// No gestational mother — she is the data-subject and the guardian; she must be present.
194 NoGestationalMother,
195 /// The child's identifier is empty or **collapsed into an adult** (identical to the gestational
196 /// mother, a known genetic progenitor, or an intended parent). The core rights invariant: the child is
197 /// its own emerging principal, never a field of an adult's identity.
198 ChildIdentityCollapsed,
199 /// The child's rights stage is not `EmergingInGestation` while the mother is pregnant (a born child is
200 /// not a *gestational* dyad).
201 RightsStageMismatch,
202 /// The gestational age is outside any plausible range (1..=300 days).
203 ImplausibleGestationalAge,
204}
205
206/// A cross-body **proposal** about the dyad — always [`EpistemicStatus::Hypothesis`], never a
207/// determination. P2 emits only *structural / rights / science* considerations; medical correlations are
208/// deferred curation (§9.3).
209///
210/// [`EpistemicStatus::Hypothesis`]: crate::record::EpistemicStatus::Hypothesis
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct DyadConsideration {
213 pub kind: ConsiderationKind,
214 /// Plain, non-diagnostic wording.
215 pub note: String,
216 pub epistemic_status: crate::record::EpistemicStatus,
217}
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum ConsiderationKind {
222 /// A statement about the rights structure of the dyad.
223 Rights,
224 /// A statement grounded in reproductive biology (the two-gamete origin; the distinct roles).
225 Science,
226 /// A pointer that content (medical correlations, values thresholds) is deferred to curation.
227 CurationDeferred,
228}
229
230impl MaternalFetalDyad {
231 /// A dyad's data is always **forum internum** (a person's — and an emerging person's — inward domain).
232 pub const fn forum_class(&self) -> ForumClass {
233 ForumClass::Internum
234 }
235
236 /// Always the most-restrictive sensitivity class (`Sanctuary`), returned as the ladder's canonical name
237 /// so the storage layer maps it without this pure crate depending on the sensitivity enum. The
238 /// high-water-mark rule makes anything derived from a dyad inherit this.
239 pub const fn sensitivity_class(&self) -> &'static str {
240 "Sanctuary"
241 }
242
243 /// The **guardian during gestation** — the gestational mother. Guardianship is a scoped, revocable
244 /// *role*, not ownership; whether/when it transfers post-birth (e.g. to intended parents in surrogacy)
245 /// is a deferred values decision (§9.4).
246 pub fn guardian(&self) -> &PrincipalRef {
247 &self.maternal.principal
248 }
249
250 /// The maternal trimester, if the mother is in a pregnant state.
251 pub fn trimester(&self) -> Option<Trimester> {
252 match self.maternal.state {
253 PhysiologicalState::Reproductive(ReproductiveState::Pregnant(t)) => Some(t),
254 _ => None,
255 }
256 }
257
258 /// Enforce the non-negotiable rights + possibility invariants.
259 pub fn validate(&self) -> Result<(), DyadInvalid> {
260 if self.trimester().is_none() {
261 return Err(DyadInvalid::NotPregnant);
262 }
263 if self.maternal.principal.is_empty() {
264 return Err(DyadInvalid::NoGestationalMother);
265 }
266 let child = self.child.pairwise_did.trim();
267 if child.is_empty() {
268 return Err(DyadInvalid::ChildIdentityCollapsed);
269 }
270 // The child is a distinct principal from the gestational mother AND every known adult (genetic or
271 // intended). Never a field of an adult's identity.
272 if child == self.maternal.principal.did.trim()
273 || self
274 .child
275 .parentage
276 .known_adults()
277 .iter()
278 .any(|a| a.did.trim() == child)
279 {
280 return Err(DyadInvalid::ChildIdentityCollapsed);
281 }
282 if self.child.rights_stage != RightsStage::EmergingInGestation {
283 return Err(DyadInvalid::RightsStageMismatch);
284 }
285 if self.gestational_age_days == 0 || self.gestational_age_days > 300 {
286 return Err(DyadInvalid::ImplausibleGestationalAge);
287 }
288 Ok(())
289 }
290
291 /// The structural / rights / science considerations for a **valid** dyad — proposals, never
292 /// determinations. These are the honest, non-medical statements the model *can* make; the cross-body
293 /// physiological correlations are curation-grade and pointedly **not** seeded (their absence is
294 /// deliberate, not a gap).
295 pub fn considerations(&self) -> Vec<DyadConsideration> {
296 use crate::record::EpistemicStatus::Hypothesis;
297 let c = |kind, note: &str| DyadConsideration {
298 kind,
299 note: note.to_string(),
300 epistemic_status: Hypothesis,
301 };
302 vec![
303 c(
304 ConsiderationKind::Science,
305 "The emerging entity arises from the union of an ovum and a sperm (two genetic \
306 progenitors). Genetic, gestational, and social/intended-parent roles are modelled \
307 distinctly — they may be different parties (donation, surrogacy), and a progenitor may be \
308 unknown or unaware.",
309 ),
310 c(
311 ConsiderationKind::Rights,
312 "The developing child is a distinct emerging principal — held in guardianship by the \
313 gestational mother, never collapsed into any adult's record, never correlated by default.",
314 ),
315 c(
316 ConsiderationKind::Rights,
317 "Social/legal personhood is modelled as accruing at or after birth; during gestation the \
318 entity is stewarded, not a competing legal person, so the gestational mother's autonomy \
319 over her own body and data remains paramount. The exact threshold (birth vs the fourth \
320 trimester) and when guardianship transfers are deferred values decisions.",
321 ),
322 c(
323 ConsiderationKind::CurationDeferred,
324 "Cross-body physiological correlations (what the maternal state may mean for development, \
325 and vice-versa) are proposals for discussion with a clinician/midwife — none are asserted \
326 here; that content is curation-grade.",
327 ),
328 ]
329 }
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335 use crate::record::EpistemicStatus;
336
337 fn dyad() -> MaternalFetalDyad {
338 MaternalFetalDyad {
339 maternal: MaternalBody {
340 principal: PrincipalRef::new("did:wf:mother"),
341 state: PhysiologicalState::Reproductive(ReproductiveState::Pregnant(
342 Trimester::Second,
343 )),
344 },
345 child: EmergingChild {
346 pairwise_did: "did:wf:child-pairwise-1".into(),
347 parentage: Parentage {
348 ovum_source: Progenitor::Known(PrincipalRef::new("did:wf:mother")),
349 sperm_source: Progenitor::Unknown,
350 intended_parents: vec![],
351 },
352 rights_stage: RightsStage::EmergingInGestation,
353 },
354 gestational_age_days: 20 * 7,
355 carnegie_stage: None,
356 interface: InterfaceKind::Placenta,
357 social_rights_threshold: SocialRightsThreshold::Undecided,
358 }
359 }
360
361 #[test]
362 fn a_valid_dyad_is_two_coupled_principals_and_guardian_is_the_gestational_mother() {
363 let d = dyad();
364 assert_eq!(d.validate(), Ok(()));
365 assert_eq!(d.trimester(), Some(Trimester::Second));
366 // The steward/guardian during gestation is the gestational mother (Timothy's direction).
367 assert_eq!(d.guardian().did, "did:wf:mother");
368 }
369
370 #[test]
371 fn the_science_a_missing_father_is_representable_not_an_error() {
372 // A sperm source that is unknown / a person who does not know is a first-class, valid case.
373 let d = dyad();
374 assert_eq!(d.child.parentage.sperm_source, Progenitor::Unknown);
375 assert_eq!(d.validate(), Ok(()));
376 }
377
378 #[test]
379 fn surrogacy_and_donors_are_distinct_roles() {
380 // Egg donor + sperm donor + a gestational carrier who is neither + two intended parents.
381 let mut d = dyad();
382 d.maternal.principal = PrincipalRef::new("did:wf:surrogate");
383 d.child.parentage = Parentage {
384 ovum_source: Progenitor::Donor,
385 sperm_source: Progenitor::Donor,
386 intended_parents: vec![
387 PrincipalRef::new("did:wf:parent-a"),
388 PrincipalRef::new("did:wf:parent-b"),
389 ],
390 };
391 assert_eq!(d.validate(), Ok(()));
392 // Guardian during gestation is the one carrying — the surrogate — not the intended parents.
393 assert_eq!(d.guardian().did, "did:wf:surrogate");
394 }
395
396 #[test]
397 fn the_child_is_never_collapsed_into_any_adult() {
398 // Into the gestational mother:
399 let mut d = dyad();
400 d.child.pairwise_did = "did:wf:mother".into();
401 assert_eq!(d.validate(), Err(DyadInvalid::ChildIdentityCollapsed));
402
403 // Into a known genetic progenitor:
404 let mut d = dyad();
405 d.child.parentage.sperm_source = Progenitor::Known(PrincipalRef::new("did:wf:father"));
406 d.child.pairwise_did = "did:wf:father".into();
407 assert_eq!(d.validate(), Err(DyadInvalid::ChildIdentityCollapsed));
408
409 // Into an intended parent:
410 let mut d = dyad();
411 d.child.parentage.intended_parents = vec![PrincipalRef::new("did:wf:intended")];
412 d.child.pairwise_did = "did:wf:intended".into();
413 assert_eq!(d.validate(), Err(DyadInvalid::ChildIdentityCollapsed));
414
415 // Empty:
416 let mut d = dyad();
417 d.child.pairwise_did = " ".into();
418 assert_eq!(d.validate(), Err(DyadInvalid::ChildIdentityCollapsed));
419 }
420
421 #[test]
422 fn a_dyad_only_exists_in_a_pregnant_state_and_in_gestation_stage() {
423 let mut d = dyad();
424 d.maternal.state = PhysiologicalState::Baseline;
425 assert_eq!(d.validate(), Err(DyadInvalid::NotPregnant));
426
427 let mut d = dyad();
428 d.child.rights_stage = RightsStage::Born; // a born child is not a gestational dyad
429 assert_eq!(d.validate(), Err(DyadInvalid::RightsStageMismatch));
430 }
431
432 #[test]
433 fn missing_gestational_mother_or_implausible_age_is_rejected() {
434 let mut d = dyad();
435 d.maternal.principal = PrincipalRef::new("");
436 assert_eq!(d.validate(), Err(DyadInvalid::NoGestationalMother));
437
438 let mut d = dyad();
439 d.gestational_age_days = 400;
440 assert_eq!(d.validate(), Err(DyadInvalid::ImplausibleGestationalAge));
441 }
442
443 #[test]
444 fn social_rights_threshold_is_a_carried_deferred_value_not_asserted() {
445 let d = dyad();
446 // The model carries the (undecided) values choice; it does not decide it.
447 assert_eq!(d.social_rights_threshold, SocialRightsThreshold::Undecided);
448 // During gestation the child is emerging, not yet a born social person.
449 assert_eq!(d.child.rights_stage, RightsStage::EmergingInGestation);
450 }
451
452 #[test]
453 fn dyad_data_is_sanctuary_class_forum_internum() {
454 let d = dyad();
455 assert_eq!(d.forum_class(), ForumClass::Internum);
456 assert_eq!(d.sensitivity_class(), "Sanctuary");
457 }
458
459 #[test]
460 fn considerations_are_structural_science_and_rights_proposals_never_determinations() {
461 let d = dyad();
462 let cons = d.considerations();
463 assert!(
464 cons.iter()
465 .all(|c| c.epistemic_status == EpistemicStatus::Hypothesis)
466 );
467 assert!(cons.iter().any(|c| c.kind == ConsiderationKind::Science));
468 assert!(cons.iter().any(|c| c.kind == ConsiderationKind::Rights));
469 assert!(
470 cons.iter()
471 .any(|c| c.kind == ConsiderationKind::CurationDeferred)
472 );
473 }
474
475 #[test]
476 fn serde_round_trips() {
477 let d = dyad();
478 let json = serde_json::to_string(&d).unwrap();
479 let back: MaternalFetalDyad = serde_json::from_str(&json).unwrap();
480 assert_eq!(d, back);
481 }
482}