Skip to main content

lean_ctx/core/
work_graph.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Bounded Work Graph for multi-agent orchestration (P11 / DIM 4).
4//!
5//! Manages parent/child agent delegation with:
6//! - Budget inheritance (child cannot exceed parent)
7//! - Fan-out limits (max concurrent children)
8//! - Stop conditions (stale, over-budget, redundant)
9//! - Provenance tracking for attribution
10
11use std::collections::{BTreeMap, BTreeSet};
12
13use crate::core::a2a::budget_cascade::{
14    BudgetAllocation, CascadeError, cascade_budget, validate_cascade,
15};
16use serde::{Deserialize, Serialize};
17
18pub const WORK_GRAPH_SCHEMA_VERSION: u16 = 1;
19const MAX_GRAPH_NODES: usize = 256;
20const MAX_FAN_OUT: usize = 16;
21const MAX_DEPTH: u16 = 8;
22const MAX_LOCAL_CONCURRENCY: usize = 32;
23const MAX_IDENTIFIER_BYTES: usize = 128;
24const MAX_RESULT_CLAIMS: usize = 64;
25const MAX_PATH_CLAIMS: usize = 64;
26
27fn default_local_concurrency() -> usize {
28    MAX_FAN_OUT
29}
30
31#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33pub enum ChildOutcome {
34    Accepted,
35    Rejected,
36    Partial,
37}
38
39#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
40pub struct ResultClaim {
41    pub key: String,
42    pub value: String,
43}
44
45#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
46pub struct ChildExecutionReceipt {
47    pub receipt_id: String,
48    pub node_id: String,
49    pub outcome_ref: String,
50    pub outcome: ChildOutcome,
51    pub tokens_consumed: u64,
52    pub cost_micros_consumed: u64,
53    /// Opaque claim fence returned when queued work becomes active.
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub execution_fence: Option<String>,
56    #[serde(default)]
57    pub claims: Vec<ResultClaim>,
58}
59
60/// Canonically verified provider spend that exceeded its authorization.
61///
62/// This is deliberately separate from [`WorkNodeBudget`]: authorization stays
63/// bounded while attribution preserves the provider-reported fact in full.
64#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
65pub struct MeasuredExecutionSpend {
66    pub spend_id: String,
67    pub node_id: String,
68    pub outcome_refs: Vec<String>,
69    pub tokens_consumed: u64,
70    pub cost_micros_consumed: u64,
71    pub execution_fence: String,
72}
73
74impl MeasuredExecutionSpend {
75    pub fn new(
76        node_id: String,
77        outcome_refs: Vec<String>,
78        tokens_consumed: u64,
79        cost_micros_consumed: u64,
80        execution_fence: String,
81    ) -> Self {
82        let spend_id = measured_spend_id(&outcome_refs);
83        Self {
84            spend_id,
85            node_id,
86            outcome_refs,
87            tokens_consumed,
88            cost_micros_consumed,
89            execution_fence,
90        }
91    }
92}
93
94#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
95pub struct ResultConflict {
96    pub key: String,
97    pub values: Vec<String>,
98    pub node_ids: Vec<String>,
99}
100
101#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
102pub struct FusedResults {
103    pub accepted: BTreeMap<String, String>,
104    pub conflicts: Vec<ResultConflict>,
105}
106
107#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
108pub struct WorkAttribution {
109    pub accepted_tokens: u64,
110    pub accepted_cost_micros: u64,
111    pub waste_tokens: u64,
112    pub waste_cost_micros: u64,
113}
114
115#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
116pub struct TeamValueReport {
117    pub accepted_tokens: u64,
118    pub total_tokens: u64,
119    pub accepted_cost_micros: u64,
120    pub total_cost_micros: u64,
121    pub waste_tokens: u64,
122    pub waste_cost_micros: u64,
123    pub accepted_cost_basis_points: u16,
124}
125
126#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
127#[serde(rename_all = "snake_case")]
128pub enum NodeStatus {
129    Pending,
130    Active,
131    Completed,
132    Stopped,
133    Failed,
134}
135
136#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub enum StopReason {
139    BudgetExhausted,
140    Stale,
141    Redundant,
142    ParentStopped,
143    ManualStop,
144    DepthExceeded,
145    FanOutExceeded,
146    PolicyDenied,
147    LeaseLost,
148    Duplicate,
149    LowValue,
150    ExecutionFailed,
151}
152
153#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
154pub struct WorkNodeBudget {
155    pub tokens_allocated: u64,
156    pub tokens_consumed: u64,
157    pub cost_micros_allocated: u64,
158    pub cost_micros_consumed: u64,
159}
160
161impl WorkNodeBudget {
162    pub fn tokens_remaining(&self) -> u64 {
163        self.tokens_allocated.saturating_sub(self.tokens_consumed)
164    }
165
166    pub fn cost_remaining(&self) -> u64 {
167        self.cost_micros_allocated
168            .saturating_sub(self.cost_micros_consumed)
169    }
170
171    pub fn is_exhausted(&self) -> bool {
172        self.tokens_remaining() == 0 || self.cost_remaining() == 0
173    }
174}
175
176/// Tracks the total budget across an entire delegation chain.
177#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
178pub struct ChainBudget {
179    pub chain_id: String,
180    pub root_budget_tokens: u64,
181    pub total_consumed_tokens: u64,
182    pub total_allocated_tokens: u64,
183    #[serde(default)]
184    pub root_budget_cost_micros: u64,
185    #[serde(default)]
186    pub total_consumed_cost_micros: u64,
187    #[serde(default)]
188    pub total_allocated_cost_micros: u64,
189    /// Verified provider spend above node authorization; never reusable.
190    #[serde(default)]
191    pub unauthorized_tokens: u64,
192    #[serde(default)]
193    pub unauthorized_cost_micros: u64,
194    pub depth: u16,
195}
196
197impl ChainBudget {
198    pub fn remaining(&self) -> u64 {
199        self.root_budget_tokens
200            .saturating_sub(self.total_consumed_tokens)
201            .saturating_sub(self.unauthorized_tokens)
202    }
203
204    pub fn utilization_pct(&self) -> f64 {
205        if self.root_budget_tokens == 0 {
206            return 0.0;
207        }
208
209        (self
210            .total_consumed_tokens
211            .saturating_add(self.unauthorized_tokens) as f64
212            / self.root_budget_tokens as f64)
213            * 100.0
214    }
215}
216
217#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
218pub struct WorkNode {
219    pub node_id: String,
220    pub agent_id: String,
221    pub parent_node_id: Option<String>,
222    pub capsule_ref: String,
223    pub status: NodeStatus,
224    pub budget: WorkNodeBudget,
225    pub depth: u16,
226    pub stop_reason: Option<StopReason>,
227    pub outcome_ref: Option<String>,
228    #[serde(default)]
229    pub claim_attempt: u32,
230    /// Current connector attempt within this execution fence, persisted before launch.
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub delivery_attempt: Option<u8>,
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub execution_fence: Option<String>,
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub lease_expires_epoch_ms: Option<u64>,
237    #[serde(default)]
238    pub path_claims: Vec<String>,
239    #[serde(default)]
240    pub task_ref: String,
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub parent_task_ref: Option<String>,
243    #[serde(default)]
244    pub policy_ref: String,
245    #[serde(default)]
246    pub expected_outcome_ref: String,
247    #[serde(default)]
248    pub execution_started: bool,
249}
250
251/// Bounded, acyclic work graph with enforced fan-out and budget constraints.
252#[derive(Clone, Debug, Serialize, Deserialize)]
253pub struct BoundedWorkGraph {
254    #[serde(default)]
255    graph_id: String,
256    nodes: BTreeMap<String, WorkNode>,
257    children: BTreeMap<String, Vec<String>>,
258    #[serde(default)]
259    chain_budgets: BTreeMap<String, ChainBudget>,
260    #[serde(default)]
261    pending_child_budgets: BTreeMap<String, WorkNodeBudget>,
262    #[serde(default)]
263    pending_child_parents: BTreeMap<String, String>,
264    #[serde(default)]
265    receipts: BTreeMap<String, ChildExecutionReceipt>,
266    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
267    failed_spend: BTreeMap<String, MeasuredExecutionSpend>,
268    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
269    reaped_executions: BTreeMap<String, String>,
270    #[serde(default)]
271    accepted_path: BTreeSet<String>,
272    #[serde(default = "default_local_concurrency")]
273    max_local_concurrency: usize,
274    max_fan_out: usize,
275    max_depth: u16,
276}
277
278impl Default for BoundedWorkGraph {
279    fn default() -> Self {
280        Self::new(MAX_FAN_OUT, MAX_DEPTH)
281    }
282}
283
284#[path = "work_graph/control_ops.rs"]
285mod control_ops;
286#[path = "work_graph/graph_ops.rs"]
287mod graph_ops;
288
289fn execution_fence(graph_id: &str, node: &WorkNode) -> String {
290    let material = format!(
291        "{}\0{}\0{}\0{}\0{}",
292        graph_id, node.node_id, node.agent_id, node.capsule_ref, node.claim_attempt
293    );
294    format!("fence:{}", blake3::hash(material.as_bytes()).to_hex())
295}
296
297pub(crate) fn path_claims_overlap(left: &str, right: &str) -> bool {
298    left == right
299        || left
300            .strip_prefix(right)
301            .is_some_and(|suffix| suffix.starts_with('/'))
302        || right
303            .strip_prefix(left)
304            .is_some_and(|suffix| suffix.starts_with('/'))
305}
306
307fn validate_identifier(value: &str, field: &'static str) -> Result<(), WorkGraphError> {
308    if value.is_empty() || value.len() > MAX_IDENTIFIER_BYTES || value.chars().any(char::is_control)
309    {
310        return Err(WorkGraphError::InvalidIdentifier(field));
311    }
312    Ok(())
313}
314
315fn validate_budget(budget: &WorkNodeBudget) -> Result<(), WorkGraphError> {
316    if budget.tokens_consumed > budget.tokens_allocated
317        || budget.cost_micros_consumed > budget.cost_micros_allocated
318    {
319        return Err(WorkGraphError::InvalidBudget);
320    }
321    Ok(())
322}
323
324fn validate_receipt(receipt: &ChildExecutionReceipt) -> Result<(), WorkGraphError> {
325    validate_identifier(&receipt.receipt_id, "receipt_id")?;
326    validate_identifier(&receipt.node_id, "node_id")?;
327    validate_identifier(&receipt.outcome_ref, "outcome_ref")?;
328    if let Some(fence) = receipt.execution_fence.as_deref()
329        && (fence.len() != 70
330            || !fence.starts_with("fence:")
331            || !fence[6..]
332                .bytes()
333                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
334    {
335        return Err(WorkGraphError::InvalidIdentifier("execution_fence"));
336    }
337    if receipt.claims.len() > MAX_RESULT_CLAIMS {
338        return Err(WorkGraphError::TooManyClaims);
339    }
340    let mut keys = BTreeSet::new();
341    for claim in &receipt.claims {
342        validate_identifier(&claim.key, "claim_key")?;
343        validate_identifier(&claim.value, "claim_value")?;
344        if !keys.insert(&claim.key) {
345            return Err(WorkGraphError::DuplicateClaim(claim.key.clone()));
346        }
347    }
348    Ok(())
349}
350
351fn validate_measured_spend(spend: &MeasuredExecutionSpend) -> Result<(), WorkGraphError> {
352    validate_identifier(&spend.spend_id, "spend_id")?;
353    validate_identifier(&spend.node_id, "node_id")?;
354    if spend.outcome_refs.is_empty() || spend.outcome_refs.len() > 2 {
355        return Err(WorkGraphError::InvalidGraph(
356            "failed spend must reference one or two receipts".into(),
357        ));
358    }
359    let mut outcome_refs = BTreeSet::new();
360    for outcome_ref in &spend.outcome_refs {
361        validate_identifier(outcome_ref, "outcome_ref")?;
362        let digest = outcome_ref
363            .strip_prefix("id:sha256:")
364            .filter(|digest| {
365                digest.len() == 64
366                    && digest
367                        .bytes()
368                        .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
369            })
370            .ok_or(WorkGraphError::InvalidIdentifier("outcome_ref"))?;
371        if !outcome_refs.insert(digest) {
372            return Err(WorkGraphError::InvalidGraph(
373                "duplicate failed spend receipt".into(),
374            ));
375        }
376    }
377    if spend.spend_id != measured_spend_id(&spend.outcome_refs) {
378        return Err(WorkGraphError::InvalidIdentifier("spend_id"));
379    }
380    if spend.execution_fence.len() != 70
381        || !spend.execution_fence.starts_with("fence:")
382        || !spend.execution_fence[6..]
383            .bytes()
384            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
385    {
386        return Err(WorkGraphError::InvalidIdentifier("execution_fence"));
387    }
388    Ok(())
389}
390
391fn measured_spend_id(outcome_refs: &[String]) -> String {
392    format!(
393        "spend:{}",
394        blake3::hash(outcome_refs.join("\0").as_bytes()).to_hex()
395    )
396}
397
398fn validate_path_claim(value: &str) -> Result<(), WorkGraphError> {
399    let relative = value
400        .strip_prefix("path:")
401        .ok_or(WorkGraphError::InvalidPathClaim)?;
402    if relative.is_empty()
403        || relative.len() > 1_024
404        || relative.starts_with('/')
405        || relative.starts_with('\\')
406        || relative
407            .split(['/', '\\'])
408            .any(|part| part.is_empty() || part == "." || part == "..")
409        || relative.chars().any(char::is_control)
410    {
411        return Err(WorkGraphError::InvalidPathClaim);
412    }
413    Ok(())
414}
415
416// ─── Errors ──────────────────────────────────────────────────────────────────
417
418#[derive(Debug, thiserror::Error)]
419pub enum WorkGraphError {
420    #[error("graph at capacity ({MAX_GRAPH_NODES} nodes)")]
421    CapacityExceeded,
422    #[error("duplicate node: {0}")]
423    DuplicateNode(String),
424    #[error("node not found: {0}")]
425    NodeNotFound(String),
426    #[error("parent not active: {0}")]
427    ParentNotActive(String),
428    #[error("depth exceeds max {0}")]
429    DepthExceeded(u16),
430    #[error("fan-out exceeds max {0}")]
431    FanOutExceeded(usize),
432    #[error("child budget ({child_requested}) exceeds parent remaining ({parent_remaining})")]
433    BudgetExceedsParent {
434        child_requested: u64,
435        parent_remaining: u64,
436    },
437    #[error("invalid status transition for node: {0}")]
438    InvalidTransition(String),
439    #[error("local concurrency exceeds max {0}")]
440    LocalConcurrencyExceeded(usize),
441    #[error("invalid or oversized {0}")]
442    InvalidIdentifier(&'static str),
443    #[error("consumed budget exceeds allocation")]
444    InvalidBudget,
445    #[error("duplicate execution receipt: {0}")]
446    DuplicateReceipt(String),
447    #[error("execution receipt exceeds node or chain budget: {0}")]
448    ReceiptExceedsBudget(String),
449    #[error("missing execution receipt for accepted node: {0}")]
450    MissingReceipt(String),
451    #[error("unaccepted node cannot establish an accepted path: {0}")]
452    RejectedAcceptedPath(String),
453    #[error("execution receipt has too many result claims")]
454    TooManyClaims,
455    #[error("node has too many path claims")]
456    TooManyPathClaims,
457    #[error("invalid project-relative path claim")]
458    InvalidPathClaim,
459    #[error("duplicate result claim key: {0}")]
460    DuplicateClaim(String),
461    #[error("work graph accounting overflow")]
462    Overflow,
463    #[error("stale or missing execution fence for node: {0}")]
464    StaleExecutionFence(String),
465    #[error("invalid work graph: {0}")]
466    InvalidGraph(String),
467    #[error("budget cascade error: {0}")]
468    Cascade(#[from] CascadeError),
469}
470
471// ─── Tests ───────────────────────────────────────────────────────────────────
472
473#[cfg(test)]
474#[path = "work_graph/tests.rs"]
475pub mod tests;