Skip to main content

wellfare_core/anatomy/
factor.rs

1//! The [`Factor`] model — the general thing that maps onto the body, with its effect, evidence tier,
2//! and bounded integer magnitude. Non-temporal; the temporal layer wraps a factor in a `FactorEvent`.
3
4use serde::{Deserialize, Serialize};
5
6/// The kind of factor mapping onto the body. Open-ended via `Other`.
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum FactorKind {
10    PathologyFinding,
11    Condition,
12    Medication,
13    Food,
14    Herb,
15    Tea,
16    WholeFood,
17    Nutrient,
18    Supplement,
19    /// sleep / exercise / social, etc.
20    Lifestyle,
21    /// heat, season, activity exposure, etc.
22    Environmental,
23    Other(String),
24}
25
26/// The direction of a factor's effect on a system.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum Effect {
30    /// Adds load / strain.
31    Adverse,
32    /// Relieves load / supports recovery.
33    Supportive,
34    /// Changes behaviour without a clear +/- (interaction-relevant).
35    Modulating,
36}
37
38/// Evidence backing a factor→system mapping, highest → lowest. Traditional-medicine and community
39/// knowledge are **preserved at their own tier, never collapsed into "medical fact"**.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum EvidenceTier {
43    /// Lowest — internet / anecdotal "hot takes"; always a Hypothesis.
44    CommunityAnecdotal,
45    /// Documented traditional / folk use.
46    TraditionalUse,
47    /// Nutritional-database composition/association.
48    NutritionalData,
49    /// Plausible biological mechanism.
50    Mechanistic,
51    /// Clinical-trial / guideline evidence (highest).
52    ClinicalEvidence,
53}
54
55impl EvidenceTier {
56    /// Whether this tier is strong enough that a *source record* could be `Asserted` rather than a
57    /// `Hypothesis`. (Computed systemic implications are always `Hypothesis` regardless.)
58    pub fn is_clinical(self) -> bool {
59        self == EvidenceTier::ClinicalEvidence
60    }
61}
62
63/// One (system, effect, evidence, magnitude) mapping carried by a factor. `weight_milli` is a
64/// bounded 0..=1000 contribution magnitude (integer, no float health arithmetic).
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct FactorTarget {
67    pub system_id: String,
68    pub effect: Effect,
69    pub evidence: EvidenceTier,
70    pub weight_milli: u32,
71}
72
73/// A factor mapping onto the body.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct Factor {
76    pub id: String,
77    pub kind: FactorKind,
78    pub label: String,
79    pub targets: Vec<FactorTarget>,
80    /// Source / provenance reference (a record id, knowledge-source id, or citation).
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub source: Option<String>,
83}
84
85impl Factor {
86    /// Creates a new instance.
87    pub fn new(id: impl Into<String>, kind: FactorKind, label: impl Into<String>) -> Self {
88        Self {
89            id: id.into(),
90            kind,
91            label: label.into(),
92            targets: Vec::new(),
93            source: None,
94        }
95    }
96
97    /// Add a (system, effect, evidence, weight) mapping. `weight_milli` is clamped to 0..=1000.
98    pub fn targeting(
99        mut self,
100        system_id: impl Into<String>,
101        effect: Effect,
102        evidence: EvidenceTier,
103        weight_milli: u32,
104    ) -> Self {
105        self.targets.push(FactorTarget {
106            system_id: system_id.into(),
107            effect,
108            evidence,
109            weight_milli: weight_milli.min(1000),
110        });
111        self
112    }
113
114    /// Attach a source / provenance reference.
115    pub fn from_source(mut self, source: impl Into<String>) -> Self {
116        self.source = Some(source.into());
117        self
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn evidence_tiers_order_clinical_highest_community_lowest() {
127        assert!(EvidenceTier::ClinicalEvidence > EvidenceTier::CommunityAnecdotal);
128        assert!(EvidenceTier::ClinicalEvidence > EvidenceTier::TraditionalUse);
129        assert!(EvidenceTier::TraditionalUse > EvidenceTier::CommunityAnecdotal);
130        assert!(EvidenceTier::ClinicalEvidence.is_clinical());
131        assert!(!EvidenceTier::TraditionalUse.is_clinical());
132    }
133
134    #[test]
135    fn weight_is_clamped_to_the_bounded_domain() {
136        let f = Factor::new("x", FactorKind::Medication, "x").targeting(
137            "digestive",
138            Effect::Adverse,
139            EvidenceTier::ClinicalEvidence,
140            5000,
141        );
142        assert_eq!(f.targets[0].weight_milli, 1000);
143    }
144
145    #[test]
146    fn model_serde_round_trips() {
147        let f = Factor::new("med:x", FactorKind::Medication, "X")
148            .targeting(
149                "digestive",
150                Effect::Adverse,
151                EvidenceTier::ClinicalEvidence,
152                100,
153            )
154            .from_source("record:123");
155        let json = serde_json::to_string(&f).unwrap();
156        let back: Factor = serde_json::from_str(&json).unwrap();
157        assert_eq!(f, back);
158    }
159}