Skip to main content

lean_ctx/core/
work_graph.rs

1//! Bounded Work Graph for multi-agent orchestration (P11 / DIM 4).
2//!
3//! Manages parent/child agent delegation with:
4//! - Budget inheritance (child cannot exceed parent)
5//! - Fan-out limits (max concurrent children)
6//! - Stop conditions (stale, over-budget, redundant)
7//! - Provenance tracking for attribution
8
9use std::collections::BTreeMap;
10
11use crate::core::a2a::budget_cascade::{
12    BudgetAllocation, CascadeError, cascade_budget, validate_cascade,
13};
14use serde::{Deserialize, Serialize};
15
16pub const WORK_GRAPH_SCHEMA_VERSION: u16 = 1;
17const MAX_GRAPH_NODES: usize = 256;
18const MAX_FAN_OUT: usize = 16;
19const MAX_DEPTH: u16 = 8;
20
21#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum NodeStatus {
24    Pending,
25    Active,
26    Completed,
27    Stopped,
28    Failed,
29}
30
31#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum StopReason {
34    BudgetExhausted,
35    Stale,
36    Redundant,
37    ParentStopped,
38    ManualStop,
39    DepthExceeded,
40    FanOutExceeded,
41}
42
43#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
44pub struct WorkNodeBudget {
45    pub tokens_allocated: u64,
46    pub tokens_consumed: u64,
47    pub cost_micros_allocated: u64,
48    pub cost_micros_consumed: u64,
49}
50
51impl WorkNodeBudget {
52    pub fn tokens_remaining(&self) -> u64 {
53        self.tokens_allocated.saturating_sub(self.tokens_consumed)
54    }
55
56    pub fn cost_remaining(&self) -> u64 {
57        self.cost_micros_allocated
58            .saturating_sub(self.cost_micros_consumed)
59    }
60
61    pub fn is_exhausted(&self) -> bool {
62        self.tokens_remaining() == 0 || self.cost_remaining() == 0
63    }
64}
65
66/// Tracks the total budget across an entire delegation chain.
67#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
68pub struct ChainBudget {
69    pub chain_id: String,
70    pub root_budget_tokens: u64,
71    pub total_consumed_tokens: u64,
72    pub total_allocated_tokens: u64,
73    pub depth: u16,
74}
75
76impl ChainBudget {
77    pub fn remaining(&self) -> u64 {
78        self.root_budget_tokens
79            .saturating_sub(self.total_consumed_tokens)
80    }
81
82    pub fn utilization_pct(&self) -> f64 {
83        if self.root_budget_tokens == 0 {
84            return 0.0;
85        }
86
87        (self.total_consumed_tokens as f64 / self.root_budget_tokens as f64) * 100.0
88    }
89}
90
91#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
92pub struct WorkNode {
93    pub node_id: String,
94    pub agent_id: String,
95    pub parent_node_id: Option<String>,
96    pub capsule_ref: String,
97    pub status: NodeStatus,
98    pub budget: WorkNodeBudget,
99    pub depth: u16,
100    pub stop_reason: Option<StopReason>,
101    pub outcome_ref: Option<String>,
102}
103
104/// Bounded, acyclic work graph with enforced fan-out and budget constraints.
105#[derive(Clone, Debug, Serialize, Deserialize)]
106pub struct BoundedWorkGraph {
107    nodes: BTreeMap<String, WorkNode>,
108    children: BTreeMap<String, Vec<String>>,
109    #[serde(default)]
110    chain_budgets: BTreeMap<String, ChainBudget>,
111    #[serde(default)]
112    pending_child_budgets: BTreeMap<String, WorkNodeBudget>,
113    max_fan_out: usize,
114    max_depth: u16,
115}
116
117impl Default for BoundedWorkGraph {
118    fn default() -> Self {
119        Self::new(MAX_FAN_OUT, MAX_DEPTH)
120    }
121}
122
123impl BoundedWorkGraph {
124    #[must_use]
125    pub fn new(max_fan_out: usize, max_depth: u16) -> Self {
126        Self {
127            nodes: BTreeMap::new(),
128            children: BTreeMap::new(),
129            chain_budgets: BTreeMap::new(),
130            pending_child_budgets: BTreeMap::new(),
131            max_fan_out: max_fan_out.clamp(1, MAX_FAN_OUT),
132            max_depth: max_depth.clamp(1, MAX_DEPTH),
133        }
134    }
135
136    /// Add a root node (no parent).
137    pub fn add_root(
138        &mut self,
139        node_id: String,
140        agent_id: String,
141        capsule_ref: String,
142        budget: WorkNodeBudget,
143    ) -> Result<&WorkNode, WorkGraphError> {
144        if self.nodes.len() >= MAX_GRAPH_NODES {
145            return Err(WorkGraphError::CapacityExceeded);
146        }
147        if self.nodes.contains_key(&node_id) {
148            return Err(WorkGraphError::DuplicateNode(node_id));
149        }
150        let node = WorkNode {
151            node_id: node_id.clone(),
152            agent_id,
153            parent_node_id: None,
154            capsule_ref,
155            status: NodeStatus::Active,
156            budget,
157            depth: 0,
158            stop_reason: None,
159            outcome_ref: None,
160        };
161        self.nodes.insert(node_id.clone(), node);
162        self.chain_budgets.insert(
163            node_id.clone(),
164            ChainBudget {
165                chain_id: node_id.clone(),
166                root_budget_tokens: self.nodes[&node_id].budget.tokens_allocated,
167                total_consumed_tokens: 0,
168                total_allocated_tokens: self.nodes[&node_id].budget.tokens_allocated,
169                depth: 0,
170            },
171        );
172        Ok(self.nodes.get(&node_id).expect("root node inserted above"))
173    }
174
175    /// Delegate work to a child node. Validates budget inheritance and fan-out.
176    pub fn delegate(
177        &mut self,
178        parent_node_id: &str,
179        child_node_id: String,
180        child_agent_id: String,
181        capsule_ref: String,
182        child_budget: WorkNodeBudget,
183    ) -> Result<&WorkNode, WorkGraphError> {
184        if self.nodes.len() >= MAX_GRAPH_NODES {
185            return Err(WorkGraphError::CapacityExceeded);
186        }
187        if self.nodes.contains_key(&child_node_id) {
188            return Err(WorkGraphError::DuplicateNode(child_node_id));
189        }
190        let parent = self
191            .nodes
192            .get(parent_node_id)
193            .ok_or_else(|| WorkGraphError::NodeNotFound(parent_node_id.to_string()))?;
194        if parent.status != NodeStatus::Active {
195            return Err(WorkGraphError::ParentNotActive(parent_node_id.to_string()));
196        }
197        let new_depth = parent.depth + 1;
198        if new_depth > self.max_depth {
199            return Err(WorkGraphError::DepthExceeded(self.max_depth));
200        }
201        if child_budget.tokens_allocated > parent.budget.tokens_remaining() {
202            return Err(WorkGraphError::BudgetExceedsParent {
203                child_requested: child_budget.tokens_allocated,
204                parent_remaining: parent.budget.tokens_remaining(),
205            });
206        }
207        if child_budget.cost_micros_allocated > parent.budget.cost_remaining() {
208            return Err(WorkGraphError::BudgetExceedsParent {
209                child_requested: child_budget.cost_micros_allocated,
210                parent_remaining: parent.budget.cost_remaining(),
211            });
212        }
213        let current_children = self.children.get(parent_node_id).map_or(0, Vec::len);
214        if current_children >= self.max_fan_out {
215            return Err(WorkGraphError::FanOutExceeded(self.max_fan_out));
216        }
217        let child_tokens_allocated = child_budget.tokens_allocated;
218        let node = WorkNode {
219            node_id: child_node_id.clone(),
220            agent_id: child_agent_id,
221            parent_node_id: Some(parent_node_id.to_string()),
222            capsule_ref,
223            status: NodeStatus::Active,
224            budget: child_budget,
225            depth: new_depth,
226            stop_reason: None,
227            outcome_ref: None,
228        };
229        self.nodes.insert(child_node_id.clone(), node);
230        self.children
231            .entry(parent_node_id.to_string())
232            .or_default()
233            .push(child_node_id.clone());
234        let chain_id = self
235            .chain_id_for_node(&child_node_id)
236            .expect("delegated child always has a root node");
237        let pending_tokens = self
238            .pending_child_budgets
239            .remove(&child_node_id)
240            .map_or(0, |budget| budget.tokens_allocated);
241        self.record_chain_allocation(&chain_id, pending_tokens, child_tokens_allocated, new_depth);
242        Ok(self
243            .nodes
244            .get(&child_node_id)
245            .expect("child node inserted above"))
246    }
247
248    /// Allocates budget for a child node using cascade rules.
249    ///
250    /// The returned budget is reserved for `child_id` until it is passed to
251    /// [`Self::delegate`], so chain allocation is not counted twice.
252    pub fn allocate_child_budget(
253        &mut self,
254        parent_id: &str,
255        child_id: &str,
256        fraction: f64,
257    ) -> Result<WorkNodeBudget, WorkGraphError> {
258        let (parent_budget_tokens, parent_used_tokens, parent_cost_remaining, parent_depth) = {
259            let parent = self
260                .nodes
261                .get(parent_id)
262                .ok_or_else(|| WorkGraphError::NodeNotFound(parent_id.to_string()))?;
263            if parent.status != NodeStatus::Active {
264                return Err(WorkGraphError::ParentNotActive(parent_id.to_string()));
265            }
266            (
267                parent.budget.tokens_allocated,
268                parent.budget.tokens_consumed,
269                parent.budget.cost_remaining(),
270                parent.depth,
271            )
272        };
273
274        let parent_remaining = parent_budget_tokens.saturating_sub(parent_used_tokens);
275        if parent_remaining == 0 {
276            return Err(WorkGraphError::BudgetExceedsParent {
277                child_requested: 1,
278                parent_remaining,
279            });
280        }
281
282        let allocation = BudgetAllocation {
283            parent_budget_tokens,
284            parent_used_tokens,
285            child_fraction: fraction,
286            minimum_budget: 0,
287            maximum_budget: parent_remaining,
288        };
289        let mut cascaded = cascade_budget(&allocation);
290        cascaded.depth = u32::from(parent_depth) + 1;
291        cascaded.lineage = self.node_lineage(parent_id);
292        cascaded.lineage.push(child_id.to_string());
293        validate_cascade(&cascaded)?;
294        if cascaded.allocated_tokens > parent_remaining {
295            return Err(WorkGraphError::BudgetExceedsParent {
296                child_requested: cascaded.allocated_tokens,
297                parent_remaining,
298            });
299        }
300
301        let cost_micros_allocated = if parent_cost_remaining == 0 {
302            0
303        } else {
304            ((parent_cost_remaining as f64 * fraction) as u64)
305                .max(1)
306                .min(parent_cost_remaining)
307        };
308        let child_budget = WorkNodeBudget {
309            tokens_allocated: cascaded.allocated_tokens,
310            tokens_consumed: 0,
311            cost_micros_allocated,
312            cost_micros_consumed: 0,
313        };
314        let chain_id = self
315            .chain_id_for_node(parent_id)
316            .expect("parent node always has a root node");
317        self.pending_child_budgets
318            .insert(child_id.to_string(), child_budget.clone());
319        self.record_chain_allocation(
320            &chain_id,
321            0,
322            child_budget.tokens_allocated,
323            parent_depth + 1,
324        );
325
326        Ok(child_budget)
327    }
328
329    /// Mark a node as completed with an outcome reference.
330    pub fn complete(&mut self, node_id: &str, outcome_ref: String) -> Result<(), WorkGraphError> {
331        let node = self
332            .nodes
333            .get_mut(node_id)
334            .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
335        if node.status != NodeStatus::Active {
336            return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
337        }
338        node.status = NodeStatus::Completed;
339        node.outcome_ref = Some(outcome_ref);
340        Ok(())
341    }
342
343    /// Stop a node and all its descendants (cascade).
344    pub fn stop(
345        &mut self,
346        node_id: &str,
347        reason: StopReason,
348    ) -> Result<Vec<String>, WorkGraphError> {
349        if !self.nodes.contains_key(node_id) {
350            return Err(WorkGraphError::NodeNotFound(node_id.to_string()));
351        }
352        let mut stopped = Vec::new();
353        self.stop_recursive(node_id, reason, &mut stopped);
354        Ok(stopped)
355    }
356
357    /// Record token consumption on a node.
358    pub fn consume_budget(
359        &mut self,
360        node_id: &str,
361        tokens: u64,
362        cost_micros: u64,
363    ) -> Result<bool, WorkGraphError> {
364        let exhausted = {
365            let node = self
366                .nodes
367                .get_mut(node_id)
368                .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
369            if node.status != NodeStatus::Active {
370                return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
371            }
372            node.budget.tokens_consumed = node.budget.tokens_consumed.saturating_add(tokens);
373            node.budget.cost_micros_consumed =
374                node.budget.cost_micros_consumed.saturating_add(cost_micros);
375            node.budget.is_exhausted()
376        };
377        let chain_id = self
378            .chain_id_for_node(node_id)
379            .expect("node always has a root node");
380        self.ensure_chain_budget(&chain_id);
381        let chain_exhausted = {
382            let chain = self
383                .chain_budgets
384                .get_mut(&chain_id)
385                .expect("chain budget initialized");
386            chain.total_consumed_tokens = chain.total_consumed_tokens.saturating_add(tokens);
387            chain.total_consumed_tokens >= chain.root_budget_tokens
388        };
389
390        if chain_exhausted {
391            self.stop_recursive(&chain_id, StopReason::BudgetExhausted, &mut Vec::new());
392            return Ok(true);
393        }
394        if exhausted {
395            let node = self.nodes.get_mut(node_id).expect("node checked above");
396            node.status = NodeStatus::Stopped;
397            node.stop_reason = Some(StopReason::BudgetExhausted);
398            return Ok(true);
399        }
400
401        Ok(false)
402    }
403
404    /// Records token consumption for a node and updates its chain budget.
405    pub fn consume_tokens(&mut self, node_id: &str, tokens: u64) -> Result<(), WorkGraphError> {
406        self.consume_budget(node_id, tokens, 0)?;
407        Ok(())
408    }
409
410    /// Returns the chain budget for a given node's chain.
411    pub fn chain_budget_for(&self, node_id: &str) -> Option<&ChainBudget> {
412        let chain_id = self.chain_id_for_node(node_id)?;
413        self.chain_budgets.get(&chain_id)
414    }
415
416    /// Returns all chains at or above their utilization threshold.
417    pub fn over_budget_chains(&self, threshold_pct: f64) -> Vec<&ChainBudget> {
418        self.chain_budgets
419            .values()
420            .filter(|budget| budget.utilization_pct() >= threshold_pct)
421            .collect()
422    }
423
424    /// Check all nodes for stop conditions and cascade.
425    pub fn enforce_stop_conditions(&mut self) -> Vec<(String, StopReason)> {
426        let exhausted: Vec<String> = self
427            .nodes
428            .iter()
429            .filter(|(_, n)| n.status == NodeStatus::Active && n.budget.is_exhausted())
430            .map(|(id, _)| id.clone())
431            .collect();
432        let mut stopped = Vec::new();
433        for node_id in exhausted {
434            let mut cascade = Vec::new();
435            self.stop_recursive(&node_id, StopReason::BudgetExhausted, &mut cascade);
436            for id in cascade {
437                stopped.push((id, StopReason::BudgetExhausted));
438            }
439        }
440        stopped
441    }
442
443    pub fn get_node(&self, node_id: &str) -> Option<&WorkNode> {
444        self.nodes.get(node_id)
445    }
446
447    pub fn children_of(&self, node_id: &str) -> &[String] {
448        self.children.get(node_id).map_or(&[], Vec::as_slice)
449    }
450
451    pub fn active_count(&self) -> usize {
452        self.nodes
453            .values()
454            .filter(|n| n.status == NodeStatus::Active)
455            .count()
456    }
457
458    pub fn total_count(&self) -> usize {
459        self.nodes.len()
460    }
461
462    #[allow(clippy::collapsible_if)]
463    fn stop_recursive(&mut self, node_id: &str, reason: StopReason, stopped: &mut Vec<String>) {
464        if let Some(node) = self.nodes.get_mut(node_id) {
465            if matches!(node.status, NodeStatus::Active | NodeStatus::Pending) {
466                node.status = NodeStatus::Stopped;
467                node.stop_reason = Some(reason);
468                stopped.push(node_id.to_string());
469            }
470        }
471        let children: Vec<String> = self.children.get(node_id).cloned().unwrap_or_default();
472        for child_id in children {
473            self.stop_recursive(&child_id, StopReason::ParentStopped, stopped);
474        }
475    }
476
477    fn chain_id_for_node(&self, node_id: &str) -> Option<String> {
478        let mut current_id = node_id;
479        let mut current = self.nodes.get(current_id)?;
480        while let Some(parent_id) = current.parent_node_id.as_deref() {
481            current_id = parent_id;
482            current = self.nodes.get(current_id)?;
483        }
484        Some(current_id.to_string())
485    }
486
487    fn node_lineage(&self, node_id: &str) -> Vec<String> {
488        let mut lineage = Vec::new();
489        let mut current_id = Some(node_id);
490        while let Some(id) = current_id {
491            let Some(node) = self.nodes.get(id) else {
492                break;
493            };
494            lineage.push(id.to_string());
495            current_id = node.parent_node_id.as_deref();
496        }
497        lineage.reverse();
498        lineage
499    }
500
501    fn ensure_chain_budget(&mut self, chain_id: &str) {
502        let root_budget_tokens = self
503            .nodes
504            .get(chain_id)
505            .map_or(0, |node| node.budget.tokens_allocated);
506        self.chain_budgets
507            .entry(chain_id.to_string())
508            .or_insert(ChainBudget {
509                chain_id: chain_id.to_string(),
510                root_budget_tokens,
511                total_consumed_tokens: 0,
512                total_allocated_tokens: root_budget_tokens,
513                depth: 0,
514            });
515    }
516
517    fn record_chain_allocation(
518        &mut self,
519        chain_id: &str,
520        previous_tokens: u64,
521        tokens_allocated: u64,
522        depth: u16,
523    ) {
524        self.ensure_chain_budget(chain_id);
525        let chain = self
526            .chain_budgets
527            .get_mut(chain_id)
528            .expect("chain budget initialized");
529        chain.total_allocated_tokens = chain
530            .total_allocated_tokens
531            .saturating_sub(previous_tokens)
532            .saturating_add(tokens_allocated);
533        chain.depth = chain.depth.max(depth);
534    }
535}
536
537// ─── Errors ──────────────────────────────────────────────────────────────────
538
539#[derive(Debug, thiserror::Error)]
540pub enum WorkGraphError {
541    #[error("graph at capacity ({MAX_GRAPH_NODES} nodes)")]
542    CapacityExceeded,
543    #[error("duplicate node: {0}")]
544    DuplicateNode(String),
545    #[error("node not found: {0}")]
546    NodeNotFound(String),
547    #[error("parent not active: {0}")]
548    ParentNotActive(String),
549    #[error("depth exceeds max {0}")]
550    DepthExceeded(u16),
551    #[error("fan-out exceeds max {0}")]
552    FanOutExceeded(usize),
553    #[error("child budget ({child_requested}) exceeds parent remaining ({parent_remaining})")]
554    BudgetExceedsParent {
555        child_requested: u64,
556        parent_remaining: u64,
557    },
558    #[error("invalid status transition for node: {0}")]
559    InvalidTransition(String),
560    #[error("budget cascade error: {0}")]
561    Cascade(#[from] CascadeError),
562}
563
564// ─── Tests ───────────────────────────────────────────────────────────────────
565
566#[cfg(test)]
567pub mod tests {
568    use crate::core::work_graph::{
569        BoundedWorkGraph, MAX_DEPTH, MAX_FAN_OUT, NodeStatus, StopReason, WorkGraphError,
570        WorkNodeBudget,
571    };
572
573    fn budget(tokens: u64, cost: u64) -> WorkNodeBudget {
574        WorkNodeBudget {
575            tokens_allocated: tokens,
576            tokens_consumed: 0,
577            cost_micros_allocated: cost,
578            cost_micros_consumed: 0,
579        }
580    }
581
582    #[test]
583    fn basic_delegation_and_budget_inheritance() {
584        let mut g = BoundedWorkGraph::default();
585        g.add_root(
586            "root".into(),
587            "parent-agent".into(),
588            "capsule:abc".into(),
589            budget(1000, 500),
590        )
591        .unwrap();
592        g.delegate(
593            "root",
594            "child-1".into(),
595            "child-agent".into(),
596            "capsule:def".into(),
597            budget(400, 200),
598        )
599        .unwrap();
600        assert_eq!(g.active_count(), 2);
601        assert_eq!(g.children_of("root"), &["child-1"]);
602    }
603
604    #[test]
605    fn child_cannot_exceed_parent_budget() {
606        let mut g = BoundedWorkGraph::default();
607        g.add_root(
608            "root".into(),
609            "a".into(),
610            "capsule:x".into(),
611            budget(100, 50),
612        )
613        .unwrap();
614        assert!(matches!(
615            g.delegate(
616                "root",
617                "c".into(),
618                "b".into(),
619                "capsule:y".into(),
620                budget(200, 30)
621            ),
622            Err(WorkGraphError::BudgetExceedsParent { .. })
623        ));
624    }
625
626    #[test]
627    fn fan_out_limit_enforced() {
628        let mut g = BoundedWorkGraph::new(2, MAX_DEPTH);
629        g.add_root(
630            "root".into(),
631            "a".into(),
632            "capsule:x".into(),
633            budget(1000, 1000),
634        )
635        .unwrap();
636        g.delegate(
637            "root",
638            "c1".into(),
639            "b".into(),
640            "capsule:1".into(),
641            budget(100, 100),
642        )
643        .unwrap();
644        g.delegate(
645            "root",
646            "c2".into(),
647            "b".into(),
648            "capsule:2".into(),
649            budget(100, 100),
650        )
651        .unwrap();
652        assert!(matches!(
653            g.delegate(
654                "root",
655                "c3".into(),
656                "b".into(),
657                "capsule:3".into(),
658                budget(100, 100)
659            ),
660            Err(WorkGraphError::FanOutExceeded(2))
661        ));
662    }
663
664    #[test]
665    fn depth_limit_enforced() {
666        let mut g = BoundedWorkGraph::new(MAX_FAN_OUT, 2);
667        g.add_root(
668            "n0".into(),
669            "a".into(),
670            "capsule:0".into(),
671            budget(1000, 1000),
672        )
673        .unwrap();
674        g.delegate(
675            "n0",
676            "n1".into(),
677            "b".into(),
678            "capsule:1".into(),
679            budget(500, 500),
680        )
681        .unwrap();
682        g.delegate(
683            "n1",
684            "n2".into(),
685            "c".into(),
686            "capsule:2".into(),
687            budget(200, 200),
688        )
689        .unwrap();
690        assert!(matches!(
691            g.delegate(
692                "n2",
693                "n3".into(),
694                "d".into(),
695                "capsule:3".into(),
696                budget(100, 100)
697            ),
698            Err(WorkGraphError::DepthExceeded(2))
699        ));
700    }
701
702    #[test]
703    fn stop_cascades_to_children() {
704        let mut g = BoundedWorkGraph::default();
705        g.add_root(
706            "root".into(),
707            "a".into(),
708            "capsule:r".into(),
709            budget(1000, 1000),
710        )
711        .unwrap();
712        g.delegate(
713            "root",
714            "c1".into(),
715            "b".into(),
716            "capsule:1".into(),
717            budget(300, 300),
718        )
719        .unwrap();
720        g.delegate(
721            "c1",
722            "gc1".into(),
723            "c".into(),
724            "capsule:gc".into(),
725            budget(100, 100),
726        )
727        .unwrap();
728        let stopped = g.stop("c1", StopReason::Stale).unwrap();
729        assert_eq!(stopped, vec!["c1", "gc1"]);
730        assert_eq!(g.get_node("c1").unwrap().status, NodeStatus::Stopped);
731        assert_eq!(
732            g.get_node("gc1").unwrap().stop_reason,
733            Some(StopReason::ParentStopped)
734        );
735    }
736
737    #[test]
738    fn budget_exhaustion_auto_stops() {
739        let mut g = BoundedWorkGraph::default();
740        g.add_root(
741            "root".into(),
742            "a".into(),
743            "capsule:r".into(),
744            budget(100, 100),
745        )
746        .unwrap();
747        let exhausted = g.consume_budget("root", 100, 50).unwrap();
748        assert!(exhausted);
749        assert_eq!(g.get_node("root").unwrap().status, NodeStatus::Stopped);
750    }
751
752    #[test]
753    fn allocate_child_budget_uses_requested_fraction() {
754        let mut g = BoundedWorkGraph::default();
755        g.add_root(
756            "root".into(),
757            "a".into(),
758            "capsule:r".into(),
759            budget(10_000, 5_000),
760        )
761        .unwrap();
762
763        let child_budget = g.allocate_child_budget("root", "child", 0.5).unwrap();
764
765        assert_eq!(child_budget, budget(5_000, 2_500));
766        let chain = g.chain_budget_for("root").unwrap();
767        assert_eq!(chain.total_allocated_tokens, 15_000);
768        assert_eq!(chain.depth, 1);
769    }
770
771    #[test]
772    fn allocate_child_budget_rejects_exhausted_parent() {
773        let mut g = BoundedWorkGraph::default();
774        g.add_root(
775            "root".into(),
776            "a".into(),
777            "capsule:r".into(),
778            budget(100, 100),
779        )
780        .unwrap();
781        g.consume_tokens("root", 100).unwrap();
782
783        assert!(g.allocate_child_budget("root", "child", 0.5).is_err());
784    }
785
786    #[test]
787    fn consume_tokens_updates_node_and_chain() {
788        let mut g = BoundedWorkGraph::default();
789        g.add_root(
790            "root".into(),
791            "a".into(),
792            "capsule:r".into(),
793            budget(1_000, 1_000),
794        )
795        .unwrap();
796
797        g.consume_tokens("root", 250).unwrap();
798
799        assert_eq!(g.get_node("root").unwrap().budget.tokens_consumed, 250);
800        assert_eq!(
801            g.chain_budget_for("root").unwrap().total_consumed_tokens,
802            250
803        );
804    }
805
806    #[test]
807    fn consume_tokens_stops_exhausted_node() {
808        let mut g = BoundedWorkGraph::default();
809        g.add_root(
810            "root".into(),
811            "a".into(),
812            "capsule:r".into(),
813            budget(100, 100),
814        )
815        .unwrap();
816
817        g.consume_tokens("root", 100).unwrap();
818
819        let node = g.get_node("root").unwrap();
820        assert_eq!(node.status, NodeStatus::Stopped);
821        assert_eq!(node.stop_reason, Some(StopReason::BudgetExhausted));
822    }
823
824    #[test]
825    fn over_budget_chains_returns_chains_above_threshold() {
826        let mut g = BoundedWorkGraph::default();
827        g.add_root(
828            "first".into(),
829            "a".into(),
830            "capsule:first".into(),
831            budget(1_000, 1_000),
832        )
833        .unwrap();
834        g.add_root(
835            "second".into(),
836            "b".into(),
837            "capsule:second".into(),
838            budget(1_000, 1_000),
839        )
840        .unwrap();
841        g.consume_tokens("first", 750).unwrap();
842
843        let over_budget = g.over_budget_chains(70.0);
844
845        assert_eq!(over_budget.len(), 1);
846        assert_eq!(over_budget[0].chain_id, "first");
847    }
848
849    #[test]
850    fn complete_sets_outcome() {
851        let mut g = BoundedWorkGraph::default();
852        g.add_root(
853            "root".into(),
854            "a".into(),
855            "capsule:r".into(),
856            budget(1000, 1000),
857        )
858        .unwrap();
859        g.complete("root", "outcome:success".into()).unwrap();
860        let node = g.get_node("root").unwrap();
861        assert_eq!(node.status, NodeStatus::Completed);
862        assert_eq!(node.outcome_ref.as_deref(), Some("outcome:success"));
863    }
864}