Skip to main content

ag_session/execution_graph/
proposal.rs

1//! Pure resolution of untrusted logical proposals against captured host inputs.
2
3use std::num::NonZeroU64;
4
5use ag_protocol::{
6    GraphProposal, GraphProposalContext, GraphProposalGate, GraphProposalNode,
7    GraphProposalPostProcessing, GraphProposalWorkspaceAccess, ProtocolRequestProfile, TurnPrompt,
8    TurnPromptAttachment,
9};
10use serde::{Deserialize, Serialize};
11
12use super::{
13    ExecutionGraph, GraphCompletionGate, GraphContext, GraphDependency, GraphExecutionProfile,
14    GraphInputBinding, GraphNode, GraphOutput, GraphPostProcessing, GraphWorkspaceAccess,
15};
16use crate::{AgentDefinition, AgentSelection, EnvId, PermissionMode, SessionId};
17
18/// Captured ceilings shared by generation, inspection, and approval.
19#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
20pub struct GraphProposalLimits {
21    /// Maximum serialized response size, in UTF-8 bytes.
22    pub bytes: usize,
23    /// Maximum prerequisite edges, including distinct gates.
24    pub edges: usize,
25    /// Maximum explicit generation requests for this proposal, across restarts.
26    pub generations: u32,
27    /// Provider calls per generation, including transport retries and repairs.
28    pub generation_provider_calls: usize,
29    /// Maximum nodes in one proposal.
30    pub nodes: usize,
31    /// Shared provider-call ceiling for the executable graph.
32    pub provider_calls: usize,
33}
34
35impl Default for GraphProposalLimits {
36    fn default() -> Self {
37        Self {
38            bytes: 65_536,
39            edges: 32,
40            generations: 3,
41            generation_provider_calls: 3,
42            nodes: 16,
43            provider_calls: 48,
44        }
45    }
46}
47
48/// Host-owned inputs captured before generation; no external work occurs here.
49pub struct GraphProposalResolution<'a> {
50    /// Exact provider and model shared by every proposed node.
51    pub agent: AgentSelection,
52    /// Saved question-and-answer history, encoded as JSON data for each node.
53    pub answers: &'a [String],
54    /// Enabled definitions captured from the session's catalog.
55    pub definitions: &'a [AgentDefinition],
56    /// Fresh host-allocated graph namespace, never supplied by the model.
57    pub graph_id: &'a str,
58    /// Captured generation and execution ceilings.
59    pub limits: &'a GraphProposalLimits,
60    /// Session permission ceiling captured by the host.
61    pub permission: PermissionMode,
62    /// Original prompt; resolution appends answers and retains its source
63    /// classification.
64    pub request: &'a TurnPrompt,
65    /// Revision feedback images, appended after the request images.
66    pub revision_attachments: &'a [TurnPromptAttachment],
67    /// Session whose shared Env is bound to every node.
68    pub session_id: &'a SessionId,
69}
70
71impl GraphProposalResolution<'_> {
72    /// Resolves only supported profiles and rejects escalation before approval.
73    ///
74    /// # Errors
75    /// Rejects size limits, unknown definitions, unsupported profiles,
76    /// permissions, and invalid graphs. Request attachments, followed by
77    /// revision attachments, are copied to every node unchanged.
78    pub fn resolve(&self, proposal: &GraphProposal) -> Result<ExecutionGraph, String> {
79        let graph = ExecutionGraph {
80            id: self.graph_id.into(),
81            nodes: self.nodes(proposal, 0)?,
82            revision: NonZeroU64::MIN,
83            session_id: self.session_id.clone(),
84        };
85        graph.validate().map_err(|error| error.to_string())?;
86
87        Ok(graph)
88    }
89
90    /// Resolves `proposal` as nodes appended to `base`, returning its next
91    /// revision. Proposed nodes may depend on `base` nodes; task identities
92    /// continue after the base's nodes, and every node spends from the
93    /// graph's existing `{graph_id}:calls` budget.
94    ///
95    /// # Errors
96    /// Rejects everything [`Self::resolve`] rejects, a `base` that is not
97    /// this resolution's graph in the captured session, and proposed node
98    /// identities the base already uses.
99    pub fn resolve_expansion(
100        &self,
101        base: &ExecutionGraph,
102        proposal: &GraphProposal,
103    ) -> Result<ExecutionGraph, String> {
104        if base.id != self.graph_id || base.session_id != *self.session_id {
105            return Err("Graph expansion targets a different graph or session".into());
106        }
107
108        base.expand(self.nodes(proposal, base.nodes.len())?)
109            .map_err(|error| error.to_string())
110    }
111
112    /// Resolves proposed nodes, numbering task identities from
113    /// `first_task_index`.
114    fn nodes(
115        &self,
116        proposal: &GraphProposal,
117        first_task_index: usize,
118    ) -> Result<Vec<GraphNode>, String> {
119        if self.limits.generations == 0
120            || self.limits.generation_provider_calls == 0
121            || self.limits.provider_calls == 0
122            || self.request.text.trim().is_empty()
123            || serde_json::json!(proposal).to_string().len() > self.limits.bytes
124            || proposal.nodes.len() > self.limits.nodes
125            || proposal
126                .nodes
127                .iter()
128                .map(|node| node.dependencies.len())
129                .sum::<usize>()
130                > self.limits.edges
131        {
132            return Err("Graph proposal exceeds captured limits or has an empty request".into());
133        }
134        let mut request = self.request.clone();
135        request
136            .attachments
137            .extend_from_slice(self.revision_attachments);
138        if !self.answers.is_empty() {
139            request
140                .text
141                .push_str("\n\nComplete clarification answer history (JSON data):\n");
142            request
143                .text
144                .push_str(&serde_json::json!(self.answers).to_string());
145        }
146        let mut nodes = Vec::with_capacity(proposal.nodes.len());
147        for (index, node) in proposal.nodes.iter().enumerate() {
148            let definition = self
149                .definitions
150                .iter()
151                .find(|definition| definition.id == node.agent_id)
152                .ok_or_else(|| format!("Unavailable agent definition: {}", node.agent_id))?;
153            nodes.push(GraphNode {
154                agent: self.agent,
155                definition: definition.clone(),
156                dependencies: node
157                    .dependencies
158                    .iter()
159                    .map(|dependency| GraphDependency {
160                        gate: match &dependency.gate {
161                            GraphProposalGate::ExecutionSucceeded {} => {
162                                GraphCompletionGate::ExecutionSucceeded
163                            }
164                            GraphProposalGate::ResultValidated { output_name } => {
165                                GraphCompletionGate::ResultValidated {
166                                    output_name: output_name.clone(),
167                                }
168                            }
169                            GraphProposalGate::ResultAccepted { output_name } => {
170                                GraphCompletionGate::ResultAccepted {
171                                    output_name: output_name.clone(),
172                                }
173                            }
174                        },
175                        node_id: dependency.node_id.clone(),
176                    })
177                    .collect(),
178                env_id: EnvId::SessionWorktree(self.session_id.clone()),
179                execution: self.profile(node, definition, first_task_index + index)?,
180                id: node.id.clone(),
181                inputs: node
182                    .inputs
183                    .iter()
184                    .map(|input| GraphInputBinding {
185                        name: input.name.clone(),
186                        output_name: input.output_name.clone(),
187                        producer_node_id: input.producer_node_id.clone(),
188                    })
189                    .collect(),
190                objective: node.objective.clone(),
191                outputs: node
192                    .outputs
193                    .iter()
194                    .map(|output| GraphOutput {
195                        name: output.name.clone(),
196                        schema: output.schema,
197                    })
198                    .collect(),
199                request: request.clone(),
200            });
201        }
202
203        Ok(nodes)
204    }
205
206    fn profile(
207        &self,
208        node: &GraphProposalNode,
209        definition: &AgentDefinition,
210        index: usize,
211    ) -> Result<GraphExecutionProfile, String> {
212        let execution = &node.execution;
213        let workspace_access = match execution.workspace_access {
214            GraphProposalWorkspaceAccess::SharedRead => GraphWorkspaceAccess::SharedRead,
215            GraphProposalWorkspaceAccess::ExclusiveWrite => GraphWorkspaceAccess::ExclusiveWrite,
216            GraphProposalWorkspaceAccess::BackgroundRead => {
217                return Err("Background graph readers are unsupported".into());
218            }
219        };
220        if workspace_access == GraphWorkspaceAccess::ExclusiveWrite
221            && (definition.read_only || self.permission == PermissionMode::ReadOnly)
222        {
223            return Err("Graph proposal requests access beyond host or agent permissions".into());
224        }
225        let context = match execution.context {
226            GraphProposalContext::Fresh => {
227                if workspace_access != GraphWorkspaceAccess::SharedRead
228                    || !matches!(
229                        execution.response_profile,
230                        ProtocolRequestProfile::UtilityPrompt
231                            | ProtocolRequestProfile::FocusedReview
232                            | ProtocolRequestProfile::ReviewMetadata
233                    )
234                {
235                    return Err("Unsupported graph utility profile".into());
236                }
237                GraphContext::Fresh
238            }
239            GraphProposalContext::TaskConversation => GraphContext::TaskConversation {
240                task_id: format!("{}:task:{index}", self.graph_id),
241            },
242        };
243
244        Ok(GraphExecutionProfile {
245            context,
246            post_processing: match execution.post_processing {
247                GraphProposalPostProcessing::None => GraphPostProcessing::None,
248                GraphProposalPostProcessing::SessionWorkflow => {
249                    GraphPostProcessing::SessionWorkflow
250                }
251            },
252            response_profile: execution.response_profile,
253            shared_budget_id: Some(format!("{}:calls", self.graph_id)),
254            workspace_access,
255        })
256    }
257}
258
259#[cfg(test)]
260#[path = "proposal_test.rs"]
261mod tests;