Skip to main content

omega_cognitive_kernel/goals/
tree.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use alloc::collections::{BTreeMap, BTreeSet};
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum GoalStatus {
10    Active,
11    Achieved,
12    Suspended,
13    Failed,
14}
15
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17pub struct GoalNode {
18    pub id: String,
19    pub targets: BTreeMap<String, f64>,
20    pub weight: f64,
21    pub priority: i32,
22    pub status: GoalStatus,
23    pub progress: f64,
24    pub parent_id: Option<String>,
25    pub children: Vec<String>,
26}
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct GoalTreeSummary {
30    pub total_nodes: usize,
31    pub achieved_nodes: usize,
32    pub active_id: Option<String>,
33    pub root_progress: f64,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
37pub struct GoalTree {
38    pub nodes: BTreeMap<String, GoalNode>,
39    pub root_id: Option<String>,
40    pub active_id: Option<String>,
41}
42
43impl GoalTree {
44    pub fn new() -> Self {
45        Self::default()
46    }
47
48    pub fn from_flat(targets: BTreeMap<String, f64>) -> Self {
49        let mut tree = Self::new();
50        tree.add_root("root", targets, 1);
51        tree
52    }
53
54    pub fn to_flat(&self) -> BTreeMap<String, f64> {
55        self.active_id
56            .as_ref()
57            .and_then(|id| self.nodes.get(id))
58            .map(|node| node.targets.clone())
59            .or_else(|| {
60                self.root_id
61                    .as_ref()
62                    .and_then(|id| self.nodes.get(id))
63                    .map(|node| node.targets.clone())
64            })
65            .unwrap_or_default()
66    }
67
68    pub fn add_root(
69        &mut self,
70        id: impl Into<String>,
71        targets: BTreeMap<String, f64>,
72        priority: i32,
73    ) {
74        let id_str = id.into();
75        let node = GoalNode {
76            id: id_str.clone(),
77            targets,
78            weight: 1.0,
79            priority,
80            status: GoalStatus::Active,
81            progress: 0.0,
82            parent_id: None,
83            children: Vec::new(),
84        };
85        self.nodes.insert(id_str.clone(), node);
86        self.root_id = Some(id_str.clone());
87        if self.active_id.is_none() {
88            self.active_id = Some(id_str);
89        }
90    }
91
92    pub fn add_child(
93        &mut self,
94        parent_id: &str,
95        id: impl Into<String>,
96        targets: BTreeMap<String, f64>,
97        weight: f64,
98        priority: i32,
99    ) -> bool {
100        if !self.nodes.contains_key(parent_id) {
101            return false;
102        }
103        let child_id = id.into();
104        if self.nodes.contains_key(&child_id) {
105            return false;
106        }
107        let node = GoalNode {
108            id: child_id.clone(),
109            targets,
110            weight: if weight.is_finite() && weight > 0.0 {
111                weight
112            } else {
113                1.0
114            },
115            priority,
116            status: GoalStatus::Active,
117            progress: 0.0,
118            parent_id: Some(parent_id.to_string()),
119            children: Vec::new(),
120        };
121        self.nodes.insert(child_id.clone(), node);
122        if let Some(parent) = self.nodes.get_mut(parent_id) {
123            if !parent.children.iter().any(|c| c == &child_id) {
124                parent.children.push(child_id);
125            }
126        }
127        true
128    }
129
130    pub fn update_from_state(&mut self, state: &BTreeMap<String, f64>, tolerance: f64) {
131        let tol = if tolerance.is_finite() && tolerance > 0.0 {
132            tolerance
133        } else {
134            0.05
135        };
136        let leaf_ids: Vec<String> = self
137            .nodes
138            .iter()
139            .filter(|(_, n)| n.children.is_empty())
140            .map(|(id, _)| id.clone())
141            .collect();
142
143        for id in leaf_ids {
144            if let Some(node) = self.nodes.get_mut(&id) {
145                if node.targets.is_empty() {
146                    continue;
147                }
148                let mut total_dist = 0.0;
149                for (k, target) in &node.targets {
150                    let cur = state.get(k).copied().unwrap_or(0.0);
151                    total_dist += libm::fabs(cur - target);
152                }
153                let mean_dist = total_dist / node.targets.len() as f64;
154                let prog = (1.0 - mean_dist).clamp(0.0, 1.0);
155                node.progress = prog;
156                if mean_dist <= tol && node.status == GoalStatus::Active {
157                    node.status = GoalStatus::Achieved;
158                }
159            }
160        }
161
162        if let Some(root) = self.root_id.clone() {
163            self.rollup_node(&root);
164        }
165    }
166
167    fn rollup_node(&mut self, id: &str) -> f64 {
168        // Use an explicit post-order stack so a valid, deeply nested goal tree
169        // cannot exhaust the call stack. The visited set also bounds traversal
170        // if a deserialized or directly-mutated tree contains malformed links.
171        let mut stack = vec![(id.to_string(), false)];
172        let mut scheduled = BTreeSet::new();
173
174        while let Some((node_id, expanded)) = stack.pop() {
175            if expanded {
176                let children = self
177                    .nodes
178                    .get(&node_id)
179                    .map(|node| node.children.clone())
180                    .unwrap_or_default();
181                let mut weighted_sum = 0.0;
182                let mut weight_total = 0.0;
183                let mut all_achieved = true;
184                for child_id in &children {
185                    if let Some(child) = self.nodes.get(child_id) {
186                        weighted_sum += child.progress * child.weight;
187                        weight_total += child.weight;
188                        if child.status != GoalStatus::Achieved {
189                            all_achieved = false;
190                        }
191                    }
192                }
193                let progress = if weight_total > 0.0 {
194                    (weighted_sum / weight_total).clamp(0.0, 1.0)
195                } else {
196                    0.0
197                };
198                if let Some(node) = self.nodes.get_mut(&node_id) {
199                    node.progress = progress;
200                    if all_achieved && node.status == GoalStatus::Active {
201                        node.status = GoalStatus::Achieved;
202                    }
203                }
204                continue;
205            }
206
207            if !scheduled.insert(node_id.clone()) {
208                continue;
209            }
210            let children = match self.nodes.get(&node_id) {
211                Some(node) if !node.children.is_empty() => node.children.clone(),
212                _ => continue,
213            };
214            stack.push((node_id, true));
215            for child_id in children.into_iter().rev() {
216                if !scheduled.contains(&child_id) {
217                    stack.push((child_id, false));
218                }
219            }
220        }
221
222        self.nodes.get(id).map(|node| node.progress).unwrap_or(0.0)
223    }
224
225    pub fn select_active(&mut self) -> Option<&GoalNode> {
226        let best_id = self
227            .nodes
228            .values()
229            .filter(|n| n.status == GoalStatus::Active && n.children.is_empty())
230            .max_by(|a, b| {
231                a.priority
232                    .cmp(&b.priority)
233                    .then_with(|| b.progress.total_cmp(&a.progress))
234            })
235            .map(|n| n.id.clone());
236
237        self.active_id = best_id;
238        self.active_id.as_ref().and_then(|id| self.nodes.get(id))
239    }
240
241    pub fn summary(&self) -> GoalTreeSummary {
242        let achieved_nodes = self
243            .nodes
244            .values()
245            .filter(|n| n.status == GoalStatus::Achieved)
246            .count();
247        let root_progress = self
248            .root_id
249            .as_ref()
250            .and_then(|id| self.nodes.get(id))
251            .map(|n| n.progress)
252            .unwrap_or(0.0);
253        GoalTreeSummary {
254            total_nodes: self.nodes.len(),
255            achieved_nodes,
256            active_id: self.active_id.clone(),
257            root_progress,
258        }
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn select_active_clears_active_id_when_all_leaves_are_achieved() {
268        let mut tree = GoalTree::new();
269        tree.add_root("root", BTreeMap::new(), 1);
270        assert!(tree.add_child("root", "first", BTreeMap::new(), 1.0, 10));
271        assert!(tree.add_child("root", "second", BTreeMap::new(), 1.0, 5));
272
273        assert!(tree.select_active().is_some());
274        assert!(tree.active_id.is_some());
275        for node in tree
276            .nodes
277            .values_mut()
278            .filter(|node| node.children.is_empty())
279        {
280            node.status = GoalStatus::Achieved;
281        }
282
283        assert!(tree.select_active().is_none());
284        assert_eq!(tree.active_id, None);
285    }
286
287    #[test]
288    fn hierarchical_rollup_and_active_selection() {
289        let mut tree = GoalTree::new();
290        tree.add_root("root", BTreeMap::new(), 1);
291
292        let mut t1 = BTreeMap::new();
293        t1.insert("x".into(), 1.0);
294        assert!(tree.add_child("root", "sub1", t1, 1.0, 10));
295
296        let mut t2 = BTreeMap::new();
297        t2.insert("y".into(), 1.0);
298        assert!(tree.add_child("root", "sub2", t2, 1.0, 5));
299
300        let mut state = BTreeMap::new();
301        state.insert("x".into(), 1.0);
302        state.insert("y".into(), 0.0);
303        tree.update_from_state(&state, 0.05);
304
305        assert_eq!(tree.nodes["sub1"].status, GoalStatus::Achieved);
306        assert_eq!(tree.nodes["sub2"].status, GoalStatus::Active);
307        assert!((tree.summary().root_progress - 0.5).abs() < 1e-9);
308        assert_eq!(tree.select_active().map(|n| n.id.as_str()), Some("sub2"));
309    }
310
311    #[test]
312    fn add_child_rejects_duplicate_ids_and_cycles_without_mutating_tree() {
313        let mut tree = GoalTree::new();
314        tree.add_root("root", BTreeMap::new(), 1);
315        assert!(tree.add_child("root", "branch", BTreeMap::new(), 1.0, 1));
316        assert!(tree.add_child("branch", "leaf", BTreeMap::new(), 1.0, 1));
317
318        let original = tree.clone();
319        let state = BTreeMap::new();
320        for (parent_id, duplicate_id) in [
321            ("root", "leaf"),   // duplicate ID from a different branch depth
322            ("leaf", "leaf"),   // self-cycle
323            ("root", "root"),   // root as its own child
324            ("leaf", "root"),   // root/ancestor cycle
325            ("leaf", "branch"), // ancestor cycle
326        ] {
327            assert!(!tree.add_child(parent_id, duplicate_id, BTreeMap::new(), 1.0, 1,));
328            assert_eq!(tree, original);
329            tree.update_from_state(&state, 0.05);
330            assert_eq!(tree, original);
331        }
332    }
333
334    #[test]
335    fn deep_goal_tree_rollup_does_not_use_call_stack() {
336        let mut tree = GoalTree::new();
337        tree.add_root("root", BTreeMap::new(), 1);
338        let depth = 4_096;
339        for index in 0..depth {
340            let parent = if index == 0 {
341                "root".to_string()
342            } else {
343                format!("node-{}", index - 1)
344            };
345            let targets = if index + 1 == depth {
346                BTreeMap::from([("x".to_string(), 1.0)])
347            } else {
348                BTreeMap::new()
349            };
350            assert!(tree.add_child(&parent, format!("node-{index}"), targets, 1.0, 1));
351        }
352
353        let state = BTreeMap::from([("x".to_string(), 1.0)]);
354        let result = std::thread::Builder::new()
355            .stack_size(64 * 1024)
356            .spawn(move || {
357                tree.update_from_state(&state, 0.05);
358                (tree.summary().root_progress, tree.nodes["root"].status)
359            })
360            .expect("spawn small-stack test thread")
361            .join()
362            .expect("deep tree rollup must not overflow the call stack");
363
364        assert_eq!(result.0, 1.0);
365        assert_eq!(result.1, GoalStatus::Achieved);
366    }
367
368    #[test]
369    fn rollup_terminates_for_malformed_child_links() {
370        let mut tree = GoalTree::new();
371        tree.add_root("root", BTreeMap::new(), 1);
372        assert!(tree.add_child("root", "child", BTreeMap::new(), 1.0, 1));
373        tree.nodes
374            .get_mut("child")
375            .unwrap()
376            .children
377            .push("root".into());
378        tree.nodes
379            .get_mut("root")
380            .unwrap()
381            .children
382            .push("missing".into());
383
384        tree.update_from_state(&BTreeMap::new(), 0.05);
385
386        assert_eq!(tree.nodes["root"].progress, 0.0);
387        assert_eq!(tree.nodes["child"].progress, 0.0);
388    }
389}