Skip to main content

merry_runtime/tool/
proposal.rs

1use crate::{
2    ProcessActionError, ProcessActionIntent, ProcessExecutionEvidence,
3    tool::patch_evidence::{WorkspacePatchExecutionEvidence, WorkspacePatchProposal},
4};
5use merry_core::{PendingToolCall, ToolCallId, ToolName};
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9/// Runtime-owned action category for registered tools.
10///
11/// This metadata is intentionally not part of provider-visible [`merry_core::ToolSpec`].
12/// Runtime policy uses it before invoking an executor.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum ToolActionKind {
16    /// Reads runtime or workspace state without changing it.
17    ReadOnly,
18    /// Mutates runtime-owned control state without direct external side effects.
19    RuntimeControl,
20    /// Writes files or other state in the configured workspace.
21    WorkspaceWrite,
22    /// Executes a local command or process.
23    CommandExec,
24    /// Uses network access.
25    Network,
26    /// Executes a user-configured external tool that is trusted by configuration.
27    TrustedExternal,
28}
29
30impl ToolActionKind {
31    /// Returns whether this action category can cause external side effects
32    /// that require the mutating action commit lifecycle.
33    #[must_use]
34    pub fn is_mutating(self) -> bool {
35        matches!(
36            self,
37            Self::WorkspaceWrite | Self::CommandExec | Self::Network
38        )
39    }
40}
41
42/// Runtime-owned, provider-neutral proposal for a mutating registered action.
43///
44/// This type is public only so tool crates can supply deterministic proposal
45/// evidence to `merry-runtime`. It is unstable implementation-facing API: it is
46/// not part of `merry_core::RuntimeJournalEvent`, is not provider wire format, and must
47/// not be rendered into provider-visible tool specs or continuations.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct ActionProposal {
51    pub(super) tool_call_id: ToolCallId,
52    pub(super) tool_name: ToolName,
53    pub(super) action_kind: ToolActionKind,
54    pub(super) label: String,
55    pub(super) subject: String,
56    pub(super) summary: String,
57    pub(super) evidence: ActionProposalEvidence,
58}
59
60impl ActionProposal {
61    /// Creates a validated mutating action proposal for a pending tool call.
62    pub fn new(
63        call: &PendingToolCall,
64        action_kind: ToolActionKind,
65        label: impl Into<String>,
66        subject: impl Into<String>,
67        summary: impl Into<String>,
68        evidence: ActionProposalEvidence,
69    ) -> Result<Self, ActionProposalError> {
70        if action_kind == ToolActionKind::ReadOnly {
71            return Err(ActionProposalError::ReadOnlyAction);
72        }
73        validate_proposal_evidence_matches_action_kind(action_kind, &evidence)?;
74
75        Ok(Self {
76            tool_call_id: call.id().clone(),
77            tool_name: call.name().clone(),
78            action_kind,
79            label: validate_compact_proposal_text("label", label.into())?,
80            subject: validate_compact_proposal_text("subject", subject.into())?,
81            summary: validate_compact_proposal_text("summary", summary.into())?,
82            evidence,
83        })
84    }
85
86    /// Returns the proposed tool call id.
87    #[must_use]
88    pub fn tool_call_id(&self) -> &ToolCallId {
89        &self.tool_call_id
90    }
91
92    /// Returns the proposed tool name.
93    #[must_use]
94    pub fn tool_name(&self) -> &ToolName {
95        &self.tool_name
96    }
97
98    /// Returns the proposed runtime action kind.
99    #[must_use]
100    pub fn action_kind(&self) -> ToolActionKind {
101        self.action_kind
102    }
103
104    /// Returns the compact proposal label.
105    #[must_use]
106    pub fn label(&self) -> &str {
107        &self.label
108    }
109
110    /// Returns the compact proposal subject.
111    #[must_use]
112    pub fn subject(&self) -> &str {
113        &self.subject
114    }
115
116    /// Returns the compact proposal summary.
117    #[must_use]
118    pub fn summary(&self) -> &str {
119        &self.summary
120    }
121
122    /// Returns provider-neutral deterministic proposal evidence.
123    #[must_use]
124    pub fn evidence(&self) -> &ActionProposalEvidence {
125        &self.evidence
126    }
127
128    pub(crate) fn validate_for_call(
129        &self,
130        call: &PendingToolCall,
131        action_kind: ToolActionKind,
132    ) -> Result<(), &'static str> {
133        if self.tool_call_id != *call.id() {
134            return Err("proposal tool call id does not match pending call");
135        }
136        if self.tool_name != *call.name() {
137            return Err("proposal tool name does not match pending call");
138        }
139        if self.action_kind != action_kind {
140            return Err("proposal action kind does not match registered tool");
141        }
142        if !self.evidence.matches_action_kind(action_kind) {
143            return Err("proposal evidence does not match registered tool action kind");
144        }
145        Ok(())
146    }
147}
148
149/// Provider-neutral deterministic evidence attached to an action proposal.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[serde(rename_all = "snake_case")]
152pub enum ActionProposalEvidence {
153    /// A constrained workspace patch proposal.
154    WorkspacePatch(WorkspacePatchProposal),
155    /// A typed local process action intent.
156    ProcessAction(ProcessActionIntent),
157}
158
159impl ActionProposalEvidence {
160    pub(super) fn matches_action_kind(&self, action_kind: ToolActionKind) -> bool {
161        matches!(
162            (action_kind, self),
163            (ToolActionKind::WorkspaceWrite, Self::WorkspacePatch(_))
164                | (ToolActionKind::CommandExec, Self::ProcessAction(_))
165        )
166    }
167}
168
169/// Provider-neutral internal evidence attached after a mutating action executes.
170///
171/// This evidence is runtime-owned audit state. It intentionally carries no
172/// provider wire data and must not be exposed through artifacts or tool result
173/// continuations.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(rename_all = "snake_case")]
176pub enum ActionExecutionEvidence {
177    /// A constrained workspace patch that was actually applied.
178    WorkspacePatch(WorkspacePatchExecutionEvidence),
179    /// Evidence from a local process action execution.
180    ProcessAction(ProcessExecutionEvidence),
181}
182
183impl ActionExecutionEvidence {
184    pub(crate) fn matches_action_kind(&self, action_kind: ToolActionKind) -> bool {
185        matches!(
186            (action_kind, self),
187            (ToolActionKind::WorkspaceWrite, Self::WorkspacePatch(_))
188                | (ToolActionKind::CommandExec, Self::ProcessAction(_))
189        )
190    }
191}
192
193/// Validation errors for runtime-owned action proposal values.
194#[derive(Debug, Clone, PartialEq, Eq, Error)]
195pub enum ActionProposalError {
196    /// Read-only actions do not need mutating action proposals.
197    #[error("read-only actions do not need action proposals")]
198    ReadOnlyAction,
199
200    /// A compact proposal text field was invalid.
201    #[error("action proposal {field} {reason}")]
202    InvalidText {
203        /// Invalid field name.
204        field: &'static str,
205        /// Validation failure detail.
206        reason: &'static str,
207    },
208
209    /// Workspace patch proposal metadata was invalid.
210    #[error("workspace patch proposal {field} {reason}")]
211    InvalidWorkspacePatch {
212        /// Invalid field name.
213        field: &'static str,
214        /// Validation failure detail.
215        reason: &'static str,
216    },
217
218    /// Proposal evidence did not match the proposal action kind.
219    #[error("action proposal evidence does not match action kind {action_kind:?}")]
220    EvidenceActionKindMismatch {
221        /// Action kind supplied for the proposal.
222        action_kind: ToolActionKind,
223    },
224
225    /// Process action proposal metadata was invalid.
226    #[error("process action proposal metadata invalid: {source}")]
227    InvalidProcessAction {
228        /// Source process action validation error.
229        #[from]
230        source: ProcessActionError,
231    },
232}
233
234pub(super) const MAX_ACTION_PROPOSAL_TEXT_BYTES: usize = 512;
235
236pub(super) fn validate_compact_proposal_text(
237    field: &'static str,
238    value: String,
239) -> Result<String, ActionProposalError> {
240    if value.trim().is_empty() {
241        return Err(ActionProposalError::InvalidText {
242            field,
243            reason: "must not be blank",
244        });
245    }
246    if value.len() > MAX_ACTION_PROPOSAL_TEXT_BYTES {
247        return Err(ActionProposalError::InvalidText {
248            field,
249            reason: "exceeds the byte limit",
250        });
251    }
252    if value.chars().any(char::is_control) {
253        return Err(ActionProposalError::InvalidText {
254            field,
255            reason: "must not contain control characters",
256        });
257    }
258    Ok(value)
259}
260
261pub(super) fn validate_proposal_evidence_matches_action_kind(
262    action_kind: ToolActionKind,
263    evidence: &ActionProposalEvidence,
264) -> Result<(), ActionProposalError> {
265    if evidence.matches_action_kind(action_kind) {
266        Ok(())
267    } else {
268        Err(ActionProposalError::EvidenceActionKindMismatch { action_kind })
269    }
270}