Skip to main content

wellfare_core/anatomy/
scorecard.rs

1//! The **score-card** — an accumulative, fully-traceable interpretation across health-relevant *aspects*.
2//!
3//! The per-system [`SystemBurden`](super::accumulate::SystemBurden) layer answers "where is load
4//! converging". This layer answers the question a person actually asks: *"so, overall — how are things,
5//! and why?"* — but it answers it the **opposite way to a health-credit score.** It is:
6//!
7//! - **Multi-aspect, never one reductive number.** A card of [`Aspect`]s (systemic load, stress,
8//!   resilience, convergence, interaction load, physiological demand) — a person is not a single grade.
9//! - **Fully traceable — the antithesis of a black box.** Every [`AspectScore`] carries the
10//!   [`Contribution`]s that produced it (which systems / factors / interactions / state, each with its
11//!   weight and evidence tier). The score is never asserted; it is *shown its work*.
12//! - **A transparent, editable weights model.** [`WeightModel`] is a plain, inspectable table of
13//!   `(system, aspect) → weight` — a "human weights model" you can read and change, not a learned net.
14//! - **The person's own tool, not an assessment weapon.** It is a discussion aid for the data-subject
15//!   and *their chosen* clinician (see the care-relationship stance: a counter-record, **not** a public
16//!   rating). It scores load / stress / resilience / convergence — the discussable *precursors* — and
17//!   **explicitly does not score "illness" or "disease"**: that would be a diagnosis, which this never is.
18//! - **Control *enables* knowing — protection and enablement are one right, not opposed.** As much as
19//!   information can be weaponised, the *lack* of it is equally a harm: the right to know oneself with real
20//!   science, and to move hypothesis → test → specialist input → action, is itself a human right. The
21//!   forum-internum classification (below) is not a lock that keeps a person ignorant — it is *their
22//!   control*, which is exactly what makes it safe for them to know, and to *deliberately* share on their
23//!   own terms with a specialist they choose. Each aspect is a `Hypothesis` — a **pathway start** toward
24//!   testing / specialist input / support (the investigative-pathway layer), never a dead-end verdict.
25//!
26//! **Honesty (unchanged).** Integer-only, coarse bands, deterministic; every aspect is an
27//! [`EpistemicStatus::Hypothesis`]; traditional/community evidence is preserved at its own tier. The
28//! **weights themselves are an illustrative seed** ([`seed_weight_model`]) of well-established directions —
29//! the authoritative weighting + framing is curation-grade (Timothy's / an expert's to supply), exactly as
30//! for the physiology seed.
31
32use serde::{Deserialize, Serialize};
33
34use crate::record::EpistemicStatus;
35
36use super::accumulate::{
37    Interaction, InteractionKind, SystemBurden, SystemicImplication, accumulate, interactions,
38    systemic_implications,
39};
40use super::factor::{EvidenceTier, Factor};
41use super::physiology::{PhysiologicalState, state_modulator, whole_body_profile};
42use super::system_key;
43use super::systems::body_system;
44
45/// A health-relevant **aspect** the card interprets — a discussion *lens*, not a diagnosis axis.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum Aspect {
49    /// Overall accumulated adverse load across all systems.
50    SystemicLoad,
51    /// Load concentrated on the stress-responsive systems (nervous / endocrine / ECS …).
52    Stress,
53    /// The supportive / recovery side — what is *helping*. First-class so the card is never only-negatives.
54    Resilience,
55    /// How much load is *converging* — multiple distinct factors pointing at the same system(s).
56    Convergence,
57    /// Load from factors *combining* — herb–drug pairs and compounding.
58    InteractionLoad,
59    /// The current physiological state's whole-body engagement (the reproductive-continuum layer).
60    PhysiologicalDemand,
61}
62
63impl Aspect {
64    /// All aspects, in card order.
65    pub fn all() -> [Aspect; 6] {
66        [
67            Aspect::SystemicLoad,
68            Aspect::Stress,
69            Aspect::Resilience,
70            Aspect::Convergence,
71            Aspect::InteractionLoad,
72            Aspect::PhysiologicalDemand,
73        ]
74    }
75
76    /// Label.
77    pub fn label(self) -> &'static str {
78        match self {
79            Aspect::SystemicLoad => "Systemic load",
80            Aspect::Stress => "Stress load",
81            Aspect::Resilience => "Resilience & support",
82            Aspect::Convergence => "Converging factors",
83            Aspect::InteractionLoad => "Combined-effect load",
84            Aspect::PhysiologicalDemand => "Physiological demand",
85        }
86    }
87
88    /// Accessibility-first plain wording.
89    pub fn plain_label(self) -> &'static str {
90        match self {
91            Aspect::SystemicLoad => "how much is adding up across your body",
92            Aspect::Stress => "load on the stress-response systems",
93            Aspect::Resilience => "what's helping and supporting recovery",
94            Aspect::Convergence => "several things pointing at the same place",
95            Aspect::InteractionLoad => "things that may combine",
96            Aspect::PhysiologicalDemand => "the extra work of your current life stage",
97        }
98    }
99
100    /// `Resilience` reads "higher is better"; every other aspect reads "higher = more to discuss". Lets a
101    /// UI colour the bands correctly (a high resilience band is reassuring, not a warning).
102    pub fn higher_is_supportive(self) -> bool {
103        matches!(self, Aspect::Resilience)
104    }
105}
106
107/// A coarse, dignity-framed band. **Never** a clinical grade or a pass/fail.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum ScoreBand {
111    /// Little to nothing accumulating here.
112    Settled,
113    /// Some load building.
114    Building,
115    /// Notably heightened — worth a look / a conversation.
116    Heightened,
117    /// Markedly heightened — worth discussing with a clinician you trust.
118    Marked,
119}
120
121impl ScoreBand {
122    fn from_score(score_milli: u32) -> ScoreBand {
123        match score_milli {
124            0..=99 => ScoreBand::Settled,
125            100..=349 => ScoreBand::Building,
126            350..=649 => ScoreBand::Heightened,
127            _ => ScoreBand::Marked,
128        }
129    }
130}
131
132/// What kind of underlying consideration a [`Contribution`] links to.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(rename_all = "snake_case")]
135pub enum ContributionKind {
136    /// A body system's accumulated load.
137    System,
138    /// A specific interaction between factors.
139    Interaction,
140    /// A systemic-implication convergence.
141    Convergence,
142    /// The current physiological state's engagement of a system.
143    State,
144}
145
146/// A single **linkage to an underlying consideration** — the traceability that makes the score-card the
147/// opposite of a black box. Says *what* contributed, *how much* (weighted), and on *what evidence*.
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149pub struct Contribution {
150    pub kind: ContributionKind,
151    /// The underlying id (system id, factor id, …) — the click-through target.
152    pub source_id: String,
153    /// Human-readable label.
154    pub label: String,
155    /// This source's weighted contribution to the aspect score (integer milli).
156    pub weighted_milli: u32,
157    /// The evidence backing this contribution (never collapsed across tiers).
158    pub evidence: EvidenceTier,
159}
160
161/// One aspect's accumulated score, its band, and — crucially — the linkages that produced it.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct AspectScore {
164    pub aspect: Aspect,
165    /// Accumulated 0..=1000.
166    pub score_milli: u32,
167    pub band: ScoreBand,
168    /// The underlying considerations, strongest first. Empty ⇒ nothing accumulating for this aspect.
169    pub contributions: Vec<Contribution>,
170    /// Strongest evidence tier among the contributions (drives how prominently it's shown).
171    pub dominant_evidence: EvidenceTier,
172    /// Always `Hypothesis` — a computed interpretation, never a fact/diagnosis.
173    pub epistemic_status: EpistemicStatus,
174}
175
176/// Where a piece of content sits in the selfhood / personhood taxonomy.
177///
178/// - **`Internum`** — *forum internum*: the inward domain of the person (the mind, the self, one's own
179///   assessment of one's own body). Near-absolute and **non-derogable** — the person's alone.
180/// - **`Externum`** — *forum externum*: outward conduct/agency, proportionately regulable.
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "snake_case")]
183pub enum ForumClass {
184    Internum,
185    Externum,
186}
187
188/// The whole card — one [`AspectScore`] per [`Aspect`], in [`Aspect::all`] order.
189///
190/// **A score-card is selfhood content.** It is a person's *inward self-assessment* of their own body —
191/// [`ForumClass::Internum`], the near-absolute, non-derogable inner domain — **never** a third party's
192/// assessment *of* them. As a derivation from health records it inherits the **most-restrictive**
193/// sensitivity class (`Sanctuary`) under the high-water-mark rule, and defaults to non-disclosure. The
194/// storage/consent layer must classify and gate it accordingly (see [`ScoreCard::forum_class`] /
195/// [`ScoreCard::sensitivity_class`]); this typing is the structural backing for "the person's own tool,
196/// not a rating weapon."
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198pub struct ScoreCard {
199    pub aspects: Vec<AspectScore>,
200}
201
202impl ScoreCard {
203    /// The score for a given aspect, if present.
204    pub fn aspect(&self, aspect: Aspect) -> Option<&AspectScore> {
205        self.aspects.iter().find(|a| a.aspect == aspect)
206    }
207
208    /// A score-card is always **forum internum** — inward selfhood content, the person's alone.
209    pub const fn forum_class(&self) -> ForumClass {
210        ForumClass::Internum
211    }
212
213    /// The sensitivity class to store/handle a score-card under: always **`Sanctuary`** (the
214    /// most-restrictive rung of the `Public → Restricted → Classified → Sanctuary` ladder). Returned as
215    /// the ladder's canonical name so the storage layer (which owns the sensitivity enum) maps it without
216    /// this pure domain crate depending on it. Absent classification already means "most-restrictive"; this
217    /// is the explicit belt-and-braces.
218    pub const fn sensitivity_class(&self) -> &'static str {
219        "Sanctuary"
220    }
221}
222
223// ===========================================================================
224// The transparent weights model
225// ===========================================================================
226
227/// One weight in the model: how much a body system contributes to an aspect (percent; `0` = not at all,
228/// `100` = fully). Plain and inspectable — this *is* the "human weights model", written out.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct SystemAspectWeight {
231    pub system_id: String,
232    pub aspect: Aspect,
233    pub weight_pct: u32,
234}
235
236/// A readable, editable table of `(system, aspect) → weight`. The interpretive core of the card, exposed
237/// rather than hidden.
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
239pub struct WeightModel {
240    pub system_weights: Vec<SystemAspectWeight>,
241}
242
243impl WeightModel {
244    /// The weight for `(system_id, aspect)` (default `0` if unlisted).
245    pub fn weight_for(&self, system_id: &str, aspect: Aspect) -> u32 {
246        self.system_weights
247            .iter()
248            .find(|w| w.aspect == aspect && system_key(&w.system_id) == system_key(system_id))
249            .map(|w| w.weight_pct)
250            .unwrap_or(0)
251    }
252}
253
254/// The **illustrative seed** weights (§: curation-grade content deferred to Timothy/an expert). Encodes
255/// only well-established directions — which systems carry the *stress* axis, which carry *resilience-
256/// relevant* recovery — coarse, not authoritative magnitudes. Extend/replace with a curated model.
257pub fn seed_weight_model() -> WeightModel {
258    // (system_id, stress_weight_pct, resilience_weight_pct)
259    let rows: &[(&str, u32, u32)] = &[
260        ("nervous", 100, 60),
261        ("endocrine", 90, 50),
262        ("ecs", 80, 70), // the endocannabinoid "internal balance" system
263        ("circulatory", 50, 40),
264        ("digestive", 40, 50),
265        ("immune_lymphatic", 40, 60),
266        ("glymphatic", 60, 80), // the brain's overnight clearance — sleep/recovery relevant
267        ("muscular", 30, 50),
268        ("respiratory", 40, 30),
269    ];
270    let mut system_weights = Vec::new();
271    for (id, stress, resilience) in rows {
272        if *stress > 0 {
273            system_weights.push(SystemAspectWeight {
274                system_id: id.to_string(),
275                aspect: Aspect::Stress,
276                weight_pct: *stress,
277            });
278        }
279        if *resilience > 0 {
280            system_weights.push(SystemAspectWeight {
281                system_id: id.to_string(),
282                aspect: Aspect::Resilience,
283                weight_pct: *resilience,
284            });
285        }
286    }
287    WeightModel { system_weights }
288}
289
290// ===========================================================================
291// Scoring
292// ===========================================================================
293
294fn clamp1000(v: u64) -> u32 {
295    v.min(1000) as u32
296}
297
298/// Strongest evidence tier among a factor set's mappings (any effect) onto `system_id`.
299fn system_evidence(factors: &[Factor], system_id: &str) -> EvidenceTier {
300    factors
301        .iter()
302        .flat_map(|f| &f.targets)
303        .filter(|t| system_key(&t.system_id) == system_key(system_id))
304        .map(|t| t.evidence)
305        .max()
306        .unwrap_or(EvidenceTier::CommunityAnecdotal)
307}
308
309fn dominant(contributions: &[Contribution]) -> EvidenceTier {
310    contributions
311        .iter()
312        .map(|c| c.evidence)
313        .max()
314        .unwrap_or(EvidenceTier::CommunityAnecdotal)
315}
316
317fn finish(aspect: Aspect, raw: u64, mut contributions: Vec<Contribution>) -> AspectScore {
318    // Strongest contribution first (stable: then by label) — the "why", most-salient-first.
319    contributions.sort_by(|a, b| {
320        b.weighted_milli
321            .cmp(&a.weighted_milli)
322            .then(a.label.cmp(&b.label))
323    });
324    let score_milli = clamp1000(raw);
325    AspectScore {
326        aspect,
327        score_milli,
328        band: ScoreBand::from_score(score_milli),
329        dominant_evidence: dominant(&contributions),
330        contributions,
331        epistemic_status: EpistemicStatus::Hypothesis,
332    }
333}
334
335/// Severity (milli) an interaction contributes to the combined-effect aspect, by kind.
336fn interaction_severity(kind: InteractionKind) -> u32 {
337    match kind {
338        InteractionKind::HerbDrug => 300, // a botanical + a medication on one system — worth checking
339        InteractionKind::Compounding => 200, // two adverse factors compounding
340        InteractionKind::Opposing => 60, // an adverse + a supportive (mitigation) — mild, informational
341    }
342}
343
344/// Compute the full score-card from a person's factors, at a physiological state, under a weights model.
345///
346/// Load aspects are computed over the **state-modulated** burdens (the reproductive-continuum modulator
347/// applied), so "the same factors, in this life stage" is what's scored. `convergence_threshold` is the
348/// number of distinct factors converging on a system before it counts (as in
349/// [`systemic_implications`](super::accumulate::systemic_implications)). Deterministic.
350pub fn score_card(
351    factors: &[Factor],
352    convergence_threshold: usize,
353    state: PhysiologicalState,
354    weights: &WeightModel,
355) -> ScoreCard {
356    let raw_burdens = accumulate(factors);
357    let burdens: Vec<SystemBurden> = state_modulator(state).apply_to_burdens(&raw_burdens);
358    let implications: Vec<SystemicImplication> =
359        systemic_implications(factors, convergence_threshold);
360    let ix: Vec<Interaction> = interactions(factors);
361
362    let mut aspects = Vec::new();
363    aspects.push(score_systemic_load(&burdens, factors));
364    aspects.push(score_weighted(Aspect::Stress, &burdens, factors, weights));
365    aspects.push(score_resilience(&burdens, factors, weights));
366    aspects.push(score_convergence(&implications));
367    aspects.push(score_interactions(&ix));
368    aspects.push(score_physiological_demand(state));
369    ScoreCard { aspects }
370}
371
372/// Overall adverse load: every system's net counts fully (no per-system weighting — this is the sum).
373fn score_systemic_load(burdens: &[SystemBurden], factors: &[Factor]) -> AspectScore {
374    let mut raw = 0u64;
375    let mut contributions = Vec::new();
376    for b in burdens {
377        if b.net_milli == 0 {
378            continue;
379        }
380        raw += b.net_milli as u64;
381        contributions.push(Contribution {
382            kind: ContributionKind::System,
383            source_id: b.system_id.clone(),
384            label: system_label(&b.system_id),
385            weighted_milli: b.net_milli,
386            evidence: system_evidence(factors, &b.system_id),
387        });
388    }
389    finish(Aspect::SystemicLoad, raw, contributions)
390}
391
392/// A weighted-over-systems adverse aspect (Stress). Each system's net is scaled by its aspect weight.
393fn score_weighted(
394    aspect: Aspect,
395    burdens: &[SystemBurden],
396    factors: &[Factor],
397    weights: &WeightModel,
398) -> AspectScore {
399    let mut raw = 0u64;
400    let mut contributions = Vec::new();
401    for b in burdens {
402        let w = weights.weight_for(&b.system_id, aspect);
403        if w == 0 || b.net_milli == 0 {
404            continue;
405        }
406        let weighted = (b.net_milli as u64 * w as u64) / 100;
407        if weighted == 0 {
408            continue;
409        }
410        raw += weighted;
411        contributions.push(Contribution {
412            kind: ContributionKind::System,
413            source_id: b.system_id.clone(),
414            label: system_label(&b.system_id),
415            weighted_milli: weighted as u32,
416            evidence: system_evidence(factors, &b.system_id),
417        });
418    }
419    finish(aspect, raw, contributions)
420}
421
422/// Resilience: the *supportive* side, weighted. Higher = more support in play (reads as reassuring).
423fn score_resilience(
424    burdens: &[SystemBurden],
425    factors: &[Factor],
426    weights: &WeightModel,
427) -> AspectScore {
428    let mut raw = 0u64;
429    let mut contributions = Vec::new();
430    for b in burdens {
431        let w = weights.weight_for(&b.system_id, Aspect::Resilience);
432        if w == 0 || b.supportive_milli == 0 {
433            continue;
434        }
435        let weighted = (b.supportive_milli as u64 * w as u64) / 100;
436        if weighted == 0 {
437            continue;
438        }
439        raw += weighted;
440        contributions.push(Contribution {
441            kind: ContributionKind::System,
442            source_id: b.system_id.clone(),
443            label: system_label(&b.system_id),
444            weighted_milli: weighted as u32,
445            evidence: system_evidence(factors, &b.system_id),
446        });
447    }
448    finish(Aspect::Resilience, raw, contributions)
449}
450
451/// Convergence: from the systemic-implication proposals. Each converging system contributes its net,
452/// amplified by how many distinct factors converge (more convergence = more worth discussing).
453fn score_convergence(implications: &[SystemicImplication]) -> AspectScore {
454    let mut raw = 0u64;
455    let mut contributions = Vec::new();
456    for im in implications {
457        let n = im.converging_factors.len() as u64;
458        // net × (converging count), so 3-factor convergence outweighs a 1-factor same-net system.
459        let weighted = (im.net_milli as u64 * n) / 1;
460        raw += weighted;
461        contributions.push(Contribution {
462            kind: ContributionKind::Convergence,
463            source_id: im.system_id.clone(),
464            label: format!(
465                "{} ({} converging)",
466                im.system_label,
467                im.converging_factors.len()
468            ),
469            weighted_milli: clamp1000(weighted),
470            evidence: im.dominant_evidence,
471        });
472    }
473    finish(Aspect::Convergence, raw, contributions)
474}
475
476/// Combined-effect load: from detected interactions, by severity.
477fn score_interactions(ix: &[Interaction]) -> AspectScore {
478    let mut raw = 0u64;
479    let mut contributions = Vec::new();
480    for it in ix {
481        let sev = interaction_severity(it.kind);
482        raw += sev as u64;
483        contributions.push(Contribution {
484            kind: ContributionKind::Interaction,
485            source_id: format!("{}+{}", it.factor_a, it.factor_b),
486            label: format!(
487                "{} & {} on {}",
488                it.factor_a,
489                it.factor_b,
490                system_label(&it.system_id)
491            ),
492            weighted_milli: sev,
493            // Interactions are structural detections; tier them at Mechanistic (a plausible interaction),
494            // not clinical certainty.
495            evidence: EvidenceTier::Mechanistic,
496        });
497    }
498    finish(Aspect::InteractionLoad, raw, contributions)
499}
500
501/// Physiological demand: from the current state's whole-body engagement profile.
502fn score_physiological_demand(state: PhysiologicalState) -> AspectScore {
503    let mut raw = 0u64;
504    let mut contributions = Vec::new();
505    for e in whole_body_profile(state) {
506        // Engagement above baseline: (scale - 100) as the demand signal.
507        let demand = (e.scale_pct.saturating_sub(100)) as u64;
508        if demand == 0 {
509            continue;
510        }
511        raw += demand;
512        contributions.push(Contribution {
513            kind: ContributionKind::State,
514            source_id: e.system_id.clone(),
515            label: e.system_label.clone(),
516            weighted_milli: demand as u32,
517            // The engagement is well-established baseline physiology (illustrative-seed magnitudes).
518            evidence: EvidenceTier::Mechanistic,
519        });
520    }
521    finish(Aspect::PhysiologicalDemand, raw, contributions)
522}
523
524fn system_label(system_id: &str) -> String {
525    body_system(system_id)
526        .map(|s| s.label.to_string())
527        .unwrap_or_else(|| system_id.to_string())
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::anatomy::factor::{Effect, FactorKind, FactorTarget};
534    use crate::anatomy::physiology::{ReproductiveState, Trimester};
535
536    fn factor(id: &str, kind: FactorKind, targets: &[(&str, Effect, EvidenceTier, u32)]) -> Factor {
537        let mut f = Factor::new(id, kind, id);
538        f.targets = targets
539            .iter()
540            .map(|(s, e, ev, w)| FactorTarget {
541                system_id: s.to_string(),
542                effect: *e,
543                evidence: *ev,
544                weight_milli: *w,
545            })
546            .collect();
547        f
548    }
549
550    fn baseline() -> PhysiologicalState {
551        PhysiologicalState::Baseline
552    }
553
554    #[test]
555    fn card_has_one_score_per_aspect_in_order() {
556        let card = score_card(&[], 1, baseline(), &seed_weight_model());
557        assert_eq!(card.aspects.len(), Aspect::all().len());
558        for (got, want) in card.aspects.iter().zip(Aspect::all()) {
559            assert_eq!(got.aspect, want);
560        }
561        // Empty factors → everything settled, no contributions, still Hypothesis.
562        for a in &card.aspects {
563            assert_eq!(a.band, ScoreBand::Settled);
564            assert!(a.contributions.is_empty());
565            assert_eq!(a.epistemic_status, EpistemicStatus::Hypothesis);
566        }
567    }
568
569    #[test]
570    fn every_score_traces_to_its_underlying_considerations() {
571        // Two adverse factors converge on the nervous system (a stress-weighted system).
572        let factors = vec![
573            factor(
574                "cond:chronic-stress",
575                FactorKind::Condition,
576                &[(
577                    "nervous",
578                    Effect::Adverse,
579                    EvidenceTier::ClinicalEvidence,
580                    400,
581                )],
582            ),
583            factor(
584                "life:poor-sleep",
585                FactorKind::Lifestyle,
586                &[("nervous", Effect::Adverse, EvidenceTier::Mechanistic, 300)],
587            ),
588        ];
589        let card = score_card(&factors, 2, baseline(), &seed_weight_model());
590
591        // Systemic load is non-zero and links to the nervous system.
592        let load = card.aspect(Aspect::SystemicLoad).unwrap();
593        assert!(load.score_milli > 0);
594        assert!(load.contributions.iter().any(|c| c.source_id == "nervous"));
595
596        // Stress is weighted heavily on the nervous system → present, and traceable.
597        let stress = card.aspect(Aspect::Stress).unwrap();
598        assert!(stress.score_milli > 0);
599        let nervous = stress
600            .contributions
601            .iter()
602            .find(|c| c.source_id == "nervous")
603            .unwrap();
604        assert_eq!(nervous.kind, ContributionKind::System);
605        assert!(!nervous.label.is_empty(), "human-readable linkage");
606        // Dominant evidence is the strongest contributing tier (clinical here).
607        assert_eq!(stress.dominant_evidence, EvidenceTier::ClinicalEvidence);
608
609        // Convergence fires (2 factors converge on one system) and links back to it.
610        let conv = card.aspect(Aspect::Convergence).unwrap();
611        assert!(conv.score_milli > 0);
612        assert!(conv.contributions.iter().any(|c| c.source_id == "nervous"));
613    }
614
615    #[test]
616    fn resilience_reads_the_supportive_side_and_higher_is_good() {
617        let factors = vec![factor(
618            "act:meditation-and-sleep",
619            FactorKind::Lifestyle,
620            &[(
621                "nervous",
622                Effect::Supportive,
623                EvidenceTier::Mechanistic,
624                500,
625            )],
626        )];
627        let card = score_card(&factors, 1, baseline(), &seed_weight_model());
628        let res = card.aspect(Aspect::Resilience).unwrap();
629        assert!(res.score_milli > 0, "support shows up as resilience");
630        assert!(res.contributions.iter().any(|c| c.source_id == "nervous"));
631        assert!(Aspect::Resilience.higher_is_supportive());
632        // Support alone leaves systemic load settled (net floors at 0).
633        assert_eq!(
634            card.aspect(Aspect::SystemicLoad).unwrap().band,
635            ScoreBand::Settled
636        );
637    }
638
639    #[test]
640    fn interaction_load_scores_a_herb_drug_pair() {
641        let factors = vec![
642            factor(
643                "med:warfarin",
644                FactorKind::Medication,
645                &[(
646                    "circulatory",
647                    Effect::Adverse,
648                    EvidenceTier::ClinicalEvidence,
649                    400,
650                )],
651            ),
652            factor(
653                "herb:ginkgo",
654                FactorKind::Herb,
655                &[(
656                    "circulatory",
657                    Effect::Adverse,
658                    EvidenceTier::TraditionalUse,
659                    300,
660                )],
661            ),
662        ];
663        let card = score_card(&factors, 1, baseline(), &seed_weight_model());
664        let ix = card.aspect(Aspect::InteractionLoad).unwrap();
665        assert_eq!(
666            ix.score_milli,
667            interaction_severity(InteractionKind::HerbDrug)
668        );
669        assert_eq!(ix.contributions.len(), 1);
670        assert_eq!(ix.contributions[0].kind, ContributionKind::Interaction);
671    }
672
673    #[test]
674    fn physiological_demand_reflects_the_life_stage_and_state_modulates_load() {
675        // A kidney-taxing med, scored in the third trimester: load is modulated up AND demand shows.
676        let med = factor(
677            "med:nephrotoxic",
678            FactorKind::Medication,
679            &[(
680                "urinary",
681                Effect::Adverse,
682                EvidenceTier::ClinicalEvidence,
683                400,
684            )],
685        );
686        let t3 = PhysiologicalState::Reproductive(ReproductiveState::Pregnant(Trimester::Third));
687        let base_card = score_card(
688            std::slice::from_ref(&med),
689            1,
690            baseline(),
691            &seed_weight_model(),
692        );
693        let preg_card = score_card(std::slice::from_ref(&med), 1, t3, &seed_weight_model());
694
695        // Physiological demand is settled at baseline, present in pregnancy.
696        assert_eq!(
697            base_card.aspect(Aspect::PhysiologicalDemand).unwrap().band,
698            ScoreBand::Settled
699        );
700        let demand = preg_card.aspect(Aspect::PhysiologicalDemand).unwrap();
701        assert!(demand.score_milli > 0);
702        assert!(
703            demand
704                .contributions
705                .iter()
706                .any(|c| c.source_id == "urinary")
707        );
708
709        // The same med lands as more systemic load in the third trimester (renal engagement scales it).
710        let base_load = base_card.aspect(Aspect::SystemicLoad).unwrap().score_milli;
711        let preg_load = preg_card.aspect(Aspect::SystemicLoad).unwrap().score_milli;
712        assert!(
713            preg_load > base_load,
714            "state modulates the load: {preg_load} > {base_load}"
715        );
716    }
717
718    #[test]
719    fn bands_are_coarse_and_monotone() {
720        assert_eq!(ScoreBand::from_score(0), ScoreBand::Settled);
721        assert_eq!(ScoreBand::from_score(99), ScoreBand::Settled);
722        assert_eq!(ScoreBand::from_score(100), ScoreBand::Building);
723        assert_eq!(ScoreBand::from_score(349), ScoreBand::Building);
724        assert_eq!(ScoreBand::from_score(350), ScoreBand::Heightened);
725        assert_eq!(ScoreBand::from_score(649), ScoreBand::Heightened);
726        assert_eq!(ScoreBand::from_score(650), ScoreBand::Marked);
727        assert_eq!(ScoreBand::from_score(5000), ScoreBand::Marked);
728    }
729
730    #[test]
731    fn a_score_card_is_forum_internum_selfhood_content_at_sanctuary_class() {
732        // The classification is intrinsic to the type — every card, even an empty one, is the person's
733        // inward, most-protected selfhood content. This is the structural backing of "not a rating weapon".
734        let card = score_card(&[], 1, baseline(), &seed_weight_model());
735        assert_eq!(card.forum_class(), ForumClass::Internum);
736        assert_eq!(card.sensitivity_class(), "Sanctuary");
737    }
738
739    #[test]
740    fn deterministic_and_serde_round_trips() {
741        let factors = vec![factor(
742            "x",
743            FactorKind::Condition,
744            &[("endocrine", Effect::Adverse, EvidenceTier::Mechanistic, 300)],
745        )];
746        let a = score_card(&factors, 1, baseline(), &seed_weight_model());
747        let b = score_card(&factors, 1, baseline(), &seed_weight_model());
748        assert_eq!(a, b, "deterministic");
749        let json = serde_json::to_string(&a).unwrap();
750        let back: ScoreCard = serde_json::from_str(&json).unwrap();
751        assert_eq!(a, back);
752    }
753}