Skip to main content

openmoat_core/
action.rs

1//! What a tool call asks to do, in two forms.
2//!
3//! [`Action`] is the call as a host adapter reports it: one per payload,
4//! before any classification. [`AtomicAction`] is one primitive operation the
5//! classifier derives from it (an argv, a path read or written, a host, an
6//! environment variable, an MCP tool name). Policy rules are matched against
7//! atoms, never against an `Action` directly; [`Action::kind`] and
8//! [`AtomicAction::kind`] map each to the rule [`Kind`] it belongs to.
9
10use serde::{Deserialize, Serialize};
11
12use crate::kind::Kind;
13
14/// A tool call as seen from a host, before classification.
15///
16/// Host adapters (`openmoat-hosts`) translate each payload into exactly one of
17/// these. Adapters never decide.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20#[non_exhaustive]
21pub enum Action {
22    /// A shell command string as the host would execute it.
23    /// A shell command line, exactly as the host would run it.
24    Shell {
25        /// The command line.
26        command: String,
27    },
28    /// A command for a shell the classifier cannot read (Claude Code `PowerShell`).
29    /// Never classified, so always `unparseable`: an `ask`, never an `allow`.
30    ForeignShell {
31        /// The shell's name, for reasons and the audit log.
32        shell: String,
33        /// The command line.
34        command: String,
35    },
36    /// A direct file read through a host tool (e.g. Claude Code `Read`).
37    /// A file read by a host tool (`Read`, `Glob`, `Grep`, `LSP`, `beforeReadFile`).
38    FsRead {
39        /// Path as the tool gave it; normalised during classification.
40        path: String,
41    },
42    /// A direct file write/edit through a host tool.
43    /// A file write or edit by a host tool (`Edit`, `Write`, `NotebookEdit`).
44    FsWrite {
45        /// Path as the tool gave it; normalised during classification.
46        path: String,
47    },
48    /// A network connection a host tool opens and may send data over
49    /// (Claude Code `Monitor` WebSocket).
50    Net {
51        /// The URL as the tool gave it.
52        url: String,
53    },
54    /// A URL read by a host's own fetch tool (Claude Code `WebFetch`): a
55    /// request the agent cannot attach a body to, judged by `fetch` and `net`
56    /// rules (ADR-017).
57    Fetch {
58        /// The URL as the tool gave it.
59        url: String,
60    },
61    /// A query a host's own web search tool (Claude Code and Cursor `WebSearch`)
62    /// sends to the host's search provider: judged by `defaults.web.search`.
63    WebSearch {
64        /// The query as the tool gave it.
65        query: String,
66    },
67    /// A host tool the adapter cannot classify, judged by `defaults.tool.unknown`.
68    /// What its arguments name is checked as well: every path and URL the
69    /// adapter finds in them, and every shell command under a key such as
70    /// `command`, so a tool OpenMoat does not know never runs unchecked.
71    UnknownTool {
72        /// The host's id (`cursor`).
73        host: String,
74        /// The tool name as the host sent it.
75        tool: String,
76        /// Paths the call may read, found in its arguments.
77        #[serde(default, skip_serializing_if = "Vec::is_empty")]
78        reads: Vec<String>,
79        /// Paths the call may write, found in its arguments.
80        #[serde(default, skip_serializing_if = "Vec::is_empty")]
81        writes: Vec<String>,
82        /// URLs or hosts the call may contact, found in its arguments.
83        #[serde(default, skip_serializing_if = "Vec::is_empty")]
84        hosts: Vec<String>,
85        /// Shell commands the call may run, found in its arguments.
86        #[serde(default, skip_serializing_if = "Vec::is_empty")]
87        commands: Vec<String>,
88    },
89    /// A call the hook payload shows only in part: input typed into a shell
90    /// that is already running, or a search over directories the payload does
91    /// not name. `action` is decided as usual and the call is at least an
92    /// `ask` (rule [`UNCHECKED_RULE`]), since `reason` names what OpenMoat
93    /// cannot see.
94    Unchecked {
95        /// What the payload shows of the call.
96        action: Box<Action>,
97        /// What it does not show.
98        reason: String,
99    },
100    /// A patch that edits several files in one call (Codex `apply_patch`):
101    /// every path it adds, updates, deletes or moves to is written.
102    /// Files changed by one multi-file patch (Codex `apply_patch`).
103    Patch {
104        /// Every file the patch adds, updates, deletes or moves to.
105        writes: Vec<String>,
106    },
107    /// Files one tool call reads together (Claude Code `SendFile`, which sends
108    /// their contents to another session): every path is read.
109    ReadFiles {
110        /// Every file the call reads.
111        paths: Vec<String>,
112    },
113    /// An MCP tool call, `mcp__<server>__<tool>`. Adapters that understand a
114    /// server's arguments add the paths and hosts the call touches so the
115    /// usual `fs.*` and `net` rules apply to it as well.
116    McpTool {
117        /// `mcp__<server>__<tool>`.
118        name: String,
119        /// Paths the call reads, derived from its arguments.
120        #[serde(default, skip_serializing_if = "Vec::is_empty")]
121        reads: Vec<String>,
122        /// Paths the call writes, derived from its arguments.
123        #[serde(default, skip_serializing_if = "Vec::is_empty")]
124        writes: Vec<String>,
125        /// URLs or hosts the call contacts, derived from its arguments.
126        #[serde(default, skip_serializing_if = "Vec::is_empty")]
127        hosts: Vec<String>,
128        /// Shell commands the call may run, derived from its arguments where
129        /// the host cannot tell an MCP tool from one of its own.
130        #[serde(default, skip_serializing_if = "Vec::is_empty")]
131        commands: Vec<String>,
132        /// The limit that stopped the adapter searching the arguments (nesting
133        /// depth, number of paths and URLs). What was not searched may name a
134        /// file or host, so the engine decides the call at least `ask`.
135        #[serde(default, skip_serializing_if = "Option::is_none")]
136        unchecked: Option<String>,
137    },
138}
139
140impl Action {
141    /// The kind of action as a user would describe it (`Patch` writes files).
142    #[must_use]
143    pub fn kind(&self) -> Kind {
144        match self {
145            Self::Shell { .. } | Self::ForeignShell { .. } => Kind::Shell,
146            Self::FsRead { .. } | Self::ReadFiles { .. } => Kind::FsRead,
147            Self::FsWrite { .. } | Self::Patch { .. } => Kind::FsWrite,
148            Self::Net { .. } => Kind::Net,
149            Self::Fetch { .. } => Kind::Fetch,
150            Self::WebSearch { .. } => Kind::WebSearch,
151            Self::UnknownTool { .. } => Kind::UnknownTool,
152            Self::McpTool { .. } => Kind::Mcp,
153            Self::Unchecked { action, .. } => action.kind(),
154        }
155    }
156
157    /// An MCP call whose arguments are not interpreted.
158    #[must_use]
159    pub fn mcp(name: impl Into<String>) -> Self {
160        Self::McpTool {
161            name: name.into(),
162            reads: Vec::new(),
163            writes: Vec::new(),
164            hosts: Vec::new(),
165            commands: Vec::new(),
166            unchecked: None,
167        }
168    }
169
170    /// An unknown tool of `host` whose arguments name nothing to check.
171    #[must_use]
172    pub fn unknown_tool(host: impl Into<String>, tool: impl Into<String>) -> Self {
173        Self::UnknownTool {
174            host: host.into(),
175            tool: tool.into(),
176            reads: Vec::new(),
177            writes: Vec::new(),
178            hosts: Vec::new(),
179            commands: Vec::new(),
180        }
181    }
182
183    /// `action`, decided at least `ask` because `reason` names what the
184    /// payload does not show ([`Action::Unchecked`]).
185    #[must_use]
186    pub fn unchecked(action: Self, reason: impl Into<String>) -> Self {
187        Self::Unchecked {
188            action: Box::new(action),
189            reason: reason.into(),
190        }
191    }
192
193    /// The action itself, without the [`Action::Unchecked`] wrapping around it.
194    #[must_use]
195    pub fn shown(&self) -> &Self {
196        match self {
197            Self::Unchecked { action, .. } => action.shown(),
198            other => other,
199        }
200    }
201}
202
203/// The rule id of a call the hook payload shows only in part
204/// ([`Action::Unchecked`]): it asks whatever else it is decided.
205pub const UNCHECKED_RULE: &str = "unchecked";
206
207/// The primitive operations an [`Action`] decomposes into.
208///
209/// One shell command typically yields several: the command itself, every
210/// path it touches, every host it may contact, every env var it reads or sets.
211#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(rename_all = "snake_case")]
213#[non_exhaustive]
214pub enum AtomicAction {
215    /// Normalised argv of one (sub-)command.
216    Shell {
217        /// Program and arguments after quote removal.
218        argv: Vec<String>,
219    },
220    /// A whole pipeline / list (`a | b && c`) with separators kept as tokens, so
221    /// rules such as `curl * | sh` can match across sub-commands. Never carries
222    /// a default verdict (see `engine.rs`).
223    Pipeline {
224        /// Words and separator tokens of the whole pipeline or list.
225        argv: Vec<String>,
226    },
227    /// Absolute path in slash-separated canonical form (`~`, `${project}` and
228    /// `cwd` already applied).
229    FsRead {
230        /// Absolute path in canonical form.
231        path: String,
232    },
233    /// A file write, create, delete or move.
234    FsWrite {
235        /// Absolute path in canonical form.
236        path: String,
237    },
238    /// Host name only (no scheme, no port).
239    Net {
240        /// Lowercase host name.
241        host: String,
242    },
243    /// The host of a URL a fetch tool reads; matched by `fetch` and `net` rules.
244    Fetch {
245        /// Lowercase host name.
246        host: String,
247    },
248    /// A shell word with no scheme that looks like a host, outside the arguments
249    /// of a program that names hosts (ADR-025): it may be a JSON path or a method
250    /// call (`check_runs.0.id`, `app.run`). Matched by `net` rules; when none
251    /// matches, the policy's catch-all decides it, not `defaults.net`.
252    NetWord {
253        /// Lowercase host name.
254        host: String,
255    },
256    /// A web search query; no rule list names it, so `defaults` decide it.
257    WebSearch {
258        /// The query as the tool gave it.
259        query: String,
260    },
261    /// A host tool the adapter cannot classify; only `defaults` decide it.
262    UnknownTool {
263        /// The host's id.
264        host: String,
265        /// The tool name as the host sent it.
266        tool: String,
267    },
268    /// An environment variable read (`$NAME`, `printenv NAME`).
269    EnvRead {
270        /// Variable name.
271        name: String,
272    },
273    /// An environment variable set (`NAME=value`, `export NAME=…`).
274    EnvSet {
275        /// Variable name.
276        name: String,
277    },
278    /// An MCP tool invocation.
279    McpTool {
280        /// `mcp__<server>__<tool>`.
281        name: String,
282    },
283}
284
285impl AtomicAction {
286    /// The rule kind this atom is matched against.
287    #[must_use]
288    pub fn kind(&self) -> Kind {
289        match self {
290            Self::Shell { .. } | Self::Pipeline { .. } => Kind::Shell,
291            Self::FsRead { .. } => Kind::FsRead,
292            Self::FsWrite { .. } => Kind::FsWrite,
293            Self::Net { .. } | Self::NetWord { .. } => Kind::Net,
294            Self::Fetch { .. } => Kind::Fetch,
295            Self::WebSearch { .. } => Kind::WebSearch,
296            Self::UnknownTool { .. } => Kind::UnknownTool,
297            Self::EnvRead { .. } => Kind::EnvRead,
298            Self::EnvSet { .. } => Kind::EnvSet,
299            Self::McpTool { .. } => Kind::Mcp,
300        }
301    }
302
303    /// The same read or write of `path`; `None` for any other atom.
304    pub(crate) fn with_path(&self, path: String) -> Option<Self> {
305        match self {
306            Self::FsRead { .. } => Some(Self::FsRead { path }),
307            Self::FsWrite { .. } => Some(Self::FsWrite { path }),
308            _ => None,
309        }
310    }
311
312    /// The text a glob rule is matched against; `None` for shell atoms, which
313    /// are matched as argv.
314    pub(crate) fn subject(&self) -> Option<&str> {
315        match self {
316            Self::Shell { .. } | Self::Pipeline { .. } => None,
317            Self::FsRead { path } | Self::FsWrite { path } => Some(path),
318            Self::Net { host } | Self::Fetch { host } | Self::NetWord { host } => Some(host),
319            Self::EnvRead { name } | Self::EnvSet { name } | Self::McpTool { name } => Some(name),
320            Self::WebSearch { query } => Some(query),
321            Self::UnknownTool { tool, .. } => Some(tool),
322        }
323    }
324
325    /// Short human description used in reasons and audit lines.
326    #[must_use]
327    pub fn describe(&self) -> String {
328        match self {
329            // the near-miss atom names the package the person probably meant
330            Self::Shell { argv } => match argv.as_slice() {
331                [tag, ecosystem, name, popular] if tag == crate::shell::installs::NEAR_MISS => {
332                    format!("{ecosystem} package \"{name}\" is not \"{popular}\"")
333                }
334                _ => format!("shell \"{}\"", argv.join(" ")),
335            },
336            Self::Pipeline { argv } => format!("pipeline \"{}\"", argv.join(" ")),
337            Self::FsRead { path } => format!("read {path}"),
338            Self::FsWrite { path } => format!("write {path}"),
339            Self::Net { host } => format!("net {host}"),
340            Self::NetWord { host } => format!("net {host} (a word that looks like a host)"),
341            Self::Fetch { host } => format!("fetch {host}"),
342            Self::WebSearch { query } => format!("web search \"{query}\""),
343            Self::UnknownTool { host, tool } => format!("unknown {host} tool {tool}"),
344            Self::EnvRead { name } => format!("env read {name}"),
345            Self::EnvSet { name } => format!("env set {name}"),
346            Self::McpTool { name } => format!("mcp {name}"),
347        }
348    }
349}