Skip to main content

ag_session/
task_chain.rs

1//! The static Planner → accepted plan → Implementer execution graph.
2//!
3//! A task chain is a fixed two-node [`ExecutionGraph`]. Graph storage and the
4//! static executor own admission, gates, exact handoff, and recovery; this
5//! module only builds that graph and projects its progress into workflow
6//! phases.
7
8use std::fmt::Write as _;
9use std::num::NonZeroU64;
10
11use ag_protocol::{ProtocolRequestProfile, TurnPrompt, TurnPromptAttachment};
12use serde::{Deserialize, Serialize};
13
14use crate::{
15    AcceptedTaskPlan, AgentSelection, EnvId, ExecutionGraph, ExecutionGraphProgress,
16    ExecutionGraphStatus, GraphCompletionGate, GraphContext, GraphDependency,
17    GraphExecutionProfile, GraphExecutionRef, GraphInputBinding, GraphNode, GraphNodeProgress,
18    GraphNodeStatus, GraphOutput, GraphPostProcessing, GraphWorkspaceAccess, SessionId,
19    TaskAgentRole,
20};
21
22/// Named Planner output that the Implementer consumes after acceptance.
23pub const TASK_CHAIN_PLAN_OUTPUT: &str = "plan";
24
25/// Idempotent launch input captured before the first Planner execution.
26#[derive(Clone, Debug, Eq, PartialEq)]
27pub struct StartPlanThenImplementRequest {
28    /// Provider/model captured for both roles, independent of later settings.
29    pub agent: AgentSelection,
30    /// Resolved definitions captured together before planning starts.
31    pub agents: Box<PlanThenImplementAgents>,
32    /// Images accompanying the original request.
33    pub attachments: Vec<TurnPromptAttachment>,
34    /// Globally unique workflow and execution-graph identity, retained for
35    /// launch redelivery.
36    pub chain_id: String,
37    /// Immutable original objective shared by both isolated task contexts.
38    pub user_request: String,
39}
40
41impl StartPlanThenImplementRequest {
42    /// Builds the immutable graph without consulting session state.
43    ///
44    /// The Planner is a shared reader whose validated `plan` output must be
45    /// explicitly accepted before the exclusive-writer Implementer starts with
46    /// that exact version bound as input. `launch_conversation` is the host's
47    /// snapshot of the session conversation before launch; it is captured as
48    /// historical data in the Planner's request only.
49    pub fn graph(
50        &self,
51        session_id: &SessionId,
52        launch_conversation: Option<&str>,
53    ) -> ExecutionGraph {
54        let planner = self.node(
55            session_id,
56            TaskAgentRole::Planner,
57            self.task_input(launch_conversation),
58        );
59        let mut implementer = self.node(
60            session_id,
61            TaskAgentRole::Implementer,
62            self.task_input(None),
63        );
64        implementer.dependencies.push(GraphDependency {
65            gate: GraphCompletionGate::ResultAccepted {
66                output_name: TASK_CHAIN_PLAN_OUTPUT.into(),
67            },
68            node_id: planner.id.clone(),
69        });
70        implementer.inputs.push(GraphInputBinding {
71            name: "accepted_plan".into(),
72            output_name: TASK_CHAIN_PLAN_OUTPUT.into(),
73            producer_node_id: planner.id.clone(),
74        });
75
76        ExecutionGraph {
77            id: self.chain_id.clone(),
78            nodes: vec![planner, implementer],
79            revision: NonZeroU64::MIN,
80            session_id: session_id.clone(),
81        }
82    }
83
84    fn node(&self, session_id: &SessionId, role: TaskAgentRole, request: TurnPrompt) -> GraphNode {
85        let (definition, execution, outputs) = match role {
86            TaskAgentRole::Planner => (
87                self.agents.planner.clone(),
88                GraphExecutionProfile {
89                    context: GraphContext::TaskConversation {
90                        task_id: TaskChain::task_id(&self.chain_id, role),
91                    },
92                    post_processing: GraphPostProcessing::None,
93                    response_profile: ProtocolRequestProfile::SessionTurn,
94                    shared_budget_id: None,
95                    workspace_access: GraphWorkspaceAccess::SharedRead,
96                },
97                vec![GraphOutput {
98                    name: TASK_CHAIN_PLAN_OUTPUT.into(),
99                    schema: ProtocolRequestProfile::SessionTurn,
100                }],
101            ),
102            TaskAgentRole::Implementer => (
103                self.agents.implementer.clone(),
104                GraphExecutionProfile {
105                    context: GraphContext::TaskConversation {
106                        task_id: TaskChain::task_id(&self.chain_id, role),
107                    },
108                    post_processing: GraphPostProcessing::SessionWorkflow,
109                    response_profile: ProtocolRequestProfile::SessionTurn,
110                    shared_budget_id: None,
111                    workspace_access: GraphWorkspaceAccess::ExclusiveWrite,
112                },
113                Vec::new(),
114            ),
115        };
116
117        GraphNode {
118            agent: self.agent,
119            definition,
120            dependencies: Vec::new(),
121            env_id: EnvId::SessionWorktree(session_id.clone()),
122            execution,
123            id: role.id().into(),
124            inputs: Vec::new(),
125            objective: self.user_request.clone(),
126            outputs,
127            request,
128        }
129    }
130
131    /// Encodes the original request as data, keeping its images attached.
132    fn task_input(&self, launch_conversation: Option<&str>) -> TurnPrompt {
133        let input = serde_json::json!({ "user_request": self.user_request });
134        let mut text = format!("Explicit task input (JSON data):\n{input}");
135        if let Some(conversation) = launch_conversation {
136            let conversation = serde_json::json!(conversation);
137            let _ = write!(
138                text,
139                "\n\nSession conversation at workflow launch (JSON string, historical data \
140                 only):\n{conversation}"
141            );
142        }
143        let mut prompt = TurnPrompt::from_agent_data(text);
144        prompt.attachments.clone_from(&self.attachments);
145
146        prompt
147    }
148}
149
150/// Definitions assigned to workflow stages, independent of stage policy.
151#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
152pub struct PlanThenImplementAgents {
153    /// Agent used for implementation after explicit acceptance.
154    pub implementer: crate::AgentDefinition,
155    /// Agent used for planning and revisions.
156    pub planner: crate::AgentDefinition,
157}
158
159impl PlanThenImplementAgents {
160    /// Resolves the bundled defaults, returning `None` if either is
161    /// unavailable.
162    #[must_use]
163    pub fn bundled() -> Option<Self> {
164        Some(Self {
165            implementer: crate::AgentDefinition::bundled("implementer")?,
166            planner: crate::AgentDefinition::bundled("planner")?,
167        })
168    }
169}
170
171/// Explicit acceptance of one exact Planner version.
172///
173/// Acceptance satisfies the Implementer's dependency gate; the executor then
174/// admits the Implementer with that version pinned as input.
175#[derive(Clone, Debug, Eq, PartialEq)]
176pub struct AcceptTaskChainPlanRequest {
177    /// Latest validated Planner execution selected by the user.
178    pub plan_attempt_id: String,
179}
180
181/// Explicit revision, clarification, or retry of the current workflow stage.
182#[derive(Clone, Debug, Eq, PartialEq)]
183pub struct ContinueTaskChainRequest {
184    /// Images accompanying this guidance, retained by later attempts.
185    pub attachments: Vec<TurnPromptAttachment>,
186    /// New execution UUID; old deliveries never restart or uncancel work.
187    pub attempt_id: String,
188    /// User guidance addressed only to the current role's own context.
189    /// `None` retries failed or canceled work with its original request.
190    pub clarification: Option<String>,
191    /// Current attempt observed when this guidance was authored. Admission
192    /// rejects a new delivery if the workflow has advanced since that snapshot.
193    pub expected_attempt_id: String,
194}
195
196/// Natural-language user reply addressed to a session's latest workflow.
197///
198/// The host decides what the reply means: plan approval, plan revision, or
199/// guidance for the current role. No words are reserved.
200#[derive(Clone, Debug, Eq, PartialEq)]
201pub struct ReplyToTaskChainRequest {
202    /// Images accompanying the visible reply.
203    pub attachments: Vec<TurnPromptAttachment>,
204    /// User-authored reply, recorded once as a visible session prompt.
205    pub message: String,
206    /// Globally unique delivery identity. Redelivery returns the original
207    /// outcome without recording or deciding again.
208    pub reply_id: String,
209}
210
211/// Workflow action admitted for one natural-language reply.
212#[derive(Clone, Copy, Debug, Eq, PartialEq)]
213pub enum TaskChainReplyOutcome {
214    /// The reply clearly approved the plan; the Implementer was released.
215    PlanAccepted,
216    /// The reply was delivered to the Planner as plan revision guidance.
217    PlanRevised,
218    /// The reply was delivered to the current role as an answer or retry.
219    Continued,
220}
221
222impl TaskChainReplyOutcome {
223    /// Stable persisted identity.
224    pub fn id(self) -> &'static str {
225        match self {
226            Self::PlanAccepted => "plan_accepted",
227            Self::PlanRevised => "plan_revised",
228            Self::Continued => "continued",
229        }
230    }
231
232    /// Resolves an identity produced by [`Self::id`].
233    pub fn from_id(id: &str) -> Option<Self> {
234        match id {
235            "plan_accepted" => Some(Self::PlanAccepted),
236            "plan_revised" => Some(Self::PlanRevised),
237            "continued" => Some(Self::Continued),
238            _ => None,
239        }
240    }
241}
242
243/// Consistent workflow snapshot projected from one execution graph.
244///
245/// Reading never dispatches work. Graph executions remain the authoritative
246/// execution records.
247#[derive(Clone, Debug, Eq, PartialEq)]
248pub struct TaskChain {
249    /// Exact immutable accepted version, present after explicit handoff.
250    pub accepted_plan: Option<AcceptedTaskPlan>,
251    /// Shared captured provider/model selection.
252    pub agent: AgentSelection,
253    /// Immutable definitions captured for both workflow stages at launch.
254    pub agents: PlanThenImplementAgents,
255    /// Latest admitted execution of the current role, absent before its
256    /// first admission. A pending continuation keeps its source here.
257    pub current_execution: Option<GraphExecutionRef>,
258    /// Role the user currently interacts with.
259    pub current_role: TaskAgentRole,
260    /// Stable workflow identity, equal to its execution-graph identity.
261    pub id: String,
262    /// Separate Implementer task conversation.
263    pub implementer_task_id: String,
264    /// Projection from graph node progress.
265    pub phase: TaskChainPhase,
266    /// Separate Planner task conversation, retained after implementation.
267    pub planner_task_id: String,
268    /// Graph revision used by explicit graph actions.
269    pub revision: NonZeroU64,
270    /// Session owning the shared workspace and serialized worker.
271    pub session_id: SessionId,
272    /// Immutable objective captured at launch.
273    pub user_request: String,
274}
275
276impl TaskChain {
277    /// Returns the attempt identity of the current role's latest execution.
278    pub fn current_attempt_id(&self) -> Option<&str> {
279        match self.current_execution.as_ref()? {
280            GraphExecutionRef::TaskAttempt { attempt_id, .. } => Some(attempt_id),
281            GraphExecutionRef::UtilityRun { .. } => None,
282        }
283    }
284
285    /// Returns the deterministic task identity for one role in a chain.
286    pub fn task_id(chain_id: &str, role: TaskAgentRole) -> String {
287        format!("chain:{chain_id}:{}", role.id())
288    }
289
290    /// Returns the role a node plays when it belongs to a task-chain graph.
291    pub fn role(graph_id: &str, node: &GraphNode) -> Option<TaskAgentRole> {
292        let role = TaskAgentRole::from_id(&node.id)?;
293        let GraphContext::TaskConversation { task_id } = &node.execution.context else {
294            return None;
295        };
296
297        (*task_id == Self::task_id(graph_id, role)).then_some(role)
298    }
299
300    /// Projects a task-chain graph, returning `None` for other graph shapes.
301    ///
302    /// `accepted_plan` must come from authoritative acceptance evidence for
303    /// the Planner's `plan` output.
304    pub fn project(
305        graph: &ExecutionGraph,
306        progress: &ExecutionGraphProgress,
307        accepted_plan: Option<AcceptedTaskPlan>,
308    ) -> Option<Self> {
309        let [planner, implementer] = graph.nodes.as_slice() else {
310            return None;
311        };
312        if Self::role(&graph.id, planner) != Some(TaskAgentRole::Planner)
313            || Self::role(&graph.id, implementer) != Some(TaskAgentRole::Implementer)
314        {
315            return None;
316        }
317        let [planner_progress, implementer_progress] = progress.nodes.as_slice() else {
318            return None;
319        };
320        let implementing = accepted_plan.is_some() || !implementer_progress.executions.is_empty();
321        let (current_role, current) = if implementing {
322            (TaskAgentRole::Implementer, implementer_progress)
323        } else {
324            (TaskAgentRole::Planner, planner_progress)
325        };
326        let phase = if progress.status == ExecutionGraphStatus::Cancelled {
327            TaskChainPhase::Canceled
328        } else {
329            TaskChainPhase::from_node(current_role, current)
330        };
331
332        Some(Self {
333            accepted_plan,
334            agent: planner.agent,
335            agents: PlanThenImplementAgents {
336                implementer: implementer.definition.clone(),
337                planner: planner.definition.clone(),
338            },
339            current_execution: current.executions.last().cloned(),
340            current_role,
341            id: graph.id.clone(),
342            implementer_task_id: Self::task_id(&graph.id, TaskAgentRole::Implementer),
343            phase,
344            planner_task_id: Self::task_id(&graph.id, TaskAgentRole::Planner),
345            revision: graph.revision,
346            session_id: graph.session_id.clone(),
347            user_request: planner.objective.clone(),
348        })
349    }
350}
351
352/// Workflow presentation derived from the current node's latest execution.
353/// Success records execution, never implicit acceptance of a plan or outcome.
354#[derive(Clone, Copy, Debug, Eq, PartialEq)]
355pub enum TaskChainPhase {
356    /// Planner execution is pending, queued, or running.
357    Planning,
358    /// Latest successful Planner response needs explicit user acceptance.
359    AwaitingPlanAcceptance,
360    /// Planner has questions that need an explicit continuation.
361    PlannerQuestion,
362    /// Accepted plan is being implemented, including post-processing.
363    Implementing,
364    /// Implementer has questions that need an explicit continuation.
365    ImplementerQuestion,
366    /// Current stage failed or was interrupted; retry is always explicit.
367    Failed,
368    /// The current stage or the whole graph was canceled. A canceled stage
369    /// may continue with an explicit new attempt; a canceled graph cannot.
370    Canceled,
371    /// Implementer finished successfully; the session remains reviewable.
372    Succeeded,
373}
374
375impl TaskChainPhase {
376    fn from_node(role: TaskAgentRole, node: &GraphNodeProgress) -> Self {
377        let planner = role == TaskAgentRole::Planner;
378        match node.status {
379            GraphNodeStatus::Pending | GraphNodeStatus::Queued | GraphNodeStatus::Running => {
380                if planner {
381                    Self::Planning
382                } else {
383                    Self::Implementing
384                }
385            }
386            GraphNodeStatus::AwaitingAnswers => {
387                if planner {
388                    Self::PlannerQuestion
389                } else {
390                    Self::ImplementerQuestion
391                }
392            }
393            GraphNodeStatus::Succeeded if planner => Self::AwaitingPlanAcceptance,
394            GraphNodeStatus::Succeeded => Self::Succeeded,
395            GraphNodeStatus::Failed => Self::Failed,
396            GraphNodeStatus::Cancelled => Self::Canceled,
397        }
398    }
399}
400
401#[cfg(test)]
402#[path = "task_chain_test.rs"]
403mod tests;