1use std::collections::BTreeMap;
22
23use serde::{Deserialize, Serialize};
24use sha2::{Digest, Sha256};
25
26use super::factor::{Effect, EvidenceTier, Factor, FactorKind, FactorTarget};
27use super::registry::SystemRegistry;
28use super::temporal::{FactorEvent, Kinetics};
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct Provenance {
33 pub source_id: String,
35 pub source_title: String,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub citation: Option<String>,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub imported_at: Option<String>,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct KnowledgeTarget {
49 pub system_id: String,
50 pub effect: Effect,
51 pub evidence: EvidenceTier,
52 pub weight_milli: u32,
53 pub kinetics: Kinetics,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct FactorKnowledge {
59 pub key: String,
61 pub kind: FactorKind,
62 pub label: String,
63 pub targets: Vec<KnowledgeTarget>,
64 pub provenance: Provenance,
65 pub version: u32,
66 #[serde(default)]
68 pub content_hash: String,
69}
70
71impl FactorKnowledge {
72 pub fn new(
74 key: impl Into<String>,
75 kind: FactorKind,
76 label: impl Into<String>,
77 provenance: Provenance,
78 ) -> Self {
79 Self {
80 key: key.into(),
81 kind,
82 label: label.into(),
83 targets: Vec::new(),
84 provenance,
85 version: 1,
86 content_hash: String::new(),
87 }
88 }
89
90 pub fn targeting(
92 mut self,
93 system_id: impl Into<String>,
94 effect: Effect,
95 evidence: EvidenceTier,
96 weight_milli: u32,
97 kinetics: Kinetics,
98 ) -> Self {
99 self.targets.push(KnowledgeTarget {
100 system_id: system_id.into(),
101 effect,
102 evidence,
103 weight_milli: weight_milli.min(1000),
104 kinetics,
105 });
106 self
107 }
108
109 pub fn compute_content_hash(&self) -> String {
111 let canonical = serde_json::to_vec(&(
113 &self.key,
114 &self.kind,
115 &self.label,
116 &self.targets,
117 &self.provenance,
118 self.version,
119 ))
120 .expect("knowledge entry serializes");
121 let digest = Sha256::digest(&canonical);
122 hex::encode(digest)
123 }
124
125 pub fn sealed(mut self) -> Self {
127 self.content_hash = self.compute_content_hash();
128 self
129 }
130
131 pub fn integrity_ok(&self) -> bool {
133 !self.content_hash.is_empty() && self.content_hash == self.compute_content_hash()
134 }
135
136 pub fn to_factor(&self, instance_id: impl Into<String>) -> Factor {
138 let mut f = Factor::new(instance_id, self.kind.clone(), self.label.clone())
139 .from_source(self.provenance.source_id.clone());
140 f.targets = self
141 .targets
142 .iter()
143 .map(|t| FactorTarget {
144 system_id: t.system_id.clone(),
145 effect: t.effect,
146 evidence: t.evidence,
147 weight_milli: t.weight_milli,
148 })
149 .collect();
150 f
151 }
152
153 pub fn to_event(
156 &self,
157 instance_id: impl Into<String>,
158 at_minute: i64,
159 dose_scale_pct: u32,
160 ) -> FactorEvent {
161 let factor = self.to_factor(instance_id);
162 let mut ev = FactorEvent::new(factor, at_minute).with_dose_pct(dose_scale_pct);
163 for t in &self.targets {
164 ev = ev.with_system_kinetics(t.system_id.clone(), t.kinetics);
165 }
166 ev
167 }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172pub struct KnowledgeSource {
173 pub id: String,
174 pub title: String,
175 pub trust_ceiling: EvidenceTier,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub url: Option<String>,
179}
180
181impl KnowledgeSource {
182 pub fn new(
184 id: impl Into<String>,
185 title: impl Into<String>,
186 trust_ceiling: EvidenceTier,
187 ) -> Self {
188 Self {
189 id: id.into(),
190 title: title.into(),
191 trust_ceiling,
192 url: None,
193 }
194 }
195}
196
197#[derive(Debug, Clone, Default, Serialize, Deserialize)]
199pub struct KnowledgeBase {
200 pub sources: Vec<KnowledgeSource>,
201 entries: BTreeMap<String, FactorKnowledge>,
202}
203
204impl KnowledgeBase {
205 pub fn new() -> Self {
207 Self::default()
208 }
209
210 pub fn register_source(&mut self, source: KnowledgeSource) {
212 if let Some(existing) = self.sources.iter_mut().find(|s| s.id == source.id) {
213 *existing = source;
214 } else {
215 self.sources.push(source);
216 }
217 }
218
219 fn ceiling_for(&self, source_id: &str) -> EvidenceTier {
221 self.sources
222 .iter()
223 .find(|s| s.id == source_id)
224 .map(|s| s.trust_ceiling)
225 .unwrap_or(EvidenceTier::CommunityAnecdotal)
226 }
227
228 pub fn insert(&mut self, mut entry: FactorKnowledge) {
232 let ceiling = self.ceiling_for(&entry.provenance.source_id);
233 for t in &mut entry.targets {
234 if t.evidence > ceiling {
235 t.evidence = ceiling;
236 }
237 }
238 let sealed = entry.sealed();
239 self.entries.insert(sealed.key.clone(), sealed);
240 }
241
242 pub fn get(&self, key: &str) -> Option<&FactorKnowledge> {
244 self.entries.get(key)
245 }
246
247 pub fn len(&self) -> usize {
249 self.entries.len()
250 }
251
252 pub fn is_empty(&self) -> bool {
254 self.entries.is_empty()
255 }
256
257 pub fn iter(&self) -> impl Iterator<Item = &FactorKnowledge> {
259 self.entries.values()
260 }
261
262 pub fn by_kind<'a>(
264 &'a self,
265 kind: &'a FactorKind,
266 ) -> impl Iterator<Item = &'a FactorKnowledge> {
267 self.entries.values().filter(move |e| &e.kind == kind)
268 }
269
270 pub fn verify_integrity(&self) -> Vec<String> {
272 self.entries
273 .values()
274 .filter(|e| !e.integrity_ok())
275 .map(|e| e.key.clone())
276 .collect()
277 }
278}
279
280#[derive(Deserialize)]
283struct ConditionMapFile {
284 conditions: BTreeMap<String, ConditionEntry>,
285}
286
287#[derive(Deserialize)]
288struct ConditionEntry {
289 #[serde(rename = "primarySystem")]
290 primary_system: String,
291 #[serde(rename = "ontologyIri", default)]
292 #[allow(dead_code)]
293 ontology_iri: Option<String>,
294}
295
296pub struct ImportResult {
298 pub entries: Vec<FactorKnowledge>,
299 pub warnings: Vec<String>,
300}
301
302pub fn import_condition_map(
309 json: &str,
310 provenance: Provenance,
311 systems: &SystemRegistry,
312) -> Result<ImportResult, String> {
313 let file: ConditionMapFile =
314 serde_json::from_str(json).map_err(|e| format!("condition-map.json parse error: {e}"))?;
315 let mut entries = Vec::new();
316 let mut warnings = Vec::new();
317 for (name, entry) in file.conditions {
318 match systems.get_by_label(&entry.primary_system) {
319 Some(sys) => {
320 let key = format!("cond:{}", super::slugify(&name));
321 entries.push(
322 FactorKnowledge::new(key, FactorKind::Condition, name, provenance.clone())
323 .targeting(
324 sys.id.clone(),
325 Effect::Adverse,
326 EvidenceTier::ClinicalEvidence,
327 500,
328 Kinetics::CHRONIC, )
330 .sealed(),
331 );
332 }
333 None => warnings.push(format!(
334 "condition '{name}': primary system '{}' is not a registered body system (register it \
335 to evaluate conditions that map to it)",
336 entry.primary_system
337 )),
338 }
339 }
340 entries.sort_by(|a, b| a.key.cmp(&b.key));
341 Ok(ImportResult { entries, warnings })
342}
343
344pub fn import_entries(json: &str) -> Result<ImportResult, String> {
348 let raw: Vec<FactorKnowledge> =
349 serde_json::from_str(json).map_err(|e| format!("knowledge JSON parse error: {e}"))?;
350 let mut warnings = Vec::new();
351 let mut entries = Vec::new();
352 for e in raw {
353 let recomputed = e.compute_content_hash();
354 if !e.content_hash.is_empty() && e.content_hash != recomputed {
355 warnings.push(format!(
356 "entry '{}': content hash mismatch (imported {}, computed {})",
357 e.key, e.content_hash, recomputed
358 ));
359 }
360 entries.push(e.sealed());
361 }
362 Ok(ImportResult { entries, warnings })
363}
364
365pub fn seed_knowledge_base() -> KnowledgeBase {
375 let mut kb = KnowledgeBase::new();
376
377 kb.register_source(KnowledgeSource::new(
378 "clinical-reference",
379 "General clinical references (condition→primary-system, well established)",
380 EvidenceTier::ClinicalEvidence,
381 ));
382 kb.register_source(KnowledgeSource::new(
383 "who-monographs",
384 "WHO monographs on selected medicinal plants (traditional-use class)",
385 EvidenceTier::TraditionalUse,
386 ));
387 kb.register_source(KnowledgeSource::new(
388 "nutrition-db",
389 "Food-composition / nutrition database (nutritional-data class)",
390 EvidenceTier::NutritionalData,
391 ));
392 kb.register_source(KnowledgeSource::new(
393 "community-anecdotal",
394 "Community / internet posts (unverified 'hot takes')",
395 EvidenceTier::CommunityAnecdotal,
396 ));
397
398 let who = || Provenance {
399 source_id: "who-monographs".into(),
400 source_title: "WHO monographs on selected medicinal plants".into(),
401 citation: None,
402 imported_at: None,
403 };
404 let nutrition = || Provenance {
405 source_id: "nutrition-db".into(),
406 source_title: "Food-composition / nutrition database".into(),
407 citation: None,
408 imported_at: None,
409 };
410 let community = || Provenance {
411 source_id: "community-anecdotal".into(),
412 source_title: "Community / internet posts".into(),
413 citation: None,
414 imported_at: None,
415 };
416
417 kb.insert(
419 FactorKnowledge::new("herb:milk-thistle", FactorKind::Herb, "Milk thistle", who())
420 .targeting(
421 "digestive",
422 Effect::Supportive,
423 EvidenceTier::TraditionalUse,
424 200,
425 Kinetics::new(30, 12 * 60),
426 ),
427 );
428 kb.insert(
430 FactorKnowledge::new("tea:chamomile", FactorKind::Tea, "Chamomile tea", who()).targeting(
431 "nervous",
432 Effect::Supportive,
433 EvidenceTier::TraditionalUse,
434 120,
435 Kinetics::new(20, 3 * 60),
436 ),
437 );
438 kb.insert(
440 FactorKnowledge::new("food:beer", FactorKind::Food, "Beer (alcohol)", nutrition())
441 .targeting(
442 "digestive",
443 Effect::Adverse,
444 EvidenceTier::NutritionalData,
445 300,
446 Kinetics::new(30, 5 * 60),
447 )
448 .targeting(
449 "urinary",
450 Effect::Adverse,
451 EvidenceTier::NutritionalData,
452 250,
453 Kinetics::new(60, 3 * 60),
454 ),
455 );
456 kb.insert(
458 FactorKnowledge::new(
459 "food:water-electrolytes",
460 FactorKind::WholeFood,
461 "Water + electrolytes",
462 nutrition(),
463 )
464 .targeting(
465 "urinary",
466 Effect::Supportive,
467 EvidenceTier::NutritionalData,
468 500,
469 Kinetics::new(20, 4 * 60),
470 ),
471 );
472 kb.insert(
474 FactorKnowledge::new(
475 "tea:detox-claim",
476 FactorKind::Tea,
477 "'Detox' tea (some people say it cleanses the liver)",
478 community(),
479 )
480 .targeting(
481 "digestive",
482 Effect::Supportive,
483 EvidenceTier::ClinicalEvidence, 80,
485 Kinetics::new(30, 2 * 60),
486 ),
487 );
488
489 kb
490}
491
492#[cfg(test)]
493mod tests {
494 use super::*;
495 use crate::anatomy::{Timeline, accumulate};
496
497 #[test]
498 fn content_hash_seals_and_detects_tampering() {
499 let mut e = FactorKnowledge::new(
500 "herb:x",
501 FactorKind::Herb,
502 "X",
503 Provenance {
504 source_id: "who-monographs".into(),
505 source_title: "WHO".into(),
506 citation: None,
507 imported_at: None,
508 },
509 )
510 .targeting(
511 "digestive",
512 Effect::Supportive,
513 EvidenceTier::TraditionalUse,
514 100,
515 Kinetics::CHRONIC,
516 )
517 .sealed();
518 assert!(e.integrity_ok());
519 e.targets[0].weight_milli = 999;
521 assert!(!e.integrity_ok());
522 }
523
524 #[test]
525 fn source_trust_ceiling_caps_overclaimed_evidence() {
526 let kb = seed_knowledge_base();
527 let hot_take = kb.get("tea:detox-claim").unwrap();
528 assert_eq!(
530 hot_take.targets[0].evidence,
531 EvidenceTier::CommunityAnecdotal
532 );
533 assert!(hot_take.integrity_ok(), "hash reflects the capped tier");
534 assert_eq!(
536 kb.get("herb:milk-thistle").unwrap().targets[0].evidence,
537 EvidenceTier::TraditionalUse
538 );
539 assert!(kb.verify_integrity().is_empty());
540 }
541
542 #[test]
543 fn import_condition_map_resolves_labels_and_warns_on_unknown() {
544 let json = r#"{
545 "conditions": {
546 "Hypertension": { "primarySystem": "Circulatory (Cardiovascular) System" },
547 "Made Up": { "primarySystem": "Imaginary System" }
548 }
549 }"#;
550 let prov = Provenance {
551 source_id: "clinical-reference".into(),
552 source_title: "condition-map".into(),
553 citation: None,
554 imported_at: None,
555 };
556 let res = import_condition_map(json, prov, &SystemRegistry::seed()).unwrap();
557 assert_eq!(res.entries.len(), 1);
558 assert_eq!(res.entries[0].key, "cond:hypertension");
559 assert_eq!(res.entries[0].targets[0].system_id, "circulatory");
560 assert!(res.entries[0].integrity_ok());
561 assert_eq!(
562 res.warnings.len(),
563 1,
564 "the imaginary system is reported, not silently dropped"
565 );
566 }
567
568 #[test]
569 fn condition_mapping_to_a_registered_extension_system_is_not_dropped() {
570 use super::super::model::SystemRepresentation;
571 use super::super::registry::{SystemDef, SystemProvenance, SystemTier};
572 let json =
576 r#"{ "conditions": { "Plantar Fasciitis": { "primarySystem": "Fascial System" } } }"#;
577 let prov = Provenance {
578 source_id: "clinical-reference".into(),
579 source_title: "condition-map".into(),
580 citation: None,
581 imported_at: None,
582 };
583
584 let seed_only = import_condition_map(json, prov.clone(), &SystemRegistry::seed()).unwrap();
586 assert!(seed_only.entries.is_empty());
587 assert_eq!(seed_only.warnings.len(), 1);
588
589 let mut reg = SystemRegistry::seed();
591 reg.register(SystemDef {
592 id: "fascial".into(),
593 label: "Fascial System".into(),
594 plain_label: "connective tissue".into(),
595 representation: SystemRepresentation::DistributedOverlay,
596 overlay_hosts: vec!["muscular".into(), "skeletal".into()],
597 color_rgba: [0.70, 0.78, 0.66, 1.0],
598 tier: SystemTier::CrossCutting,
599 parent: None,
600 relations: Vec::new(),
601 provenance: SystemProvenance::User,
602 });
603 let extended = import_condition_map(json, prov, ®).unwrap();
604 assert_eq!(
605 extended.entries.len(),
606 1,
607 "the registered system now resolves"
608 );
609 assert!(extended.warnings.is_empty());
610 assert_eq!(extended.entries[0].targets[0].system_id, "fascial");
611 }
612
613 #[test]
614 fn seed_entries_instantiate_and_flow_through_the_temporal_engine() {
615 let kb = seed_knowledge_base();
616 let beer = kb
618 .get("food:beer")
619 .unwrap()
620 .to_event("intake:beer-1", 0, 300);
621 let tl = Timeline::new().with_event(beer);
622 let dig = tl
623 .burden_at(60)
624 .into_iter()
625 .find(|b| b.system_id == "digestive")
626 .unwrap();
627 assert!(
628 dig.net_milli > 0,
629 "hepatic load present after the beer event"
630 );
631
632 let f = kb
634 .get("herb:milk-thistle")
635 .unwrap()
636 .to_factor("intake:mt-1");
637 let burdens = accumulate(&[f]);
638 assert!(
639 burdens
640 .iter()
641 .any(|b| b.system_id == "digestive" && b.supportive_milli > 0)
642 );
643 }
644
645 #[test]
646 fn import_entries_flags_a_tampered_hash() {
647 let good = seed_knowledge_base();
648 let entry = good.get("tea:chamomile").unwrap().clone();
649 let mut json_val = serde_json::to_value([&entry]).unwrap();
650 json_val[0]["content_hash"] = serde_json::Value::String("deadbeef".into());
652 let res = import_entries(&json_val.to_string()).unwrap();
653 assert_eq!(res.warnings.len(), 1);
654 assert!(res.entries[0].integrity_ok());
656 }
657}