Skip to main content

omega_cognitive_kernel/l0/
predictor.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use crate::error::Result;
5use crate::types::{Observation, Prediction, RuleEffect};
6use hashbrown::HashMap;
7
8pub trait Predictor {
9    fn predict(
10        &self,
11        observations: &[Observation],
12        memory_ctx: &HashMap<String, serde_json::Value>,
13    ) -> Result<Vec<Prediction>>;
14}
15
16pub struct ModelBasedPredictor;
17
18impl ModelBasedPredictor {
19    fn effect_from_ctx(memory_ctx: &HashMap<String, serde_json::Value>) -> RuleEffect {
20        memory_ctx
21            .get("cognitive_effect")
22            .and_then(|v| serde_json::from_value::<RuleEffect>(v.clone()).ok())
23            .unwrap_or_default()
24    }
25
26    fn strategy_confidence(memory_ctx: &HashMap<String, serde_json::Value>) -> f64 {
27        let Some(strategies) = memory_ctx.get("strategies").and_then(|v| v.as_array()) else {
28            return 0.0;
29        };
30        if strategies.is_empty() {
31            return 0.0;
32        }
33        let best = strategies
34            .iter()
35            .filter_map(|s| s.get("weight").and_then(|w| w.as_f64()))
36            .fold(0.0_f64, f64::max);
37        ((best - 1.0) / 4.0).clamp(0.0, 1.0)
38    }
39
40    fn recent_case_error(memory_ctx: &HashMap<String, serde_json::Value>) -> f64 {
41        memory_ctx
42            .get("cases")
43            .and_then(|v| v.as_array())
44            .and_then(|arr| arr.first())
45            .and_then(|c| c.get("error_mean"))
46            .and_then(|e| e.as_f64())
47            .unwrap_or(0.5)
48    }
49}
50
51impl Predictor for ModelBasedPredictor {
52    fn predict(
53        &self,
54        observations: &[Observation],
55        memory_ctx: &HashMap<String, serde_json::Value>,
56    ) -> Result<Vec<Prediction>> {
57        let effect = Self::effect_from_ctx(memory_ctx);
58        let strat_conf = Self::strategy_confidence(memory_ctx);
59        let case_err = Self::recent_case_error(memory_ctx);
60
61        // Base uncertainty: starts elevated, reduced by strategy confidence.
62        let mut uncertainty = if observations.is_empty() {
63            0.85
64        } else {
65            0.55 + case_err * 0.35 - strat_conf * 0.25
66        };
67        uncertainty = uncertainty.clamp(0.15, 0.95);
68
69        // S1 consequence: committed RuleEffect actually lowers uncertainty.
70        uncertainty = (uncertainty * effect.error_damping).max(effect.min_uncertainty);
71
72        Ok(vec![Prediction {
73            expected: serde_json::json!({
74                "next": "stable",
75                "strategy_confidence": strat_conf,
76                "damping": effect.error_damping
77            }),
78            uncertainty,
79            horizon_secs: 1.0,
80        }])
81    }
82}