Skip to main content

lean_ctx/tools/
ctx_work_graph.rs

1// SPDX-License-Identifier: Apache-2.0
2use serde_json::json;
3
4use crate::core::work_graph::{
5    BoundedWorkGraph, ChildExecutionReceipt, ChildOutcome, ResultClaim, StopReason, UsageSource,
6    WorkNodeBudget,
7};
8use crate::core::work_graph_store::{ClaimNodeExecution, WorkGraphStore, validate_id};
9
10#[derive(Clone, Copy)]
11pub struct Request<'a> {
12    pub action: &'a str,
13    pub project_root: &'a str,
14    pub agent_id: &'a str,
15    pub graph_id: &'a str,
16    pub if_revision: Option<&'a str>,
17    pub node_id: Option<&'a str>,
18    pub parent_node_id: Option<&'a str>,
19    pub to_agent: Option<&'a str>,
20    pub capsule_ref: Option<&'a str>,
21    pub outcome_ref: Option<&'a str>,
22    pub tokens: Option<u64>,
23    pub cost_micros: Option<u64>,
24    pub max_concurrency: Option<usize>,
25    pub receipt_id: Option<&'a str>,
26    pub execution_fence: Option<&'a str>,
27    pub outcome: Option<&'a str>,
28    pub claims: Option<&'a serde_json::Value>,
29    pub accepted_nodes: Option<&'a serde_json::Value>,
30    pub stop_reason: Option<&'a str>,
31    pub timeout_ms: Option<u64>,
32    pub path_claims: Option<&'a serde_json::Value>,
33    pub task_ref: Option<&'a str>,
34    pub policy_ref: Option<&'a str>,
35    pub expected_outcome_ref: Option<&'a str>,
36}
37
38pub fn handle(request: Request<'_>) -> Result<String, String> {
39    if request.action == "execute" {
40        return Err(EXECUTE_REMOVED.to_string());
41    }
42    if request.agent_id.is_empty() {
43        return Err("agent must be registered first via ctx_agent".to_string());
44    }
45    ensure_active_agent(request.project_root, request.agent_id)?;
46    if request.action != "list" {
47        validate_id(request.graph_id, "graph_id")?;
48    }
49    check_required_fields(&request)?;
50    if request.if_revision.is_some()
51        && matches!(
52            request.action,
53            "create" | "fuse" | "attribution" | "value_report" | "get" | "list"
54        )
55    {
56        return Err(format!(
57            "if_revision applies to observe and to mutating actions, not to {}",
58            request.action
59        ));
60    }
61    match request.action {
62        "create" => create(&request),
63        "delegate" => delegate(&request),
64        "claim" => claim(&request),
65        "start" => start(&request),
66        "consume" => consume(&request),
67        "complete" => complete(&request),
68        "receipt" => receipt(&request),
69        "accept" => accept(&request),
70        "fuse" => fuse(&request),
71        "attribution" => attribution(&request),
72        "value_report" => value_report(&request),
73        "cancel" => cancel(&request),
74        "get" => get(&request),
75        "observe" => observe(&request),
76        "list" => list(request.project_root, request.agent_id),
77        other => Err(format!("unknown work graph action: {other}")),
78    }
79}
80
81/// Replies to the removed launcher action with the host-start path.
82const EXECUTE_REMOVED: &str = "execute was removed: LeanCTX no longer launches agents. Launch the \
83     child agent yourself and bind it to the node with action=start (returns the launch \
84     environment); finish with action=receipt or stop it with action=cancel";
85
86/// Bind a host-launched child agent to one fenced claim of its node. The host
87/// starts the process; LeanCTX verifies the handed-over context capsule, holds
88/// the node and path leases, and issues the child's delivery profile when the
89/// host is configured as delivery issuer. A receipt or cancel ends it; an
90/// expired lease is stopped on the next claim. Every stop revokes delivery.
91fn start(request: &Request<'_>) -> Result<String, String> {
92    use crate::core::work_graph_delegation as delegation;
93
94    if let Some(policy) =
95        crate::core::policy::runtime::for_project(std::path::Path::new(request.project_root))?
96        && !policy.tool_allowed("ctx_work_graph")
97    {
98        return Err("project policy denies Work Graph execution".into());
99    }
100    let node_id = required(request.node_id, "node_id")?;
101    let window_ms = delegation::start_window_ms(
102        request
103            .timeout_ms
104            .unwrap_or(delegation::DEFAULT_START_WINDOW_MS),
105    )?;
106    // A malformed issuer configuration must fail before any node is claimed.
107    let issuer = delegation::DeliveryIssuerConfig::from_environment()?;
108    // The issuer signs as the root host. A process that holds the host's
109    // issuer configuration under another agent identity (a child whose host
110    // ignored launch.unset_env) must not sign for its own delegations.
111    if let Some(issuer) = &issuer
112        && issuer.host_agent() != request.agent_id
113    {
114        return Err(format!(
115            "{} belongs to host agent {}; it must not reach agent {}",
116            delegation::ISSUER_ENV,
117            issuer.host_agent(),
118            request.agent_id
119        ));
120    }
121    let now_epoch_ms = epoch_ms()?;
122    let lease_expires_epoch_ms = now_epoch_ms
123        .checked_add(window_ms)
124        .ok_or_else(|| "execution lease expiry overflow".to_string())?;
125    let claimed = mutate_store(request, |store| {
126        let graph = store.graph_mut(request.graph_id)?;
127        authorize_node_or_parent(graph, node_id, request.agent_id)?;
128        let claim = store.claim_node_execution(
129            request.graph_id,
130            node_id,
131            now_epoch_ms,
132            lease_expires_epoch_ms,
133        )?;
134        let ClaimNodeExecution::Claimed(node) = claim else {
135            return Ok(None);
136        };
137        let graph = store.graph(request.graph_id).expect("graph checked above");
138        let root_agent = graph
139            .root_agent_for(node_id)
140            .map_err(|error| error.to_string())?
141            .to_string();
142        let parent_capsule_ref = node
143            .parent_node_id
144            .as_deref()
145            .and_then(|parent| graph.get_node(parent))
146            .map(|parent| parent.capsule_ref.clone());
147        Ok(Some((*node, root_agent, parent_capsule_ref)))
148    })?;
149    let Some((node, root_agent, parent_capsule_ref)) = claimed else {
150        return Err("expired execution was stopped and cannot be reclaimed".into());
151    };
152    let fence = node
153        .execution_fence
154        .clone()
155        .ok_or_else(|| "claim did not produce execution fence".to_string())?;
156    // Every failure from here on stops the claim again, so a refused start
157    // never strands a claimed node. The shared leases must never outlive the
158    // node lease: a stopped child's paths are released by the graph at that
159    // instant, and a later claimant must then find the shared leases free.
160    let acquired = incarnation_leases(request.project_root, request.graph_id, &node, &fence)
161        .and_then(|leases| {
162            let remaining_ms = lease_expires_epoch_ms.saturating_sub(epoch_ms()?);
163            if remaining_ms == 0 {
164                return Err("execution window elapsed before its leases were acquired".into());
165            }
166            acquire_incarnation_leases(&node.agent_id, &leases, remaining_ms)
167        });
168    if let Err(error) = acquired {
169        abort_start(
170            request,
171            node_id,
172            &node.agent_id,
173            &fence,
174            StopReason::LeaseLost,
175        )?;
176        return Err(error);
177    }
178    let plan = delegation::StartPlan {
179        graph_id: request.graph_id.to_string(),
180        node,
181        root_agent_id: root_agent,
182        parent_capsule_ref,
183        project_root: request.project_root.into(),
184        window_ms,
185    };
186    let transport = crate::core::a2a::health::local_transport();
187    let mut reserved = None;
188    let launch = (|| {
189        plan.validate()?;
190        let (signed_capsule, delivery) = transport
191            .reserve(&plan.node.agent_id, &fence)
192            .map_err(|error| error.to_string())?
193            .ok_or_else(|| {
194                format!(
195                    "no unreserved signed context capsule is queued for agent {}",
196                    plan.node.agent_id
197                )
198            })?;
199        reserved = Some(delivery.clone());
200        if delivery.capsule_ref != plan.node.capsule_ref {
201            return Err("queued delivery does not match claimed node capsule".into());
202        }
203        let root_key = crate::core::agent_identity::get_stored_public_key(&plan.root_agent_id)
204            .map_err(|error| format!("root-agent trust key unavailable: {error}"))?;
205        plan.verify_capsule(&signed_capsule, &root_key)?;
206        // Publish the attempt before any delivery authority exists for it.
207        WorkGraphStore::mutate(request.project_root, |store| {
208            store
209                .graph_mut(request.graph_id)?
210                .begin_delivery_attempt(node_id, &fence, 1)
211                .map_err(|error| error.to_string())
212        })?;
213        let task_id = delegation::attempt_task_id(
214            &delegation::execution_key(
215                std::path::Path::new(request.project_root),
216                request.graph_id,
217                node_id,
218                &fence,
219            )?,
220            1,
221        );
222        let profile = match &issuer {
223            Some(issuer) => {
224                let issued =
225                    issuer.issue(&plan, 1, &task_id, signed_capsule.capsule.sensitivity)?;
226                Some(
227                    issued
228                        .launch_value(&task_id, std::path::Path::new(request.project_root))
229                        .ok_or("issued delivery profile failed launch validation")?,
230                )
231            }
232            None => None,
233        };
234        if !transport.acknowledge(&plan.node.agent_id, &delivery.relay_id, &fence) {
235            let _ = transport.quarantine_reserved(&plan.node.agent_id, &delivery.relay_id, &fence);
236            reserved = None;
237            return Err("capsule acknowledgement lost its reservation".into());
238        }
239        reserved = None;
240        Ok((task_id, profile))
241    })();
242    let (task_id, profile) = match launch {
243        Ok(launch) => launch,
244        Err(error) => {
245            if let Some(delivery) = reserved {
246                let _ =
247                    transport.negative_acknowledge(&plan.node.agent_id, &delivery.relay_id, &fence);
248            }
249            abort_start(
250                request,
251                node_id,
252                &plan.node.agent_id,
253                &fence,
254                StopReason::ExecutionFailed,
255            )?;
256            return Err(error);
257        }
258    };
259    let graph: serde_json::Value =
260        serde_json::from_str(&get(request)?).map_err(|error| error.to_string())?;
261    serde_json::to_string(&json!({
262        "graph": graph,
263        "launch": {
264            "graph_id": request.graph_id,
265            "node_id": node_id,
266            "agent_id": plan.node.agent_id,
267            "execution_fence": fence,
268            "task_id": task_id,
269            "lease_expires_epoch_ms": lease_expires_epoch_ms,
270            "delegated_delivery": profile.is_some(),
271            "env": {
272                delegation::CHILD_DELIVERY_ENV:
273                    profile.as_deref().unwrap_or(delegation::NO_CHILD_DELIVERY),
274            },
275            "unset_env": [delegation::ISSUER_ENV],
276            "finish": "action=receipt with this execution_fence, or action=cancel; \
277                       the lease ends at lease_expires_epoch_ms",
278        },
279    }))
280    .map_err(|error| error.to_string())
281}
282
283fn epoch_ms() -> Result<u64, String> {
284    std::time::SystemTime::now()
285        .duration_since(std::time::UNIX_EPOCH)
286        .map_err(|error| format!("system clock before Unix epoch: {error}"))?
287        .as_millis()
288        .try_into()
289        .map_err(|_| "system clock exceeds u64 milliseconds".to_string())
290}
291
292type IncarnationLease = (
293    crate::core::agent_lease::AgentLeaseResourceKindV1,
294    String,
295    String,
296);
297
298/// Node and path leases of one execution incarnation, keyed by its fence.
299/// Path leases are project-bound and shared with `ctx_agent` leases, so an
300/// agent holding a path there excludes a node claiming it here, and back.
301fn incarnation_leases(
302    project_root: &str,
303    graph_id: &str,
304    node: &crate::core::work_graph::WorkNode,
305    fence: &str,
306) -> Result<Vec<IncarnationLease>, String> {
307    use crate::core::agent_lease::AgentLeaseResourceKindV1;
308    let mut leases = vec![(
309        AgentLeaseResourceKindV1::WorkGraphNode,
310        crate::core::work_graph_delegation::node_lease_resource(
311            project_root,
312            graph_id,
313            &node.node_id,
314        )?,
315        fence.to_string(),
316    )];
317    for (index, claim) in node.path_claims.iter().enumerate() {
318        leases.push((
319            AgentLeaseResourceKindV1::Path,
320            crate::core::work_graph_delegation::path_lease_resource(project_root, claim)?,
321            format!("{fence}:{index}"),
322        ));
323    }
324    Ok(leases)
325}
326
327fn acquire_incarnation_leases(
328    owner: &str,
329    leases: &[IncarnationLease],
330    duration_ms: u64,
331) -> Result<(), String> {
332    use crate::core::agent_lease::{
333        AGENT_LEASE_SCHEMA_VERSION, AgentLeaseAcquireV1, AgentLeaseRequestV1, acquire_shared,
334    };
335    for (kind, resource, lease_request_ref) in leases {
336        let acquired = acquire_shared(AgentLeaseRequestV1 {
337            schema_version: AGENT_LEASE_SCHEMA_VERSION,
338            lease_request_ref: lease_request_ref.clone(),
339            resource_kind: *kind,
340            resource_ref: resource.clone(),
341            owner_agent_id: owner.to_string(),
342            duration_ms,
343        })
344        .map_err(|error| error.to_string())?;
345        if let AgentLeaseAcquireV1::HeldBy { .. } = acquired {
346            return Err(format!("lease is held by another execution: {resource}"));
347        }
348    }
349    Ok(())
350}
351
352/// Releases every lease of one incarnation by its owner and fence, never by
353/// recomputed resource names: a project root spelled differently at release
354/// time must not leave the leases behind.
355fn release_incarnation_leases(owner: &str, fence: &str) {
356    // Leases expire with the execution window; a failed early release only
357    // delays reuse and never extends authority.
358    if let Err(error) = crate::core::agent_lease::release_fence_shared(owner, fence) {
359        tracing::warn!(event = "work_graph_lease_release_failed", %error);
360    }
361}
362
363/// Stop a claim whose launch was refused; the stop revokes delivery and frees
364/// the slot before any lease of this incarnation is released.
365fn abort_start(
366    request: &Request<'_>,
367    node_id: &str,
368    owner: &str,
369    fence: &str,
370    reason: StopReason,
371) -> Result<(), String> {
372    WorkGraphStore::mutate(request.project_root, |store| {
373        store
374            .graph_mut(request.graph_id)?
375            .stop_unlaunched(node_id, reason)
376            .map(|_| ())
377            .map_err(|error| error.to_string())
378    })?;
379    release_incarnation_leases(owner, fence);
380    Ok(())
381}
382
383/// The caller's mutation of its graph. With `if_revision` it runs only while
384/// the graph still has that `write_revision` (from observe), checked under
385/// the same persistence lock; otherwise it fails as a revision conflict and
386/// changes nothing. The revision proves freshness, never authorization.
387fn mutate_store<T>(
388    request: &Request<'_>,
389    mutate: impl FnOnce(&mut WorkGraphStore) -> Result<T, String>,
390) -> Result<T, String> {
391    match request.if_revision {
392        Some(expected) => WorkGraphStore::mutate_if_revision(
393            request.project_root,
394            request.graph_id,
395            expected,
396            mutate,
397        )
398        .map_err(|error| {
399            if error == "work graph revision conflict" {
400                "work graph revision conflict: the graph changed since this write_revision; \
401                 observe again for the current write_revision"
402                    .to_string()
403            } else {
404                error
405            }
406        }),
407        None => WorkGraphStore::mutate(request.project_root, mutate),
408    }
409}
410
411fn create(request: &Request<'_>) -> Result<String, String> {
412    let node_id = required(request.node_id, "node_id")?;
413    validate_id(node_id, "node_id")?;
414    let tokens = positive(request.tokens, "tokens")?;
415    let cost = positive(request.cost_micros, "cost_micros")?;
416    let capsule = required(request.capsule_ref, "capsule_ref")?;
417    let task_ref = required(request.task_ref, "task_ref")?;
418    let policy_ref = required(request.policy_ref, "policy_ref")?;
419    let expected_outcome_ref = required(request.expected_outcome_ref, "expected_outcome_ref")?;
420    bounded_ref(capsule, "capsule_ref")?;
421    let mut graph = BoundedWorkGraph::default()
422        .with_local_concurrency(request.max_concurrency.unwrap_or(4))
423        .with_graph_id(request.graph_id)
424        .map_err(|error| error.to_string())?;
425    graph
426        .add_root(
427            node_id.to_string(),
428            request.agent_id.to_string(),
429            capsule.to_string(),
430            budget(tokens, cost),
431        )
432        .map_err(|error| error.to_string())?;
433    graph
434        .configure_root_context(node_id, task_ref, policy_ref, expected_outcome_ref)
435        .map_err(|error| error.to_string())?;
436    WorkGraphStore::mutate(request.project_root, |store| {
437        store.create(request.graph_id, graph)
438    })?;
439    get(request)
440}
441
442fn delegate(request: &Request<'_>) -> Result<String, String> {
443    let parent = required(request.parent_node_id, "parent_node_id")?;
444    let node = required(request.node_id, "node_id")?;
445    validate_id(parent, "parent_node_id")?;
446    validate_id(node, "node_id")?;
447    let target = required(request.to_agent, "to_agent")?;
448    validate_id(target, "to_agent")?;
449    ensure_active_agent(request.project_root, target)?;
450    let capsule = required(request.capsule_ref, "capsule_ref")?;
451    let task_ref = required(request.task_ref, "task_ref")?;
452    let expected_outcome_ref = required(request.expected_outcome_ref, "expected_outcome_ref")?;
453    bounded_ref(capsule, "capsule_ref")?;
454    let tokens = positive(request.tokens, "tokens")?;
455    let cost = positive(request.cost_micros, "cost_micros")?;
456    let path_claims: Vec<String> = request
457        .path_claims
458        .map_or_else(
459            || Ok(Vec::new()),
460            |value| serde_json::from_value::<Vec<String>>(value.clone()),
461        )
462        .map_err(|error| format!("invalid path_claims: {error}"))?
463        .into_iter()
464        .map(|claim| canonical_path_claim(request.project_root, &claim))
465        .collect::<Result<_, _>>()?;
466    mutate_store(request, |store| {
467        let graph = store.graph_mut(request.graph_id)?;
468        authorize_node(graph, parent, request.agent_id)?;
469        graph
470            .queue_child(
471                parent,
472                node.to_string(),
473                target.to_string(),
474                capsule.to_string(),
475                budget(tokens, cost),
476            )
477            .map_err(|error| error.to_string())?;
478        graph
479            .set_path_claims(node, path_claims)
480            .map_err(|error| error.to_string())?;
481        graph
482            .configure_child_context(node, task_ref, expected_outcome_ref)
483            .map_err(|error| error.to_string())?;
484        Ok(())
485    })?;
486    get(request)
487}
488
489fn claim(request: &Request<'_>) -> Result<String, String> {
490    let node = required(request.node_id, "node_id")?;
491    validate_id(node, "node_id")?;
492    let lease_window_ms = request.timeout_ms.unwrap_or(300_000).clamp(1, 3_600_000);
493    let now_epoch_ms: u64 = std::time::SystemTime::now()
494        .duration_since(std::time::UNIX_EPOCH)
495        .map_err(|error| format!("system clock before Unix epoch: {error}"))?
496        .as_millis()
497        .try_into()
498        .map_err(|_| "system clock exceeds u64 milliseconds".to_string())?;
499    let lease_expires_epoch_ms = now_epoch_ms
500        .checked_add(lease_window_ms)
501        .ok_or_else(|| "execution lease expiry overflow".to_string())?;
502    mutate_store(request, |store| {
503        let graph = store.graph_mut(request.graph_id)?;
504        authorize_node(graph, node, request.agent_id)?;
505        graph
506            .claim_and_activate_until(node, Some(lease_expires_epoch_ms))
507            .map_err(|error| error.to_string())?;
508        Ok(())
509    })?;
510    get(request)
511}
512
513fn consume(request: &Request<'_>) -> Result<String, String> {
514    let node = required(request.node_id, "node_id")?;
515    validate_id(node, "node_id")?;
516    let tokens = request.tokens.unwrap_or(0);
517    let cost = request.cost_micros.unwrap_or(0);
518    if tokens == 0 && cost == 0 {
519        return Err("tokens or cost_micros must be positive".to_string());
520    }
521    mutate_store(request, |store| {
522        let graph = store.graph_mut(request.graph_id)?;
523        authorize_node(graph, node, request.agent_id)?;
524        graph
525            .consume_budget(node, tokens, cost)
526            .map_err(|error| error.to_string())?;
527        Ok(())
528    })?;
529    get(request)
530}
531
532fn complete(request: &Request<'_>) -> Result<String, String> {
533    let node = required(request.node_id, "node_id")?;
534    validate_id(node, "node_id")?;
535    let outcome = required(request.outcome_ref, "outcome_ref")?;
536    bounded_ref(outcome, "outcome_ref")?;
537    mutate_store(request, |store| {
538        let graph = store.graph_mut(request.graph_id)?;
539        authorize_node(graph, node, request.agent_id)?;
540        if graph
541            .get_node(node)
542            .is_some_and(|work_node| work_node.parent_node_id.is_some())
543        {
544            return Err("child nodes must finish with a child receipt".to_string());
545        }
546        if has_unfinished_descendants(graph, node) {
547            return Err("root cannot complete while descendants are unfinished".to_string());
548        }
549        graph
550            .complete(node, outcome.to_string())
551            .map_err(|error| error.to_string())
552    })?;
553    get(request)
554}
555
556/// Terminal child receipt from the node owner or the host that delegated it.
557/// A claimed node is bound by its fence; the figures are reported by the
558/// caller and stay bounded by the node and chain budgets.
559fn receipt(request: &Request<'_>) -> Result<String, String> {
560    let node = required(request.node_id, "node_id")?;
561    validate_id(node, "node_id")?;
562    let receipt_id = required(request.receipt_id, "receipt_id")?;
563    validate_id(receipt_id, "receipt_id")?;
564    let outcome_ref = required(request.outcome_ref, "outcome_ref")?;
565    bounded_ref(outcome_ref, "outcome_ref")?;
566    let outcome = match required(request.outcome, "outcome")? {
567        "accepted" => ChildOutcome::Accepted,
568        "rejected" => ChildOutcome::Rejected,
569        "partial" => ChildOutcome::Partial,
570        _ => return Err("outcome must be accepted|rejected|partial".to_string()),
571    };
572    let claims: Vec<ResultClaim> = request
573        .claims
574        .map_or_else(
575            || Ok(Vec::new()),
576            |value| serde_json::from_value(value.clone()),
577        )
578        .map_err(|error| format!("invalid claims: {error}"))?;
579    let finished = mutate_store(request, |store| {
580        let graph = store.graph_mut(request.graph_id)?;
581        authorize_node_or_parent(graph, node, request.agent_id)?;
582        let work_node = graph
583            .get_node(node)
584            .ok_or_else(|| format!("node not found: {node}"))?
585            .clone();
586        if work_node.execution_fence.is_some() && request.execution_fence.is_none() {
587            return Err(
588                "receipt requires the execution_fence returned by action=start or action=claim"
589                    .into(),
590            );
591        }
592        graph
593            .record_child_receipt(ChildExecutionReceipt {
594                receipt_id: receipt_id.to_string(),
595                node_id: node.to_string(),
596                outcome_ref: outcome_ref.to_string(),
597                outcome,
598                tokens_consumed: request.tokens.unwrap_or(0),
599                cost_micros_consumed: request.cost_micros.unwrap_or(0),
600                execution_fence: request.execution_fence.map(str::to_string),
601                claims,
602                usage_source: UsageSource::Reported,
603            })
604            .map_err(|error| error.to_string())?;
605        Ok(work_node)
606    })?;
607    // The receipt reports the child finished, so its leases end with it.
608    if let (true, Some(fence)) = (
609        finished.execution_started,
610        finished.execution_fence.as_deref(),
611    ) {
612        release_incarnation_leases(&finished.agent_id, fence);
613    }
614    get(request)
615}
616
617fn accept(request: &Request<'_>) -> Result<String, String> {
618    let authorizer = required(request.node_id, "node_id")?;
619    let accepted: Vec<String> = request
620        .accepted_nodes
621        .ok_or_else(|| "accepted_nodes is required".to_string())
622        .and_then(|value| {
623            serde_json::from_value(value.clone())
624                .map_err(|error| format!("invalid accepted_nodes: {error}"))
625        })?;
626    if accepted.is_empty() {
627        return Err("accepted_nodes must not be empty".to_string());
628    }
629    mutate_store(request, |store| {
630        let graph = store.graph_mut(request.graph_id)?;
631        let root = graph
632            .get_node(authorizer)
633            .ok_or_else(|| format!("node not found: {authorizer}"))?;
634        if root.parent_node_id.is_some() || root.agent_id != request.agent_id {
635            return Err("accepted path may only be selected by the root owner".to_string());
636        }
637        for node in &accepted {
638            validate_id(node, "accepted_node")?;
639        }
640        graph
641            .mark_accepted_path(&accepted)
642            .map_err(|error| error.to_string())
643    })?;
644    get(request)
645}
646
647fn fuse(request: &Request<'_>) -> Result<String, String> {
648    let store = WorkGraphStore::load(request.project_root)?;
649    let graph = store
650        .graph(request.graph_id)
651        .ok_or_else(|| format!("graph not found: {}", request.graph_id))?;
652    authorize_member(graph, request.agent_id)?;
653    let result = graph
654        .fuse_accepted_results()
655        .map_err(|error| error.to_string())?;
656    serde_json::to_string(&result).map_err(|error| error.to_string())
657}
658
659fn attribution(request: &Request<'_>) -> Result<String, String> {
660    let store = WorkGraphStore::load(request.project_root)?;
661    let graph = store
662        .graph(request.graph_id)
663        .ok_or_else(|| format!("graph not found: {}", request.graph_id))?;
664    authorize_member(graph, request.agent_id)?;
665    let result = graph.attribution().map_err(|error| error.to_string())?;
666    serde_json::to_string(&result).map_err(|error| error.to_string())
667}
668
669fn value_report(request: &Request<'_>) -> Result<String, String> {
670    let store = WorkGraphStore::load(request.project_root)?;
671    let graph = store
672        .graph(request.graph_id)
673        .ok_or_else(|| format!("graph not found: {}", request.graph_id))?;
674    authorize_member(graph, request.agent_id)?;
675    serde_json::to_string(
676        &graph
677            .team_value_report()
678            .map_err(|error| error.to_string())?,
679    )
680    .map_err(|error| error.to_string())
681}
682
683/// Durable stop by the node owner or its delegating host. The stop revokes the
684/// child's delegated delivery at once; the host ends its own child process.
685fn cancel(request: &Request<'_>) -> Result<String, String> {
686    let node = required(request.node_id, "node_id")?;
687    validate_id(node, "node_id")?;
688    mutate_store(request, |store| {
689        let graph = store.graph_mut(request.graph_id)?;
690        authorize_node_or_parent(graph, node, request.agent_id)?;
691        let reason = match request.stop_reason.unwrap_or("manual_stop") {
692            "manual_stop" => StopReason::ManualStop,
693            "stale" => StopReason::Stale,
694            "redundant" => StopReason::Redundant,
695            "policy_denied" => StopReason::PolicyDenied,
696            "lease_lost" => StopReason::LeaseLost,
697            "duplicate" => StopReason::Duplicate,
698            "low_value" => StopReason::LowValue,
699            "execution_failed" => StopReason::ExecutionFailed,
700            other => return Err(format!("unsupported stop_reason: {other}")),
701        };
702        graph
703            .stop(node, reason)
704            .map(|_| ())
705            .map_err(|error| error.to_string())
706    })?;
707    // The stop revokes delivery at once. The stopped children's leases stay
708    // until their windows end: the host may still be ending those processes.
709    get(request)
710}
711
712fn get(request: &Request<'_>) -> Result<String, String> {
713    let store = WorkGraphStore::load(request.project_root)?;
714    let graph = store
715        .graph(request.graph_id)
716        .ok_or_else(|| format!("graph not found: {}", request.graph_id))?;
717    authorize_member(graph, request.agent_id)?;
718    serde_json::to_string(graph).map_err(|error| error.to_string())
719}
720
721fn observe(request: &Request<'_>) -> Result<String, String> {
722    let store = WorkGraphStore::load(request.project_root)?;
723    let graph = store
724        .graph(request.graph_id)
725        .ok_or_else(|| format!("graph not found: {}", request.graph_id))?;
726    authorize_member(graph, request.agent_id)?;
727    let mut observation = graph.observe_if_changed(request.if_revision);
728    // The precondition for a guarded write (if_revision on a mutating action).
729    observation["write_revision"] = store.graph_revision(request.graph_id)?.into();
730    serde_json::to_string(&observation).map_err(|error| error.to_string())
731}
732
733fn list(project_root: &str, agent_id: &str) -> Result<String, String> {
734    let store = WorkGraphStore::load(project_root)?;
735    serde_json::to_string(
736        &json!({"graph_ids": store.graph_ids_for_agent(agent_id).collect::<Vec<_>>() }),
737    )
738    .map_err(|error| error.to_string())
739}
740
741fn budget(tokens: u64, cost: u64) -> WorkNodeBudget {
742    WorkNodeBudget {
743        tokens_allocated: tokens,
744        tokens_consumed: 0,
745        cost_micros_allocated: cost,
746        cost_micros_consumed: 0,
747    }
748}
749
750/// Names every missing field of an action at once. Reported one at a time,
751/// callers retried field by field (telemetry 10/2026: 11 of 45 failures).
752fn check_required_fields(request: &Request<'_>) -> Result<(), String> {
753    let fields: &[&str] = match request.action {
754        "create" => &[
755            "node_id",
756            "capsule_ref",
757            "task_ref",
758            "policy_ref",
759            "expected_outcome_ref",
760            "tokens",
761            "cost_micros",
762        ],
763        "delegate" => &[
764            "parent_node_id",
765            "node_id",
766            "to_agent",
767            "capsule_ref",
768            "task_ref",
769            "expected_outcome_ref",
770            "tokens",
771            "cost_micros",
772        ],
773        "claim" | "start" | "consume" | "cancel" => &["node_id"],
774        "complete" => &["node_id", "outcome_ref"],
775        "receipt" => &["node_id", "receipt_id", "outcome_ref", "outcome"],
776        "accept" => &["node_id", "accepted_nodes"],
777        _ => &[],
778    };
779    let present = |field: &str| match field {
780        "node_id" => request.node_id.is_some_and(|v| !v.is_empty()),
781        "parent_node_id" => request.parent_node_id.is_some_and(|v| !v.is_empty()),
782        "to_agent" => request.to_agent.is_some_and(|v| !v.is_empty()),
783        "capsule_ref" => request.capsule_ref.is_some_and(|v| !v.is_empty()),
784        "task_ref" => request.task_ref.is_some_and(|v| !v.is_empty()),
785        "policy_ref" => request.policy_ref.is_some_and(|v| !v.is_empty()),
786        "expected_outcome_ref" => request.expected_outcome_ref.is_some_and(|v| !v.is_empty()),
787        "outcome_ref" => request.outcome_ref.is_some_and(|v| !v.is_empty()),
788        "receipt_id" => request.receipt_id.is_some_and(|v| !v.is_empty()),
789        "outcome" => request.outcome.is_some_and(|v| !v.is_empty()),
790        "tokens" => request.tokens.is_some(),
791        "cost_micros" => request.cost_micros.is_some(),
792        "accepted_nodes" => request.accepted_nodes.is_some(),
793        _ => true,
794    };
795    let missing: Vec<&str> = fields.iter().copied().filter(|f| !present(f)).collect();
796    if missing.is_empty() {
797        return Ok(());
798    }
799    Err(format!(
800        "{} requires {}; missing: {}",
801        request.action,
802        fields.join(", "),
803        missing.join(", ")
804    ))
805}
806
807fn required<'a>(value: Option<&'a str>, field: &str) -> Result<&'a str, String> {
808    value
809        .filter(|value| !value.is_empty())
810        .ok_or_else(|| format!("{field} is required"))
811}
812
813fn positive(value: Option<u64>, field: &str) -> Result<u64, String> {
814    value
815        .filter(|value| *value > 0)
816        .ok_or_else(|| format!("{field} must be positive"))
817}
818
819fn bounded_ref(value: &str, field: &str) -> Result<(), String> {
820    if value.len() > 4096 {
821        return Err(format!("{field} exceeds 4096 bytes"));
822    }
823    Ok(())
824}
825
826fn canonical_path_claim(project_root: &str, claim: &str) -> Result<String, String> {
827    let relative = claim
828        .strip_prefix("path:")
829        .ok_or_else(|| "path claim must use path: scheme".to_string())?;
830    if relative.is_empty()
831        || relative.starts_with('/')
832        || relative.starts_with('\\')
833        || relative
834            .split(['/', '\\'])
835            .any(|part| part.is_empty() || part == "." || part == "..")
836        || relative.chars().any(char::is_control)
837    {
838        return Err("path claim must be a normalized project-relative path".into());
839    }
840    let root = std::path::Path::new(project_root)
841        .canonicalize()
842        .map_err(|error| format!("invalid project root: {error}"))?;
843    let candidate = root.join(relative);
844    let mut cursor = root.clone();
845    for component in std::path::Path::new(relative).components() {
846        cursor.push(component);
847        if let Ok(metadata) = std::fs::symlink_metadata(&cursor)
848            && metadata.file_type().is_symlink()
849        {
850            return Err(format!("path claim traverses symlink: {relative}"));
851        }
852    }
853    if candidate.exists() {
854        let canonical = candidate
855            .canonicalize()
856            .map_err(|error| format!("invalid path claim: {error}"))?;
857        if !canonical.starts_with(&root) {
858            return Err("path claim escapes project root".into());
859        }
860    }
861    let project_hash = crate::core::project_hash::hash_project_root(project_root);
862    Ok(format!("path:{project_hash}/{relative}"))
863}
864
865fn authorize_node(graph: &BoundedWorkGraph, node_id: &str, agent_id: &str) -> Result<(), String> {
866    let node = graph
867        .get_node(node_id)
868        .ok_or_else(|| format!("node not found: {node_id}"))?;
869    if node.agent_id != agent_id {
870        return Err(format!("agent {agent_id} does not own node {node_id}"));
871    }
872    Ok(())
873}
874
875/// The node's owner, or the owner of its direct parent that delegated it.
876fn authorize_node_or_parent(
877    graph: &BoundedWorkGraph,
878    node_id: &str,
879    agent_id: &str,
880) -> Result<(), String> {
881    let node = graph
882        .get_node(node_id)
883        .ok_or_else(|| format!("node not found: {node_id}"))?;
884    let delegator = node
885        .parent_node_id
886        .as_deref()
887        .and_then(|parent| graph.get_node(parent))
888        .map(|parent| parent.agent_id.as_str());
889    if node.agent_id == agent_id || delegator == Some(agent_id) {
890        return Ok(());
891    }
892    Err(format!(
893        "agent {agent_id} neither owns node {node_id} nor delegated it"
894    ))
895}
896
897fn authorize_member(graph: &BoundedWorkGraph, agent_id: &str) -> Result<(), String> {
898    if graph.contains_agent(agent_id) {
899        return Ok(());
900    }
901    Err(format!("agent {agent_id} is not a member of this graph"))
902}
903
904fn has_unfinished_descendants(graph: &BoundedWorkGraph, node_id: &str) -> bool {
905    graph.children_of(node_id).iter().any(|child_id| {
906        graph.get_node(child_id).is_some_and(|node| {
907            matches!(
908                node.status,
909                crate::core::work_graph::NodeStatus::Pending
910                    | crate::core::work_graph::NodeStatus::Active
911            )
912        }) || has_unfinished_descendants(graph, child_id)
913    })
914}
915
916fn ensure_active_agent(project_root: &str, agent_id: &str) -> Result<(), String> {
917    let registry = crate::core::agents::AgentRegistry::load_or_create();
918    if registry
919        .list_active(Some(project_root))
920        .iter()
921        .any(|agent| agent.agent_id == agent_id)
922    {
923        return Ok(());
924    }
925    Err(format!(
926        "agent is not active in this project: {agent_id} — register it first with \
927         ctx_agent action=register (agent ids are per project)"
928    ))
929}
930
931#[cfg(test)]
932#[path = "ctx_work_graph_lifecycle_tests.rs"]
933mod lifecycle_tests;