Skip to main content

adk_harness/
plan_graph.rs

1//! The plan graph (spec 3.1 §7.11, feature `graph`).
2//!
3//! An approved `exit_plan_mode` with `steps` compiles to a checkpointed `StateGraph`: one
4//! node per step running the harness agent with the step's instruction, edges from
5//! `depends_on`, `interrupt_before` on every `Approve` gate, and a reviewer node after every
6//! `Review` gate. From the user's next turn, while the session is in Ask or Auto, each turn
7//! runs the graph instead of a free-form turn, until the plan is done.
8//!
9//! | Gate | Node | What happens |
10//! |---|---|---|
11//! | `None` | `step:<id>` | the step runs |
12//! | `Approve` | `step:<id>`, with `interrupt_before` | the run pauses on a held call (`plan_step_gate`) whose fingerprint binds the plan hash and the step id; `Harness::decide` answers it |
13//! | `Review` | `step:<id>` → `review:<id>` | the step runs, then the reviewer member reviews it in an isolated delegation |
14//!
15//! Checkpoints live in the harness's [`Checkpointer`], so a step survives process loss, and
16//! [`PlanGraphs::rewind`] forks a thread at the checkpoint after a step with
17//! `TimeTravelHandle::fork_at`, so the steps before it never run again.
18
19use std::collections::{HashMap, VecDeque};
20use std::sync::{Arc, OnceLock};
21
22use adk_core::audit_log::AuditActor;
23use adk_core::{
24    AdkError, Agent, ApprovalScope, Content, ErrorCategory, ErrorComponent, Event, EventStream,
25    FunctionResponseData, InvocationContext, Part, Result, ToolConfirmationDecision,
26    ToolConfirmationRequest, ToolContext,
27};
28use adk_graph::agent::session_thread_id;
29use adk_graph::{
30    Checkpoint, Checkpointer, CompiledGraph, END, ExecutionConfig, GraphError, Interrupt, Node,
31    NodeContext, NodeOutput, START, State, StateGraph, StateSchema,
32};
33use serde::{Deserialize, Serialize};
34use serde_json::{Value, json};
35use tokio::sync::{mpsc, oneshot};
36
37use crate::audit::HarnessAudit;
38use crate::run_context::ScopedContext;
39use crate::tools::{PlanGate, PlanStep};
40
41/// Name of the held call an `Approve` gate surfaces (spec 3.1 §7.11).
42///
43/// # Example
44///
45/// ```rust
46/// assert_eq!(adk_harness::PLAN_GATE_TOOL, "plan_step_gate");
47/// ```
48pub const PLAN_GATE_TOOL: &str = "plan_step_gate";
49
50/// The node of plan step `id`.
51///
52/// # Example
53///
54/// ```rust
55/// assert_eq!(adk_harness::plan_step_node("2"), "step:2");
56/// ```
57pub fn plan_step_node(id: &str) -> String {
58    format!("step:{id}")
59}
60
61/// The reviewer node after plan step `id`, for a `Review` gate.
62///
63/// # Example
64///
65/// ```rust
66/// assert_eq!(adk_harness::plan_review_node("2"), "review:2");
67/// ```
68pub fn plan_review_node(id: &str) -> String {
69    format!("review:{id}")
70}
71
72/// State key a step writes when it completes.
73fn done_key(id: &str) -> String {
74    format!("done:{id}")
75}
76
77/// The shape a plan compiles to (spec 3.1 §7.11).
78///
79/// # Example
80///
81/// ```rust
82/// use adk_harness::{PlanGate, PlanStep, compile_plan};
83///
84/// let step = |id: &str, deps: &[&str], gate| PlanStep {
85///     id: id.into(),
86///     title: id.into(),
87///     instruction: format!("do {id}"),
88///     depends_on: deps.iter().map(|d| d.to_string()).collect(),
89///     gate,
90/// };
91/// let shape = compile_plan(
92///     &[step("1", &[], PlanGate::None), step("2", &["1"], PlanGate::Approve)],
93///     "abc",
94/// )
95/// .unwrap();
96/// assert_eq!(shape.nodes, vec!["step:1", "step:2"]);
97/// assert_eq!(shape.interrupt_before, vec!["step:2"]);
98/// ```
99#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
100#[serde(rename_all = "camelCase")]
101pub struct PlanGraphShape {
102    /// The approved plan's hash.
103    pub plan_hash: String,
104    /// Node names in a dependency order: `step:<id>` per step and `review:<id>` after a
105    /// `Review` gate.
106    pub nodes: Vec<String>,
107    /// Edges, `__start__` and `__end__` included, sorted.
108    pub edges: Vec<(String, String)>,
109    /// Nodes the run pauses before: every `Approve` gate.
110    pub interrupt_before: Vec<String>,
111    /// Super-steps one run may take: the node count plus one.
112    pub recursion_limit: usize,
113}
114
115impl PlanGraphShape {
116    /// The graph as a `WorkflowSchema`, the interchange format of adk-graph (spec 3.1
117    /// §7.11): every node is an agent node.
118    pub fn workflow_schema(&self) -> adk_graph::workflow::WorkflowSchema {
119        adk_graph::workflow::WorkflowSchema {
120            edges: self
121                .edges
122                .iter()
123                .map(|(from, to)| adk_graph::workflow::WorkflowEdge {
124                    from: from.clone(),
125                    to: to.clone(),
126                    condition: None,
127                    from_port: None,
128                    to_port: None,
129                })
130                .collect(),
131            conditions: Vec::new(),
132            action_nodes: HashMap::new(),
133            agent_nodes: self.nodes.clone(),
134        }
135    }
136}
137
138fn invalid(message: impl Into<String>) -> AdkError {
139    AdkError::new(
140        ErrorComponent::Tool,
141        ErrorCategory::InvalidInput,
142        "harness.plan.invalid",
143        message,
144    )
145}
146
147/// Compiles plan steps to the plan graph's shape (spec 3.1 §7.11).
148///
149/// # Errors
150///
151/// Returns `harness.plan.invalid` when there are no steps, an id is empty or repeated, a
152/// step depends on itself or on an unknown step, or the dependencies form a cycle.
153pub fn compile_plan(steps: &[PlanStep], plan_hash: &str) -> Result<PlanGraphShape> {
154    if steps.is_empty() {
155        return Err(invalid("a plan graph needs at least one step"));
156    }
157    let mut index = HashMap::new();
158    for (position, step) in steps.iter().enumerate() {
159        if step.id.trim().is_empty() {
160            return Err(invalid("step ids must not be empty"));
161        }
162        if index.insert(step.id.as_str(), position).is_some() {
163            return Err(invalid(format!("step id '{}' is used twice", step.id)));
164        }
165    }
166    for step in steps {
167        for dep in &step.depends_on {
168            if dep == &step.id {
169                return Err(invalid(format!("step '{}' depends on itself", step.id)));
170            }
171            if !index.contains_key(dep.as_str()) {
172                return Err(invalid(format!(
173                    "step '{}' depends on an unknown step '{dep}'",
174                    step.id
175                )));
176            }
177        }
178    }
179    // Kahn's algorithm in declaration order, so the node order is stable.
180    let mut indegree: Vec<usize> = steps.iter().map(|step| step.depends_on.len()).collect();
181    let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); steps.len()];
182    for (position, step) in steps.iter().enumerate() {
183        for dep in &step.depends_on {
184            dependents[index[dep.as_str()]].push(position);
185        }
186    }
187    let mut ready: VecDeque<usize> = (0..steps.len()).filter(|i| indegree[*i] == 0).collect();
188    let mut order = Vec::with_capacity(steps.len());
189    while let Some(next) = ready.pop_front() {
190        order.push(next);
191        for &dependent in &dependents[next] {
192            indegree[dependent] -= 1;
193            if indegree[dependent] == 0 {
194                ready.push_back(dependent);
195            }
196        }
197    }
198    if order.len() != steps.len() {
199        return Err(invalid("the steps' dependencies form a cycle"));
200    }
201    let exit = |step: &PlanStep| match step.gate {
202        PlanGate::Review => plan_review_node(&step.id),
203        PlanGate::None | PlanGate::Approve => plan_step_node(&step.id),
204    };
205    let mut nodes = Vec::new();
206    let mut edges = Vec::new();
207    let mut interrupt_before = Vec::new();
208    for &position in &order {
209        let step = &steps[position];
210        nodes.push(plan_step_node(&step.id));
211        match step.gate {
212            PlanGate::Review => {
213                nodes.push(plan_review_node(&step.id));
214                edges.push((plan_step_node(&step.id), plan_review_node(&step.id)));
215            }
216            PlanGate::Approve => interrupt_before.push(plan_step_node(&step.id)),
217            PlanGate::None => {}
218        }
219        if step.depends_on.is_empty() {
220            edges.push((START.to_string(), plan_step_node(&step.id)));
221        }
222        for dep in &step.depends_on {
223            edges.push((exit(&steps[index[dep.as_str()]]), plan_step_node(&step.id)));
224        }
225        if dependents[position].is_empty() {
226            edges.push((exit(step), END.to_string()));
227        }
228    }
229    edges.sort();
230    edges.dedup();
231    let recursion_limit = nodes.len() + 1;
232    Ok(PlanGraphShape {
233        plan_hash: plan_hash.to_string(),
234        nodes,
235        edges,
236        interrupt_before,
237        recursion_limit,
238    })
239}
240
241/// Where an installed plan stands (spec 3.1 §7.11).
242///
243/// # Example
244///
245/// ```rust
246/// assert_eq!(serde_json::to_value(adk_harness::PlanRunStatus::Done).unwrap(), "done");
247/// ```
248#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "snake_case")]
250pub enum PlanRunStatus {
251    /// Turns run the plan graph.
252    Running,
253    /// Every step ran.
254    Done,
255    /// A gate was denied.
256    Cancelled,
257}
258
259/// The plan graph a session runs (spec 3.1 §7.11), kept in the harness's checkpointer.
260///
261/// # Example
262///
263/// ```rust,ignore
264/// if let Some(plan) = graphs.active("app", "alice", "s1").await? {
265///     println!("{} steps on {}", plan.steps.len(), plan.thread_id);
266/// }
267/// ```
268#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "camelCase")]
270pub struct ActivePlan {
271    /// The approved plan's hash.
272    pub plan_hash: String,
273    /// The approved plan.
274    pub plan: String,
275    /// Its steps.
276    pub steps: Vec<PlanStep>,
277    /// The graph thread turns run on.
278    pub thread_id: String,
279    /// Where it stands.
280    pub status: PlanRunStatus,
281    /// How many times it was rewound; part of every gate's fingerprint, so a step that runs
282    /// again after a rewind is approved again.
283    pub rewinds: u32,
284}
285
286/// The plan graphs of a harness (spec 3.1 §7.11): the store of installed plans and the
287/// runner of their turns.
288///
289/// # Example
290///
291/// ```rust,ignore
292/// let graphs = harness.runtime().plan_graph().expect("feature graph, plan_graph on");
293/// let new_thread = graphs.rewind("app", "alice", "s1", "2").await?;
294/// ```
295pub struct PlanGraphs {
296    checkpointer: Arc<dyn Checkpointer>,
297    harness: String,
298    reviewer: OnceLock<Arc<dyn Agent>>,
299    /// Snapshots taken before each step (spec 3.1 §7.27).
300    snapshots: OnceLock<Arc<crate::snapshot::Snapshots>>,
301}
302
303impl std::fmt::Debug for PlanGraphs {
304    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305        f.debug_struct("PlanGraphs")
306            .field("harness", &self.harness)
307            .field("reviewer", &self.reviewer.get().map(|agent| agent.name().to_string()))
308            .finish_non_exhaustive()
309    }
310}
311
312/// Something the turn's stream yields for a node: an event, or one the node waits on until
313/// the caller has taken it (and a runner has recorded it).
314pub(crate) enum Forward {
315    Event(Event),
316    Synced(Event, oneshot::Sender<()>),
317}
318
319pub(crate) type Sink = mpsc::UnboundedSender<Forward>;
320
321/// Streams the events a graph run's nodes forward while it runs, then what `finish` makes
322/// of its outcome.
323pub(crate) fn drive<F, G, S>(
324    run: F,
325    mut forwarded: mpsc::UnboundedReceiver<Forward>,
326    finish: G,
327) -> EventStream
328where
329    F: std::future::Future<Output = adk_graph::Result<State>> + Send + 'static,
330    G: FnOnce(adk_graph::Result<State>) -> S + Send + 'static,
331    S: futures::Stream<Item = Result<Event>> + Send + 'static,
332{
333    Box::pin(async_stream::stream! {
334        let outcome = {
335            tokio::pin!(run);
336            loop {
337                tokio::select! {
338                    biased;
339                    Some(next) = forwarded.recv() => match next {
340                        Forward::Event(event) => yield Ok(event),
341                        Forward::Synced(event, taken) => {
342                            yield Ok(event);
343                            let _ = taken.send(());
344                        }
345                    },
346                    outcome = &mut run => break outcome,
347                }
348            }
349        };
350        while let Ok(next) = forwarded.try_recv() {
351            match next {
352                Forward::Event(event) => yield Ok(event),
353                Forward::Synced(event, taken) => {
354                    yield Ok(event);
355                    let _ = taken.send(());
356                }
357            }
358        }
359        let tail = finish(outcome);
360        tokio::pin!(tail);
361        while let Some(item) = futures::StreamExt::next(&mut tail).await {
362            yield item;
363        }
364    })
365}
366
367/// Runs the harness agent `root` as graph node `node`, with `content` as the turn's user
368/// content, forwarding its events. Returns whether it held a call, and its last answer.
369pub(crate) async fn run_agent_node(
370    node: &str,
371    root: &Arc<dyn Agent>,
372    harness: &str,
373    parent: Arc<dyn InvocationContext>,
374    content: Content,
375    sink: &Sink,
376) -> adk_graph::Result<(bool, String)> {
377    run_agent_node_counted(node, root, harness, parent, content, sink)
378        .await
379        .map(|(held, output, _)| (held, output))
380}
381
382/// [`run_agent_node`], also returning how many tool calls the harness made, for the goal
383/// stall rule (spec 3.2 §10 HK3).
384pub(crate) async fn run_agent_node_counted(
385    node: &str,
386    root: &Arc<dyn Agent>,
387    harness: &str,
388    parent: Arc<dyn InvocationContext>,
389    content: Content,
390    sink: &Sink,
391) -> adk_graph::Result<(bool, String, usize)> {
392    let scoped = Arc::new(
393        ScopedContext::new(parent)
394            .for_agent(root.clone(), harness.to_string())
395            .with_user_content(content),
396    );
397    let mut stream = root.run(scoped).await.map_err(|error| failed(node, error))?;
398    let mut held = false;
399    let mut output = String::new();
400    let mut tool_calls = 0;
401    while let Some(item) = futures::StreamExt::next(&mut stream).await {
402        let event = item.map_err(|error| failed(node, error))?;
403        held |= event.actions.tool_confirmation.is_some();
404        if event.author == harness
405            && !event.llm_response.partial
406            && let Some(content) = &event.llm_response.content
407        {
408            let text: String = content.parts.iter().filter_map(Part::text).collect();
409            if !text.is_empty() {
410                output = text;
411            }
412            tool_calls += content
413                .parts
414                .iter()
415                .filter(|part| matches!(part, Part::FunctionCall { .. }))
416                .count();
417        }
418        let _ = sink.send(Forward::Event(event));
419    }
420    Ok((held, output, tool_calls))
421}
422
423impl PlanGraphs {
424    pub(crate) fn new(checkpointer: Arc<dyn Checkpointer>, harness: &str) -> Self {
425        Self {
426            checkpointer,
427            harness: harness.to_string(),
428            reviewer: OnceLock::new(),
429            snapshots: OnceLock::new(),
430        }
431    }
432
433    /// Snapshots the workspace before each step (spec 3.1 §7.27).
434    pub(crate) fn set_snapshots(&self, snapshots: Arc<crate::snapshot::Snapshots>) {
435        let _ = self.snapshots.set(snapshots);
436    }
437
438    /// Where the session's plan stands: its hash, thread and the steps completed on it, in
439    /// plan order (spec 3.1 §7.27).
440    pub(crate) async fn mark(
441        &self,
442        app: &str,
443        user: &str,
444        session: &str,
445    ) -> Result<Option<crate::snapshot::PlanMark>> {
446        let Some(plan) = self.active(app, user, session).await? else {
447            return Ok(None);
448        };
449        let done: Vec<String> = match self.checkpointer.load(&plan.thread_id).await? {
450            Some(checkpoint) => plan
451                .steps
452                .iter()
453                .filter(|step| checkpoint.state.contains_key(&done_key(&step.id)))
454                .map(|step| step.id.clone())
455                .collect(),
456            None => Vec::new(),
457        };
458        Ok(Some(crate::snapshot::PlanMark {
459            plan_hash: plan.plan_hash,
460            thread_id: plan.thread_id,
461            completed: done,
462            running: plan.status == PlanRunStatus::Running,
463        }))
464    }
465
466    /// Starts the session's plan over on a new thread, so every step runs again on the
467    /// next turn, its `Approve` gates asking again (a rewind to before the first step,
468    /// spec 3.1 §7.27). Returns the new thread's id.
469    ///
470    /// # Errors
471    ///
472    /// Returns `harness.plan.invalid` when the session has no plan, or the checkpointer's
473    /// error.
474    pub(crate) async fn restart(&self, app: &str, user: &str, session: &str) -> Result<String> {
475        let mut plan = self
476            .active(app, user, session)
477            .await?
478            .ok_or_else(|| invalid("the session has no plan to rewind"))?;
479        let base = plan.thread_id.split(":rewind:").next().unwrap_or(&plan.thread_id).to_string();
480        plan.rewinds += 1;
481        plan.thread_id = format!("{base}:rewind:{}", plan.rewinds);
482        plan.status = PlanRunStatus::Running;
483        self.save(app, user, session, &plan).await?;
484        Ok(plan.thread_id)
485    }
486
487    /// Puts the session's plan back on `thread_id`, the thread it ran on before a rewind
488    /// (`/redo`, spec 3.1 §7.27). Gates ask again: the rewind count still grows.
489    ///
490    /// # Errors
491    ///
492    /// Returns `harness.plan.invalid` when the session has no plan, or the checkpointer's
493    /// error.
494    pub(crate) async fn restore_thread(
495        &self,
496        app: &str,
497        user: &str,
498        session: &str,
499        thread_id: &str,
500    ) -> Result<String> {
501        let mut plan = self
502            .active(app, user, session)
503            .await?
504            .ok_or_else(|| invalid("the session has no plan to restore"))?;
505        plan.rewinds += 1;
506        plan.thread_id = thread_id.to_string();
507        let done = match self.checkpointer.load(thread_id).await? {
508            Some(checkpoint) => {
509                plan.steps.iter().all(|step| checkpoint.state.contains_key(&done_key(&step.id)))
510            }
511            None => false,
512        };
513        plan.status = if done { PlanRunStatus::Done } else { PlanRunStatus::Running };
514        self.save(app, user, session, &plan).await?;
515        Ok(plan.thread_id)
516    }
517
518    #[cfg(feature = "team")]
519    pub(crate) fn set_reviewer(&self, reviewer: Arc<dyn Agent>) {
520        let _ = self.reviewer.set(reviewer);
521    }
522
523    /// The checkpointer plans and their graph threads are kept in.
524    pub fn checkpointer(&self) -> &Arc<dyn Checkpointer> {
525        &self.checkpointer
526    }
527
528    /// The agent `Review` gates delegate to, if the harness has one.
529    pub fn reviewer(&self) -> Option<&Arc<dyn Agent>> {
530        self.reviewer.get()
531    }
532
533    fn pointer_thread(app: &str, user: &str, session: &str) -> String {
534        format!("{}:harness-plan", session_thread_id(app, user, session))
535    }
536
537    /// The plan installed for the session, in any status.
538    ///
539    /// # Errors
540    ///
541    /// Returns the checkpointer's error.
542    pub async fn active(&self, app: &str, user: &str, session: &str) -> Result<Option<ActivePlan>> {
543        let Some(checkpoint) =
544            self.checkpointer.load(&Self::pointer_thread(app, user, session)).await?
545        else {
546            return Ok(None);
547        };
548        Ok(checkpoint
549            .state
550            .get("plan")
551            .and_then(|value| serde_json::from_value(value.clone()).ok()))
552    }
553
554    async fn save(&self, app: &str, user: &str, session: &str, plan: &ActivePlan) -> Result<()> {
555        let thread = Self::pointer_thread(app, user, session);
556        let version = self.checkpointer.load(&thread).await?.map_or(1, |head| head.version + 1);
557        let mut state = State::new();
558        state.insert(
559            "plan".to_string(),
560            serde_json::to_value(plan).map_err(|error| invalid(error.to_string()))?,
561        );
562        let checkpoint = Checkpoint::new(&thread, state, 0, Vec::new()).with_version(version);
563        self.checkpointer.save(&checkpoint).await?;
564        Ok(())
565    }
566
567    /// Checks that `steps` compile, and that a `Review` gate has a reviewer.
568    pub(crate) fn validate(&self, steps: &[PlanStep], plan_hash: &str) -> Result<PlanGraphShape> {
569        let shape = compile_plan(steps, plan_hash)?;
570        if self.reviewer.get().is_none()
571            && let Some(step) = steps.iter().find(|step| step.gate == PlanGate::Review)
572        {
573            return Err(invalid(format!(
574                "step '{}' has a review gate, but the harness has no reviewer member",
575                step.id
576            )));
577        }
578        Ok(shape)
579    }
580
581    /// Installs an approved plan for the session: from its next turn in Ask or Auto, turns
582    /// run the plan graph. Records `harness.plan.compiled` (spec 3.1 §9.3).
583    pub(crate) async fn install(
584        &self,
585        ctx: &dyn ToolContext,
586        plan: &str,
587        steps: &[PlanStep],
588        plan_hash: &str,
589    ) -> Result<PlanGraphShape> {
590        let shape = self.validate(steps, plan_hash)?;
591        let (app, user, session) = (ctx.app_name(), ctx.user_id(), ctx.session_id());
592        let short = &plan_hash[..plan_hash.len().min(16)];
593        let active = ActivePlan {
594            plan_hash: plan_hash.to_string(),
595            plan: plan.to_string(),
596            steps: steps.to_vec(),
597            thread_id: format!("{}:plan:{short}", session_thread_id(app, user, session)),
598            status: PlanRunStatus::Running,
599            rewinds: 0,
600        };
601        if let Some(audit) = HarnessAudit::for_tool(ctx) {
602            audit
603                .record(
604                    "harness.plan.compiled",
605                    json!({
606                        "planHash": plan_hash,
607                        "steps": steps.iter().map(|step| json!({
608                            "id": step.id,
609                            "title": step.title,
610                            "dependsOn": step.depends_on,
611                            "gate": step.gate,
612                        })).collect::<Vec<_>>(),
613                        "nodes": shape.nodes,
614                        "interruptBefore": shape.interrupt_before,
615                    }),
616                )
617                .await?;
618        }
619        self.save(app, user, session, &active).await?;
620        tracing::info!(plan.hash = %plan_hash, plan.steps = steps.len(), "plan graph installed");
621        Ok(shape)
622    }
623
624    /// Rewinds the session's plan to just after `step_id` completed (spec 3.1 §7.11, H4):
625    /// forks its thread at that checkpoint with `TimeTravelHandle::fork_at` and makes the
626    /// fork the thread the next turn runs. Nothing up to `step_id` runs again; the steps
627    /// after it run on the next turn, their `Approve` gates asking again.
628    ///
629    /// Returns the new thread's id.
630    ///
631    /// # Errors
632    ///
633    /// Returns `harness.plan.invalid` when the session has no plan, the plan has no step
634    /// `step_id`, or no checkpoint shows the step completed.
635    pub async fn rewind(
636        &self,
637        app: &str,
638        user: &str,
639        session: &str,
640        step_id: &str,
641    ) -> Result<String> {
642        let mut plan = self
643            .active(app, user, session)
644            .await?
645            .ok_or_else(|| invalid("the session has no plan to rewind"))?;
646        if !plan.steps.iter().any(|step| step.id == step_id) {
647            return Err(invalid(format!("the plan has no step '{step_id}'")));
648        }
649        let shape = compile_plan(&plan.steps, &plan.plan_hash)?;
650        let mut graph = StateGraph::new(StateSchema::simple(&[]));
651        for node in &shape.nodes {
652            graph = graph.add_node_fn(node, |_ctx| async { Ok(NodeOutput::new()) });
653        }
654        for (from, to) in &shape.edges {
655            graph = graph.add_edge(from, to);
656        }
657        let graph = graph.compile()?.with_checkpointer_arc(self.checkpointer.clone());
658        let handle = graph.time_travel(&plan.thread_id)?;
659        let key = done_key(step_id);
660        let step = handle
661            .steps()
662            .await?
663            .into_iter()
664            .find(|info| info.state_keys.contains(&key))
665            .ok_or_else(|| invalid(format!("step '{step_id}' has not completed on this plan")))?;
666        let base = plan.thread_id.split(":rewind:").next().unwrap_or(&plan.thread_id).to_string();
667        let thread = format!("{base}:rewind:{}", plan.rewinds + 1);
668        handle.fork_at(step.step, &thread).await?;
669        plan.thread_id = thread.clone();
670        plan.rewinds += 1;
671        plan.status = PlanRunStatus::Running;
672        self.save(app, user, session, &plan).await?;
673        tracing::info!(plan.hash = %plan.plan_hash, plan.step = step_id, plan.thread = %thread, "plan rewound");
674        Ok(thread)
675    }
676
677    /// Runs this turn of the session's plan, when one is running and the mode lets it.
678    pub(crate) async fn route(
679        self: &Arc<Self>,
680        mode: crate::mode::HarnessMode,
681        root: Arc<dyn Agent>,
682        ctx: Arc<dyn InvocationContext>,
683    ) -> Result<Option<EventStream>> {
684        use crate::mode::HarnessMode;
685        if !matches!(mode, HarnessMode::Ask | HarnessMode::Auto) {
686            return Ok(None);
687        }
688        let Some(plan) = self.active(ctx.app_name(), ctx.user_id(), ctx.session_id()).await? else {
689            return Ok(None);
690        };
691        if plan.status != PlanRunStatus::Running {
692            return Ok(None);
693        }
694        Ok(Some(self.clone().run_turn(plan, root, ctx)?))
695    }
696
697    fn build(
698        &self,
699        plan: &ActivePlan,
700        shape: &PlanGraphShape,
701        root: Arc<dyn Agent>,
702        sink: Sink,
703    ) -> Result<CompiledGraph> {
704        let gates = Arc::new(GateBook {
705            author: plan_author(&self.harness),
706            plan_hash: plan.plan_hash.clone(),
707            rewinds: plan.rewinds,
708        });
709        let mut graph = StateGraph::new(StateSchema::simple(&["input"]));
710        let order: Arc<Vec<String>> =
711            Arc::new(plan.steps.iter().map(|step| step.id.clone()).collect());
712        for step in &plan.steps {
713            graph = graph.add_node(StepNode {
714                node: plan_step_node(&step.id),
715                step: step.clone(),
716                harness: self.harness.clone(),
717                root: root.clone(),
718                gates: gates.clone(),
719                sink: sink.clone(),
720                snapshots: self.snapshots.get().cloned(),
721                order: order.clone(),
722            });
723            if step.gate == PlanGate::Review {
724                let reviewer = self.reviewer.get().cloned().ok_or_else(|| {
725                    invalid(format!("step '{}' has a review gate but no reviewer", step.id))
726                })?;
727                graph = graph.add_node(ReviewNode {
728                    node: plan_review_node(&step.id),
729                    step: step.clone(),
730                    reviewer,
731                    gates: gates.clone(),
732                    sink: sink.clone(),
733                });
734            }
735        }
736        for (from, to) in &shape.edges {
737            graph = graph.add_edge(from, to);
738        }
739        let interrupt: Vec<&str> = shape.interrupt_before.iter().map(String::as_str).collect();
740        Ok(graph
741            .compile()?
742            .with_checkpointer_arc(self.checkpointer.clone())
743            .with_interrupt_before(&interrupt)
744            .with_recursion_limit(shape.recursion_limit))
745    }
746
747    fn run_turn(
748        self: Arc<Self>,
749        plan: ActivePlan,
750        root: Arc<dyn Agent>,
751        ctx: Arc<dyn InvocationContext>,
752    ) -> Result<EventStream> {
753        let shape = compile_plan(&plan.steps, &plan.plan_hash)?;
754        let (sink, forwarded) = mpsc::unbounded_channel();
755        let graph = self.build(&plan, &shape, root, sink)?;
756        let gates = GateBook {
757            author: plan_author(&self.harness),
758            plan_hash: plan.plan_hash.clone(),
759            rewinds: plan.rewinds,
760        };
761        let config = ExecutionConfig::new(&plan.thread_id).with_parent_context(ctx.clone());
762        tracing::info!(plan.hash = %plan.plan_hash, plan.thread = %plan.thread_id, "running the plan graph");
763        let run = async move { graph.invoke(State::new(), config).await };
764        Ok(drive(run, forwarded, move |outcome| {
765            async_stream::stream! {
766                let (app, user, session) = (ctx.app_name(), ctx.user_id(), ctx.session_id());
767                match outcome {
768                    Ok(state) => {
769                        let cancelled =
770                            state.get("planStatus").and_then(Value::as_str) == Some("cancelled");
771                        let mut finished = plan.clone();
772                        finished.status =
773                            if cancelled { PlanRunStatus::Cancelled } else { PlanRunStatus::Done };
774                        if let Err(error) = self.save(app, user, session, &finished).await {
775                            yield Err(error);
776                            return;
777                        }
778                        let text = if cancelled {
779                            format!("The plan stopped: a step's gate was denied ({} steps planned).", plan.steps.len())
780                        } else {
781                            format!("The plan is complete: {} steps ran.", plan.steps.len())
782                        };
783                        yield Ok(gates.note(ctx.as_ref(), text));
784                    }
785                    Err(GraphError::Interrupted(interrupted)) => {
786                        for interrupt in &interrupted.interrupts {
787                            // A gate the executor paused before: surface it as a held call.
788                            if let Interrupt::Before(node) = interrupt
789                                && let Some(step) =
790                                    plan.steps.iter().find(|step| plan_step_node(&step.id) == *node)
791                            {
792                                match gates.pause(ctx.as_ref(), step).await {
793                                    Ok(events) => {
794                                        for event in events {
795                                            yield Ok(event);
796                                        }
797                                    }
798                                    Err(error) => {
799                                        yield Err(error);
800                                        return;
801                                    }
802                                }
803                            }
804                        }
805                    }
806                    Err(error) => yield Err(error.into()),
807                }
808            }
809        }))
810    }
811}
812
813/// Author of the plan's own events: gate holds, their answers and plan notes.
814fn plan_author(harness: &str) -> String {
815    format!("{harness}_plan")
816}
817
818/// The `Approve` gates of one plan run.
819struct GateBook {
820    author: String,
821    plan_hash: String,
822    rewinds: u32,
823}
824
825impl GateBook {
826    fn call_id(&self, step: &PlanStep) -> String {
827        format!(
828            "plan-gate-{}-{}-{}",
829            &self.plan_hash[..self.plan_hash.len().min(12)],
830            self.rewinds,
831            step.id
832        )
833    }
834
835    /// The request a person decides; its fingerprint binds the plan hash, the run and the
836    /// step, so an edited plan or a rewound step needs a new approval.
837    fn request(&self, ctx: &dyn InvocationContext, step: &PlanStep) -> ToolConfirmationRequest {
838        ToolConfirmationRequest::new(
839            PLAN_GATE_TOOL,
840            json!({
841                "planHash": self.plan_hash,
842                "run": self.rewinds,
843                "stepId": step.id,
844                "title": step.title,
845                "instruction": step.instruction,
846            }),
847        )
848        .with_function_call_id(self.call_id(step))
849        .with_acting_context(ctx.acting_context())
850    }
851
852    fn audit(ctx: &dyn InvocationContext) -> Option<HarnessAudit> {
853        let trail = ctx.run_config().audit.clone()?;
854        Some(HarnessAudit::new(trail, AuditActor::for_context(ctx), ctx.session_id()))
855    }
856
857    async fn record(
858        &self,
859        ctx: &dyn InvocationContext,
860        step: &PlanStep,
861        decision: &str,
862    ) -> Result<()> {
863        if let Some(audit) = Self::audit(ctx) {
864            audit
865                .record(
866                    "harness.plan.step",
867                    json!({
868                        "planHash": self.plan_hash,
869                        "stepId": step.id,
870                        "gate": step.gate,
871                        "decision": decision,
872                        "run": self.rewinds,
873                    }),
874                )
875                .await?;
876        }
877        Ok(())
878    }
879
880    fn event(&self, ctx: &dyn InvocationContext) -> Event {
881        let mut event = Event::new(ctx.invocation_id());
882        event.author = self.author.clone();
883        event.branch = ctx.branch().to_string();
884        event
885    }
886
887    fn note(&self, ctx: &dyn InvocationContext, text: String) -> Event {
888        let mut event = self.event(ctx);
889        event.llm_response.content = Some(Content::new("model").with_text(text));
890        event
891    }
892
893    /// How the session answered the gate, if it did: `Some(true)` approved,
894    /// `Some(false)` denied.
895    fn answered(&self, ctx: &dyn InvocationContext, step: &PlanStep) -> Option<bool> {
896        let call_id = self.call_id(step);
897        let mut answer = None;
898        for content in ctx.session().conversation_history() {
899            for part in &content.parts {
900                if let Part::FunctionResponse { function_response, id, .. } = part
901                    && id.as_deref() == Some(call_id.as_str())
902                    && function_response.name == PLAN_GATE_TOOL
903                {
904                    answer = function_response
905                        .response
906                        .get("status")
907                        .and_then(Value::as_str)
908                        .map(|status| status == "approved");
909                }
910            }
911        }
912        answer
913    }
914
915    /// Whether the gate's call is held in the session now.
916    fn held(&self, ctx: &dyn InvocationContext) -> Vec<String> {
917        ctx.session()
918            .held_tool_calls(&self.author, ctx.branch())
919            .into_iter()
920            .filter_map(|call| call.request.function_call_id)
921            .collect()
922    }
923
924    /// Surfaces the gate as a held call for a person to decide, and records it pending.
925    /// Returns the hold's events — the call, then its pending response carrying the
926    /// request, as an agent holds a call — or none when the call is held already.
927    async fn pause(&self, ctx: &dyn InvocationContext, step: &PlanStep) -> Result<Vec<Event>> {
928        let request = self.request(ctx, step);
929        if let Some(store) = &ctx.run_config().approval_store {
930            store
931                .record_pending(
932                    &ApprovalScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id()),
933                    &request,
934                )
935                .await?;
936        }
937        if self.held(ctx).contains(&self.call_id(step)) {
938            return Ok(Vec::new());
939        }
940        self.record(ctx, step, "pending").await?;
941        tracing::info!(plan.step = %step.id, "plan step waits for approval");
942        let mut call = self.event(ctx);
943        call.llm_response.content = Some(Content {
944            role: "model".to_string(),
945            parts: vec![Part::FunctionCall {
946                name: PLAN_GATE_TOOL.to_string(),
947                args: request.args.clone(),
948                id: request.function_call_id.clone(),
949                thought_signature: None,
950            }],
951        });
952        let mut held = self.event(ctx);
953        held.llm_response.content = Some(Content {
954            role: "function".to_string(),
955            parts: vec![Part::FunctionResponse {
956                function_response: FunctionResponseData::new(
957                    PLAN_GATE_TOOL,
958                    adk_core::confirmation_pending_response(format!(
959                        "plan step '{}' waits for approval",
960                        step.id
961                    )),
962                ),
963                id: request.function_call_id.clone(),
964                annotations: None,
965            }],
966        });
967        held.llm_response.turn_complete = true;
968        held.actions.tool_confirmation = Some(request);
969        Ok(vec![call, held])
970    }
971
972    /// The gate's decision from the approval store, consumed: `Some(true)` approved.
973    async fn take(&self, ctx: &dyn InvocationContext, step: &PlanStep) -> Result<Option<bool>> {
974        let Some(store) = &ctx.run_config().approval_store else {
975            return Ok(None);
976        };
977        let scope = ApprovalScope::new(ctx.app_name(), ctx.user_id(), ctx.session_id());
978        let fingerprint = self.request(ctx, step).fingerprint();
979        Ok(store
980            .take_approval(&scope, &fingerprint)
981            .await?
982            .map(|approval| approval.decision == ToolConfirmationDecision::Approve))
983    }
984
985    fn answer(&self, ctx: &dyn InvocationContext, step: &PlanStep, approved: bool) -> Event {
986        let mut event = self.event(ctx);
987        let status = if approved { "approved" } else { "denied" };
988        event.llm_response.content = Some(Content {
989            role: "function".to_string(),
990            parts: vec![Part::FunctionResponse {
991                function_response: FunctionResponseData::new(
992                    PLAN_GATE_TOOL,
993                    json!({ "status": status, "stepId": step.id }),
994                ),
995                id: Some(self.call_id(step)),
996                annotations: None,
997            }],
998        });
999        event
1000    }
1001}
1002
1003/// Sends `event` and waits until the turn's caller has taken it, so a runner has recorded
1004/// it before the step's agent reads the session.
1005async fn send_synced(sink: &Sink, event: Event) {
1006    let (taken, waited) = oneshot::channel();
1007    if sink.send(Forward::Synced(event, taken)).is_ok() {
1008        let _ = waited.await;
1009    }
1010}
1011
1012fn failed(node: &str, error: AdkError) -> GraphError {
1013    GraphError::AgentFailed { node: node.to_string(), source: Box::new(error) }
1014}
1015
1016fn node_error(node: &str, message: impl Into<String>) -> GraphError {
1017    GraphError::NodeExecutionFailed { node: node.to_string(), message: message.into() }
1018}
1019
1020/// One plan step: runs the harness agent with the step's instruction (spec 3.1 §7.11).
1021struct StepNode {
1022    node: String,
1023    step: PlanStep,
1024    harness: String,
1025    root: Arc<dyn Agent>,
1026    gates: Arc<GateBook>,
1027    sink: Sink,
1028    snapshots: Option<Arc<crate::snapshot::Snapshots>>,
1029    /// Every step id, in plan order, for the snapshot's plan mark.
1030    order: Arc<Vec<String>>,
1031}
1032
1033impl StepNode {
1034    fn instruction(&self) -> String {
1035        format!(
1036            "[plan step {id}: {title} — plan {hash}, run {run}]\n{instruction}\n\nDo this step \
1037             only, then stop and summarize what you did.",
1038            id = self.step.id,
1039            title = self.step.title,
1040            hash = &self.gates.plan_hash[..self.gates.plan_hash.len().min(12)],
1041            run = self.gates.rewinds,
1042            instruction = self.step.instruction,
1043        )
1044    }
1045
1046    fn started(&self, ctx: &dyn InvocationContext, instruction: &str) -> bool {
1047        ctx.session().conversation_history().iter().any(|content| {
1048            content.role == "user"
1049                && content.parts.iter().any(|part| part.text() == Some(instruction))
1050        })
1051    }
1052}
1053
1054#[async_trait::async_trait]
1055impl Node for StepNode {
1056    fn name(&self) -> &str {
1057        &self.node
1058    }
1059
1060    fn description(&self) -> &str {
1061        &self.step.title
1062    }
1063
1064    async fn execute(&self, ctx: &NodeContext) -> adk_graph::Result<NodeOutput> {
1065        let parent =
1066            ctx.config.parent_context.clone().ok_or_else(|| {
1067                node_error(&self.node, "a plan step runs only inside a harness turn")
1068            })?;
1069        if self.step.gate == PlanGate::Approve {
1070            match self.gates.answered(parent.as_ref(), &self.step) {
1071                Some(true) => {}
1072                Some(false) => {
1073                    return Ok(NodeOutput::new()
1074                        .with_update("planStatus", "cancelled")
1075                        .with_goto([END]));
1076                }
1077                None => match self
1078                    .gates
1079                    .take(parent.as_ref(), &self.step)
1080                    .await
1081                    .map_err(|e| failed(&self.node, e))?
1082                {
1083                    Some(approved) => {
1084                        let decision = if approved { "approved" } else { "denied" };
1085                        self.gates
1086                            .record(parent.as_ref(), &self.step, decision)
1087                            .await
1088                            .map_err(|e| failed(&self.node, e))?;
1089                        send_synced(
1090                            &self.sink,
1091                            self.gates.answer(parent.as_ref(), &self.step, approved),
1092                        )
1093                        .await;
1094                        if !approved {
1095                            return Ok(NodeOutput::new()
1096                                .with_update("planStatus", "cancelled")
1097                                .with_goto([END]));
1098                        }
1099                    }
1100                    None => {
1101                        for event in self
1102                            .gates
1103                            .pause(parent.as_ref(), &self.step)
1104                            .await
1105                            .map_err(|e| failed(&self.node, e))?
1106                        {
1107                            let _ = self.sink.send(Forward::Event(event));
1108                        }
1109                        return Ok(NodeOutput::interrupt_with_data(
1110                            "plan step waits for approval",
1111                            json!({ "stepId": self.step.id }),
1112                        ));
1113                    }
1114                },
1115            }
1116        }
1117
1118        let instruction = self.instruction();
1119        let content = Content::new("user").with_text(instruction.clone());
1120        if !self.started(parent.as_ref(), &instruction) {
1121            // The workspace as it was before this step (spec 3.1 §7.27).
1122            if let Some(snapshots) = &self.snapshots {
1123                let mark = crate::snapshot::PlanMark {
1124                    plan_hash: self.gates.plan_hash.clone(),
1125                    thread_id: ctx.config.thread_id.clone(),
1126                    completed: self
1127                        .order
1128                        .iter()
1129                        .filter(|id| ctx.state.contains_key(&done_key(id)))
1130                        .cloned()
1131                        .collect(),
1132                    running: true,
1133                };
1134                crate::snapshot::before_step(snapshots, parent.as_ref(), &self.step.id, mark).await;
1135            }
1136            let mut event = Event::new(parent.invocation_id());
1137            event.author = "user".to_string();
1138            event.branch = parent.branch().to_string();
1139            event.llm_response.content = Some(content.clone());
1140            send_synced(&self.sink, event).await;
1141        }
1142        let (held, output) =
1143            run_agent_node(&self.node, &self.root, &self.harness, parent, content, &self.sink)
1144                .await?;
1145        if held {
1146            return Ok(NodeOutput::interrupt_with_data(
1147                "plan step holds a tool call",
1148                json!({ "stepId": self.step.id }),
1149            ));
1150        }
1151        Ok(NodeOutput::new().with_update(&done_key(&self.step.id), json!({ "output": output })))
1152    }
1153}
1154
1155/// The reviewer after a `Review` gate: an isolated delegation to the reviewer member
1156/// (spec 3.1 §7.10, §7.11).
1157struct ReviewNode {
1158    node: String,
1159    step: PlanStep,
1160    reviewer: Arc<dyn Agent>,
1161    gates: Arc<GateBook>,
1162    sink: Sink,
1163}
1164
1165#[async_trait::async_trait]
1166impl Node for ReviewNode {
1167    fn name(&self) -> &str {
1168        &self.node
1169    }
1170
1171    fn description(&self) -> &str {
1172        "Reviews the step before the plan continues."
1173    }
1174
1175    async fn execute(&self, ctx: &NodeContext) -> adk_graph::Result<NodeOutput> {
1176        let parent =
1177            ctx.config.parent_context.clone().ok_or_else(|| {
1178                node_error(&self.node, "a review runs only inside a harness turn")
1179            })?;
1180        let output = review(parent.clone(), &self.reviewer, &self.step, &self.sink).await.map_err(
1181            |error| GraphError::AgentFailed { node: self.node.clone(), source: Box::new(error) },
1182        )?;
1183        self.gates
1184            .record(parent.as_ref(), &self.step, "reviewed")
1185            .await
1186            .map_err(|e| failed(&self.node, e))?;
1187        Ok(NodeOutput::new().with_update(&format!("review:{}", self.step.id), output))
1188    }
1189}
1190
1191#[cfg(feature = "team")]
1192async fn review(
1193    parent: Arc<dyn InvocationContext>,
1194    reviewer: &Arc<dyn Agent>,
1195    step: &PlanStep,
1196    sink: &Sink,
1197) -> Result<Value> {
1198    use adk_core::Tool;
1199    let tool = adk_tool::AgentTool::new(reviewer.clone())
1200        .session_snapshot(adk_tool::AgentToolSessionSnapshot::Isolated)
1201        .forward_artifacts(false)
1202        .forward_shared_state(false)
1203        .forward_memory(false)
1204        .forward_events(true)
1205        .history_max_events(0)
1206        .state_keys(Vec::<String>::new())
1207        .max_delegation_depth(1)
1208        .timeout(crate::team::MEMBER_TIMEOUT);
1209    let sink = sink.clone();
1210    let tool_ctx = Arc::new(
1211        crate::run_context::InvocationToolContext::new(parent, format!("plan-review-{}", step.id))
1212            .with_event_sink(Arc::new(move |event| {
1213                let _ = sink.send(Forward::Event(event));
1214            })),
1215    );
1216    tool.execute(
1217        tool_ctx,
1218        json!({
1219            "request": format!(
1220                "Review the work of plan step {}: {}.\nThe step's instruction was:\n{}\n\nReport \
1221                 problems with file paths, or say it is ready.",
1222                step.id, step.title, step.instruction
1223            )
1224        }),
1225    )
1226    .await
1227}
1228
1229#[cfg(not(feature = "team"))]
1230async fn review(
1231    _parent: Arc<dyn InvocationContext>,
1232    _reviewer: &Arc<dyn Agent>,
1233    step: &PlanStep,
1234    _sink: &Sink,
1235) -> Result<Value> {
1236    Err(invalid(format!("step '{}' needs a reviewer member, which needs feature `team`", step.id)))
1237}