Skip to main content

vtcode_core/tools/tool_intent/readonly/
mod.rs

1use crate::tools::command_args::{
2    command_words_after_environment_prefix, has_unsafe_readonly_options, shell_command_text_with_args,
3};
4use crate::tools::output_spooler::SpooledOutputReference;
5use serde_json::Value;
6use std::path::Path;
7
8/// Conservative allow-list of read-only inspection commands used by
9/// `command_session`. Any command that could write, move, or delete must be
10/// rejected so it is not cached or parallelized as read-only.
11///
12/// `cd` is included because changing the working directory mutates nothing;
13/// models habitually prefix exploration with `cd <workspace> && …` and plan
14/// mode must not reject that pattern (checkpoint turn_810).
15///
16/// `ast-grep`/`sg` are deliberately absent. VT Code no longer ships the
17/// ast-grep binary, and `sg` also names the shadow-utils group-switch
18/// command, which runs an arbitrary command (`sg <group> -c '<command>'`).
19/// Allow-listing it would classify such an invocation as a read-only
20/// inspection and skip the approval gate.
21///
22/// Programs that stay on the list but can still write or execute need an
23/// option-level guard in `command_args::has_unsafe_readonly_options` — for
24/// example `bat --pager <command>`, which spawns the named program.
25const READONLY_UNIFIED_EXEC_COMMANDS: &[&str] = &[
26    "rg", "ls", "cat", "diff", "find", "wc", "grep", "egrep", "fgrep", "head", "tail", "sort", "uniq", "bat", "sed",
27    "awk", "cut", "tr", "echo", "pwd", "printf", "true", "false", "test", "cd", "fd", "tree", "which", "stat", "file",
28    "du", "df", "realpath", "basename", "dirname", "nl", "column", "jq", "date", "whoami", "uname",
29];
30
31pub fn is_readonly_base_command(command: &str) -> bool {
32    READONLY_UNIFIED_EXEC_COMMANDS.contains(&command)
33}
34
35/// Read-only subcommand allow-list for multi-word tools whose base command is
36/// not inherently safe (`git`, `cargo`, package managers). Only inspection
37/// subcommands are listed; anything that can mutate the worktree, index,
38/// refs, or lockfiles must stay out.
39///
40/// Unconditionally read-only: every form of these subcommands is an
41/// inspection, so this list is also safe for the flag-skipping parallel-safe
42/// extractor. Flag-shaped subcommands whose bare form reads but whose operand
43/// forms mutate live in [`is_readonly_flag_shaped_git_subcommand`].
44fn is_readonly_subcommand(first: &str, second: Option<&str>, third: Option<&str>) -> bool {
45    match first {
46        "git" => matches!(
47            second,
48            Some(
49                "status"
50                    | "log"
51                    | "diff"
52                    | "show"
53                    | "blame"
54                    | "ls-files"
55                    | "rev-parse"
56                    | "describe"
57                    | "shortlog"
58                    | "grep"
59                    | "rev-list"
60                    | "ls-tree"
61                    | "cat-file"
62                    | "diff-tree"
63                    | "merge-base"
64                    | "range-diff"
65                    | "whatchanged"
66                    | "count-objects"
67                    | "var"
68                    | "version"
69                    | "help"
70            )
71        ),
72        "cargo" => match second {
73            Some("check" | "test" | "metadata" | "tree" | "clippy") => true,
74            Some("nextest") => matches!(third, Some("run" | "list")),
75            _ => false,
76        },
77        "npm" | "pnpm" | "yarn" => match second {
78            Some("test") => true,
79            Some("run") => matches!(third, Some("test")),
80            _ => false,
81        },
82        _ => false,
83    }
84}
85
86/// Flag-shaped git subcommands whose bare or flag-only form is a pure read
87/// (`git tag`, `git branch -a`, `git remote -v`, `git reflog`, `git stash
88/// list`, `git worktree list`), while the same name with an operand mutates
89/// (`tag v1`, `branch -D x`, `reflog expire`, `stash pop`, `remote add`,
90/// `worktree add`). The mutating operand survives as the third word, so this
91/// classification is position-safe only on the read-only path, which keeps
92/// operands; the flag-skipping parallel-safe extractor must never consult it
93/// (there `git tag -f x` would look identical to `git tag`).
94///
95/// Two hardening rules keep the bare/flag-only forms honest:
96/// - bare `stash` is excluded: bare `git stash` is `git stash push`, which
97///   stashes uncommitted work, and flag-only push forms (`-k`, `-u`, `-a`,
98///   `-m=msg`) carry no operand to betray them;
99/// - `branch` carries a mutating-flag denylist, because inline-value flags
100///   (`--set-upstream-to=origin/x`, `--unset-upstream`, `--edit-description`)
101///   and glued short mutators (`-m<name>`, `-c<name>`, `-u<upstream>`) start
102///   with `-` and are invisible to the operand finder.
103fn is_readonly_flag_shaped_git_subcommand(
104    subcommand: Option<&str>,
105    operand: Option<&str>,
106    command_words: &[String],
107    sub_index: usize,
108) -> bool {
109    if subcommand == Some("branch") {
110        let mutates = command_words.iter().skip(sub_index + 1).any(|word| {
111            matches!(word.as_str(), "--set-upstream" | "--unset-upstream" | "--edit-description")
112                || word.starts_with("--set-upstream-to")
113                || word.starts_with("-u")
114                || word.starts_with("-m")
115                || word.starts_with("-M")
116                || word.starts_with("-c")
117                || word.starts_with("-C")
118        });
119        if mutates {
120            return false;
121        }
122    }
123
124    matches!(
125        (subcommand, operand),
126        (Some("tag") | Some("branch"), None)
127            | (Some("reflog"), None | Some("show"))
128            | (Some("remote"), None | Some("show") | Some("get-url"))
129            | (Some("stash"), Some("list") | Some("show"))
130            | (Some("worktree"), Some("list"))
131    )
132}
133
134/// A version or help probe prints to stdout and mutates nothing for any
135/// program, including subcommand-based tools (`cargo --version`, `node
136/// --version`, `python3 -V`) that the subcommand allow-list cannot classify
137/// because every word after the program is a flag. At least one probe flag
138/// is required (a bare program name like `tsc` still compiles) and ALL
139/// trailing words must be probe flags, so `python3 script.py` or `git commit
140/// -v` stay outside. Lowercase `-v` is deliberately excluded: it means
141/// verbose rather than version for most tools, and for shell interpreters
142/// (`bash -v`) it reads stdin.
143fn is_version_or_help_probe(command_words: &[String]) -> bool {
144    fn is_probe_flag(word: &str) -> bool {
145        matches!(word, "-h" | "--help" | "-V" | "--version")
146    }
147
148    let mut flags = command_words.iter().skip(1);
149    flags.next().is_some_and(|word| is_probe_flag(word)) && flags.all(|word| is_probe_flag(word))
150}
151
152/// Parse a shell script into simple command words after proving that it has no
153/// dynamic expansion, file redirection, or unsupported background operator.
154///
155/// The tree-sitter parser is the single shell-grammar boundary used by the
156/// safety subsystem. Callers receive already-tokenized command words and must
157/// still apply their own command-policy predicate; an unknown command never
158/// becomes read-only merely because parsing succeeded.
159pub(crate) fn static_shell_command_words(command: &str) -> Option<Vec<Vec<String>>> {
160    let sanitized = sanitize_static_shell_command(command)?;
161    parse_shell_command_words(&sanitized)
162}
163
164/// Parse a command whose only shell operators outside quotes are output
165/// redirections. This is intentionally separate from the read-only parser:
166/// writing a build log is still a mutating command for the authoritative tool
167/// intent, but it should not hide the verification nature of `cargo check` in
168/// progress accounting.
169pub(crate) fn static_shell_command_words_with_output_plumbing(command: &str) -> Option<Vec<Vec<String>>> {
170    if !crate::command_safety::shell_parser::has_only_output_redirections(command) {
171        return None;
172    }
173    parse_shell_command_words(command)
174}
175
176/// Tokenize shell invocations without proving static execution or safety.
177/// Permission and activity predicates must sanitize before using these words;
178/// diagnostic-only consumers may inspect dynamic shell text without grants.
179pub(super) fn parse_shell_command_words(command: &str) -> Option<Vec<Vec<String>>> {
180    let commands = crate::command_safety::shell_parser::parse_shell_commands_tree_sitter(command).ok()?;
181    if commands.is_empty() {
182        return None;
183    }
184
185    commands
186        .into_iter()
187        .map(|command| {
188            let mut words = Vec::new();
189            for word in command {
190                let tokens = shell_words::split(&word).ok()?;
191                words.extend(tokens);
192            }
193            (!words.is_empty()).then_some(words)
194        })
195        .collect()
196}
197
198/// Shared head of both read-only classifiers: strip environment prefixes,
199/// resolve the lowercased program name, and apply the option-level guard.
200/// Returns the stripped words plus the program name, or `None` when the
201/// command cannot be classified (fail closed). The parallel-safe classifier
202/// shares this head; its stricter tail (no builds/tests, git allow-list
203/// only) stays separate on purpose.
204///
205/// The guard reads the original `words` (not the stripped view) so
206/// environment-injected options stay visible; keep that argument as-is.
207fn readonly_command_head(words: &[String]) -> Option<(&[String], String)> {
208    let command_words = command_words_after_environment_prefix(words);
209    let first = command_words
210        .first()
211        .and_then(|word| Path::new(word).file_name())
212        .and_then(|name| name.to_str())
213        .map(str::to_ascii_lowercase)?;
214    if has_unsafe_readonly_options(words) {
215        return None;
216    }
217    Some((command_words, first))
218}
219
220/// Returns whether one parsed command is an allow-listed read-only command.
221/// Option-level guards are shared with raw argument validation so activity
222/// accounting cannot accidentally become less strict than tool intent.
223pub(crate) fn command_words_are_readonly(words: &[String]) -> bool {
224    let Some((command_words, first)) = readonly_command_head(words) else {
225        return false;
226    };
227    if first == "command" {
228        return matches!(command_words.get(1).map(String::as_str), Some("-v" | "-V"))
229            && command_words.len() > 2
230            && command_words
231                .iter()
232                .skip(2)
233                .all(|word| !word.starts_with('-') && !word.is_empty());
234    }
235
236    if is_readonly_base_command(&first)
237        || is_version_or_help_probe(command_words)
238        || is_known_readonly_dry_run(command_words, &first)
239    {
240        return true;
241    }
242
243    let lowered = command_words
244        .iter()
245        .filter(|word| !word.starts_with('-') && !word.contains('='))
246        .take(3)
247        .map(|word| word.to_ascii_lowercase())
248        .collect::<Vec<_>>();
249    if first != "git" {
250        let (second, third) = (lowered.get(1).map(String::as_str), lowered.get(2).map(String::as_str));
251        return is_readonly_subcommand(&first, second, third);
252    }
253
254    let Some((sub_index, operand)) = git_subcommand_and_operand(command_words) else {
255        return false;
256    };
257    let subcommand = command_words.get(sub_index).map(String::as_str);
258    is_readonly_subcommand("git", subcommand, None)
259        || is_readonly_flag_shaped_git_subcommand(subcommand, operand, command_words, sub_index)
260}
261
262/// Locate the git subcommand and the first operand after it, skipping global
263/// options — including their separate values (`-C <dir>`, `-c <config>`,
264/// `--git-dir <path>`, `--shallow-file <info>`), whose inline forms
265/// (`-C<dir>`, `--git-dir=<path>`) carry no extra word. Without this, the
266/// option value occupies the subcommand slot and worktree-style exploration
267/// (`git -C <dir> log`) is misread as an unknown subcommand.
268///
269/// Position-based on purpose: the operand of a flag-shaped subcommand stays
270/// visible as the second tuple field, which is what keeps `git tag v1`
271/// distinguishable from `git tag -l`. Fails closed on any unknown
272/// global-shaped word: an unrecognized option may consume a separate value,
273/// which would otherwise smuggle the real (possibly mutating) subcommand past
274/// the allow-list (`git --shallow-file log commit -m x`).
275///
276/// Returns the subcommand's index into `command_words` (callers re-read it —
277/// real git subcommands are case-sensitive, so no lowercasing happens here)
278/// plus the first non-flag operand after it, or `None` when the command must
279/// stay denied.
280fn git_subcommand_and_operand(command_words: &[String]) -> Option<(usize, Option<&str>)> {
281    const GLOBAL_OPTIONS_WITH_VALUE: &[&str] = &[
282        "-C",
283        "-c",
284        "--git-dir",
285        "--work-tree",
286        "--namespace",
287        "--super-prefix",
288        "--exec-path",
289        "--config-env",
290        "--shallow-file",
291        "--attr-source",
292    ];
293    const GLOBAL_OPTIONS_FLAG_ONLY: &[&str] = &[
294        "-p",
295        "--paginate",
296        "--no-pager",
297        "--bare",
298        "--literal-pathspecs",
299        "--no-replace-objects",
300        "--no-optional-locks",
301        "--end-of-options",
302        "--version",
303        "--help",
304        "--html-path",
305    ];
306
307    let mut index = 1;
308    while let Some(word) = command_words.get(index) {
309        if !word.starts_with('-') {
310            let operand = command_words
311                .iter()
312                .skip(index + 1)
313                .find(|candidate| !candidate.starts_with('-'))
314                .map(String::as_str);
315            return Some((index, operand));
316        }
317        if GLOBAL_OPTIONS_WITH_VALUE.contains(&word.as_str()) {
318            index += 2; // skip the option and its separate value
319            continue;
320        }
321        if GLOBAL_OPTIONS_FLAG_ONLY.contains(&word.as_str()) {
322            index += 1;
323            continue;
324        }
325        // Unknown global-shaped word: an option this allow-list does not know
326        // may take a separate value, so the next word could be that value
327        // rather than the subcommand. Fail closed.
328        return None;
329    }
330    None
331}
332
333/// Return whether one command is a side-effect-free inspection suitable for
334/// concurrent execution. Build and test commands remain read-only for policy
335/// purposes, but are excluded here because they write caches, lockfiles, or
336/// build artifacts and contend on shared package-manager state.
337fn command_words_are_parallel_safe(words: &[String]) -> bool {
338    let Some((command_words, first)) = readonly_command_head(words) else {
339        return false;
340    };
341
342    if is_readonly_base_command(&first) {
343        return true;
344    }
345    // Version/help probes are side-effect-free for any program.
346    if is_version_or_help_probe(command_words) {
347        return true;
348    }
349    if first != "git" {
350        return false;
351    }
352
353    let subcommand = command_words
354        .iter()
355        .skip(1)
356        .find(|word| !word.starts_with('-') && !word.contains('='))
357        .map(|word| word.to_ascii_lowercase());
358    is_readonly_subcommand("git", subcommand.as_deref(), None)
359}
360
361fn is_known_readonly_dry_run(words: &[String], program: &str) -> bool {
362    if !matches!(program, "npm" | "pnpm" | "yarn") {
363        return false;
364    }
365
366    let Some(subcommand) = words.iter().skip(1).find(|word| !word.starts_with('-') && !word.contains('=')) else {
367        return false;
368    };
369
370    subcommand == "install" && words.iter().any(|word| word == "--dry-run")
371}
372
373fn matches_at(chars: &[char], index: usize, pattern: &[char]) -> bool {
374    chars
375        .get(index..index.saturating_add(pattern.len()))
376        .is_some_and(|candidate| candidate == pattern)
377}
378
379/// Remove only stderr plumbing that cannot write workspace state and reject
380/// all other redirection/background syntax. Operators inside quoted arguments
381/// remain ordinary data and are never rewritten.
382fn sanitize_static_shell_command(command: &str) -> Option<String> {
383    if crate::command_safety::shell_parser::contains_dynamic_shell_syntax(command) {
384        return None;
385    }
386
387    let chars = command.chars().collect::<Vec<_>>();
388    let mut sanitized = String::with_capacity(command.len());
389    let mut index = 0;
390    let mut in_single_quote = false;
391    let mut in_double_quote = false;
392
393    while index < chars.len() {
394        let character = chars[index];
395        if character == '\'' && !in_double_quote {
396            in_single_quote = !in_single_quote;
397            sanitized.push(character);
398            index += 1;
399            continue;
400        }
401        if character == '"' && !in_single_quote {
402            in_double_quote = !in_double_quote;
403            sanitized.push(character);
404            index += 1;
405            continue;
406        }
407        if in_single_quote || in_double_quote {
408            sanitized.push(character);
409            index += 1;
410            continue;
411        }
412
413        let preceded_by_boundary = index == 0
414            || chars
415                .get(index.saturating_sub(1))
416                .is_some_and(|previous| previous.is_whitespace() || matches!(previous, '|' | '&' | ';'));
417        if preceded_by_boundary && matches_at(&chars, index, &['2', '>', '&', '1']) {
418            index += 4;
419            continue;
420        }
421        if cfg!(unix)
422            && preceded_by_boundary
423            && matches_at(&chars, index, &['2', '>', '/', 'd', 'e', 'v', '/', 'n', 'u', 'l', 'l'])
424        {
425            index += 11;
426            continue;
427        }
428
429        match character {
430            '<' | '>' => return None,
431            '&' if matches_at(&chars, index, &['&', '&']) => {
432                sanitized.push('&');
433                sanitized.push('&');
434                index += 2;
435            }
436            '&' => return None,
437            _ => {
438                sanitized.push(character);
439                index += 1;
440            }
441        }
442    }
443
444    (!sanitized.trim().is_empty()).then_some(sanitized)
445}
446
447/// Shared extract + static-parse prologue for command-session classifiers.
448///
449/// Extracts the full classification candidate (including the quoted argv
450/// suffix) and proves a static shape through the tree-sitter boundary.
451/// Returns `None` when the args cannot prove one invocation (conflicting raw
452/// alias, dynamic syntax, redirection) — every caller maps `None` to
453/// fail-closed `false`, in the same order as before.
454fn parsed_session_commands(args: &Value) -> Option<Vec<Vec<String>>> {
455    let raw = shell_command_text_with_args(args)?;
456    static_shell_command_words(&raw)
457}
458
459/// Shared read-only gate over already-parsed segments: a `&&` chain is
460/// accepted only when every segment independently passes the allow-list.
461/// (`sanitize_static_shell_command` already rejected `;`, `||`,
462/// redirections, and background `&` up front.)
463fn all_commands_readonly(commands: &[Vec<String>]) -> bool {
464    commands.iter().all(|words| command_words_are_readonly(words))
465}
466
467pub fn is_readonly_command_session_command(args: &Value) -> bool {
468    let Some(commands) = parsed_session_commands(args) else {
469        return false;
470    };
471
472    all_commands_readonly(&commands)
473}
474
475/// A stricter read-only command shape that may run concurrently after hooks,
476/// command admission, and preflight have all succeeded.
477pub(crate) fn is_parallel_safe_command_session_command(args: &Value) -> bool {
478    if args.get("session_id").is_some()
479        || args.get("chars").is_some()
480        || args.get("input").is_some()
481        || args.get("tty").and_then(Value::as_bool) == Some(true)
482        || args
483            .get("sandbox_permissions")
484            .and_then(Value::as_str)
485            .is_some_and(|value| value != "use_default")
486    {
487        return false;
488    }
489    let Some(commands) = parsed_session_commands(args) else {
490        return false;
491    };
492    commands.len() == 1 && command_words_are_parallel_safe(&commands[0])
493}
494
495/// Returns `true` when a safe shell inspection command reads the internal tool
496/// output spool directory. Such reads must stay inline: spooling their output
497/// again would create a recursive chain of spool references.
498pub fn is_spool_file_read_command(tool_name: &str, args: &Value) -> bool {
499    if super::classify::canonical_command_session_tool_name(tool_name).is_none() {
500        return false;
501    }
502
503    // Parse once through the shared prologue: the same segments feed both
504    // the read-only gate below and the spool-path scan, so a completed
505    // command output (see `prepare_execution_output`) pays the extract +
506    // sanitize + tree-sitter pipeline a single time.
507    let Some(commands) = parsed_session_commands(args) else {
508        return false;
509    };
510    if !all_commands_readonly(&commands) {
511        return false;
512    }
513    commands
514        .iter()
515        .flatten()
516        .any(|word| SpooledOutputReference::recognizes_path(Path::new(word)))
517}
518
519#[cfg(test)]
520mod tests;