lean-ctx 3.9.13

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Bounded Work Graph for multi-agent orchestration (P11 / DIM 4).
//!
//! Manages parent/child agent delegation with:
//! - Budget inheritance (child cannot exceed parent)
//! - Fan-out limits (max concurrent children)
//! - Stop conditions (stale, over-budget, redundant)
//! - Provenance tracking for attribution

use std::collections::BTreeMap;

use crate::core::a2a::budget_cascade::{
    BudgetAllocation, CascadeError, cascade_budget, validate_cascade,
};
use serde::{Deserialize, Serialize};

pub const WORK_GRAPH_SCHEMA_VERSION: u16 = 1;
const MAX_GRAPH_NODES: usize = 256;
const MAX_FAN_OUT: usize = 16;
const MAX_DEPTH: u16 = 8;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NodeStatus {
    Pending,
    Active,
    Completed,
    Stopped,
    Failed,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
    BudgetExhausted,
    Stale,
    Redundant,
    ParentStopped,
    ManualStop,
    DepthExceeded,
    FanOutExceeded,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct WorkNodeBudget {
    pub tokens_allocated: u64,
    pub tokens_consumed: u64,
    pub cost_micros_allocated: u64,
    pub cost_micros_consumed: u64,
}

impl WorkNodeBudget {
    pub fn tokens_remaining(&self) -> u64 {
        self.tokens_allocated.saturating_sub(self.tokens_consumed)
    }

    pub fn cost_remaining(&self) -> u64 {
        self.cost_micros_allocated
            .saturating_sub(self.cost_micros_consumed)
    }

    pub fn is_exhausted(&self) -> bool {
        self.tokens_remaining() == 0 || self.cost_remaining() == 0
    }
}

/// Tracks the total budget across an entire delegation chain.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ChainBudget {
    pub chain_id: String,
    pub root_budget_tokens: u64,
    pub total_consumed_tokens: u64,
    pub total_allocated_tokens: u64,
    pub depth: u16,
}

impl ChainBudget {
    pub fn remaining(&self) -> u64 {
        self.root_budget_tokens
            .saturating_sub(self.total_consumed_tokens)
    }

    pub fn utilization_pct(&self) -> f64 {
        if self.root_budget_tokens == 0 {
            return 0.0;
        }

        (self.total_consumed_tokens as f64 / self.root_budget_tokens as f64) * 100.0
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct WorkNode {
    pub node_id: String,
    pub agent_id: String,
    pub parent_node_id: Option<String>,
    pub capsule_ref: String,
    pub status: NodeStatus,
    pub budget: WorkNodeBudget,
    pub depth: u16,
    pub stop_reason: Option<StopReason>,
    pub outcome_ref: Option<String>,
}

/// Bounded, acyclic work graph with enforced fan-out and budget constraints.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BoundedWorkGraph {
    nodes: BTreeMap<String, WorkNode>,
    children: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    chain_budgets: BTreeMap<String, ChainBudget>,
    #[serde(default)]
    pending_child_budgets: BTreeMap<String, WorkNodeBudget>,
    max_fan_out: usize,
    max_depth: u16,
}

impl Default for BoundedWorkGraph {
    fn default() -> Self {
        Self::new(MAX_FAN_OUT, MAX_DEPTH)
    }
}

impl BoundedWorkGraph {
    #[must_use]
    pub fn new(max_fan_out: usize, max_depth: u16) -> Self {
        Self {
            nodes: BTreeMap::new(),
            children: BTreeMap::new(),
            chain_budgets: BTreeMap::new(),
            pending_child_budgets: BTreeMap::new(),
            max_fan_out: max_fan_out.clamp(1, MAX_FAN_OUT),
            max_depth: max_depth.clamp(1, MAX_DEPTH),
        }
    }

    /// Add a root node (no parent).
    pub fn add_root(
        &mut self,
        node_id: String,
        agent_id: String,
        capsule_ref: String,
        budget: WorkNodeBudget,
    ) -> Result<&WorkNode, WorkGraphError> {
        if self.nodes.len() >= MAX_GRAPH_NODES {
            return Err(WorkGraphError::CapacityExceeded);
        }
        if self.nodes.contains_key(&node_id) {
            return Err(WorkGraphError::DuplicateNode(node_id));
        }
        let node = WorkNode {
            node_id: node_id.clone(),
            agent_id,
            parent_node_id: None,
            capsule_ref,
            status: NodeStatus::Active,
            budget,
            depth: 0,
            stop_reason: None,
            outcome_ref: None,
        };
        self.nodes.insert(node_id.clone(), node);
        self.chain_budgets.insert(
            node_id.clone(),
            ChainBudget {
                chain_id: node_id.clone(),
                root_budget_tokens: self.nodes[&node_id].budget.tokens_allocated,
                total_consumed_tokens: 0,
                total_allocated_tokens: self.nodes[&node_id].budget.tokens_allocated,
                depth: 0,
            },
        );
        Ok(self.nodes.get(&node_id).unwrap())
    }

    /// Delegate work to a child node. Validates budget inheritance and fan-out.
    pub fn delegate(
        &mut self,
        parent_node_id: &str,
        child_node_id: String,
        child_agent_id: String,
        capsule_ref: String,
        child_budget: WorkNodeBudget,
    ) -> Result<&WorkNode, WorkGraphError> {
        if self.nodes.len() >= MAX_GRAPH_NODES {
            return Err(WorkGraphError::CapacityExceeded);
        }
        if self.nodes.contains_key(&child_node_id) {
            return Err(WorkGraphError::DuplicateNode(child_node_id));
        }
        let parent = self
            .nodes
            .get(parent_node_id)
            .ok_or_else(|| WorkGraphError::NodeNotFound(parent_node_id.to_string()))?;
        if parent.status != NodeStatus::Active {
            return Err(WorkGraphError::ParentNotActive(parent_node_id.to_string()));
        }
        let new_depth = parent.depth + 1;
        if new_depth > self.max_depth {
            return Err(WorkGraphError::DepthExceeded(self.max_depth));
        }
        if child_budget.tokens_allocated > parent.budget.tokens_remaining() {
            return Err(WorkGraphError::BudgetExceedsParent {
                child_requested: child_budget.tokens_allocated,
                parent_remaining: parent.budget.tokens_remaining(),
            });
        }
        if child_budget.cost_micros_allocated > parent.budget.cost_remaining() {
            return Err(WorkGraphError::BudgetExceedsParent {
                child_requested: child_budget.cost_micros_allocated,
                parent_remaining: parent.budget.cost_remaining(),
            });
        }
        let current_children = self.children.get(parent_node_id).map_or(0, Vec::len);
        if current_children >= self.max_fan_out {
            return Err(WorkGraphError::FanOutExceeded(self.max_fan_out));
        }
        let child_tokens_allocated = child_budget.tokens_allocated;
        let node = WorkNode {
            node_id: child_node_id.clone(),
            agent_id: child_agent_id,
            parent_node_id: Some(parent_node_id.to_string()),
            capsule_ref,
            status: NodeStatus::Active,
            budget: child_budget,
            depth: new_depth,
            stop_reason: None,
            outcome_ref: None,
        };
        self.nodes.insert(child_node_id.clone(), node);
        self.children
            .entry(parent_node_id.to_string())
            .or_default()
            .push(child_node_id.clone());
        let chain_id = self
            .chain_id_for_node(&child_node_id)
            .expect("delegated child always has a root node");
        let pending_tokens = self
            .pending_child_budgets
            .remove(&child_node_id)
            .map_or(0, |budget| budget.tokens_allocated);
        self.record_chain_allocation(&chain_id, pending_tokens, child_tokens_allocated, new_depth);
        Ok(self.nodes.get(&child_node_id).unwrap())
    }

    /// Allocates budget for a child node using cascade rules.
    ///
    /// The returned budget is reserved for `child_id` until it is passed to
    /// [`Self::delegate`], so chain allocation is not counted twice.
    pub fn allocate_child_budget(
        &mut self,
        parent_id: &str,
        child_id: &str,
        fraction: f64,
    ) -> Result<WorkNodeBudget, WorkGraphError> {
        let (parent_budget_tokens, parent_used_tokens, parent_cost_remaining, parent_depth) = {
            let parent = self
                .nodes
                .get(parent_id)
                .ok_or_else(|| WorkGraphError::NodeNotFound(parent_id.to_string()))?;
            if parent.status != NodeStatus::Active {
                return Err(WorkGraphError::ParentNotActive(parent_id.to_string()));
            }
            (
                parent.budget.tokens_allocated,
                parent.budget.tokens_consumed,
                parent.budget.cost_remaining(),
                parent.depth,
            )
        };

        let parent_remaining = parent_budget_tokens.saturating_sub(parent_used_tokens);
        if parent_remaining == 0 {
            return Err(WorkGraphError::BudgetExceedsParent {
                child_requested: 1,
                parent_remaining,
            });
        }

        let allocation = BudgetAllocation {
            parent_budget_tokens,
            parent_used_tokens,
            child_fraction: fraction,
            minimum_budget: 0,
            maximum_budget: parent_remaining,
        };
        let mut cascaded = cascade_budget(&allocation);
        cascaded.depth = u32::from(parent_depth) + 1;
        cascaded.lineage = self.node_lineage(parent_id);
        cascaded.lineage.push(child_id.to_string());
        validate_cascade(&cascaded)?;
        if cascaded.allocated_tokens > parent_remaining {
            return Err(WorkGraphError::BudgetExceedsParent {
                child_requested: cascaded.allocated_tokens,
                parent_remaining,
            });
        }

        let cost_micros_allocated = if parent_cost_remaining == 0 {
            0
        } else {
            ((parent_cost_remaining as f64 * fraction) as u64)
                .max(1)
                .min(parent_cost_remaining)
        };
        let child_budget = WorkNodeBudget {
            tokens_allocated: cascaded.allocated_tokens,
            tokens_consumed: 0,
            cost_micros_allocated,
            cost_micros_consumed: 0,
        };
        let chain_id = self
            .chain_id_for_node(parent_id)
            .expect("parent node always has a root node");
        self.pending_child_budgets
            .insert(child_id.to_string(), child_budget.clone());
        self.record_chain_allocation(
            &chain_id,
            0,
            child_budget.tokens_allocated,
            parent_depth + 1,
        );

        Ok(child_budget)
    }

    /// Mark a node as completed with an outcome reference.
    pub fn complete(&mut self, node_id: &str, outcome_ref: String) -> Result<(), WorkGraphError> {
        let node = self
            .nodes
            .get_mut(node_id)
            .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
        if node.status != NodeStatus::Active {
            return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
        }
        node.status = NodeStatus::Completed;
        node.outcome_ref = Some(outcome_ref);
        Ok(())
    }

    /// Stop a node and all its descendants (cascade).
    pub fn stop(
        &mut self,
        node_id: &str,
        reason: StopReason,
    ) -> Result<Vec<String>, WorkGraphError> {
        if !self.nodes.contains_key(node_id) {
            return Err(WorkGraphError::NodeNotFound(node_id.to_string()));
        }
        let mut stopped = Vec::new();
        self.stop_recursive(node_id, reason, &mut stopped);
        Ok(stopped)
    }

    /// Record token consumption on a node.
    pub fn consume_budget(
        &mut self,
        node_id: &str,
        tokens: u64,
        cost_micros: u64,
    ) -> Result<bool, WorkGraphError> {
        let exhausted = {
            let node = self
                .nodes
                .get_mut(node_id)
                .ok_or_else(|| WorkGraphError::NodeNotFound(node_id.to_string()))?;
            if node.status != NodeStatus::Active {
                return Err(WorkGraphError::InvalidTransition(node_id.to_string()));
            }
            node.budget.tokens_consumed = node.budget.tokens_consumed.saturating_add(tokens);
            node.budget.cost_micros_consumed =
                node.budget.cost_micros_consumed.saturating_add(cost_micros);
            node.budget.is_exhausted()
        };
        let chain_id = self
            .chain_id_for_node(node_id)
            .expect("node always has a root node");
        self.ensure_chain_budget(&chain_id);
        let chain_exhausted = {
            let chain = self
                .chain_budgets
                .get_mut(&chain_id)
                .expect("chain budget initialized");
            chain.total_consumed_tokens = chain.total_consumed_tokens.saturating_add(tokens);
            chain.total_consumed_tokens >= chain.root_budget_tokens
        };

        if chain_exhausted {
            self.stop_recursive(&chain_id, StopReason::BudgetExhausted, &mut Vec::new());
            return Ok(true);
        }
        if exhausted {
            let node = self.nodes.get_mut(node_id).expect("node checked above");
            node.status = NodeStatus::Stopped;
            node.stop_reason = Some(StopReason::BudgetExhausted);
            return Ok(true);
        }

        Ok(false)
    }

    /// Records token consumption for a node and updates its chain budget.
    pub fn consume_tokens(&mut self, node_id: &str, tokens: u64) -> Result<(), WorkGraphError> {
        self.consume_budget(node_id, tokens, 0)?;
        Ok(())
    }

    /// Returns the chain budget for a given node's chain.
    pub fn chain_budget_for(&self, node_id: &str) -> Option<&ChainBudget> {
        let chain_id = self.chain_id_for_node(node_id)?;
        self.chain_budgets.get(&chain_id)
    }

    /// Returns all chains at or above their utilization threshold.
    pub fn over_budget_chains(&self, threshold_pct: f64) -> Vec<&ChainBudget> {
        self.chain_budgets
            .values()
            .filter(|budget| budget.utilization_pct() >= threshold_pct)
            .collect()
    }

    /// Check all nodes for stop conditions and cascade.
    pub fn enforce_stop_conditions(&mut self) -> Vec<(String, StopReason)> {
        let exhausted: Vec<String> = self
            .nodes
            .iter()
            .filter(|(_, n)| n.status == NodeStatus::Active && n.budget.is_exhausted())
            .map(|(id, _)| id.clone())
            .collect();
        let mut stopped = Vec::new();
        for node_id in exhausted {
            let mut cascade = Vec::new();
            self.stop_recursive(&node_id, StopReason::BudgetExhausted, &mut cascade);
            for id in cascade {
                stopped.push((id, StopReason::BudgetExhausted));
            }
        }
        stopped
    }

    pub fn get_node(&self, node_id: &str) -> Option<&WorkNode> {
        self.nodes.get(node_id)
    }

    pub fn children_of(&self, node_id: &str) -> &[String] {
        self.children.get(node_id).map_or(&[], Vec::as_slice)
    }

    pub fn active_count(&self) -> usize {
        self.nodes
            .values()
            .filter(|n| n.status == NodeStatus::Active)
            .count()
    }

    pub fn total_count(&self) -> usize {
        self.nodes.len()
    }

    #[allow(clippy::collapsible_if)]
    fn stop_recursive(&mut self, node_id: &str, reason: StopReason, stopped: &mut Vec<String>) {
        if let Some(node) = self.nodes.get_mut(node_id) {
            if matches!(node.status, NodeStatus::Active | NodeStatus::Pending) {
                node.status = NodeStatus::Stopped;
                node.stop_reason = Some(reason);
                stopped.push(node_id.to_string());
            }
        }
        let children: Vec<String> = self.children.get(node_id).cloned().unwrap_or_default();
        for child_id in children {
            self.stop_recursive(&child_id, StopReason::ParentStopped, stopped);
        }
    }

    fn chain_id_for_node(&self, node_id: &str) -> Option<String> {
        let mut current_id = node_id;
        let mut current = self.nodes.get(current_id)?;
        while let Some(parent_id) = current.parent_node_id.as_deref() {
            current_id = parent_id;
            current = self.nodes.get(current_id)?;
        }
        Some(current_id.to_string())
    }

    fn node_lineage(&self, node_id: &str) -> Vec<String> {
        let mut lineage = Vec::new();
        let mut current_id = Some(node_id);
        while let Some(id) = current_id {
            let Some(node) = self.nodes.get(id) else {
                break;
            };
            lineage.push(id.to_string());
            current_id = node.parent_node_id.as_deref();
        }
        lineage.reverse();
        lineage
    }

    fn ensure_chain_budget(&mut self, chain_id: &str) {
        let root_budget_tokens = self
            .nodes
            .get(chain_id)
            .map_or(0, |node| node.budget.tokens_allocated);
        self.chain_budgets
            .entry(chain_id.to_string())
            .or_insert(ChainBudget {
                chain_id: chain_id.to_string(),
                root_budget_tokens,
                total_consumed_tokens: 0,
                total_allocated_tokens: root_budget_tokens,
                depth: 0,
            });
    }

    fn record_chain_allocation(
        &mut self,
        chain_id: &str,
        previous_tokens: u64,
        tokens_allocated: u64,
        depth: u16,
    ) {
        self.ensure_chain_budget(chain_id);
        let chain = self
            .chain_budgets
            .get_mut(chain_id)
            .expect("chain budget initialized");
        chain.total_allocated_tokens = chain
            .total_allocated_tokens
            .saturating_sub(previous_tokens)
            .saturating_add(tokens_allocated);
        chain.depth = chain.depth.max(depth);
    }
}

// ─── Errors ──────────────────────────────────────────────────────────────────

#[derive(Debug, thiserror::Error)]
pub enum WorkGraphError {
    #[error("graph at capacity ({MAX_GRAPH_NODES} nodes)")]
    CapacityExceeded,
    #[error("duplicate node: {0}")]
    DuplicateNode(String),
    #[error("node not found: {0}")]
    NodeNotFound(String),
    #[error("parent not active: {0}")]
    ParentNotActive(String),
    #[error("depth exceeds max {0}")]
    DepthExceeded(u16),
    #[error("fan-out exceeds max {0}")]
    FanOutExceeded(usize),
    #[error("child budget ({child_requested}) exceeds parent remaining ({parent_remaining})")]
    BudgetExceedsParent {
        child_requested: u64,
        parent_remaining: u64,
    },
    #[error("invalid status transition for node: {0}")]
    InvalidTransition(String),
    #[error("budget cascade error: {0}")]
    Cascade(#[from] CascadeError),
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use crate::core::work_graph::{
        BoundedWorkGraph, MAX_DEPTH, MAX_FAN_OUT, NodeStatus, StopReason, WorkGraphError,
        WorkNodeBudget,
    };

    fn budget(tokens: u64, cost: u64) -> WorkNodeBudget {
        WorkNodeBudget {
            tokens_allocated: tokens,
            tokens_consumed: 0,
            cost_micros_allocated: cost,
            cost_micros_consumed: 0,
        }
    }

    #[test]
    fn basic_delegation_and_budget_inheritance() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "parent-agent".into(),
            "capsule:abc".into(),
            budget(1000, 500),
        )
        .unwrap();
        g.delegate(
            "root",
            "child-1".into(),
            "child-agent".into(),
            "capsule:def".into(),
            budget(400, 200),
        )
        .unwrap();
        assert_eq!(g.active_count(), 2);
        assert_eq!(g.children_of("root"), &["child-1"]);
    }

    #[test]
    fn child_cannot_exceed_parent_budget() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:x".into(),
            budget(100, 50),
        )
        .unwrap();
        assert!(matches!(
            g.delegate(
                "root",
                "c".into(),
                "b".into(),
                "capsule:y".into(),
                budget(200, 30)
            ),
            Err(WorkGraphError::BudgetExceedsParent { .. })
        ));
    }

    #[test]
    fn fan_out_limit_enforced() {
        let mut g = BoundedWorkGraph::new(2, MAX_DEPTH);
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:x".into(),
            budget(1000, 1000),
        )
        .unwrap();
        g.delegate(
            "root",
            "c1".into(),
            "b".into(),
            "capsule:1".into(),
            budget(100, 100),
        )
        .unwrap();
        g.delegate(
            "root",
            "c2".into(),
            "b".into(),
            "capsule:2".into(),
            budget(100, 100),
        )
        .unwrap();
        assert!(matches!(
            g.delegate(
                "root",
                "c3".into(),
                "b".into(),
                "capsule:3".into(),
                budget(100, 100)
            ),
            Err(WorkGraphError::FanOutExceeded(2))
        ));
    }

    #[test]
    fn depth_limit_enforced() {
        let mut g = BoundedWorkGraph::new(MAX_FAN_OUT, 2);
        g.add_root(
            "n0".into(),
            "a".into(),
            "capsule:0".into(),
            budget(1000, 1000),
        )
        .unwrap();
        g.delegate(
            "n0",
            "n1".into(),
            "b".into(),
            "capsule:1".into(),
            budget(500, 500),
        )
        .unwrap();
        g.delegate(
            "n1",
            "n2".into(),
            "c".into(),
            "capsule:2".into(),
            budget(200, 200),
        )
        .unwrap();
        assert!(matches!(
            g.delegate(
                "n2",
                "n3".into(),
                "d".into(),
                "capsule:3".into(),
                budget(100, 100)
            ),
            Err(WorkGraphError::DepthExceeded(2))
        ));
    }

    #[test]
    fn stop_cascades_to_children() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:r".into(),
            budget(1000, 1000),
        )
        .unwrap();
        g.delegate(
            "root",
            "c1".into(),
            "b".into(),
            "capsule:1".into(),
            budget(300, 300),
        )
        .unwrap();
        g.delegate(
            "c1",
            "gc1".into(),
            "c".into(),
            "capsule:gc".into(),
            budget(100, 100),
        )
        .unwrap();
        let stopped = g.stop("c1", StopReason::Stale).unwrap();
        assert_eq!(stopped, vec!["c1", "gc1"]);
        assert_eq!(g.get_node("c1").unwrap().status, NodeStatus::Stopped);
        assert_eq!(
            g.get_node("gc1").unwrap().stop_reason,
            Some(StopReason::ParentStopped)
        );
    }

    #[test]
    fn budget_exhaustion_auto_stops() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:r".into(),
            budget(100, 100),
        )
        .unwrap();
        let exhausted = g.consume_budget("root", 100, 50).unwrap();
        assert!(exhausted);
        assert_eq!(g.get_node("root").unwrap().status, NodeStatus::Stopped);
    }

    #[test]
    fn allocate_child_budget_uses_requested_fraction() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:r".into(),
            budget(10_000, 5_000),
        )
        .unwrap();

        let child_budget = g.allocate_child_budget("root", "child", 0.5).unwrap();

        assert_eq!(child_budget, budget(5_000, 2_500));
        let chain = g.chain_budget_for("root").unwrap();
        assert_eq!(chain.total_allocated_tokens, 15_000);
        assert_eq!(chain.depth, 1);
    }

    #[test]
    fn allocate_child_budget_rejects_exhausted_parent() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:r".into(),
            budget(100, 100),
        )
        .unwrap();
        g.consume_tokens("root", 100).unwrap();

        assert!(g.allocate_child_budget("root", "child", 0.5).is_err());
    }

    #[test]
    fn consume_tokens_updates_node_and_chain() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:r".into(),
            budget(1_000, 1_000),
        )
        .unwrap();

        g.consume_tokens("root", 250).unwrap();

        assert_eq!(g.get_node("root").unwrap().budget.tokens_consumed, 250);
        assert_eq!(
            g.chain_budget_for("root").unwrap().total_consumed_tokens,
            250
        );
    }

    #[test]
    fn consume_tokens_stops_exhausted_node() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:r".into(),
            budget(100, 100),
        )
        .unwrap();

        g.consume_tokens("root", 100).unwrap();

        let node = g.get_node("root").unwrap();
        assert_eq!(node.status, NodeStatus::Stopped);
        assert_eq!(node.stop_reason, Some(StopReason::BudgetExhausted));
    }

    #[test]
    fn over_budget_chains_returns_chains_above_threshold() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "first".into(),
            "a".into(),
            "capsule:first".into(),
            budget(1_000, 1_000),
        )
        .unwrap();
        g.add_root(
            "second".into(),
            "b".into(),
            "capsule:second".into(),
            budget(1_000, 1_000),
        )
        .unwrap();
        g.consume_tokens("first", 750).unwrap();

        let over_budget = g.over_budget_chains(70.0);

        assert_eq!(over_budget.len(), 1);
        assert_eq!(over_budget[0].chain_id, "first");
    }

    #[test]
    fn complete_sets_outcome() {
        let mut g = BoundedWorkGraph::default();
        g.add_root(
            "root".into(),
            "a".into(),
            "capsule:r".into(),
            budget(1000, 1000),
        )
        .unwrap();
        g.complete("root", "outcome:success".into()).unwrap();
        let node = g.get_node("root").unwrap();
        assert_eq!(node.status, NodeStatus::Completed);
        assert_eq!(node.outcome_ref.as_deref(), Some("outcome:success"));
    }
}