Skip to main content

adk_graph/
governed.rs

1//! Governed graph nodes: a node whose call goes through the governed path, at most once
2//! per lineage (spec 3.3 §12 developer track, §7.1–§7.4, §11 S-I1, S-I2).
3//!
4//! A graph opts a node in with [`CompiledGraph::with_governed_node`] or
5//! [`GraphAgentBuilder::governed_node`](crate::agent::GraphAgentBuilder::governed_node).
6//! Every dispatch of that node then runs this bracket instead of calling the node
7//! directly:
8//!
9//! | Order | Check | Outcome |
10//! |-------|-------|---------|
11//! | 0 | Gate: the parent invocation, or the `RunConfig` of [`CompiledGraph::invoke_with_run_config`] | Without one the node is not run ([`GovernedError::NotRun`]) |
12//! | 1 | Kill switch | Frozen: refused before anything is touched ([`GovernedError::Frozen`]) |
13//! | 1a | [`Node::will_act`] | A node that does nothing here completes with no writes and no decision; one that cannot act fails without asking anyone |
14//! | 1b | An action ledger and a checkpointer | Without either the node is not run ([`GovernedError::Unavailable`]): its call could not be kept to once |
15//! | 2 | Action-ledger lookup | A completed call is answered from its record and the effect log; a failed one fails again; one begun without an outcome fails closed |
16//! | 3 | [`adk_core::authorize_tool_call`] | Pending: the node pauses and the call waits in the inbox. Refused: not run. Execute: begin, run, complete, append to the effect log |
17//!
18//! The ledger lookup comes before the governed path, unlike `LlmAgent`'s order: a call
19//! that already happened is answered from its record, so it never creates a decision
20//! (spec 3.3 §11 S-I1).
21//!
22//! The ledger key is `graph/{acting agent id}/{lineage root}/{node}/{occurrence}/{digest}`,
23//! where the occurrence counts the node's completed runs in the lineage and the digest is
24//! [`adk_core::json_digest`] of [`Node::call_args`]. A fork keeps the lineage root and the
25//! occurrence counts, so a fork whose call is unchanged is answered from the original's
26//! record, and a fork whose call changed waits for a person.
27//!
28//! A node resuming its own pause before a decision exists pauses again without asking
29//! anyone again; a call that changed while it waited, or that a record answers, has its
30//! waiting decision withdrawn. A governed node inside a subgraph keys its record by the
31//! parent's lineage.
32//!
33//! A call that may have reached its destination without an outcome coming back — a timeout,
34//! or an HTTP node's answer it could not accept — keeps its record begun, so a later
35//! dispatch fails closed with `graph.outcome_unknown`. An action node sends a governed call
36//! once: its error handling neither retries it nor hides its failure.
37//!
38//! The effect log thread `{lineage root}:effects` holds each executed call's writes. Only
39//! this bracket writes it; forks never do, and checkpoint retention never prunes it, so
40//! sibling forks find effects another fork ran.
41//!
42//! # Example
43//!
44//! ```
45//! use adk_core::ToolEffect;
46//! use adk_graph::edge::{END, START};
47//! use adk_graph::governed::GovernedNode;
48//! use adk_graph::graph::StateGraph;
49//! use adk_graph::node::NodeOutput;
50//!
51//! let graph = StateGraph::with_channels(&["charge"])
52//!     .add_node_fn("pay", |_ctx| async { Ok(NodeOutput::new()) })
53//!     .add_edge(START, "pay")
54//!     .add_edge("pay", END)
55//!     .compile()?
56//!     .with_node_effect("pay", ToolEffect::NonIdempotent)
57//!     .with_governed_node("pay", GovernedNode::new().with_approval().spending_money());
58//! assert_eq!(graph.shape().nodes[0].governed, Some(GovernedNode::new().with_approval().spending_money()));
59//! # Ok::<(), adk_graph::GraphError>(())
60//! ```
61
62use std::collections::BTreeMap;
63use std::sync::Arc;
64use std::time::Duration;
65
66use adk_core::{
67    ActionOutcome, ActionRecord, ApprovalScope, GovernedCall, RunConfig, ToolAuthorization,
68    ToolConfirmationRequest, ToolEffect, ToolGate, ToolOrigin,
69};
70use chrono::{DateTime, Utc};
71use serde::{Deserialize, Serialize};
72use serde_json::Value;
73use thiserror::Error;
74
75use crate::checkpoint::Checkpointer;
76use crate::error::{GraphError, Result};
77use crate::graph::CompiledGraph;
78use crate::interrupt::GraphToolConfirmationPause;
79use crate::node::{Node, NodeContext, NodeOutput};
80use crate::record::NodeStatus;
81use crate::state::{Checkpoint, State};
82
83/// How a governed node is governed (spec 3.3 §12).
84///
85/// # Example
86///
87/// ```
88/// use adk_graph::governed::GovernedNode;
89///
90/// let pay = GovernedNode::new().with_approval().spending_money();
91/// assert!(pay.requires_approval && pay.spends_money);
92/// assert_eq!(serde_json::to_value(pay)?, serde_json::json!({
93///     "requiresApproval": true,
94///     "spendsMoney": true,
95/// }));
96/// # Ok::<(), serde_json::Error>(())
97/// ```
98#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct GovernedNode {
101    /// Whether every call waits for a person, whatever the policy says.
102    pub requires_approval: bool,
103    /// Whether the call spends money, so surfaces treat its decision as high risk.
104    pub spends_money: bool,
105}
106
107impl GovernedNode {
108    /// A governed node that the policy alone decides and that spends no money.
109    pub fn new() -> Self {
110        Self::default()
111    }
112
113    /// Every call waits for a person.
114    #[must_use]
115    pub fn with_approval(mut self) -> Self {
116        self.requires_approval = true;
117        self
118    }
119
120    /// The call spends money.
121    #[must_use]
122    pub fn spending_money(mut self) -> Self {
123        self.spends_money = true;
124        self
125    }
126}
127
128/// Why a governed node did not run, or failed without running (spec 3.3 §12).
129///
130/// A run reports these as [`GraphError::NodeExecutionFailed`] whose message starts with
131/// [`code`](Self::code); [`GovernedError::code_of`] reads the code back.
132///
133/// # Example
134///
135/// ```
136/// use adk_graph::GraphError;
137/// use adk_graph::governed::GovernedError;
138///
139/// let error: GraphError = GovernedError::NotRun { node: "pay".to_string() }.into();
140/// assert_eq!(GovernedError::code_of(&error), Some("graph.not_run"));
141/// ```
142#[derive(Debug, Clone, PartialEq, Eq, Error)]
143#[non_exhaustive]
144pub enum GovernedError {
145    /// The run has no approval gate, so the node is not run.
146    #[error(
147        "graph.not_run: governed node '{node}' was not run: the run has no approval gate. Run \
148         the graph as a GraphAgent under a Runner, or with invoke_with_run_config"
149    )]
150    NotRun {
151        /// The governed node.
152        node: String,
153    },
154    /// The kill switch is frozen.
155    #[error("graph.frozen: governed node '{node}' was not run: {reason}")]
156    Frozen {
157        /// The governed node.
158        node: String,
159        /// Why the kill switch refused it.
160        reason: String,
161    },
162    /// The policy, a person, or the resumption check refused the call.
163    #[error("graph.refused: governed node '{node}' was not run: {reason}")]
164    Refused {
165        /// The governed node.
166        node: String,
167        /// Why the call was refused.
168        reason: String,
169    },
170    /// The call ran before and failed; it is not run again.
171    #[error(
172        "graph.recorded_failure: governed node '{node}' already ran this call and it failed: \
173         {error}. It is not run again; fork with changed state to make a new call"
174    )]
175    RecordedFailure {
176        /// The governed node.
177        node: String,
178        /// The error the call failed with.
179        error: String,
180    },
181    /// The call began and recorded no outcome, so it may have taken effect.
182    #[error(
183        "graph.outcome_unknown: governed node '{node}' began this call before and recorded no \
184         outcome, so it may have taken effect. It is not run again; check the effect, then \
185         fork with changed state to make a new call (ledger key '{key}')"
186    )]
187    OutcomeUnknown {
188        /// The governed node.
189        node: String,
190        /// The call's action-ledger key.
191        key: String,
192    },
193    /// The call completed, but its writes are not in the effect log.
194    #[error(
195        "graph.effect_unavailable: governed node '{node}' already completed this call, but \
196         its writes are not in the effect log. It is not run again (ledger key '{key}')"
197    )]
198    EffectUnavailable {
199        /// The governed node.
200        node: String,
201        /// The call's action-ledger key.
202        key: String,
203    },
204    /// An approver edited the call and the node cannot run an edited call.
205    #[error(
206        "graph.edit_unsupported: governed node '{node}' cannot run an edited call, so it was \
207         not run. Approve the call as shown, or deny it"
208    )]
209    EditUnsupported {
210        /// The governed node.
211        node: String,
212    },
213    /// The action ledger, the approval gate or the effect log could not be read or written,
214    /// or the run has no action ledger or the graph no checkpointer to keep the call to once.
215    #[error("graph.unavailable: governed node '{node}' was not run: {detail}")]
216    Unavailable {
217        /// The governed node.
218        node: String,
219        /// What could not be reached.
220        detail: String,
221    },
222}
223
224impl GovernedError {
225    /// Every code a governed failure starts with.
226    pub const CODES: [&'static str; 8] = [
227        "graph.not_run",
228        "graph.frozen",
229        "graph.refused",
230        "graph.recorded_failure",
231        "graph.outcome_unknown",
232        "graph.effect_unavailable",
233        "graph.edit_unsupported",
234        "graph.unavailable",
235    ];
236
237    /// The stable code this failure's message starts with.
238    ///
239    /// # Example
240    ///
241    /// ```
242    /// use adk_graph::governed::GovernedError;
243    ///
244    /// let error = GovernedError::EditUnsupported { node: "pay".to_string() };
245    /// assert_eq!(error.code(), "graph.edit_unsupported");
246    /// assert!(error.to_string().starts_with("graph.edit_unsupported:"));
247    /// ```
248    pub fn code(&self) -> &'static str {
249        match self {
250            Self::NotRun { .. } => Self::CODES[0],
251            Self::Frozen { .. } => Self::CODES[1],
252            Self::Refused { .. } => Self::CODES[2],
253            Self::RecordedFailure { .. } => Self::CODES[3],
254            Self::OutcomeUnknown { .. } => Self::CODES[4],
255            Self::EffectUnavailable { .. } => Self::CODES[5],
256            Self::EditUnsupported { .. } => Self::CODES[6],
257            Self::Unavailable { .. } => Self::CODES[7],
258        }
259    }
260
261    /// The governed code a graph error carries, if it is a governed failure.
262    ///
263    /// # Example
264    ///
265    /// ```
266    /// use adk_graph::GraphError;
267    /// use adk_graph::governed::GovernedError;
268    ///
269    /// let other = GraphError::NodeExecutionFailed { node: "x".into(), message: "boom".into() };
270    /// assert_eq!(GovernedError::code_of(&other), None);
271    /// ```
272    pub fn code_of(error: &GraphError) -> Option<&'static str> {
273        let GraphError::NodeExecutionFailed { message, .. } = error else { return None };
274        Self::CODES
275            .into_iter()
276            .find(|code| message.strip_prefix(code).is_some_and(|rest| rest.starts_with(':')))
277    }
278
279    /// The node this failure belongs to.
280    fn node(&self) -> &str {
281        match self {
282            Self::NotRun { node }
283            | Self::Frozen { node, .. }
284            | Self::Refused { node, .. }
285            | Self::RecordedFailure { node, .. }
286            | Self::OutcomeUnknown { node, .. }
287            | Self::EffectUnavailable { node, .. }
288            | Self::EditUnsupported { node }
289            | Self::Unavailable { node, .. } => node,
290        }
291    }
292
293    /// The status a node that failed this way is recorded with.
294    fn status(&self) -> NodeStatus {
295        match self {
296            Self::NotRun { .. } => NodeStatus::NotRun,
297            Self::Frozen { .. } | Self::Refused { .. } | Self::EditUnsupported { .. } => {
298                NodeStatus::Refused
299            }
300            Self::RecordedFailure { .. }
301            | Self::OutcomeUnknown { .. }
302            | Self::EffectUnavailable { .. }
303            | Self::Unavailable { .. } => NodeStatus::Failed,
304        }
305    }
306}
307
308impl From<GovernedError> for GraphError {
309    fn from(error: GovernedError) -> Self {
310        GraphError::NodeExecutionFailed {
311            node: error.node().to_string(),
312            message: error.to_string(),
313        }
314    }
315}
316
317/// Checkpoint metadata key of one effect-log entry.
318pub const EFFECT_METADATA_KEY: &str = "adk.graph.effect";
319
320/// What one executed governed call wrote, as the effect log keeps it (spec 3.3 §12).
321///
322/// # Example
323///
324/// ```
325/// use adk_graph::governed::EffectRecord;
326///
327/// let effect = EffectRecord {
328///     key: "graph/urn:adk:agent:app/invoice-run/t1/pay/1/fnv1a128:00".to_string(),
329///     node: "pay".to_string(),
330///     writes: [("charge".to_string(), serde_json::json!({ "id": "ch_1" }))].into(),
331///     goto: None,
332///     goto_parent: None,
333///     thread: "t1".to_string(),
334///     checkpoint: "c2".to_string(),
335///     at: chrono::Utc::now(),
336/// };
337/// assert_eq!(serde_json::to_value(&effect)?["writes"]["charge"]["id"], "ch_1");
338/// # Ok::<(), serde_json::Error>(())
339/// ```
340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
341#[serde(rename_all = "camelCase")]
342pub struct EffectRecord {
343    /// The call's action-ledger key.
344    pub key: String,
345    /// The governed node that made the call.
346    pub node: String,
347    /// The state updates the node returned.
348    pub writes: BTreeMap<String, Value>,
349    /// The successors the node named in place of its edges, if it named any.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub goto: Option<Vec<String>>,
352    /// The nodes of the graph holding a subgraph that the node handed control to, if it
353    /// named any.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub goto_parent: Option<Vec<String>>,
356    /// The thread the call ran on.
357    pub thread: String,
358    /// The checkpoint that records the step the call ran in.
359    pub checkpoint: String,
360    /// When the call completed, to the microsecond.
361    pub at: DateTime<Utc>,
362}
363
364/// The effect-log thread of the lineage that started at thread `root`.
365///
366/// # Example
367///
368/// ```
369/// assert_eq!(adk_graph::governed::effect_log_thread("t1"), "t1:effects");
370/// ```
371pub fn effect_log_thread(root: &str) -> String {
372    format!("{root}:effects")
373}
374
375/// Every entry of the effect log of the lineage that started at thread `root`, oldest
376/// first.
377///
378/// # Errors
379///
380/// Returns the checkpointer's error, or [`GraphError::SerializationError`] for a
381/// malformed entry.
382///
383/// # Example
384///
385/// ```
386/// use adk_graph::checkpoint::MemoryCheckpointer;
387///
388/// # #[tokio::main(flavor = "current_thread")]
389/// # async fn main() -> adk_graph::Result<()> {
390/// let checkpointer = MemoryCheckpointer::new();
391/// assert!(adk_graph::governed::effect_log(&checkpointer, "t1").await?.is_empty());
392/// # Ok(())
393/// # }
394/// ```
395pub async fn effect_log(checkpointer: &dyn Checkpointer, root: &str) -> Result<Vec<EffectRecord>> {
396    let entries = checkpointer.list(&effect_log_thread(root)).await?;
397    entries
398        .iter()
399        .filter_map(|checkpoint| checkpoint.metadata.get(EFFECT_METADATA_KEY))
400        .map(|value| {
401            serde_json::from_value(value.clone()).map_err(|error| {
402                GraphError::SerializationError(format!("effect log entry is malformed: {error}"))
403            })
404        })
405        .collect()
406}
407
408/// Appends `entry` to the effect log of `root`, after its newest entry.
409async fn append_effect(
410    checkpointer: &dyn Checkpointer,
411    root: &str,
412    entry: &EffectRecord,
413) -> Result<()> {
414    let thread = effect_log_thread(root);
415    let value = serde_json::to_value(entry)?;
416    // Sibling forks append to one log; a conflict means another fork appended first.
417    for _ in 0..16 {
418        let (version, index) = checkpointer
419            .load(&thread)
420            .await?
421            .map_or((1, 0), |newest| (newest.version + 1, newest.step + 1));
422        let checkpoint = Checkpoint::new(&thread, State::new(), index, Vec::new())
423            .with_version(version)
424            .with_metadata(EFFECT_METADATA_KEY, value.clone());
425        match checkpointer.save(&checkpoint).await {
426            Ok(_) => return Ok(()),
427            Err(GraphError::CheckpointConflict { .. }) => continue,
428            Err(error) => return Err(error),
429        }
430    }
431    Err(GraphError::CheckpointError(format!(
432        "the effect log '{thread}' kept changing while an entry was appended"
433    )))
434}
435
436/// The agent name a governed node acts under when the run has no parent invocation.
437pub(crate) const STANDALONE_AGENT_NAME: &str = "graph";
438
439/// How many refused attempts one call may record before its key is exhausted.
440const MAX_SLOTS: u32 = 16;
441
442/// Everything one dispatch of a governed node needs, taken from the executor before the
443/// step's futures start.
444pub(crate) struct GovernedDispatch {
445    pub(crate) node_name: String,
446    pub(crate) node: Arc<dyn Node>,
447    pub(crate) governed: GovernedNode,
448    pub(crate) effect: ToolEffect,
449    /// The node's shape entry, which its `ToolOrigin` binds to.
450    pub(crate) declaration: Value,
451    pub(crate) root: String,
452    pub(crate) run_id: String,
453    pub(crate) occurrence: u32,
454    /// The request this node paused with, when this dispatch resumes that pause.
455    pub(crate) held: Option<ToolConfirmationRequest>,
456    pub(crate) checkpointer: Option<Arc<dyn Checkpointer>>,
457    pub(crate) thread_id: String,
458    /// The id of the checkpoint that will record this step.
459    pub(crate) checkpoint_id: String,
460    pub(crate) run_timeout: Option<Duration>,
461}
462
463/// What one dispatch of a governed node produced.
464pub(crate) struct GovernedRun {
465    pub(crate) output: Result<NodeOutput>,
466    pub(crate) status: NodeStatus,
467    pub(crate) effect_key: Option<String>,
468    /// The request the node paused with, when it paused for a decision.
469    pub(crate) held: Option<ToolConfirmationRequest>,
470}
471
472impl GovernedRun {
473    fn failed(error: GovernedError, effect_key: Option<String>) -> Self {
474        let status = error.status();
475        Self { output: Err(error.into()), status, effect_key, held: None }
476    }
477}
478
479impl CompiledGraph {
480    /// Puts a node's calls on the governed path (spec 3.3 §12).
481    ///
482    /// The node then runs only through the approval gate of the run that holds it, at
483    /// most once per call in its lineage; see the [module documentation](self). A graph
484    /// that governs no node behaves as before.
485    ///
486    /// # Example
487    ///
488    /// ```
489    /// use adk_graph::edge::{END, START};
490    /// use adk_graph::governed::GovernedNode;
491    /// use adk_graph::graph::StateGraph;
492    /// use adk_graph::node::NodeOutput;
493    ///
494    /// let graph = StateGraph::with_channels(&["sent"])
495    ///     .add_node_fn("notify", |_ctx| async { Ok(NodeOutput::new()) })
496    ///     .add_edge(START, "notify")
497    ///     .add_edge("notify", END)
498    ///     .compile()?
499    ///     .with_governed_node("notify", GovernedNode::new().with_approval());
500    /// assert!(graph.shape().nodes[0].governed.is_some());
501    /// # Ok::<(), adk_graph::GraphError>(())
502    /// ```
503    #[must_use]
504    pub fn with_governed_node(mut self, node: &str, governed: GovernedNode) -> Self {
505        self.governed_nodes.insert(node.to_string(), governed);
506        self
507    }
508
509    /// Whether `node` is governed.
510    pub(crate) fn is_governed(&self, node: &str) -> bool {
511        self.governed_nodes.contains_key(node)
512    }
513
514    /// Fails when a name governed is not a node of this graph: the node meant would run
515    /// ungoverned.
516    pub(crate) fn check_governed_nodes(&self) -> Result<()> {
517        let mut unknown: Vec<&String> =
518            self.governed_nodes.keys().filter(|name| !self.nodes.contains_key(*name)).collect();
519        unknown.sort();
520        match unknown.first() {
521            Some(name) => Err(GraphError::InvalidGraph(format!(
522                "governed node '{name}' is not a node of this graph, so the node it names \
523                 would run ungoverned. Govern a node by the name it was added under"
524            ))),
525            None => Ok(()),
526        }
527    }
528}
529
530/// Runs one dispatch of a governed node through the bracket described in the
531/// [module documentation](self).
532pub(crate) async fn dispatch(dispatch: GovernedDispatch, ctx: &NodeContext) -> GovernedRun {
533    debug_assert!(ctx.governed_call(), "a governed node's context is marked as its call");
534    let node = dispatch.node_name.clone();
535    let parent = ctx.config.parent_context.clone();
536    let explicit = ctx.run_config();
537
538    // 0. The gate. Without one the node never falls back to running ungoverned.
539    let run_config: &RunConfig = match (&explicit, &parent) {
540        (Some(config), _) => config,
541        (None, Some(parent)) => parent.run_config(),
542        (None, None) => {
543            tracing::warn!(node = %node, "governed node not run: the run has no approval gate");
544            return GovernedRun::failed(GovernedError::NotRun { node }, None);
545        }
546    };
547    let gate = match (&explicit, &parent) {
548        (None, Some(parent)) => ToolGate::for_context(parent.as_ref()),
549        (_, Some(parent)) => ToolGate::new(
550            run_config,
551            parent.agent_name(),
552            parent.invocation_id(),
553            ApprovalScope::new(parent.app_name(), parent.user_id(), parent.session_id()),
554        ),
555        (_, None) => ToolGate::new(
556            run_config,
557            STANDALONE_AGENT_NAME,
558            &dispatch.run_id,
559            ApprovalScope::new(
560                crate::node::STANDALONE_APP_NAME,
561                crate::node::STANDALONE_USER_ID,
562                &dispatch.thread_id,
563            ),
564        ),
565    };
566    let agent_name = parent.as_ref().map_or(STANDALONE_AGENT_NAME, |parent| parent.agent_name());
567
568    // 1. The kill switch, before anything is touched.
569    if let Err(frozen) = run_config.check_governance() {
570        return GovernedRun::failed(GovernedError::Frozen { node, reason: frozen.message }, None);
571    }
572
573    // A node that does nothing here, or cannot act, asks no one about a call that would
574    // not run.
575    match dispatch.node.will_act(ctx) {
576        Ok(true) => {}
577        Ok(false) => {
578            tracing::debug!(node = %node, "governed node does nothing here; no decision");
579            if let Some(held) = dispatch.held.as_ref() {
580                withdraw(&gate, held, &node).await;
581            }
582            return GovernedRun {
583                output: Ok(NodeOutput::new()),
584                status: NodeStatus::Done,
585                effect_key: None,
586                held: None,
587            };
588        }
589        Err(error) => {
590            if let Some(held) = dispatch.held.as_ref() {
591                withdraw(&gate, held, &node).await;
592            }
593            return GovernedRun {
594                output: Err(error),
595                status: NodeStatus::Failed,
596                effect_key: None,
597                held: None,
598            };
599        }
600    }
601
602    // The call is kept to once by the action ledger and the lineage's checkpoints.
603    let Some(ledger) = run_config.action_ledger.clone() else {
604        return GovernedRun::failed(
605            GovernedError::Unavailable {
606                node,
607                detail: "the run has no action ledger, so its call could not be kept to once. \
608                         Set RunConfig::action_ledger"
609                    .to_string(),
610            },
611            None,
612        );
613    };
614    if dispatch.checkpointer.is_none() {
615        return GovernedRun::failed(
616            GovernedError::Unavailable {
617                node,
618                detail: "the graph has no checkpointer, so its call could not be kept to once \
619                         in its lineage. Add one with with_checkpointer"
620                    .to_string(),
621            },
622            None,
623        );
624    }
625
626    let call_args = dispatch.node.call_args(ctx).unwrap_or_else(|| state_args(&ctx.state));
627    let base_key = format!(
628        "graph/{}/{}/{node}/{}/{}",
629        gate.acting_context().agent.id,
630        dispatch.root,
631        dispatch.occurrence,
632        adk_core::json_digest(&call_args)
633    );
634
635    // 2. The action ledger, before the governed path: a call that already happened is
636    // answered from its record and creates no decision.
637    let answered = match lookup(ledger.as_ref(), &node, &base_key).await {
638        Lookup::Free(key) => Ok(key),
639        Lookup::Done(key) => Err(replay(&dispatch, key).await),
640        Lookup::Failed(run) => Err(*run),
641    };
642    let key = match answered {
643        Ok(key) => key,
644        Err(run) => {
645            // The record answers the call, so a decision it waited for is moot. A ledger
646            // that could not be read answers nothing.
647            let unread = matches!(
648                &run.output,
649                Err(error) if GovernedError::code_of(error) == Some("graph.unavailable")
650            );
651            if let Some(held) = dispatch.held.as_ref().filter(|_| !unread) {
652                withdraw(&gate, held, &node).await;
653            }
654            return run;
655        }
656    };
657
658    // A node resuming its own pause waits for that call's decision, as `LlmAgent` does: it
659    // is not asked about again. A call whose arguments changed since is a new call, and
660    // the hold for the old one is withdrawn.
661    let mut resuming = None;
662    if let Some(held) = dispatch.held.clone() {
663        if held.args == call_args {
664            match adk_core::confirmation_decision_available(&gate, &held).await {
665                Ok(false) => {
666                    tracing::debug!(node = %node, "governed node still waits for its decision");
667                    let interrupt =
668                        GraphToolConfirmationPause::pending_interrupt(node, held.clone());
669                    return GovernedRun {
670                        output: Ok(NodeOutput::new().with_interrupt(interrupt)),
671                        status: NodeStatus::Paused,
672                        effect_key: Some(key),
673                        held: Some(held),
674                    };
675                }
676                Ok(true) => resuming = Some(held),
677                Err(error) => {
678                    return GovernedRun::failed(
679                        GovernedError::Unavailable {
680                            node,
681                            detail: format!(
682                                "the approval store could not be read: {}",
683                                error.redacted()
684                            ),
685                        },
686                        Some(key),
687                    );
688                }
689            }
690        } else {
691            withdraw(&gate, &held, &node).await;
692        }
693    }
694
695    // 3. The governed path.
696    let mut call = GovernedCall::new(
697        node.clone(),
698        format!("{}/{node}/{}", dispatch.run_id, dispatch.occurrence),
699        call_args.clone(),
700    )
701    .with_effect(dispatch.effect)
702    .requiring_confirmation(dispatch.governed.requires_approval);
703    call.origin = Some(ToolOrigin::new(format!("graph:{agent_name}"), &dispatch.declaration, None));
704    if let Some(held) = resuming {
705        call = call.resuming(held);
706    }
707    let args = match adk_core::authorize_tool_call(&gate, call).await {
708        Ok(ToolAuthorization::Execute { args, .. }) => args,
709        Ok(ToolAuthorization::Pending { request, reason }) => {
710            tracing::info!(node = %node, reason = %reason, "governed node waits for a decision");
711            let interrupt = GraphToolConfirmationPause::pending_interrupt(node, request.clone());
712            return GovernedRun {
713                output: Ok(NodeOutput::new().with_interrupt(interrupt)),
714                status: NodeStatus::Paused,
715                effect_key: Some(key),
716                held: Some(request),
717            };
718        }
719        Ok(ToolAuthorization::Refuse { reason, .. }) => {
720            tracing::info!(node = %node, "governed node refused");
721            return GovernedRun::failed(GovernedError::Refused { node, reason }, Some(key));
722        }
723        Err(error) if error.code.starts_with("governance.") => {
724            return GovernedRun::failed(
725                GovernedError::Frozen { node, reason: error.message },
726                None,
727            );
728        }
729        Err(error) => {
730            return GovernedRun::failed(
731                GovernedError::Unavailable {
732                    node,
733                    detail: format!("the approval gate failed: {}", error.redacted()),
734                },
735                Some(key),
736            );
737        }
738    };
739    let edited = (args != call_args).then_some(args);
740
741    // Begin, run, complete.
742    let record = ActionRecord::new(
743        key.clone(),
744        node.clone(),
745        edited.as_ref().unwrap_or(&call_args),
746        dispatch.effect,
747    );
748    let begun = match ledger.begin(&record).await {
749        Ok(()) => Some(ledger.as_ref()),
750        Err(error) if error.code == "tool.action_ledger.duplicate_key" => {
751            // Another run began this call between the lookup and now.
752            return GovernedRun::failed(
753                GovernedError::OutcomeUnknown { node, key: key.clone() },
754                Some(key),
755            );
756        }
757        Err(error) => {
758            return GovernedRun::failed(
759                GovernedError::Unavailable {
760                    node,
761                    detail: format!(
762                        "the action ledger could not record the call: {}",
763                        error.redacted()
764                    ),
765                },
766                Some(key),
767            );
768        }
769    };
770    // A freeze can land between the decision and the call.
771    if let Err(frozen) = run_config.check_governance() {
772        complete(
773            begun,
774            &node,
775            &key,
776            ActionOutcome::Failed { error: adk_core::not_run_text(&frozen) },
777        )
778        .await;
779        return GovernedRun::failed(
780            GovernedError::Frozen { node, reason: frozen.message },
781            Some(key),
782        );
783    }
784
785    crate::executor::begin_attempt(ctx);
786    let ran = run_with_timeout(&node, dispatch.run_timeout, async {
787        match edited {
788            Some(args) => dispatch.node.run_call(ctx, args).await,
789            None => dispatch.node.execute(ctx).await,
790        }
791    })
792    .await;
793
794    match ran {
795        Ok(output) if output.interrupt.is_some() => {
796            // The node paused instead of acting, so the call did not run.
797            let note = adk_core::not_run_text(&adk_core::AdkError::agent(
798                "the node paused before it acted",
799            ));
800            complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
801            GovernedRun {
802                output: Ok(output),
803                status: NodeStatus::Paused,
804                effect_key: Some(key),
805                held: None,
806            }
807        }
808        Ok(output) => {
809            let writes: BTreeMap<String, Value> =
810                output.updates.iter().map(|(key, value)| (key.clone(), value.clone())).collect();
811            let digest = adk_core::json_digest(&serde_json::to_value(&writes).unwrap_or_default());
812            complete(begun, &node, &key, ActionOutcome::Succeeded { result_digest: digest }).await;
813            if let Some(checkpointer) = &dispatch.checkpointer {
814                let entry = EffectRecord {
815                    key: key.clone(),
816                    node: node.clone(),
817                    writes,
818                    goto: output.goto.clone(),
819                    goto_parent: output.goto_parent.clone(),
820                    thread: dispatch.thread_id.clone(),
821                    checkpoint: dispatch.checkpoint_id.clone(),
822                    at: crate::record::now(),
823                };
824                if let Err(error) =
825                    append_effect(checkpointer.as_ref(), &dispatch.root, &entry).await
826                {
827                    // The call ran; a later replay fails closed with effect_unavailable.
828                    tracing::error!(
829                        node = %node,
830                        error = %error,
831                        "the effect log could not record a governed call's writes"
832                    );
833                }
834            }
835            GovernedRun {
836                output: Ok(output),
837                status: NodeStatus::Done,
838                effect_key: Some(key),
839                held: None,
840            }
841        }
842        Err(error) if GovernedError::code_of(&error) == Some("graph.refused") => {
843            // The node refused to send the call, such as for a changed credential.
844            let note =
845                adk_core::not_run_text(&adk_core::AdkError::agent("the node refused the call"));
846            complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
847            GovernedRun {
848                output: Err(error),
849                status: NodeStatus::Refused,
850                effect_key: Some(key),
851                held: None,
852            }
853        }
854        Err(error) if GovernedError::code_of(&error) == Some("graph.edit_unsupported") => {
855            let note = adk_core::not_run_text(&adk_core::AdkError::agent(
856                "the node cannot run an edited call",
857            ));
858            complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
859            GovernedRun::failed(GovernedError::EditUnsupported { node }, Some(key))
860        }
861        Err(error)
862            if matches!(error, GraphError::NodeTimedOut { .. })
863                || GovernedError::code_of(&error) == Some("graph.outcome_unknown") =>
864        {
865            // The call may have taken effect, so its record stays begun: a replay fails
866            // closed with outcome_unknown.
867            tracing::warn!(node = %node, "governed node's outcome is unknown");
868            GovernedRun {
869                output: Err(error),
870                status: NodeStatus::Failed,
871                effect_key: Some(key),
872                held: None,
873            }
874        }
875        Err(error) => {
876            complete(begun, &node, &key, ActionOutcome::Failed { error: error.to_string() }).await;
877            GovernedRun {
878                output: Err(error),
879                status: NodeStatus::Failed,
880                effect_key: Some(key),
881                held: None,
882            }
883        }
884    }
885}
886
887/// What the action ledger holds for a call.
888enum Lookup {
889    /// Nothing, or only refused attempts: the call may run under this key.
890    Free(String),
891    /// The call completed under this key.
892    Done(String),
893    /// The call cannot run: it failed, or its outcome is unknown, or the ledger failed.
894    Failed(Box<GovernedRun>),
895}
896
897/// Reads the ledger for the call `base` names. A refused attempt is recorded as not run
898/// and asks again under the next slot, `{base}#2`, because a ledger key begins once.
899async fn lookup(ledger: &dyn adk_core::ActionLedger, node: &str, base: &str) -> Lookup {
900    for slot in 1..=MAX_SLOTS {
901        let key = if slot == 1 { base.to_string() } else { format!("{base}#{slot}") };
902        let record = match ledger.get(&key).await {
903            Ok(record) => record,
904            Err(error) => {
905                return Lookup::Failed(Box::new(GovernedRun::failed(
906                    GovernedError::Unavailable {
907                        node: node.to_string(),
908                        detail: format!(
909                            "the action ledger could not be read: {}",
910                            error.redacted()
911                        ),
912                    },
913                    Some(key),
914                )));
915            }
916        };
917        let Some(record) = record else { return Lookup::Free(key) };
918        match record.outcome {
919            Some(ActionOutcome::Succeeded { .. }) => return Lookup::Done(key),
920            Some(ActionOutcome::Failed { error }) if adk_core::is_not_run(&error) => continue,
921            Some(ActionOutcome::Failed { error }) => {
922                return Lookup::Failed(Box::new(GovernedRun::failed(
923                    GovernedError::RecordedFailure { node: node.to_string(), error },
924                    Some(key),
925                )));
926            }
927            // Begun without an outcome, or an outcome this version does not know.
928            _ => {
929                return Lookup::Failed(Box::new(GovernedRun::failed(
930                    GovernedError::OutcomeUnknown { node: node.to_string(), key: key.clone() },
931                    Some(key),
932                )));
933            }
934        }
935    }
936    Lookup::Failed(Box::new(GovernedRun::failed(
937        GovernedError::Unavailable {
938            node: node.to_string(),
939            detail: format!("the call was refused {MAX_SLOTS} times; fork to make a new call"),
940        },
941        Some(base.to_string()),
942    )))
943}
944
945/// Answers a call that already completed from the effect log, without running it.
946async fn replay(dispatch: &GovernedDispatch, key: String) -> GovernedRun {
947    let node = dispatch.node_name.clone();
948    let Some(checkpointer) = &dispatch.checkpointer else {
949        return GovernedRun::failed(
950            GovernedError::EffectUnavailable { node, key: key.clone() },
951            Some(key),
952        );
953    };
954    let effect = match effect_log(checkpointer.as_ref(), &dispatch.root).await {
955        Ok(entries) => entries.into_iter().rev().find(|entry| entry.key == key),
956        Err(error) => {
957            return GovernedRun::failed(
958                GovernedError::Unavailable {
959                    node,
960                    detail: format!("the effect log could not be read: {error}"),
961                },
962                Some(key),
963            );
964        }
965    };
966    let Some(effect) = effect else {
967        return GovernedRun::failed(
968            GovernedError::EffectUnavailable { node, key: key.clone() },
969            Some(key),
970        );
971    };
972    tracing::info!(node = %node, effect.key = %key, "governed call answered from its record");
973    let mut output = NodeOutput::new().with_updates(effect.writes.into_iter().collect());
974    output.goto = effect.goto;
975    output.goto_parent = effect.goto_parent;
976    GovernedRun {
977        output: Ok(output),
978        status: NodeStatus::Recorded,
979        effect_key: Some(key),
980        held: None,
981    }
982}
983
984/// Withdraws the decision a governed node waited for when it will not wait any more.
985async fn withdraw(gate: &ToolGate<'_>, held: &ToolConfirmationRequest, node: &str) {
986    if let Err(error) = adk_core::withdraw_held_call(gate, held).await {
987        tracing::warn!(node = %node, error = %error, "a governed node's waiting decision could not be withdrawn");
988    }
989}
990
991/// Records a begun call's outcome; a failure is logged, and a replay then reports the
992/// outcome as unknown.
993async fn complete(
994    ledger: Option<&dyn adk_core::ActionLedger>,
995    node: &str,
996    key: &str,
997    outcome: ActionOutcome,
998) {
999    let Some(ledger) = ledger else { return };
1000    if let Err(error) = ledger.complete(key, outcome).await {
1001        tracing::error!(
1002            node = %node,
1003            effect.key = %key,
1004            error = %error,
1005            "the action ledger could not record a governed call's outcome"
1006        );
1007    }
1008}
1009
1010/// Runs a governed node's call under its run timeout, once: a timed-out call is never
1011/// retried, because it may have taken effect.
1012async fn run_with_timeout(
1013    node: &str,
1014    timeout: Option<Duration>,
1015    call: impl std::future::Future<Output = Result<NodeOutput>>,
1016) -> Result<NodeOutput> {
1017    match timeout {
1018        Some(limit) => tokio::time::timeout(limit, call).await.unwrap_or_else(|_| {
1019            Err(GraphError::NodeTimedOut { node: node.to_string(), elapsed: limit })
1020        }),
1021        None => call.await,
1022    }
1023}
1024
1025/// The call of a node that does not describe one: the whole state it reads, less the
1026/// session id a [`GraphAgent`](crate::agent::GraphAgent) writes on every turn, so a fork in a
1027/// new session binds the same call.
1028fn state_args(state: &State) -> Value {
1029    let sorted: BTreeMap<&String, &Value> =
1030        state.iter().filter(|(key, _)| key.as_str() != SESSION_ID_KEY).collect();
1031    serde_json::to_value(sorted).unwrap_or(Value::Null)
1032}
1033
1034/// The state key a graph agent's default input mapper writes the session id under.
1035const SESSION_ID_KEY: &str = "session_id";
1036
1037#[cfg(feature = "action-http")]
1038/// The failure of a governed call that was sent and whose outcome did not come back
1039/// (spec 3.3 §12): its record stays begun, so it is never run again.
1040pub(crate) fn sent_without_outcome(node: &str, detail: &str) -> GraphError {
1041    GraphError::NodeExecutionFailed {
1042        node: node.to_string(),
1043        message: format!(
1044            "graph.outcome_unknown: governed node '{node}' sent its call and {detail}, so it may \
1045             have taken effect. It is not run again; check the effect, then fork with changed \
1046             state to make a new call"
1047        ),
1048    }
1049}