omega_cognitive_kernel/memory/
strategy.rs1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use crate::types::Trajectory;
5use alloc::collections::BTreeMap;
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct Strategy {
11 pub name: String,
13 pub weight: f64,
15 pub success_count: u32,
17 pub fail_count: u32,
19 #[serde(default)]
21 pub idle_steps: u32,
22}
23
24#[derive(Debug, Clone, Default, Serialize, Deserialize)]
26pub struct StrategyStats {
27 pub strategy_count: usize,
29 pub idle_count: usize,
31 pub mean_weight: f64,
33 pub mean_idle_steps: f64,
35 pub max_idle_steps: u32,
37 pub mean_idle_weight: f64,
39 pub mean_active_weight: f64,
41}
42
43#[derive(Debug, Default)]
44pub struct StrategyMemory {
46 strategies: BTreeMap<String, Strategy>,
47}
48
49impl StrategyMemory {
50 pub fn absorb(&mut self, traj: &Trajectory) {
52 for s in self.strategies.values_mut() {
53 s.idle_steps = s.idle_steps.saturating_add(1);
54 }
55
56 let success = traj.prediction_errors.iter().all(|&e| e < 0.4);
57 let key = if traj.actions.is_empty() {
58 "noop".to_string()
59 } else {
60 traj.actions[0].name.clone()
61 };
62 self.bump(&key, success);
63 }
64
65 pub fn absorb_reward(&mut self, action: &str, reward: f64) {
67 let success = reward >= 0.5;
68 self.bump(action, success);
69 let entry = self
70 .strategies
71 .entry(action.to_string())
72 .or_insert(Strategy {
73 name: action.to_string(),
74 weight: 1.0,
75 success_count: 0,
76 fail_count: 0,
77 idle_steps: 0,
78 });
79 let delta = (reward - 0.5) * 0.2;
80 entry.weight = (entry.weight + delta).clamp(0.1, 10.0);
81 entry.idle_steps = 0;
82 }
83
84 fn bump(&mut self, key: &str, success: bool) {
85 let entry = self.strategies.entry(key.to_string()).or_insert(Strategy {
86 name: key.to_string(),
87 weight: 1.0,
88 success_count: 0,
89 fail_count: 0,
90 idle_steps: 0,
91 });
92 entry.idle_steps = 0;
93 if success {
94 entry.success_count += 1;
95 entry.weight = (entry.weight * 1.05).min(10.0);
96 } else {
97 entry.fail_count += 1;
98 entry.weight = (entry.weight * 0.95).max(0.1);
99 }
100 }
101
102 pub fn set_weight(&mut self, name: &str, weight: f64) -> bool {
105 if let Some(s) = self.strategies.get_mut(name) {
106 s.weight = weight.clamp(0.1, 10.0);
107 s.idle_steps = 0;
108 true
109 } else {
110 false
111 }
112 }
113
114 pub fn decay_idle(&mut self, idle_threshold: u32, factor: f64) {
116 let factor = factor.clamp(0.5, 0.99);
117 for s in self.strategies.values_mut() {
118 if s.idle_steps >= idle_threshold {
119 s.weight = (s.weight * factor).max(0.1);
120 }
121 }
122 }
123
124 pub fn stats(&self, idle_threshold: u32) -> StrategyStats {
126 let n = self.strategies.len();
127 if n == 0 {
128 return StrategyStats::default();
129 }
130 let mut sum_w = 0.0;
131 let mut sum_idle = 0u64;
132 let mut max_idle = 0u32;
133 let mut idle_count = 0usize;
134 let mut sum_idle_w = 0.0;
135 let mut sum_active_w = 0.0;
136 let mut active_count = 0usize;
137
138 let mut ordered: Vec<_> = self.strategies.values().collect();
139 ordered.sort_unstable_by(|left, right| left.name.cmp(&right.name));
140 for s in ordered {
141 sum_w += s.weight;
142 sum_idle += s.idle_steps as u64;
143 max_idle = max_idle.max(s.idle_steps);
144 if s.idle_steps >= idle_threshold {
145 idle_count += 1;
146 sum_idle_w += s.weight;
147 } else {
148 active_count += 1;
149 sum_active_w += s.weight;
150 }
151 }
152
153 StrategyStats {
154 strategy_count: n,
155 idle_count,
156 mean_weight: sum_w / n as f64,
157 mean_idle_steps: sum_idle as f64 / n as f64,
158 max_idle_steps: max_idle,
159 mean_idle_weight: if idle_count == 0 {
160 0.0
161 } else {
162 sum_idle_w / idle_count as f64
163 },
164 mean_active_weight: if active_count == 0 {
165 0.0
166 } else {
167 sum_active_w / active_count as f64
168 },
169 }
170 }
171
172 pub fn retrieve(&self, _query: &str, k: usize) -> Vec<Strategy> {
174 let mut v: Vec<_> = self.strategies.values().cloned().collect();
175 v.sort_by(|a, b| {
176 b.weight
177 .partial_cmp(&a.weight)
178 .unwrap_or(core::cmp::Ordering::Equal)
179 .then_with(|| a.name.cmp(&b.name))
180 });
181 v.into_iter().take(k).collect()
182 }
183
184 pub fn snapshot(&self) -> BTreeMap<String, Strategy> {
186 self.strategies.clone()
187 }
188
189 pub fn restore(strategies: BTreeMap<String, Strategy>) -> Self {
191 Self { strategies }
192 }
193}
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198 use crate::types::{Action, Trajectory};
199 use alloc::collections::BTreeMap;
200
201 fn traj_with_action(name: &str, low_error: bool) -> Trajectory {
202 Trajectory {
203 observations: vec![],
204 predictions: vec![],
205 actions: vec![Action {
206 name: name.into(),
207 params: BTreeMap::new(),
208 constraints_checked: true,
209 }],
210 outcomes: vec![],
211 prediction_errors: if low_error { vec![0.1] } else { vec![0.8] },
212 meta: BTreeMap::new(),
213 }
214 }
215
216 #[test]
217 fn success_increases_weight() {
218 let mut sm = StrategyMemory::default();
219 sm.absorb(&traj_with_action("observe", true));
220 sm.absorb(&traj_with_action("observe", true));
221 let strategies = sm.retrieve("any", 5);
222 assert_eq!(strategies.len(), 1);
223 assert!(strategies[0].weight > 1.0);
224 assert_eq!(strategies[0].success_count, 2);
225 }
226
227 #[test]
228 fn failure_decreases_weight() {
229 let mut sm = StrategyMemory::default();
230 sm.absorb(&traj_with_action("risky", false));
231 let strategies = sm.retrieve("any", 5);
232 assert!(strategies[0].weight < 1.0);
233 assert_eq!(strategies[0].fail_count, 1);
234 }
235
236 #[test]
237 fn set_weight_clamps() {
238 let mut sm = StrategyMemory::default();
239 sm.absorb(&traj_with_action("observe", true));
240 assert!(sm.set_weight("observe", 99.0));
241 assert!((sm.retrieve("", 1)[0].weight - 10.0).abs() < 1e-9);
242 assert!(!sm.set_weight("missing", 1.0));
243 }
244
245 #[test]
246 fn idle_decay_lowers_unused_strategy() {
247 let mut sm = StrategyMemory::default();
248 sm.absorb(&traj_with_action("explore", true));
249 let before = sm.retrieve("any", 1)[0].weight;
250 for _ in 0..6 {
251 sm.absorb(&traj_with_action("observe", true));
252 }
253 sm.decay_idle(3, 0.9);
254 let explore = sm
255 .retrieve("any", 10)
256 .into_iter()
257 .find(|s| s.name == "explore")
258 .unwrap();
259 assert!(explore.weight < before);
260 }
261
262 #[test]
263 fn stats_reports_idle() {
264 let mut sm = StrategyMemory::default();
265 sm.absorb(&traj_with_action("explore", true));
266 for _ in 0..6 {
267 sm.absorb(&traj_with_action("observe", true));
268 }
269 let st = sm.stats(3);
270 assert!(st.strategy_count >= 2);
271 assert!(st.idle_count >= 1);
272 assert!(st.max_idle_steps >= 3);
273 }
274}