Skip to main content

wellfare_core/anatomy/
pathway.rs

1//! The **investigative pathway** — the engine of the thesis: *know thyself → hypothesis → what would help
2//! you know → specialist input → action*.
3//!
4//! This is the point of Qualia made operational. The rest of the engine surfaces **hypotheses** (a
5//! score-card aspect, a converging [`SystemicImplication`]) — honest, coarse, non-diagnostic. On its own a
6//! hypothesis can be a dead-end or, worse, a locked-away worry. This layer turns each hypothesis into a
7//! **path toward knowing and acting**: the questions worth considering, what could be observed or tested,
8//! the levers the person actually controls, and *when* bringing in a specialist they trust would help — and
9//! it **ranks** those by **value of information** (the one new primitive): which step would most help
10//! discriminate among the live hypotheses and move the person from uncertainty toward understanding.
11//!
12//! **It enables; it never directs or diagnoses.** Every step is a *proposal*
13//! ([`EpistemicStatus::Hypothesis`]) — "here is something that might help you find out / discuss / act on",
14//! never "you have X" or "you must do Y". The person stays the agent; a specialist step points *to their
15//! chosen* clinician (the care-relationship stance), not to a gatekeeper. This is the corrective to
16//! information-asymmetry — the right to know oneself with real science — with the person in control.
17//!
18//! **Honesty (unchanged).** Integer-only, coarse, deterministic; evidence tiers preserved. The **step
19//! library is curation-grade** — *which* questions/tests/levers attach to a hypothesis is Timothy's / an
20//! expert's / a clinician's to supply (§9); this module builds the machinery (the pathway + the VOI
21//! primitive + the ranking + the framing), not the authoritative content.
22
23use serde::{Deserialize, Serialize};
24
25use crate::record::EpistemicStatus;
26
27use super::accumulate::SystemicImplication;
28use super::factor::EvidenceTier;
29
30/// A hypothesis under investigation — e.g. a converging [`SystemicImplication`] or a score-card aspect.
31/// Carries a **coarse prior** (0..=1000: how much is currently pointing at it) and its evidence tier.
32/// Never a diagnosis; a thing worth *finding out more about*.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Hypothesis {
35    pub id: String,
36    pub label: String,
37    /// Coarse prior weight (how much is currently converging on this), 0..=1000.
38    pub prior_milli: u32,
39    pub evidence: EvidenceTier,
40}
41
42/// The kind of investigative step — the *modes* of moving from a hypothesis toward knowing/acting.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum StepKind {
46    /// A question worth considering (of oneself, or to raise with a clinician).
47    Question,
48    /// Something to notice / track over time (self-observation).
49    Observation,
50    /// An investigation / test that could help discriminate.
51    Test,
52    /// A lever the person themselves controls (sleep, movement, nutrition, …).
53    LifestyleLever,
54    /// When/why bringing in a specialist the person *chooses* would help.
55    SpecialistInput,
56}
57
58/// One investigative step, and **which hypotheses it bears on** — the linkage that makes the pathway
59/// traceable rather than a black box. A signed bearing per hypothesis: `> 0` a result would *support* it,
60/// `< 0` a result would *tell against* it (that combination is what lets a step *discriminate*).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct InvestigativeStep {
63    pub id: String,
64    pub kind: StepKind,
65    pub label: String,
66    /// `hypothesis_id → signed bearing` (magnitude ~0..=1000). Empty ⇒ bears on nothing (VOI 0).
67    pub bears_on: Vec<(String, i32)>,
68    pub evidence: EvidenceTier,
69}
70
71/// A step ranked by its value of information.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct RankedStep {
74    pub step: InvestigativeStep,
75    /// Value of information, 0..=1000.
76    pub voi_milli: u32,
77}
78
79/// A ranked investigative pathway — the steps that would most help, most-valuable first. A **proposal**,
80/// never a plan imposed on the person.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct InvestigativePathway {
83    pub hypotheses: Vec<Hypothesis>,
84    pub steps: Vec<RankedStep>,
85    /// Always `Hypothesis` — a set of things that *might* help, never directives/diagnoses.
86    pub epistemic_status: EpistemicStatus,
87}
88
89fn clamp1000(v: u64) -> u32 {
90    v.min(1000) as u32
91}
92
93/// **Value of information** (0..=1000) of a step given the current hypotheses — the new primitive.
94///
95/// A transparent, monotone proxy (not a decision-theoretic optimum): it rewards a step that bears
96/// **strongly on high-prior hypotheses** (*relevance*) and that would **separate** them — supporting some
97/// while telling against others among the high-prior set (*discrimination*). A test that only bears on an
98/// already-unlikely hypothesis is low-value; a test that would split two live, similarly-weighted
99/// hypotheses is high-value — which is exactly what "what should I find out next" wants.
100pub fn value_of_information(step: &InvestigativeStep, hypotheses: &[Hypothesis]) -> u32 {
101    let mut relevance = 0u64;
102    let mut support = 0u64; // relevance mass of the "would support" bearings
103    let mut against = 0u64; // relevance mass of the "would tell against" bearings
104    for (hid, bearing) in &step.bears_on {
105        let Some(h) = hypotheses.iter().find(|h| &h.id == hid) else {
106            continue;
107        };
108        // relevance contribution = prior × |bearing|, coarse-scaled.
109        let contrib = h.prior_milli as u64 * bearing.unsigned_abs() as u64 / 1000;
110        relevance += contrib;
111        if *bearing > 0 {
112            support += contrib;
113        } else if *bearing < 0 {
114            against += contrib;
115        }
116    }
117    // Discrimination bonus: a step that both supports and tells-against (among high-prior hypotheses)
118    // separates the field — reward the smaller of the two masses (you only "separate" as much as the
119    // weaker side).
120    let discrimination = support.min(against);
121    clamp1000(relevance + discrimination)
122}
123
124/// Build the VOI-ranked investigative pathway for a set of hypotheses + candidate steps. Deterministic:
125/// steps sort by VOI descending, then by id. Steps with zero VOI (bear on nothing live) are dropped — the
126/// pathway shows only what would actually help.
127pub fn investigative_pathway(
128    hypotheses: Vec<Hypothesis>,
129    steps: Vec<InvestigativeStep>,
130) -> InvestigativePathway {
131    let mut ranked: Vec<RankedStep> = steps
132        .into_iter()
133        .map(|step| {
134            let voi_milli = value_of_information(&step, &hypotheses);
135            RankedStep { step, voi_milli }
136        })
137        .filter(|r| r.voi_milli > 0)
138        .collect();
139    ranked.sort_by(|a, b| {
140        b.voi_milli
141            .cmp(&a.voi_milli)
142            .then(a.step.id.cmp(&b.step.id))
143    });
144    InvestigativePathway {
145        hypotheses,
146        steps: ranked,
147        epistemic_status: EpistemicStatus::Hypothesis,
148    }
149}
150
151/// Derive investigable [`Hypothesis`]es from the anatomy engine's [`SystemicImplication`] proposals — the
152/// bridge from "where is load converging" to "what's worth finding out about". The implication's net load
153/// becomes the coarse prior; its dominant evidence carries through.
154pub fn hypotheses_from_implications(implications: &[SystemicImplication]) -> Vec<Hypothesis> {
155    implications
156        .iter()
157        .map(|im| Hypothesis {
158            id: im.system_id.clone(),
159            label: im.system_label.clone(),
160            prior_milli: im.net_milli.min(1000),
161            evidence: im.dominant_evidence,
162        })
163        .collect()
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn hyp(id: &str, prior: u32) -> Hypothesis {
171        Hypothesis {
172            id: id.into(),
173            label: id.into(),
174            prior_milli: prior,
175            evidence: EvidenceTier::Mechanistic,
176        }
177    }
178
179    fn step(id: &str, kind: StepKind, bears: &[(&str, i32)]) -> InvestigativeStep {
180        InvestigativeStep {
181            id: id.into(),
182            kind,
183            label: id.into(),
184            bears_on: bears.iter().map(|(h, w)| (h.to_string(), *w)).collect(),
185            evidence: EvidenceTier::Mechanistic,
186        }
187    }
188
189    #[test]
190    fn voi_rewards_bearing_on_high_prior_hypotheses() {
191        let hyps = vec![hyp("live", 800), hyp("unlikely", 50)];
192        let on_live = step("s1", StepKind::Test, &[("live", 1000)]);
193        let on_unlikely = step("s2", StepKind::Test, &[("unlikely", 1000)]);
194        assert!(
195            value_of_information(&on_live, &hyps) > value_of_information(&on_unlikely, &hyps),
196            "a test bearing on the live hypothesis is worth more"
197        );
198    }
199
200    #[test]
201    fn voi_rewards_discrimination_between_two_live_hypotheses() {
202        // Two similarly-live hypotheses. A step that would SUPPORT one and TELL AGAINST the other separates
203        // them → higher VOI than a step that only bears on one.
204        let hyps = vec![hyp("a", 600), hyp("b", 600)];
205        let discriminating = step("disc", StepKind::Test, &[("a", 1000), ("b", -1000)]);
206        let one_sided = step("one", StepKind::Test, &[("a", 1000)]);
207        assert!(
208            value_of_information(&discriminating, &hyps) > value_of_information(&one_sided, &hyps),
209            "a test that separates two live hypotheses is the most informative"
210        );
211    }
212
213    #[test]
214    fn pathway_ranks_by_voi_and_drops_useless_steps() {
215        let hyps = vec![hyp("live", 900), hyp("dead", 0)];
216        let steps = vec![
217            step("useless", StepKind::Question, &[("dead", 1000)]), // bears only on a dead hypothesis
218            step("weak", StepKind::Observation, &[("live", 200)]),
219            step("strong", StepKind::Test, &[("live", 1000)]),
220        ];
221        let path = investigative_pathway(hyps, steps);
222        assert_eq!(path.epistemic_status, EpistemicStatus::Hypothesis);
223        // The zero-VOI step is dropped; the strong step ranks first.
224        let ids: Vec<&str> = path.steps.iter().map(|r| r.step.id.as_str()).collect();
225        assert_eq!(
226            ids,
227            vec!["strong", "weak"],
228            "ranked by VOI, useless dropped"
229        );
230        assert!(path.steps[0].voi_milli > path.steps[1].voi_milli);
231    }
232
233    #[test]
234    fn a_pathway_covers_the_modes_of_knowing_and_acting() {
235        // The step kinds together span the enablement modes: ask, observe, test, act, and bring-in-a-specialist.
236        let hyps = vec![hyp("h", 700)];
237        let steps = vec![
238            step("q", StepKind::Question, &[("h", 500)]),
239            step("o", StepKind::Observation, &[("h", 500)]),
240            step("t", StepKind::Test, &[("h", 800)]),
241            step("l", StepKind::LifestyleLever, &[("h", 400)]),
242            step("s", StepKind::SpecialistInput, &[("h", 600)]),
243        ];
244        let path = investigative_pathway(hyps, steps);
245        let kinds: std::collections::BTreeSet<StepKind> =
246            path.steps.iter().map(|r| r.step.kind).collect();
247        assert!(kinds.contains(&StepKind::Question));
248        assert!(kinds.contains(&StepKind::LifestyleLever)); // a lever the person controls
249        assert!(kinds.contains(&StepKind::SpecialistInput)); // toward a chosen specialist
250        // Every step is offered as part of a Hypothesis-status pathway (a proposal, never a directive).
251        assert_eq!(path.epistemic_status, EpistemicStatus::Hypothesis);
252    }
253
254    #[test]
255    fn empty_inputs_give_an_empty_but_honest_pathway() {
256        let path = investigative_pathway(vec![], vec![]);
257        assert!(path.steps.is_empty());
258        assert_eq!(path.epistemic_status, EpistemicStatus::Hypothesis);
259    }
260
261    #[test]
262    fn serde_round_trips() {
263        let hyps = vec![hyp("h", 500)];
264        let steps = vec![step("s", StepKind::Test, &[("h", 700)])];
265        let path = investigative_pathway(hyps, steps);
266        let json = serde_json::to_string(&path).unwrap();
267        let back: InvestigativePathway = serde_json::from_str(&json).unwrap();
268        assert_eq!(path, back);
269    }
270}