Skip to main content

wellfare_core/anatomy/
temporal.rs

1//! S2 — the **temporal-state engine**.
2//!
3//! Slice 1 answers "where does load converge *right now*". This layer answers "how does it *build up
4//! and recover over time*, and which interventions bend which subsystem's curve". A [`Factor`] becomes
5//! a time-stamped [`FactorEvent`] with a dose scaler and per-system [`Kinetics`] (onset → clearance).
6//! [`EnvironmentModulator`]s (heat, season) scale matching contributions over a window. A [`Timeline`]
7//! integrates events + interventions + environment; sampling it at a time reproduces a slice-1 factor
8//! set (so [`accumulate`](super::accumulate) / [`systemic_implications`](super::systemic_implications)
9//! run unchanged on any instant), and [`Timeline::system_trajectory`] traces one system's net burden.
10//!
11//! **The point of the layer** (the hot-week / beer / water example): different subsystems recover on
12//! different clocks and respond to different interventions. Alcohol on the hepatic/digestive system
13//! clears slowly on its own half-life — water and electrolytes do **not** speed it. Diuretic fluid loss
14//! on the renal/urinary system *is* offset by a rehydration intervention, so it recovers far sooner.
15//! The engine shows that divergence; it never asserts one.
16//!
17//! **Honesty:** all magnitudes stay integer milli (no float health arithmetic — the kinetic curves are
18//! evaluated with integer math). Temporal projection is **coarse and illustrative**: [`RecoveryBand`]
19//! is "hours / days / weeks", with explicit uncertainty. It is **never** an operational safety
20//! threshold — no BAC number, no fitness-to-drive/operate claim.
21
22use serde::{Deserialize, Serialize};
23
24use super::factor::{Effect, Factor, FactorTarget};
25use super::system_key;
26use super::{accumulate::SystemBurden, accumulate::accumulate};
27
28/// How a factor-event's contribution to a system rises to a peak, then clears.
29///
30/// - `onset_minutes`: time from the event to peak contribution (0 = immediate).
31/// - `half_life_minutes`: clearance half-life *after* the peak. `0` means it does **not** clear while
32///   present (a chronic condition, a standing environmental exposure) — it holds at peak.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Kinetics {
35    pub onset_minutes: u32,
36    pub half_life_minutes: u32,
37}
38
39impl Kinetics {
40    /// Immediate onset, never clears (chronic / standing).
41    pub const CHRONIC: Kinetics = Kinetics {
42        onset_minutes: 0,
43        half_life_minutes: 0,
44    };
45
46    /// Creates a new instance.
47    pub fn new(onset_minutes: u32, half_life_minutes: u32) -> Self {
48        Self {
49            onset_minutes,
50            half_life_minutes,
51        }
52    }
53
54    /// Effective magnitude of a `base_milli` contribution `elapsed_minutes` after the event, given a
55    /// dose scaler (percent; 100 = as authored). Integer math throughout; result clamped to 0..=1000.
56    ///
57    /// Rise is linear to the peak over `onset_minutes`; decay halves every `half_life_minutes` with a
58    /// linear interpolation inside each half-life (coarse but monotone and honest).
59    pub fn magnitude_at(self, base_milli: u32, dose_scale_pct: u32, elapsed_minutes: i64) -> u32 {
60        if elapsed_minutes < 0 {
61            return 0; // the event has not happened yet
62        }
63        let e = elapsed_minutes as u64;
64        let peak = (base_milli as u64 * dose_scale_pct as u64 / 100).min(1000);
65        if peak == 0 {
66            return 0;
67        }
68        let onset = self.onset_minutes as u64;
69        let shaped = if onset > 0 && e < onset {
70            peak * e / onset // linear rise to peak
71        } else if self.half_life_minutes == 0 {
72            peak // chronic / standing — never clears
73        } else {
74            let since_peak = e - onset; // e >= onset (onset may be 0)
75            let hl = self.half_life_minutes as u64;
76            let n = (since_peak / hl).min(63); // full halvings (cap to avoid shift overflow → 0)
77            let r = since_peak % hl;
78            let hi = peak >> n;
79            let lo = peak >> (n + 1).min(63);
80            hi - (hi - lo) * r / hl // linear interpolation within the current half-life
81        };
82        shaped.min(1000) as u32
83    }
84}
85
86/// A [`Factor`] applied at a point in time, with a dose scaler and per-system kinetics.
87///
88/// The factor's slice-1 `targets` supply the (system, effect, evidence, base weight); kinetics decide
89/// how each target's contribution evolves. A target's kinetics come from `system_kinetics` if present,
90/// else `default_kinetics` — this is what lets one event clear on different clocks per system.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
92pub struct FactorEvent {
93    pub factor: Factor,
94    /// Event time on the timeline, in minutes (may be negative for "before now").
95    pub at_minute: i64,
96    /// Scales every target weight (percent; 100 = as authored). A "slab" of beer vs a single can.
97    pub dose_scale_pct: u32,
98    /// Fallback kinetics for targets without a per-system override.
99    pub default_kinetics: Kinetics,
100    /// Per-system kinetics overrides (`system_id` → kinetics).
101    #[serde(default)]
102    pub system_kinetics: Vec<(String, Kinetics)>,
103}
104
105impl FactorEvent {
106    /// Creates a new instance.
107    pub fn new(factor: Factor, at_minute: i64) -> Self {
108        Self {
109            factor,
110            at_minute,
111            dose_scale_pct: 100,
112            default_kinetics: Kinetics::CHRONIC,
113            system_kinetics: Vec::new(),
114        }
115    }
116
117    /// Set the dose scaler (percent; 100 = as authored).
118    pub fn with_dose_pct(mut self, dose_scale_pct: u32) -> Self {
119        self.dose_scale_pct = dose_scale_pct;
120        self
121    }
122
123    /// Set the fallback kinetics used for targets without a per-system override.
124    pub fn with_default_kinetics(mut self, k: Kinetics) -> Self {
125        self.default_kinetics = k;
126        self
127    }
128
129    /// Override the kinetics for a specific system id (e.g. hepatic clears slower than renal).
130    pub fn with_system_kinetics(mut self, system_id: impl Into<String>, k: Kinetics) -> Self {
131        self.system_kinetics.push((system_id.into(), k));
132        self
133    }
134
135    fn kinetics_for(&self, system_id: &str) -> Kinetics {
136        self.system_kinetics
137            .iter()
138            .find(|(id, _)| system_key(id) == system_key(system_id))
139            .map(|(_, k)| *k)
140            .unwrap_or(self.default_kinetics)
141    }
142}
143
144/// An environmental condition (heat, season, sustained activity) that scales matching contributions
145/// over a time window. Entered or imported — never a live weather/cloud call.
146///
147/// `scale_pct` amplifies (>100) or dampens (<100) the magnitude of contributions whose system and
148/// effect match `target_system` / `target_effect` (`None` = match any) while `now` is within
149/// `[from_minute, to_minute]`.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151pub struct EnvironmentModulator {
152    pub label: String,
153    pub from_minute: i64,
154    pub to_minute: i64,
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub target_system: Option<String>,
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub target_effect: Option<Effect>,
159    pub scale_pct: u32,
160}
161
162impl EnvironmentModulator {
163    fn applies(&self, now: i64, system_id: &str, effect: Effect) -> bool {
164        if now < self.from_minute || now > self.to_minute {
165            return false;
166        }
167        if let Some(sys) = &self.target_system {
168            if system_key(sys) != system_key(system_id) {
169                return false;
170            }
171        }
172        match self.target_effect {
173            Some(e) if e != effect => false,
174            _ => true,
175        }
176    }
177}
178
179/// A person's timeline of factor events + interventions + environment. Interventions are simply
180/// `FactorEvent`s carrying `Effect::Supportive` targets — no separate type, so they net against
181/// adverse load through the same slice-1 accumulation.
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
183pub struct Timeline {
184    pub events: Vec<FactorEvent>,
185    #[serde(default)]
186    pub environment: Vec<EnvironmentModulator>,
187}
188
189/// One sampled point of a system's burden over time.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191pub struct TrajectoryPoint {
192    pub minute: i64,
193    pub net_milli: u32,
194    pub adverse_milli: u32,
195    pub supportive_milli: u32,
196}
197
198impl Timeline {
199    /// Creates a new instance.
200    pub fn new() -> Self {
201        Self::default()
202    }
203
204    /// Builder — sets the event.
205    pub fn with_event(mut self, e: FactorEvent) -> Self {
206        self.events.push(e);
207        self
208    }
209
210    /// Builder — sets the environment.
211    pub fn with_environment(mut self, m: EnvironmentModulator) -> Self {
212        self.environment.push(m);
213        self
214    }
215
216    /// Reconstruct the slice-1 factor set as it stands at `minute`: each event contributes a [`Factor`]
217    /// whose target weights are its kinetic magnitude at that instant, scaled by any active environment.
218    /// Targets that have decayed (or not yet started) to zero are dropped; a fully-cleared event drops
219    /// out entirely — so it stops being a "converging factor" once it's gone.
220    pub fn snapshot_at(&self, minute: i64) -> Vec<Factor> {
221        let mut out = Vec::new();
222        for ev in &self.events {
223            let elapsed = minute - ev.at_minute;
224            let mut targets: Vec<FactorTarget> = Vec::new();
225            for t in &ev.factor.targets {
226                let base = ev.kinetics_for(&t.system_id).magnitude_at(
227                    t.weight_milli,
228                    ev.dose_scale_pct,
229                    elapsed,
230                );
231                if base == 0 {
232                    continue;
233                }
234                let scaled = self.apply_environment(minute, &t.system_id, t.effect, base);
235                if scaled == 0 {
236                    continue;
237                }
238                targets.push(FactorTarget {
239                    system_id: t.system_id.clone(),
240                    effect: t.effect,
241                    evidence: t.evidence,
242                    weight_milli: scaled,
243                });
244            }
245            if targets.is_empty() {
246                continue;
247            }
248            out.push(Factor {
249                id: ev.factor.id.clone(),
250                kind: ev.factor.kind.clone(),
251                label: ev.factor.label.clone(),
252                targets,
253                source: ev.factor.source.clone(),
254            });
255        }
256        out
257    }
258
259    /// Per-system burden at `minute` (slice-1 [`accumulate`] over the snapshot).
260    pub fn burden_at(&self, minute: i64) -> Vec<SystemBurden> {
261        accumulate(&self.snapshot_at(minute))
262    }
263
264    /// Trace one system's net/adverse/supportive burden across the given sample minutes.
265    pub fn system_trajectory(&self, system_id: &str, samples: &[i64]) -> Vec<TrajectoryPoint> {
266        samples
267            .iter()
268            .map(|&minute| {
269                let burden = self
270                    .burden_at(minute)
271                    .into_iter()
272                    .find(|b| system_key(&b.system_id) == system_key(system_id));
273                match burden {
274                    Some(b) => TrajectoryPoint {
275                        minute,
276                        net_milli: b.net_milli,
277                        adverse_milli: b.adverse_milli,
278                        supportive_milli: b.supportive_milli,
279                    },
280                    None => TrajectoryPoint {
281                        minute,
282                        net_milli: 0,
283                        adverse_milli: 0,
284                        supportive_milli: 0,
285                    },
286                }
287            })
288            .collect()
289    }
290
291    fn apply_environment(&self, minute: i64, system_id: &str, effect: Effect, base: u32) -> u32 {
292        let mut v = base as u64;
293        for m in &self.environment {
294            if m.applies(minute, system_id, effect) {
295                v = v * m.scale_pct as u64 / 100;
296            }
297        }
298        v.min(1000) as u32
299    }
300}
301
302/// A coarse, honest recovery horizon — **never** a precise time or a safety threshold.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(rename_all = "snake_case")]
305pub enum RecoveryBand {
306    /// Returns toward baseline within ~half a day.
307    Hours,
308    /// Within a few days.
309    Days,
310    /// Within a few weeks.
311    Weeks,
312    /// Longer than weeks within the sampled window (or a standing/chronic load).
313    Extended,
314}
315
316/// Classify a system trajectory's recovery horizon into a coarse band. Finds the peak net burden, then
317/// the first later sample at or below a near-baseline threshold (10% of peak, floored at 20 milli), and
318/// buckets the elapsed time. Returns `None` if there is no adverse load to recover from.
319///
320/// **Coarse and illustrative** — the band answers "hours vs days vs weeks", not a clock time, and never
321/// implies a fitness-to-operate judgement. The trajectory must be sampled finely enough to catch the
322/// crossing; a load still above threshold at the last sample is [`RecoveryBand::Extended`].
323pub fn recovery_band(points: &[TrajectoryPoint]) -> Option<RecoveryBand> {
324    let peak_idx = points
325        .iter()
326        .enumerate()
327        .max_by_key(|(_, p)| p.net_milli)
328        .map(|(i, _)| i)?;
329    let peak = points[peak_idx].net_milli;
330    if peak == 0 {
331        return None; // nothing adverse to recover from
332    }
333    let threshold = (peak / 10).max(20);
334    let peak_minute = points[peak_idx].minute;
335    let recovered_at = points[peak_idx..]
336        .iter()
337        .find(|p| p.net_milli <= threshold)
338        .map(|p| p.minute - peak_minute);
339    Some(match recovered_at {
340        Some(mins) if mins <= 12 * 60 => RecoveryBand::Hours,
341        Some(mins) if mins <= 3 * 24 * 60 => RecoveryBand::Days,
342        Some(mins) if mins <= 21 * 24 * 60 => RecoveryBand::Weeks,
343        _ => RecoveryBand::Extended,
344    })
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350    use crate::anatomy::{EvidenceTier, FactorKind};
351
352    fn minutes_over(hours_end: i64, step_min: i64) -> Vec<i64> {
353        (0..=(hours_end * 60 / step_min))
354            .map(|i| i * step_min)
355            .collect()
356    }
357
358    #[test]
359    fn kinetics_rise_peak_and_halve() {
360        let k = Kinetics::new(60, 120); // 1h onset, 2h half-life
361        assert_eq!(k.magnitude_at(400, 100, -10), 0); // before the event
362        assert_eq!(k.magnitude_at(400, 100, 0), 0); // at the event, pre-onset
363        assert_eq!(k.magnitude_at(400, 100, 30), 200); // half-way up the rise
364        assert_eq!(k.magnitude_at(400, 100, 60), 400); // peak
365        assert_eq!(k.magnitude_at(400, 100, 180), 200); // one half-life past peak
366        assert_eq!(k.magnitude_at(400, 100, 300), 100); // two half-lives past peak
367        // Decays toward zero over many half-lives.
368        assert!(k.magnitude_at(400, 100, 60 + 120 * 10) < 5);
369    }
370
371    #[test]
372    fn dose_scaling_amplifies_but_stays_bounded() {
373        let k = Kinetics::new(0, 0); // immediate, chronic
374        assert_eq!(k.magnitude_at(300, 100, 0), 300);
375        assert_eq!(k.magnitude_at(300, 200, 0), 600); // double dose
376        assert_eq!(k.magnitude_at(300, 1000, 0), 1000); // clamped to the model ceiling
377    }
378
379    #[test]
380    fn chronic_kinetics_never_clears() {
381        let k = Kinetics::CHRONIC;
382        assert_eq!(k.magnitude_at(500, 100, 0), 500);
383        assert_eq!(k.magnitude_at(500, 100, 100_000), 500);
384    }
385
386    #[test]
387    fn snapshot_reproduces_a_slice1_factor_set_that_accumulates() {
388        let beer = Factor::new("intake:beer", FactorKind::Food, "beer").targeting(
389            "digestive",
390            Effect::Adverse,
391            EvidenceTier::Mechanistic,
392            300,
393        );
394        let tl = Timeline::new()
395            .with_event(FactorEvent::new(beer, 0).with_default_kinetics(Kinetics::new(30, 240)));
396        // At peak the snapshot has one loaded factor; far in the future it has cleared away.
397        let at_peak = tl.snapshot_at(30);
398        assert_eq!(at_peak.len(), 1);
399        assert!(at_peak[0].targets[0].weight_milli > 0);
400        assert!(
401            tl.snapshot_at(100_000).is_empty(),
402            "fully-cleared event drops out of the snapshot"
403        );
404    }
405
406    #[test]
407    fn environment_amplifies_matching_adverse_load() {
408        let sweat = Factor::new("intake:none", FactorKind::Environmental, "fluid loss").targeting(
409            "urinary",
410            Effect::Adverse,
411            EvidenceTier::Mechanistic,
412            300,
413        );
414        let base = Timeline::new().with_event(
415            FactorEvent::new(sweat.clone(), 0).with_default_kinetics(Kinetics::CHRONIC),
416        );
417        let hot = base.clone().with_environment(EnvironmentModulator {
418            label: "heatwave".into(),
419            from_minute: 0,
420            to_minute: 10_000,
421            target_system: Some("urinary".into()),
422            target_effect: Some(Effect::Adverse),
423            scale_pct: 150,
424        });
425        let cool_net = base
426            .burden_at(60)
427            .into_iter()
428            .find(|b| b.system_id == "urinary")
429            .unwrap()
430            .net_milli;
431        let hot_net = hot
432            .burden_at(60)
433            .into_iter()
434            .find(|b| b.system_id == "urinary")
435            .unwrap()
436            .net_milli;
437        assert_eq!(cool_net, 300);
438        assert_eq!(hot_net, 450, "heat amplifies the renal/fluid load by 50%");
439    }
440
441    /// The load-bearing example: a hot week + a slab of beer + water later. The renal/urinary system
442    /// (offset by rehydration) must recover on a *faster* clock than the hepatic/digestive system
443    /// (alcohol clearance — time + liver only), which the water does not touch.
444    #[test]
445    fn hot_week_beer_and_water_recover_on_different_clocks() {
446        // One intake event: hepatic load (slow, long half-life) + renal fluid load (medium).
447        let beer = Factor::new("intake:slab-of-beer", FactorKind::Food, "a slab of beer")
448            .targeting("digestive", Effect::Adverse, EvidenceTier::Mechanistic, 300) // hepatic/alcohol
449            .targeting("urinary", Effect::Adverse, EvidenceTier::Mechanistic, 300); // diuresis → fluid loss
450        let beer_event = FactorEvent::new(beer, 0)
451            .with_dose_pct(300) // "a slab", not a can
452            .with_system_kinetics("digestive", Kinetics::new(30, 300)) // alcohol clears slowly
453            .with_system_kinetics("urinary", Kinetics::new(60, 180)); // fluid turns over faster
454
455        // Rehydration intervention 2h in: supportive on the renal/urinary system only.
456        let water = Factor::new(
457            "act:water-electrolytes",
458            FactorKind::Lifestyle,
459            "water + electrolytes",
460        )
461        .targeting(
462            "urinary",
463            Effect::Supportive,
464            EvidenceTier::Mechanistic,
465            600,
466        );
467        let water_event =
468            FactorEvent::new(water, 120).with_default_kinetics(Kinetics::new(20, 240));
469
470        // A week-long heatwave amplifies the renal fluid load (worse dehydration in the heat).
471        let tl = Timeline::new()
472            .with_event(beer_event)
473            .with_event(water_event)
474            .with_environment(EnvironmentModulator {
475                label: "summer heatwave".into(),
476                from_minute: 0,
477                to_minute: 7 * 24 * 60,
478                target_system: Some("urinary".into()),
479                target_effect: Some(Effect::Adverse),
480                scale_pct: 140,
481            });
482
483        let samples = minutes_over(48, 15); // 48h, every 15 min
484        let renal = tl.system_trajectory("urinary", &samples);
485        let hepatic = tl.system_trajectory("digestive", &samples);
486
487        let renal_band = recovery_band(&renal).unwrap();
488        let hepatic_band = recovery_band(&hepatic).unwrap();
489
490        // Renal recovers within hours (water offsets it); hepatic takes longer (no offset).
491        assert_eq!(
492            renal_band,
493            RecoveryBand::Hours,
494            "rehydration bends the renal curve down fast"
495        );
496        assert_ne!(
497            hepatic_band,
498            RecoveryBand::Hours,
499            "alcohol clearance is not sped by water"
500        );
501
502        // Concretely: by 12h the renal net is near baseline while the hepatic net is still loaded.
503        let at_12h =
504            |pts: &[TrajectoryPoint]| pts.iter().find(|p| p.minute == 12 * 60).unwrap().net_milli;
505        let renal_12h = at_12h(&renal);
506        let hepatic_12h = at_12h(&hepatic);
507        assert!(renal_12h < 60, "renal recovered by 12h: {renal_12h}");
508        assert!(
509            hepatic_12h > renal_12h,
510            "hepatic still more loaded than renal at 12h: {hepatic_12h} vs {renal_12h}"
511        );
512    }
513
514    #[test]
515    fn recovery_band_none_when_no_adverse_load() {
516        let pts = vec![
517            TrajectoryPoint {
518                minute: 0,
519                net_milli: 0,
520                adverse_milli: 0,
521                supportive_milli: 0,
522            },
523            TrajectoryPoint {
524                minute: 60,
525                net_milli: 0,
526                adverse_milli: 0,
527                supportive_milli: 0,
528            },
529        ];
530        assert!(recovery_band(&pts).is_none());
531    }
532
533    #[test]
534    fn timeline_serde_round_trips() {
535        let tl = Timeline::new().with_event(
536            FactorEvent::new(
537                Factor::new("f", FactorKind::Herb, "f").targeting(
538                    "digestive",
539                    Effect::Supportive,
540                    EvidenceTier::TraditionalUse,
541                    100,
542                ),
543                0,
544            )
545            .with_dose_pct(150)
546            .with_system_kinetics("digestive", Kinetics::new(10, 60)),
547        );
548        let json = serde_json::to_string(&tl).unwrap();
549        let back: Timeline = serde_json::from_str(&json).unwrap();
550        assert_eq!(tl, back);
551    }
552}