1use 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 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub execution_fence: Option<String>,
56 #[serde(default)]
57 pub claims: Vec<ResultClaim>,
58 #[serde(default, skip_serializing_if = "UsageSource::is_measured")]
60 pub usage_source: UsageSource,
61}
62
63#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum UsageSource {
69 #[default]
70 Measured,
71 Reported,
72}
73
74impl UsageSource {
75 fn is_measured(&self) -> bool {
76 *self == Self::Measured
77 }
78}
79
80#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
85pub struct MeasuredExecutionSpend {
86 pub spend_id: String,
87 pub node_id: String,
88 pub outcome_refs: Vec<String>,
89 pub tokens_consumed: u64,
90 pub cost_micros_consumed: u64,
91 pub execution_fence: String,
92}
93
94impl MeasuredExecutionSpend {
95 pub fn new(
96 node_id: String,
97 outcome_refs: Vec<String>,
98 tokens_consumed: u64,
99 cost_micros_consumed: u64,
100 execution_fence: String,
101 ) -> Self {
102 let spend_id = measured_spend_id(&outcome_refs);
103 Self {
104 spend_id,
105 node_id,
106 outcome_refs,
107 tokens_consumed,
108 cost_micros_consumed,
109 execution_fence,
110 }
111 }
112}
113
114#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
115pub struct ResultConflict {
116 pub key: String,
117 pub values: Vec<String>,
118 pub node_ids: Vec<String>,
119}
120
121#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
122pub struct FusedResults {
123 pub accepted: BTreeMap<String, String>,
124 pub conflicts: Vec<ResultConflict>,
125}
126
127#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
128pub struct WorkAttribution {
129 pub accepted_tokens: u64,
130 pub accepted_cost_micros: u64,
131 pub waste_tokens: u64,
132 pub waste_cost_micros: u64,
133}
134
135#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
136pub struct TeamValueReport {
137 pub accepted_tokens: u64,
138 pub total_tokens: u64,
139 pub accepted_cost_micros: u64,
140 pub total_cost_micros: u64,
141 pub waste_tokens: u64,
142 pub waste_cost_micros: u64,
143 pub accepted_cost_basis_points: u16,
144}
145
146#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
147#[serde(rename_all = "snake_case")]
148pub enum NodeStatus {
149 Pending,
150 Active,
151 Completed,
152 Stopped,
153 Failed,
154}
155
156#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
157#[serde(rename_all = "snake_case")]
158pub enum StopReason {
159 BudgetExhausted,
160 Stale,
161 Redundant,
162 ParentStopped,
163 ManualStop,
164 DepthExceeded,
165 FanOutExceeded,
166 PolicyDenied,
167 LeaseLost,
168 Duplicate,
169 LowValue,
170 ExecutionFailed,
171}
172
173#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
174pub struct WorkNodeBudget {
175 pub tokens_allocated: u64,
176 pub tokens_consumed: u64,
177 pub cost_micros_allocated: u64,
178 pub cost_micros_consumed: u64,
179}
180
181impl WorkNodeBudget {
182 pub fn tokens_remaining(&self) -> u64 {
183 self.tokens_allocated.saturating_sub(self.tokens_consumed)
184 }
185
186 pub fn cost_remaining(&self) -> u64 {
187 self.cost_micros_allocated
188 .saturating_sub(self.cost_micros_consumed)
189 }
190
191 pub fn is_exhausted(&self) -> bool {
192 self.tokens_remaining() == 0 || self.cost_remaining() == 0
193 }
194}
195
196#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
198pub struct ChainBudget {
199 pub chain_id: String,
200 pub root_budget_tokens: u64,
201 pub total_consumed_tokens: u64,
202 pub total_allocated_tokens: u64,
203 #[serde(default)]
204 pub root_budget_cost_micros: u64,
205 #[serde(default)]
206 pub total_consumed_cost_micros: u64,
207 #[serde(default)]
208 pub total_allocated_cost_micros: u64,
209 #[serde(default)]
211 pub unauthorized_tokens: u64,
212 #[serde(default)]
213 pub unauthorized_cost_micros: u64,
214 pub depth: u16,
215}
216
217impl ChainBudget {
218 pub fn remaining(&self) -> u64 {
219 self.root_budget_tokens
220 .saturating_sub(self.total_consumed_tokens)
221 .saturating_sub(self.unauthorized_tokens)
222 }
223
224 pub fn utilization_pct(&self) -> f64 {
225 if self.root_budget_tokens == 0 {
226 return 0.0;
227 }
228
229 (self
230 .total_consumed_tokens
231 .saturating_add(self.unauthorized_tokens) as f64
232 / self.root_budget_tokens as f64)
233 * 100.0
234 }
235}
236
237#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
238pub struct WorkNode {
239 pub node_id: String,
240 pub agent_id: String,
241 pub parent_node_id: Option<String>,
242 pub capsule_ref: String,
243 pub status: NodeStatus,
244 pub budget: WorkNodeBudget,
245 pub depth: u16,
246 pub stop_reason: Option<StopReason>,
247 pub outcome_ref: Option<String>,
248 #[serde(default)]
249 pub claim_attempt: u32,
250 #[serde(default, skip_serializing_if = "Option::is_none")]
252 pub delivery_attempt: Option<u8>,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub execution_fence: Option<String>,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub lease_expires_epoch_ms: Option<u64>,
257 #[serde(default)]
258 pub path_claims: Vec<String>,
259 #[serde(default)]
260 pub task_ref: String,
261 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub parent_task_ref: Option<String>,
263 #[serde(default)]
264 pub policy_ref: String,
265 #[serde(default)]
266 pub expected_outcome_ref: String,
267 #[serde(default)]
268 pub execution_started: bool,
269}
270
271#[derive(Clone, Debug, Serialize, Deserialize)]
273pub struct BoundedWorkGraph {
274 #[serde(default)]
275 graph_id: String,
276 nodes: BTreeMap<String, WorkNode>,
277 children: BTreeMap<String, Vec<String>>,
278 #[serde(default)]
279 chain_budgets: BTreeMap<String, ChainBudget>,
280 #[serde(default)]
281 pending_child_budgets: BTreeMap<String, WorkNodeBudget>,
282 #[serde(default)]
283 pending_child_parents: BTreeMap<String, String>,
284 #[serde(default)]
285 receipts: BTreeMap<String, ChildExecutionReceipt>,
286 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
287 failed_spend: BTreeMap<String, MeasuredExecutionSpend>,
288 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
289 reaped_executions: BTreeMap<String, String>,
290 #[serde(default)]
291 accepted_path: BTreeSet<String>,
292 #[serde(default = "default_local_concurrency")]
293 max_local_concurrency: usize,
294 max_fan_out: usize,
295 max_depth: u16,
296}
297
298impl Default for BoundedWorkGraph {
299 fn default() -> Self {
300 Self::new(MAX_FAN_OUT, MAX_DEPTH)
301 }
302}
303
304#[path = "work_graph/control_ops.rs"]
305mod control_ops;
306#[path = "work_graph/graph_ops.rs"]
307mod graph_ops;
308
309fn execution_fence(graph_id: &str, node: &WorkNode) -> String {
310 let material = format!(
311 "{}\0{}\0{}\0{}\0{}",
312 graph_id, node.node_id, node.agent_id, node.capsule_ref, node.claim_attempt
313 );
314 format!("fence:{}", blake3::hash(material.as_bytes()).to_hex())
315}
316
317pub(crate) fn path_claims_overlap(left: &str, right: &str) -> bool {
318 left == right
319 || left
320 .strip_prefix(right)
321 .is_some_and(|suffix| suffix.starts_with('/'))
322 || right
323 .strip_prefix(left)
324 .is_some_and(|suffix| suffix.starts_with('/'))
325}
326
327fn validate_identifier(value: &str, field: &'static str) -> Result<(), WorkGraphError> {
328 if value.is_empty() || value.len() > MAX_IDENTIFIER_BYTES || value.chars().any(char::is_control)
329 {
330 return Err(WorkGraphError::InvalidIdentifier(field));
331 }
332 Ok(())
333}
334
335fn validate_budget(budget: &WorkNodeBudget) -> Result<(), WorkGraphError> {
336 if budget.tokens_consumed > budget.tokens_allocated
337 || budget.cost_micros_consumed > budget.cost_micros_allocated
338 {
339 return Err(WorkGraphError::InvalidBudget);
340 }
341 Ok(())
342}
343
344fn validate_receipt(receipt: &ChildExecutionReceipt) -> Result<(), WorkGraphError> {
345 validate_identifier(&receipt.receipt_id, "receipt_id")?;
346 validate_identifier(&receipt.node_id, "node_id")?;
347 validate_identifier(&receipt.outcome_ref, "outcome_ref")?;
348 if let Some(fence) = receipt.execution_fence.as_deref()
349 && (fence.len() != 70
350 || !fence.starts_with("fence:")
351 || !fence[6..]
352 .bytes()
353 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
354 {
355 return Err(WorkGraphError::InvalidIdentifier("execution_fence"));
356 }
357 if receipt.claims.len() > MAX_RESULT_CLAIMS {
358 return Err(WorkGraphError::TooManyClaims);
359 }
360 let mut keys = BTreeSet::new();
361 for claim in &receipt.claims {
362 validate_identifier(&claim.key, "claim_key")?;
363 validate_identifier(&claim.value, "claim_value")?;
364 if !keys.insert(&claim.key) {
365 return Err(WorkGraphError::DuplicateClaim(claim.key.clone()));
366 }
367 }
368 Ok(())
369}
370
371fn validate_measured_spend(spend: &MeasuredExecutionSpend) -> Result<(), WorkGraphError> {
372 validate_identifier(&spend.spend_id, "spend_id")?;
373 validate_identifier(&spend.node_id, "node_id")?;
374 if spend.outcome_refs.is_empty() || spend.outcome_refs.len() > 2 {
375 return Err(WorkGraphError::InvalidGraph(
376 "failed spend must reference one or two receipts".into(),
377 ));
378 }
379 let mut outcome_refs = BTreeSet::new();
380 for outcome_ref in &spend.outcome_refs {
381 validate_identifier(outcome_ref, "outcome_ref")?;
382 let digest = outcome_ref
383 .strip_prefix("id:sha256:")
384 .filter(|digest| {
385 digest.len() == 64
386 && digest
387 .bytes()
388 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
389 })
390 .ok_or(WorkGraphError::InvalidIdentifier("outcome_ref"))?;
391 if !outcome_refs.insert(digest) {
392 return Err(WorkGraphError::InvalidGraph(
393 "duplicate failed spend receipt".into(),
394 ));
395 }
396 }
397 if spend.spend_id != measured_spend_id(&spend.outcome_refs) {
398 return Err(WorkGraphError::InvalidIdentifier("spend_id"));
399 }
400 if spend.execution_fence.len() != 70
401 || !spend.execution_fence.starts_with("fence:")
402 || !spend.execution_fence[6..]
403 .bytes()
404 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
405 {
406 return Err(WorkGraphError::InvalidIdentifier("execution_fence"));
407 }
408 Ok(())
409}
410
411fn measured_spend_id(outcome_refs: &[String]) -> String {
412 format!(
413 "spend:{}",
414 blake3::hash(outcome_refs.join("\0").as_bytes()).to_hex()
415 )
416}
417
418fn validate_path_claim(value: &str) -> Result<(), WorkGraphError> {
419 let relative = value
420 .strip_prefix("path:")
421 .ok_or(WorkGraphError::InvalidPathClaim)?;
422 if relative.is_empty()
423 || relative.len() > 1_024
424 || relative.starts_with('/')
425 || relative.starts_with('\\')
426 || relative
427 .split(['/', '\\'])
428 .any(|part| part.is_empty() || part == "." || part == "..")
429 || relative.chars().any(char::is_control)
430 {
431 return Err(WorkGraphError::InvalidPathClaim);
432 }
433 Ok(())
434}
435
436#[derive(Debug, thiserror::Error)]
439pub enum WorkGraphError {
440 #[error("graph at capacity ({MAX_GRAPH_NODES} nodes)")]
441 CapacityExceeded,
442 #[error("duplicate node: {0}")]
443 DuplicateNode(String),
444 #[error("node not found: {0}")]
445 NodeNotFound(String),
446 #[error("parent not active: {0}")]
447 ParentNotActive(String),
448 #[error("depth exceeds max {0}")]
449 DepthExceeded(u16),
450 #[error("fan-out exceeds max {0}")]
451 FanOutExceeded(usize),
452 #[error("child budget ({child_requested}) exceeds parent remaining ({parent_remaining})")]
453 BudgetExceedsParent {
454 child_requested: u64,
455 parent_remaining: u64,
456 },
457 #[error(
458 "invalid status transition for node: {0} (only a pending child of an active parent can \
459 be claimed; completed, failed and cancelled nodes are final — inspect with action=get)"
460 )]
461 InvalidTransition(String),
462 #[error(
463 "local concurrency exceeds max {0} (finish an active node with complete or receipt, \
464 or cancel one, first)"
465 )]
466 LocalConcurrencyExceeded(usize),
467 #[error("invalid or oversized {0}")]
468 InvalidIdentifier(&'static str),
469 #[error("consumed budget exceeds allocation")]
470 InvalidBudget,
471 #[error("duplicate execution receipt: {0}")]
472 DuplicateReceipt(String),
473 #[error("execution receipt exceeds node or chain budget: {0}")]
474 ReceiptExceedsBudget(String),
475 #[error("missing execution receipt for accepted node: {0}")]
476 MissingReceipt(String),
477 #[error("unaccepted node cannot establish an accepted path: {0}")]
478 RejectedAcceptedPath(String),
479 #[error("execution receipt has too many result claims")]
480 TooManyClaims,
481 #[error("node has too many path claims")]
482 TooManyPathClaims,
483 #[error("invalid project-relative path claim")]
484 InvalidPathClaim,
485 #[error("duplicate result claim key: {0}")]
486 DuplicateClaim(String),
487 #[error("work graph accounting overflow")]
488 Overflow,
489 #[error("stale or missing execution fence for node: {0}")]
490 StaleExecutionFence(String),
491 #[error("invalid work graph: {0}")]
492 InvalidGraph(String),
493 #[error("budget cascade error: {0}")]
494 Cascade(#[from] CascadeError),
495}
496
497#[cfg(test)]
500#[path = "work_graph/tests.rs"]
501pub mod tests;