Skip to main content

wellfare_core/anatomy/
lens.rs

1//! S4 (domain half) — the **two-lens view model**.
2//!
3//! One engine, two audiences (plan §1). Given a person's factors, [`build_view`] produces an
4//! [`AnatomyView`] shaped for a [`Lens`]:
5//!
6//! - **[`Lens::Person`]** — a plain, simple "how am I doing" picture. Every system with any load is
7//!   shown with a plain-language headline and a coarse [`WellbeingLevel`]; detail sits behind
8//!   progressive disclosure (accessibility is core). The hard boundary: **not advice** — "worth
9//!   discussing with a clinician".
10//! - **[`Lens::Clinician`]** — an OSCE-Prac *aid*. Only the convergence-flagged systems are surfaced,
11//!   with the converging factors, herb–drug / compounding / opposing interactions, and the dominant
12//!   evidence tier, framed as **considerations** for the professional's own evaluation. The hard
13//!   boundary: **not a diagnosis or an order**.
14//!
15//! Both lenses are honest by construction: computed systemic implications carry
16//! [`EpistemicStatus::Hypothesis`], evidence tiers are shown (never collapsed into "fact"), and every
17//! view carries an explicit uncertainty note. **The clinician lens deliberately surfaces only
18//! *structural* considerations** (what converges, what interacts, at what evidence tier) — it does not
19//! invent clinical specifics (which tests to order, which drug to start); those are Timothy's / a
20//! clinician's sign-off (⚑ S4 curation datum), added later as data, not fabricated here.
21//!
22//! The raw per-system burden that colours the 3D body (S5) is [`accumulate`](super::accumulate) —
23//! lens-independent; this module produces the *narrative*, not the colour.
24
25use serde::{Deserialize, Serialize};
26
27use crate::record::EpistemicStatus;
28
29use super::accumulate::{
30    Interaction, InteractionKind, accumulate, interactions, systemic_implications,
31};
32use super::factor::{EvidenceTier, Factor};
33use super::systems::body_system;
34
35/// Which audience the view is shaped for.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum Lens {
39    Person,
40    Clinician,
41}
42
43/// A coarse, plain wellbeing level for a system — never a diagnosis, never a number to the person.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum WellbeingLevel {
47    /// Little or nothing accumulating.
48    Settled,
49    /// A little going on — worth being aware of.
50    WorthWatching,
51    /// Several things adding up.
52    UnderStrain,
53}
54
55impl WellbeingLevel {
56    /// The canonical coarse classifier — the only person-facing readout of `net_milli`.
57    pub fn from_net(net_milli: u32) -> Self {
58        match net_milli {
59            0..=99 => WellbeingLevel::Settled,
60            100..=299 => WellbeingLevel::WorthWatching,
61            _ => WellbeingLevel::UnderStrain,
62        }
63    }
64}
65
66/// Encode an accumulated system burden (`net_milli`, 0..=1000) as **σ** — a position on the shared
67/// EMF spectrum (400–700 nm) that the engine's parity oracles render to *both* the visual spectrum
68/// (`qualia_core_db::render::spectral::sigma_to_linear_rgb`) and the sonic spectrum
69/// (`render::acoustic::sigma_to_center_frequency_hz`). σ is the one truth; colour and pitch are two
70/// encodings of it — an organ under strain both *looks* and *sounds* it. σ is also the tenth axis of
71/// `Tensor10D`, so an organ's `.10d` node can carry this value directly.
72///
73/// Mapping: settled → green (~550 nm, σ≈0.50), through amber, to under-strain → red (~680 nm, σ≈0.93)
74/// — the same green→amber→red "heat" hue arc as the coarse [`WellbeingLevel`] bands, but as a
75/// continuous physical quantity. Honest by construction: σ derives from the transparent bounded-integer
76/// `net_milli` accumulation (no float health arithmetic), and the person still sees only the coarse band
77/// — the continuous spectrum is the *substrate*, not a false-precision clinical readout.
78#[inline]
79pub fn burden_to_sigma(net_milli: u32) -> f32 {
80    const GREEN: f32 = 0.50; // ~550 nm — settled
81    const RED: f32 = 0.93; // ~680 nm — under strain
82    let t = (net_milli.min(1000) as f32) / 1000.0;
83    GREEN + t * (RED - GREEN)
84}
85
86/// One system's entry in a view.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct SystemView {
89    pub system_id: String,
90    /// Clinical label (behind disclosure for the person lens).
91    pub system_label: String,
92    /// Plain-language label (the default the person sees).
93    pub plain_label: String,
94    pub level: WellbeingLevel,
95    pub net_milli: u32,
96    /// The one-line, lens-appropriate headline (plain for the person; structural for the clinician).
97    pub headline: String,
98    /// Progressive-disclosure detail — advanced items, hidden by default.
99    pub detail: Vec<String>,
100    /// Factor ids converging adverse load here (empty if below the convergence threshold).
101    pub converging_factors: Vec<String>,
102    pub dominant_evidence: EvidenceTier,
103    pub interactions: Vec<Interaction>,
104    /// `Hypothesis` for anything computed — never asserted as fact.
105    pub epistemic_status: EpistemicStatus,
106}
107
108/// The full view for one lens.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct AnatomyView {
111    pub lens: Lens,
112    /// Systems with something to say, worst-first.
113    pub systems: Vec<SystemView>,
114    /// One plain overall sentence.
115    pub summary: String,
116    /// The hard framing boundary for this lens.
117    pub boundary: String,
118    /// Explicit uncertainty — illustrative, not a measurement/diagnosis.
119    pub uncertainty_note: String,
120}
121
122const PERSON_BOUNDARY: &str = "This is a general picture to help you get a sense of things — it is not medical advice or a diagnosis. If anything here concerns you, it's worth discussing with a clinician.";
123const CLINICIAN_BOUNDARY: &str = "Decision-support considerations only — not a diagnosis, a test order, or a prescription. Surfaced from the person's own records for the clinician's independent evaluation (OSCE-Prac aid).";
124const UNCERTAINTY_NOTE: &str = "Illustrative model, not a measurement. Bodies vary; computed implications are hypotheses to explore, not facts.";
125
126/// Build the view for a lens from a person's factors. `convergence_threshold` is the number of distinct
127/// adverse factors on a system before it is "flagged" (see [`systemic_implications`]).
128pub fn build_view(factors: &[Factor], lens: Lens, convergence_threshold: usize) -> AnatomyView {
129    let burdens = accumulate(factors);
130    let implications = systemic_implications(factors, convergence_threshold);
131    let all_interactions = interactions(factors);
132
133    let systems = match lens {
134        Lens::Person => person_systems(&burdens, &implications),
135        Lens::Clinician => clinician_systems(&implications, &all_interactions),
136    };
137
138    let summary = match lens {
139        Lens::Person => person_summary(&systems),
140        Lens::Clinician => clinician_summary(&systems, &all_interactions),
141    };
142
143    AnatomyView {
144        lens,
145        systems,
146        summary,
147        boundary: lens_boundary(lens).to_string(),
148        uncertainty_note: UNCERTAINTY_NOTE.to_string(),
149    }
150}
151
152fn lens_boundary(lens: Lens) -> &'static str {
153    match lens {
154        Lens::Person => PERSON_BOUNDARY,
155        Lens::Clinician => CLINICIAN_BOUNDARY,
156    }
157}
158
159/// Person lens: every system carrying net load, plain and simple, worst-first.
160fn person_systems(
161    burdens: &[super::accumulate::SystemBurden],
162    implications: &[super::accumulate::SystemicImplication],
163) -> Vec<SystemView> {
164    let mut views: Vec<SystemView> = burdens
165        .iter()
166        .filter(|b| b.net_milli > 0)
167        .map(|b| {
168            let (label, plain) = labels_for(&b.system_id);
169            let level = WellbeingLevel::from_net(b.net_milli);
170            let imp = implications.iter().find(|i| i.system_id == b.system_id);
171            let converging = imp
172                .map(|i| i.converging_factors.clone())
173                .unwrap_or_default();
174            SystemView {
175                headline: person_headline(&plain, level, converging.len()),
176                detail: person_detail(&label, b),
177                system_id: b.system_id.clone(),
178                system_label: label,
179                plain_label: plain,
180                level,
181                net_milli: b.net_milli,
182                converging_factors: converging,
183                dominant_evidence: imp
184                    .map(|i| i.dominant_evidence)
185                    .unwrap_or(EvidenceTier::CommunityAnecdotal),
186                interactions: imp.map(|i| i.interactions.clone()).unwrap_or_default(),
187                epistemic_status: EpistemicStatus::Hypothesis,
188            }
189        })
190        .collect();
191    views.sort_by(|a, b| {
192        b.net_milli
193            .cmp(&a.net_milli)
194            .then(a.system_id.cmp(&b.system_id))
195    });
196    views
197}
198
199/// Clinician lens: the convergence-flagged systems, with structural considerations.
200fn clinician_systems(
201    implications: &[super::accumulate::SystemicImplication],
202    _all_interactions: &[Interaction],
203) -> Vec<SystemView> {
204    let mut views: Vec<SystemView> = implications
205        .iter()
206        .map(|i| {
207            let (label, plain) = labels_for(&i.system_id);
208            SystemView {
209                headline: clinician_headline(&label, i),
210                detail: clinician_detail(i),
211                system_id: i.system_id.clone(),
212                system_label: label,
213                plain_label: plain,
214                level: WellbeingLevel::from_net(i.net_milli),
215                net_milli: i.net_milli,
216                converging_factors: i.converging_factors.clone(),
217                dominant_evidence: i.dominant_evidence,
218                interactions: i.interactions.clone(),
219                epistemic_status: i.epistemic_status,
220            }
221        })
222        .collect();
223    views.sort_by(|a, b| {
224        b.net_milli
225            .cmp(&a.net_milli)
226            .then(a.system_id.cmp(&b.system_id))
227    });
228    views
229}
230
231fn labels_for(system_id: &str) -> (String, String) {
232    match body_system(system_id) {
233        Some(s) => (s.label.to_string(), s.plain_label.to_string()),
234        None => (system_id.to_string(), system_id.to_string()),
235    }
236}
237
238fn person_headline(plain: &str, level: WellbeingLevel, converging: usize) -> String {
239    match level {
240        WellbeingLevel::Settled => format!("Your {plain} looks settled."),
241        WellbeingLevel::WorthWatching => {
242            format!("Your {plain} has a little going on — worth being aware of.")
243        }
244        WellbeingLevel::UnderStrain if converging >= 2 => {
245            format!("A few things you've logged seem to be adding up for your {plain}.")
246        }
247        WellbeingLevel::UnderStrain => {
248            format!("Something you've logged is weighing on your {plain}.")
249        }
250    }
251}
252
253fn person_detail(label: &str, b: &super::accumulate::SystemBurden) -> Vec<String> {
254    let mut d = Vec::new();
255    d.push(format!("System: {label}."));
256    if !b.adverse_contributors.is_empty() {
257        d.push(format!(
258            "Contributing: {}.",
259            b.adverse_contributors.join(", ")
260        ));
261    }
262    if !b.supportive_contributors.is_empty() {
263        d.push(format!(
264            "Helping: {}.",
265            b.supportive_contributors.join(", ")
266        ));
267    }
268    d
269}
270
271fn clinician_headline(label: &str, i: &super::accumulate::SystemicImplication) -> String {
272    let n = i.converging_factors.len();
273    let ix = i.interactions.len();
274    let mut h = format!(
275        "{label}: {n} converging factor{} (net load {}, dominant evidence {}).",
276        if n == 1 { "" } else { "s" },
277        i.net_milli,
278        evidence_word(i.dominant_evidence),
279    );
280    if ix > 0 {
281        h.push_str(&format!(
282            " {ix} interaction{} to review.",
283            if ix == 1 { "" } else { "s" }
284        ));
285    }
286    h.push_str(" Consider whether this pattern warrants review.");
287    h
288}
289
290fn clinician_detail(i: &super::accumulate::SystemicImplication) -> Vec<String> {
291    let mut d = Vec::new();
292    d.push(format!(
293        "Converging factors: {}.",
294        i.converging_factors.join(", ")
295    ));
296    for it in &i.interactions {
297        d.push(format!(
298            "{}: {} + {} on this system — {}.",
299            interaction_word(it.kind),
300            it.factor_a,
301            it.factor_b,
302            interaction_note(it.kind),
303        ));
304    }
305    d.push(format!(
306        "Dominant evidence tier: {}.",
307        evidence_word(i.dominant_evidence)
308    ));
309    d.push("Structural considerations only — clinical specifics (tests, medications, referrals) are the clinician's own judgement.".to_string());
310    d
311}
312
313fn person_summary(systems: &[SystemView]) -> String {
314    let strained = systems
315        .iter()
316        .filter(|s| s.level == WellbeingLevel::UnderStrain)
317        .count();
318    match (systems.len(), strained) {
319        (0, _) => "Nothing much is adding up right now from what you've logged.".to_string(),
320        (_, 0) => {
321            "A few small things to be aware of, but nothing is standing out strongly.".to_string()
322        }
323        (_, n) => format!(
324            "A few things seem to be adding up across {n} area{}. It may be worth a chat with a clinician.",
325            if n == 1 { "" } else { "s" }
326        ),
327    }
328}
329
330fn clinician_summary(systems: &[SystemView], all_interactions: &[Interaction]) -> String {
331    let herb_drug = all_interactions
332        .iter()
333        .filter(|i| i.kind == InteractionKind::HerbDrug)
334        .count();
335    let mut s = format!(
336        "{} system{} flagged by convergence.",
337        systems.len(),
338        if systems.len() == 1 { "" } else { "s" }
339    );
340    if herb_drug > 0 {
341        s.push_str(&format!(
342            " {herb_drug} herb–drug interaction{} present.",
343            if herb_drug == 1 { "" } else { "s" }
344        ));
345    }
346    s
347}
348
349fn evidence_word(t: EvidenceTier) -> &'static str {
350    match t {
351        EvidenceTier::CommunityAnecdotal => "community/anecdotal",
352        EvidenceTier::TraditionalUse => "traditional-use",
353        EvidenceTier::NutritionalData => "nutritional-data",
354        EvidenceTier::Mechanistic => "mechanistic",
355        EvidenceTier::ClinicalEvidence => "clinical",
356    }
357}
358
359fn interaction_word(k: InteractionKind) -> &'static str {
360    match k {
361        InteractionKind::HerbDrug => "Herb–drug",
362        InteractionKind::Compounding => "Compounding",
363        InteractionKind::Opposing => "Opposing",
364    }
365}
366
367fn interaction_note(k: InteractionKind) -> &'static str {
368    match k {
369        InteractionKind::HerbDrug => "a medication and a botanical acting on the same system",
370        InteractionKind::Compounding => "two adverse factors on the same system",
371        InteractionKind::Opposing => "an adverse and a supportive factor on the same system",
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use crate::anatomy::{Effect, FactorKind};
379
380    #[test]
381    fn burden_sigma_walks_green_to_red_within_the_emf_band() {
382        let settled = burden_to_sigma(0);
383        let strained = burden_to_sigma(1000);
384        // Settled sits at green (~550 nm), strain at red (~680 nm).
385        assert!((settled - 0.50).abs() < 1e-6, "settled σ={settled}");
386        assert!((strained - 0.93).abs() < 1e-6, "strained σ={strained}");
387        // More burden → longer wavelength (redder). The whole point of the encoding.
388        assert!(strained > settled);
389        // Monotonic through the band, and clamped past the ceiling (no runaway σ).
390        assert!(burden_to_sigma(150) > settled && burden_to_sigma(150) < strained);
391        assert!(
392            burden_to_sigma(5000) <= 0.93 + 1e-6,
393            "σ clamps at the red end"
394        );
395        // The coarse band and the continuous σ agree at the extremes.
396        assert_eq!(WellbeingLevel::from_net(0), WellbeingLevel::Settled);
397        assert_eq!(WellbeingLevel::from_net(1000), WellbeingLevel::UnderStrain);
398    }
399
400    fn med(id: &str, system: &str, w: u32) -> Factor {
401        Factor::new(id, FactorKind::Medication, id).targeting(
402            system,
403            Effect::Adverse,
404            EvidenceTier::ClinicalEvidence,
405            w,
406        )
407    }
408    fn herb(id: &str, system: &str, effect: Effect, w: u32) -> Factor {
409        Factor::new(id, FactorKind::Herb, id).targeting(
410            system,
411            effect,
412            EvidenceTier::TraditionalUse,
413            w,
414        )
415    }
416
417    #[test]
418    fn person_lens_is_plain_non_diagnostic_and_worst_first() {
419        let factors = vec![
420            med("cond:nafld", "digestive", 500),
421            med("med:hepatotoxic", "digestive", 300),
422            med("med:mild", "urinary", 120),
423        ];
424        let view = build_view(&factors, Lens::Person, 2);
425        assert_eq!(view.lens, Lens::Person);
426        // Digestive (net 800) before urinary (net 120).
427        assert_eq!(view.systems[0].system_id, "digestive");
428        assert!(view.systems[0].net_milli > view.systems[1].net_milli);
429        // Plain label surfaced; headline uses it and is non-diagnostic.
430        assert_eq!(view.systems[0].plain_label, "digestion");
431        assert!(view.systems[0].headline.contains("digestion"));
432        assert!(!view.systems[0].headline.to_lowercase().contains("diagnos"));
433        // Everything computed is a hypothesis; the boundary says "not medical advice".
434        assert!(
435            view.systems
436                .iter()
437                .all(|s| s.epistemic_status == EpistemicStatus::Hypothesis)
438        );
439        assert!(view.boundary.contains("not medical advice"));
440    }
441
442    #[test]
443    fn clinician_lens_surfaces_structural_considerations_and_the_herb_drug_interaction() {
444        let factors = vec![
445            med("med:warfarin", "circulatory", 400),
446            herb("herb:ginkgo", "circulatory", Effect::Adverse, 300),
447        ];
448        let view = build_view(&factors, Lens::Clinician, 2);
449        assert_eq!(view.systems.len(), 1);
450        let c = &view.systems[0];
451        assert_eq!(c.system_id, "circulatory");
452        assert_eq!(c.interactions.len(), 1);
453        assert_eq!(c.interactions[0].kind, InteractionKind::HerbDrug);
454        // Headline is structural, includes the review prompt, and stays a hypothesis.
455        assert!(c.headline.contains("converging factor"));
456        assert!(
457            c.headline
458                .contains("Consider whether this pattern warrants review")
459        );
460        assert_eq!(c.epistemic_status, EpistemicStatus::Hypothesis);
461        // Boundary forbids diagnosis/order; summary counts the herb–drug interaction.
462        assert!(view.boundary.contains("not a diagnosis"));
463        assert!(view.summary.contains("herb–drug"));
464        // Detail explicitly leaves clinical specifics to the clinician (no invented tests/meds).
465        assert!(
466            c.detail
467                .iter()
468                .any(|d| d.contains("clinician's own judgement"))
469        );
470    }
471
472    #[test]
473    fn person_summary_is_gentle_when_nothing_converges() {
474        let view = build_view(&[], Lens::Person, 2);
475        assert!(view.systems.is_empty());
476        assert!(view.summary.contains("Nothing much is adding up"));
477    }
478
479    #[test]
480    fn view_serde_round_trips() {
481        let view = build_view(&[med("m", "digestive", 400)], Lens::Person, 1);
482        let json = serde_json::to_string(&view).unwrap();
483        let back: AnatomyView = serde_json::from_str(&json).unwrap();
484        assert_eq!(view, back);
485    }
486}