Skip to main content

wellfare_core/
n3_rules.rs

1/// N3Logic clinical rule engine for WellFair.
2///
3/// Translates the four N3 rule files from legacy_pwa/extensions/n3_reasoner/rules/
4/// into SPARQL SELECT + aggregation queries executed over the health Turtle graph.
5/// Each rule fires if its aggregated metric thresholds are met.
6///
7/// Routing lanes (per qualiaDB IngestionPipeline):
8///   N3Logic implication (=>) → BilateralMicroCommons (lane 2) — requires identity context
9///   Standard threshold SHACL → PassthroughStandard (lane 0) or Permissive (lane 1)
10///
11/// The "person" is implicit: we aggregate over all observations in the loaded Turtle.
12/// Aggregation strategy: AVG over available records. Rules only fire when data is present.
13use crate::store::HealthStore;
14use crate::webizen::{LANE_BILATERAL, LANE_PASSTHROUGH};
15
16/// One triggered clinical pattern.
17#[derive(Debug)]
18pub struct N3RuleMatch {
19    pub pattern: &'static str,
20    pub confidence: &'static str,
21    pub routing_lane: u8,
22    /// The original N3 source file this came from.
23    pub n3_source: &'static str,
24    /// Optional recommended action (present for safety-critical rules).
25    pub recommended_action: Option<&'static str>,
26}
27
28impl N3RuleMatch {
29    fn to_json(&self) -> String {
30        let action = self
31            .recommended_action
32            .map(|a| format!(",\"recommendedAction\":\"{}\"", a))
33            .unwrap_or_default();
34        format!(
35            "{{\"pattern\":\"{}\",\"confidence\":\"{}\",\"routingLane\":{},\"n3Source\":\"{}\"{}}}",
36            self.pattern, self.confidence, self.routing_lane, self.n3_source, action
37        )
38    }
39}
40
41/// Extract a single f64 average from a SPARQL query returning `?avg`.
42fn query_avg(store: &HealthStore, sparql: &str) -> Option<f64> {
43    match store.query(sparql) {
44        Ok(json) => {
45            // SPARQL JSON results: {"results":{"bindings":[{"avg":{"value":"..."}}]}}
46            // Simple extraction without a full JSON parser.
47            if let Some(start) = json.find("\"value\":\"") {
48                let after = &json[start + 9..];
49                if let Some(end) = after.find('"') {
50                    return after[..end].parse::<f64>().ok();
51                }
52            }
53            None
54        }
55        Err(_) => None,
56    }
57}
58
59const HEALTH: &str = "https://health.example.org/ns#";
60const FHIR: &str = "http://hl7.org/fhir/";
61const SNOMED: &str = "http://snomed.info/id/";
62
63// SNOMED codes used in the Turtle serialisers (rdf.rs).
64const SNOMED_HEART_RATE: &str = "364075005";
65const SNOMED_STEPS: &str = "256235009";
66
67/// Evaluate all 7 N3 clinical rules against a pre-loaded `HealthStore`.
68/// Returns only the rules that fire (empty vec = no concerns found).
69pub fn evaluate_n3_rules(store: &HealthStore) -> Vec<N3RuleMatch> {
70    let mut matches = Vec::new();
71
72    // ── Aggregate health metrics ───────────────────────────────────────────────
73
74    // Average sleep efficiency (health:sleepEfficiency)
75    let avg_sleep_eff = query_avg(
76        store,
77        &format!(
78            "SELECT (AVG(?e) AS ?avg) WHERE {{ ?obs <{}sleepEfficiency> ?e }}",
79            HEALTH
80        ),
81    );
82
83    // Average sleep hours (health:sleepHours — added by rdf.rs update)
84    let avg_sleep_hrs = query_avg(
85        store,
86        &format!(
87            "SELECT (AVG(?h) AS ?avg) WHERE {{ ?obs <{}sleepHours> ?h }}",
88            HEALTH
89        ),
90    );
91
92    // Average resting heart rate (fhir:Observation.valueQuantity on HR records)
93    let avg_hr = query_avg(
94        store,
95        &format!(
96            "SELECT (AVG(?hr) AS ?avg) WHERE {{ \
97           ?obs <{}snomedConcept> <{}{}>  ; \
98                <{}Observation.valueQuantity> ?hr \
99         }}",
100            HEALTH, SNOMED, SNOMED_HEART_RATE, FHIR
101        ),
102    );
103
104    // Average daily steps (fhir:Observation.valueQuantity on steps records)
105    let avg_steps = query_avg(
106        store,
107        &format!(
108            "SELECT (AVG(?s) AS ?avg) WHERE {{ \
109           ?obs <{}snomedConcept> <{}{}>  ; \
110                <{}Observation.valueQuantity> ?s \
111         }}",
112            HEALTH, SNOMED, SNOMED_STEPS, FHIR
113        ),
114    );
115
116    // Stress score and Maslow safety score (vault-level data, may not be present).
117    let avg_stress = query_avg(
118        store,
119        &format!(
120            "SELECT (AVG(?s) AS ?avg) WHERE {{ ?obs <{}stressScore> ?s }}",
121            HEALTH
122        ),
123    );
124    let avg_maslow = query_avg(
125        store,
126        &format!(
127            "SELECT (AVG(?m) AS ?avg) WHERE {{ ?obs <{}maslowSafetyScore> ?m }}",
128            HEALTH
129        ),
130    );
131
132    // ── sleep_debt.n3 ─────────────────────────────────────────────────────────
133    // { ?person health:sleepEfficiency ?e . ?e math:lessThan 70 .
134    //   ?person health:sleepHours ?h . ?h math:lessThan 6 . }
135    // => { ?person health:pattern health:ChronicSleepDebt . }
136    if let (Some(eff), Some(hrs)) = (avg_sleep_eff, avg_sleep_hrs) {
137        if eff < 70.0 && hrs < 6.0 {
138            matches.push(N3RuleMatch {
139                pattern: "ChronicSleepDebt",
140                confidence: "high",
141                routing_lane: LANE_BILATERAL,
142                n3_source: "sleep_debt.n3",
143                recommended_action: None,
144            });
145        }
146    }
147
148    // ── cardiovascular_risk.n3 — Tachycardia ─────────────────────────────────
149    // { ?person health:restingHR ?hr . ?hr math:greaterThan 100 . }
150    // => { ?person health:pattern health:TachycardiaFlag . }
151    if let Some(hr) = avg_hr {
152        if hr > 100.0 {
153            matches.push(N3RuleMatch {
154                pattern: "TachycardiaFlag",
155                confidence: "high",
156                routing_lane: LANE_BILATERAL,
157                n3_source: "cardiovascular_risk.n3",
158                recommended_action: None,
159            });
160        }
161
162        // ── cardiovascular_risk.n3 — Deconditioning ───────────────────────────
163        // { ?person health:dailySteps ?steps . ?steps math:lessThan 3000 .
164        //   ?person health:restingHR ?hr . ?hr math:greaterThan 80 . }
165        // => { ?person health:pattern health:DeconditioningRisk . }
166        if let Some(steps) = avg_steps {
167            if steps < 3000.0 && hr > 80.0 {
168                matches.push(N3RuleMatch {
169                    pattern: "DeconditioningRisk",
170                    confidence: "moderate",
171                    routing_lane: LANE_BILATERAL,
172                    n3_source: "cardiovascular_risk.n3",
173                    recommended_action: None,
174                });
175            }
176        }
177    }
178
179    // ── adrenal_fatigue.n3 ────────────────────────────────────────────────────
180    // { ?person health:sleepHours ?h . ?h math:lessThan 5 .
181    //   ?person health:restingHR ?hr . ?hr math:greaterThan 90 . }
182    // => { ?person health:pattern health:AdrenalFatigueSuspected . }
183    if let (Some(hrs), Some(hr)) = (avg_sleep_hrs, avg_hr) {
184        if hrs < 5.0 && hr > 90.0 {
185            matches.push(N3RuleMatch {
186                pattern: "AdrenalFatigueSuspected",
187                confidence: "moderate",
188                routing_lane: LANE_BILATERAL,
189                n3_source: "adrenal_fatigue.n3",
190                recommended_action: None,
191            });
192        }
193    }
194
195    // ── trauma_cascade.n3 — TraumaCascadeActive ───────────────────────────────
196    // { ?person health:stressScore ?s . ?s math:greaterThan 75 .
197    //   ?person health:maslowSafetyScore ?m . ?m math:lessThan 40 .
198    //   ?person health:sleepHours ?h . ?h math:lessThan 5 . }
199    // => { ?person health:pattern health:TraumaCascadeActive .
200    //      ?person health:recommendedAction "urgent-welfare-review" . }
201    if let (Some(stress), Some(maslow), Some(hrs)) = (avg_stress, avg_maslow, avg_sleep_hrs) {
202        if stress > 75.0 && maslow < 40.0 && hrs < 5.0 {
203            matches.push(N3RuleMatch {
204                pattern: "TraumaCascadeActive",
205                confidence: "high",
206                routing_lane: LANE_BILATERAL,
207                n3_source: "trauma_cascade.n3",
208                recommended_action: Some("urgent-welfare-review"),
209            });
210        }
211    }
212
213    // ── trauma_cascade.n3 — SystemicFrailty ──────────────────────────────────
214    // { ?person health:dailySteps ?steps . ?steps math:lessThan 2000 .
215    //   ?person health:restingHR ?hr . ?hr math:greaterThan 85 . }
216    // => { ?person health:pattern health:SystemicFrailty . }
217    if let (Some(steps), Some(hr)) = (avg_steps, avg_hr) {
218        if steps < 2000.0 && hr > 85.0 {
219            matches.push(N3RuleMatch {
220                pattern: "SystemicFrailty",
221                confidence: "moderate",
222                routing_lane: LANE_BILATERAL,
223                n3_source: "trauma_cascade.n3",
224                recommended_action: None,
225            });
226        }
227    }
228
229    // Rules that use only PassthroughStandard data (no identity context needed):
230    // These re-use the metric values already computed above.
231
232    // Low daily activity flag (standalone, lane 0)
233    if let Some(steps) = avg_steps {
234        if steps < 5000.0 {
235            matches.push(N3RuleMatch {
236                pattern: "LowActivityFlag",
237                confidence: "low",
238                routing_lane: LANE_PASSTHROUGH,
239                n3_source: "cardiovascular_risk.n3",
240                recommended_action: None,
241            });
242        }
243    }
244
245    matches
246}
247
248/// Convenience: build a HealthStore from Turtle, run all N3 rules, return JSON.
249pub fn evaluate_n3_rules_turtle(turtle: &str) -> String {
250    let prefixes = crate::rdf::generate_rdf_prefixes();
251    let full = format!("{}\n{}", prefixes, turtle);
252    let mut store = match HealthStore::new() {
253        Ok(s) => s,
254        Err(e) => return format!("{{\"error\":\"{}\"}}", e),
255    };
256    if let Err(e) = store.load_turtle(&full) {
257        return format!("{{\"error\":\"{}\"}}", e);
258    }
259    let results = evaluate_n3_rules(&store);
260    let json_items: Vec<String> = results.iter().map(|r| r.to_json()).collect();
261    format!("[{}]", json_items.join(","))
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::rdf::generate_rdf_prefixes;
268
269    fn store_with(data: &str) -> HealthStore {
270        let prefixes = generate_rdf_prefixes();
271        let full = format!("{}\n{}", prefixes, data);
272        let mut s = HealthStore::new().unwrap();
273        s.load_turtle(&full).unwrap();
274        s
275    }
276
277    #[test]
278    fn test_tachycardia_fires() {
279        // Heart rate 110 BPM > 100 threshold
280        let data = format!(
281            "<urn:health:hr:1> a <http://hl7.org/fhir/Observation> ; \
282             <https://health.example.org/ns#snomedConcept> \
283             <http://snomed.info/id/364075005> ; \
284             <http://hl7.org/fhir/Observation.valueQuantity> 110 ."
285        );
286        let store = store_with(&data);
287        let matches = evaluate_n3_rules(&store);
288        assert!(
289            matches.iter().any(|m| m.pattern == "TachycardiaFlag"),
290            "TachycardiaFlag should fire for HR 110"
291        );
292    }
293
294    #[test]
295    fn test_sleep_debt_fires() {
296        // Sleep efficiency 60% < 70 AND sleep hours 5.0 < 6
297        let data = format!(
298            "<urn:health:sleep:1> a <http://hl7.org/fhir/Observation> ; \
299             <https://health.example.org/ns#sleepEfficiency> 60 ; \
300             <https://health.example.org/ns#sleepHours> 5.0 ."
301        );
302        let store = store_with(&data);
303        let matches = evaluate_n3_rules(&store);
304        assert!(
305            matches.iter().any(|m| m.pattern == "ChronicSleepDebt"),
306            "ChronicSleepDebt should fire for eff=60, hrs=5.0"
307        );
308    }
309
310    #[test]
311    fn test_normal_data_no_flags() {
312        // Normal HR 65 BPM, good sleep efficiency 85%, 8 hours, 8000 steps
313        let data = format!(
314            "<urn:health:hr:ok> a <http://hl7.org/fhir/Observation> ; \
315             <https://health.example.org/ns#snomedConcept> <http://snomed.info/id/364075005> ; \
316             <http://hl7.org/fhir/Observation.valueQuantity> 65 . \
317             <urn:health:sleep:ok> a <http://hl7.org/fhir/Observation> ; \
318             <https://health.example.org/ns#sleepEfficiency> 85 ; \
319             <https://health.example.org/ns#sleepHours> 8.0 . \
320             <urn:health:steps:ok> a <http://hl7.org/fhir/Observation> ; \
321             <https://health.example.org/ns#snomedConcept> <http://snomed.info/id/256235009> ; \
322             <http://hl7.org/fhir/Observation.valueQuantity> 8000 ."
323        );
324        let store = store_with(&data);
325        let matches = evaluate_n3_rules(&store);
326        let critical: Vec<_> = matches.iter().filter(|m| m.routing_lane == 2).collect();
327        assert!(
328            critical.is_empty(),
329            "No BilateralMicroCommons rules should fire for normal data. Got: {:?}",
330            critical.iter().map(|m| m.pattern).collect::<Vec<_>>()
331        );
332    }
333
334    #[test]
335    fn test_adrenal_fatigue_fires() {
336        // Sleep 4.5h < 5 AND HR 95 > 90
337        let data = format!(
338            "<urn:health:sleep:1> a <http://hl7.org/fhir/Observation> ; \
339             <https://health.example.org/ns#sleepHours> 4.5 . \
340             <urn:health:hr:1> a <http://hl7.org/fhir/Observation> ; \
341             <https://health.example.org/ns#snomedConcept> <http://snomed.info/id/364075005> ; \
342             <http://hl7.org/fhir/Observation.valueQuantity> 95 ."
343        );
344        let store = store_with(&data);
345        let matches = evaluate_n3_rules(&store);
346        assert!(
347            matches
348                .iter()
349                .any(|m| m.pattern == "AdrenalFatigueSuspected"),
350            "AdrenalFatigueSuspected should fire for sleep=4.5h, HR=95"
351        );
352    }
353}