Skip to main content

vtcode_core/tools/tool_intent/activity/
mod.rs

1//! Shell activity classification for progress accounting and output previews.
2//!
3//! Mutation safety remains owned by [`super::classify_tool_intent`]. This
4//! module adds the narrower distinction between repository inspection and
5//! verification without duplicating that safety decision in binary consumers.
6
7use std::path::Path;
8
9use serde_json::Value;
10use vtcode_commons::validation::NonEmptySlice;
11
12use crate::tools::command_args::shell_command_text_with_args;
13
14use super::readonly::{
15    command_words_are_readonly, static_shell_command_words, static_shell_command_words_with_output_plumbing,
16};
17
18mod verifier;
19pub(crate) use verifier::pipefail_verifier_pipeline;
20pub use verifier::{
21    GENERIC_VERIFIER_DESCRIPTION, VERIFIER_SHELL_FORM_NOTE, default_verifier_for_workspace,
22    rewrite_truncation_only_verifier, shell_command_contains_verifier, shell_command_is_admitted_verification_attempt,
23    shell_command_is_output_search, shell_command_is_standalone_grep_search, verification_recovery_directive,
24    verifier_reference,
25};
26use verifier::{
27    contains_verification_invocation, has_logical_sequencing, is_verification_invocation, rewrite_verifier_pipeline,
28};
29
30/// Progress semantics for a command invocation.
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub enum ShellActivity {
33    /// Read-only repository or environment inspection.
34    Inspection,
35    /// A build, test, lint, or compile command that verifies work.
36    Verification,
37    /// A command that may mutate state and is not primarily verification.
38    Mutation,
39}
40
41/// Shell-call arguments as the execution kernel runs them.
42///
43/// The kernel applies `rewrite_verifier_pipeline` to every
44/// command-run call before execution, so the process that runs (and whose
45/// exit status the outcome reports) is the standalone verifier, not the typed
46/// pipeline. Static filtering pipelines instead enable pipefail. Gate
47/// bookkeeping must classify that same command; classifying the
48/// typed pipeline would call a truthful `cargo check 2>&1 | tail -5` success a
49/// mutation and leave the gate pending. Arguments the kernel runs unchanged
50/// (already-normalized arguments included, since the rewrite is idempotent)
51/// are borrowed as-is.
52pub fn shell_args_as_executed<'a>(tool_name: &str, args: &'a Value) -> std::borrow::Cow<'a, Value> {
53    if !super::is_command_run_tool_call(tool_name, args) {
54        return std::borrow::Cow::Borrowed(args);
55    }
56    let Some(rewritten) = rewrite_verifier_pipeline(args) else {
57        return std::borrow::Cow::Borrowed(args);
58    };
59    let mut executed = args.clone();
60    match executed.as_object_mut() {
61        Some(payload) => {
62            if payload.get("raw_command").is_some_and(Value::is_string) {
63                payload.insert("raw_command".to_string(), Value::String(rewritten.clone()));
64            }
65            // The rewrite already includes the suffix (or elides its truncator).
66            // Keeping args would append it a second time at launch.
67            payload.remove("args");
68            payload.insert("command".to_string(), Value::String(rewritten));
69            std::borrow::Cow::Owned(executed)
70        }
71        None => std::borrow::Cow::Borrowed(args),
72    }
73}
74
75fn is_known_inspection(words: &[String]) -> bool {
76    if words
77        .iter()
78        .any(|word| matches!(word.as_str(), ">" | ">>" | "|" | "&&" | ";" | "||"))
79    {
80        return false;
81    }
82    command_words_are_readonly(words)
83}
84
85fn classify_provable_shell_sequence(command: &str) -> Option<ShellActivity> {
86    let (segments, has_output_plumbing) = if let Some(segments) = static_shell_command_words(command) {
87        (segments, false)
88    } else {
89        (static_shell_command_words_with_output_plumbing(command)?, true)
90    };
91    if has_output_plumbing && segments.len() != 1 {
92        return None;
93    }
94    let has_multiple_segments = segments.len() > 1;
95    let mut saw_verification = false;
96
97    for words in segments {
98        if is_verification_invocation(&words) {
99            saw_verification = true;
100        } else if !command_words_are_readonly(&words) {
101            return None;
102        }
103    }
104
105    if has_output_plumbing && !saw_verification {
106        return None;
107    }
108
109    // Shell execution does not guarantee that a pipeline or logical chain's
110    // final status reflects every verification stage. Do not let a successful
111    // downstream command clear the anti-blind checkpoint after an earlier
112    // verifier failed.
113    //
114    // Exception: a pure `&&` chain of verification (or readonly) segments
115    // short-circuits on first failure, so its exit status does represent every
116    // stage. `cargo fmt --check && cargo check --locked && cargo nextest run`
117    // must clear the gate; `;`, `||`, `|`, and background `&` still mask
118    // failures and stay `Mutation`.
119    if saw_verification && has_multiple_segments {
120        if shell_uses_only_and_chaining(command) {
121            return Some(ShellActivity::Verification);
122        }
123        return Some(ShellActivity::Mutation);
124    }
125
126    Some(if saw_verification {
127        ShellActivity::Verification
128    } else {
129        ShellActivity::Inspection
130    })
131}
132
133fn has_shell_sequence(command: &str) -> bool {
134    static_shell_command_words(command).is_none_or(|segments| segments.len() > 1)
135}
136
137/// Quote-aware check that a shell command chains segments only with `&&`.
138///
139/// Returns `false` when an unquoted `;`, newline, `||`, single `&`
140/// (background), or `|` (pipeline) is present, since those operators let a
141/// downstream success mask an earlier verifier failure. `&&` short-circuits,
142/// so a pure `&&` chain of verifiers has a faithful aggregate exit status and
143/// may clear the anti-blind-editing gate. Backslash escapes outside single
144/// quotes are honored, so a shell-literal `\"` cannot open a phantom quote
145/// state that hides a later live operator.
146fn shell_uses_only_and_chaining(command: &str) -> bool {
147    let chars: Vec<char> = command.chars().collect();
148    let mut index = 0;
149    let mut in_single_quote = false;
150    let mut in_double_quote = false;
151
152    while index < chars.len() {
153        let character = chars[index];
154        // Outside single quotes a backslash escapes the next character for the
155        // shell: `\"` is a literal quote (no quote-state change) and `\;` is an
156        // inert character, not an operator. Skip the pair so the scanner stays
157        // aligned with the shell and fails closed.
158        if character == '\\' && !in_single_quote && index + 1 < chars.len() {
159            index += 2;
160            continue;
161        }
162        if character == '\'' && !in_double_quote {
163            in_single_quote = !in_single_quote;
164            index += 1;
165            continue;
166        }
167        if character == '"' && !in_single_quote {
168            in_double_quote = !in_double_quote;
169            index += 1;
170            continue;
171        }
172        if in_single_quote || in_double_quote {
173            index += 1;
174            continue;
175        }
176        match character {
177            // Token extraction walks nested commands and drops negation;
178            // neither shape proves each check actually returned success.
179            ';' | '\n' | '|' | '!' | '(' | ')' => return false,
180            '&' => {
181                let next_is_and = chars.get(index + 1) == Some(&'&');
182                if !next_is_and {
183                    return false;
184                }
185                // A `||`-style `|` was already rejected above; `&&` consumes
186                // both characters. `|||`, `&&&`, and similar malformed
187                // sequences fail closed.
188                let third = chars.get(index + 2);
189                if third == Some(&'&') || third == Some(&'|') {
190                    return false;
191                }
192                index += 2;
193                continue;
194            }
195            _ => {}
196        }
197        index += 1;
198    }
199
200    true
201}
202
203/// Match required checks within a statically proven, status-preserving chain.
204/// This is evidence accounting only; execution and permission gates still apply.
205pub(crate) fn shell_command_covers_required_check(command: &str, required: &str) -> bool {
206    if !shell_uses_only_and_chaining(command) || !shell_uses_only_and_chaining(required) {
207        return false;
208    }
209    let Some(segments) = static_shell_command_words(command) else {
210        return false;
211    };
212    let Some(required_segments) = static_shell_command_words(required) else {
213        return false;
214    };
215    if segments.iter().any(|words| {
216        words.first().is_some_and(|word| word == "cd")
217            || (!is_verification_invocation(words) && !command_words_are_readonly(words))
218    }) {
219        return false;
220    }
221    segments
222        .windows(required_segments.len())
223        .any(|window| window == required_segments)
224}
225
226/// Classify a shell call without weakening the authoritative mutation guard.
227///
228/// Standalone output plumbing such as `2>&1` or `> build.log` does not turn a
229/// primary verification command into a mutation for progress accounting.
230/// Pipelines and `;`/`||` chains remain mutations because their final
231/// status does not reliably represent every verification stage. Pure `&&`
232/// chains of verification-or-readonly segments are `Verification` since `&&`
233/// short-circuits on first failure.
234#[must_use]
235pub fn classify_shell_activity(tool_name: &str, args: &Value) -> ShellActivity {
236    let command = shell_command_text_with_args(args);
237    if command.is_none() && crate::tools::command_args::raw_command_text(args).is_some() {
238        return ShellActivity::Mutation;
239    }
240    if command.as_deref().and_then(pipefail_verifier_pipeline).is_some() {
241        return ShellActivity::Verification;
242    }
243    let words = crate::tools::command_args::command_words(args).ok().flatten();
244    let has_unclassified_shell_sequence = command.as_deref().is_some_and(has_shell_sequence);
245
246    if let Some(activity) = command.as_deref().and_then(classify_provable_shell_sequence) {
247        return activity;
248    }
249    // A failed sequence proof cannot fall back to the original tool intent:
250    // appended arguments may make an otherwise read-only tail mutate state.
251    if has_unclassified_shell_sequence {
252        return ShellActivity::Mutation;
253    }
254
255    let intent = super::classify_tool_intent(tool_name, args);
256
257    if !has_unclassified_shell_sequence && words.as_deref().is_some_and(is_known_inspection) {
258        return ShellActivity::Inspection;
259    }
260
261    let starts_with_verification = words.as_deref().is_some_and(is_verification_invocation);
262    let contains_verification =
263        starts_with_verification || command.as_deref().is_some_and(contains_verification_invocation);
264    if !intent.mutating {
265        return if contains_verification {
266            ShellActivity::Verification
267        } else {
268            ShellActivity::Inspection
269        };
270    }
271
272    if starts_with_verification
273        && !has_unclassified_shell_sequence
274        && !words.as_deref().is_some_and(has_logical_sequencing)
275    {
276        ShellActivity::Verification
277    } else {
278        ShellActivity::Mutation
279    }
280}
281
282fn is_literal_timer(words: &[String]) -> bool {
283    let seconds = match words {
284        [program, seconds] if program == "sleep" => Some(seconds.as_str()),
285        [program, flag, code] if matches!(program.as_str(), "python" | "python3") && flag == "-c" => code
286            .strip_prefix("import time; time.sleep(")
287            .and_then(|code| code.strip_suffix(')')),
288        _ => None,
289    };
290    seconds.is_some_and(|seconds| {
291        !seconds.is_empty()
292            && seconds.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.')
293            && seconds
294                .parse::<f64>()
295                .is_ok_and(|seconds| seconds.is_finite() && seconds >= 0.0)
296    })
297}
298
299/// Whether an exec result creates workspace mutation debt. This is accounting
300/// only: permission and admission still use the stricter static classifiers.
301/// Unknown syntax or commands retain debt; changed-file evidence always wins.
302#[must_use]
303pub fn exec_mutation_should_incur_debt(command: &str, output: &Value) -> bool {
304    if exec_output_has_changes(output) {
305        return true;
306    }
307    let mut parser = tree_sitter::Parser::new();
308    if parser.set_language(&tree_sitter_bash::LANGUAGE.into()).is_err() {
309        return true;
310    }
311    let Some(tree) = parser.parse(command, None) else {
312        return true;
313    };
314    let root = tree.root_node();
315    root.has_error() || root.named_child_count() == 0 || !nonmutating_shell_node(root, command)
316}
317
318pub(crate) fn exec_output_has_changes(output: &Value) -> bool {
319    output
320        .get("modified_files")
321        .and_then(Value::as_array)
322        .is_some_and(|files| !files.is_empty())
323        || crate::tools::file_ops::diff_output_has_effective_change(output) == Some(true)
324}
325
326/// Path- and dot-prefixed globs cannot expand into options. Keep this narrower than
327/// general expansion: variables, substitutions, bare globs and dynamic heads
328/// remain unproven, and the parent command still checks program/options.
329fn is_literal_path_glob(word: &str) -> bool {
330    let prefix = match word.split_once('/') {
331        Some((prefix, _)) => prefix,
332        None if word.starts_with('.') => ".",
333        None => return false,
334    };
335    !prefix.starts_with('-')
336        && !prefix.contains(['*', '?', '[', ']'])
337        && word.contains(['*', '?'])
338        && !word.contains(['[', ']'])
339        && !word
340            .chars()
341            .any(|character| character.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(character))
342}
343
344/// Inline grep filters remain one option even when the literal pattern has globs.
345/// This is accounting proof only; shell admission is unchanged.
346fn is_literal_grep_filter(word: &str) -> bool {
347    let Some((option, pattern)) = word.split_once('=') else {
348        return false;
349    };
350    matches!(option, "--include" | "--exclude" | "--exclude-dir")
351        && !pattern.is_empty()
352        && !pattern.chars().any(|c| c.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(c))
353}
354
355/// Recognize the shell's file-existence test on one quoted variable. Other
356/// test expressions can contain substitutions or arithmetic with effects.
357fn is_quoted_variable_file_test(text: &str) -> bool {
358    let Some(expression) = text.strip_prefix('[').and_then(|s| s.strip_suffix(']')) else {
359        return false;
360    };
361    let Some(operand) = expression.trim().strip_prefix("-f ") else {
362        return false;
363    };
364    let Some(variable) = operand
365        .trim()
366        .strip_prefix('"')
367        .and_then(|s| s.strip_suffix('"'))
368        .and_then(|s| s.strip_prefix('$'))
369    else {
370        return false;
371    };
372    let mut chars = variable.chars();
373    chars.next().is_some_and(|ch| ch == '_' || ch.is_ascii_alphabetic())
374        && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
375}
376
377/// Walk every supported node, including commands nested in substitutions.
378/// Unlike command extraction, this proof must never discard unknown syntax.
379fn nonmutating_shell_node(node: tree_sitter::Node<'_>, source: &str) -> bool {
380    use crate::command_safety::shell_parser::contains_dynamic_shell_syntax;
381    let Ok(text) = node.utf8_text(source.as_bytes()) else {
382        return false;
383    };
384    match node.kind() {
385        "test_command" => return is_quoted_variable_file_test(text),
386        "command" => {
387            let Some(name) = node.child_by_field_name("name") else {
388                return false;
389            };
390            let Ok(name_text) = name.utf8_text(source.as_bytes()) else {
391                return false;
392            };
393            if contains_dynamic_shell_syntax(name_text) {
394                return false;
395            }
396            let mut words = Vec::new();
397            let mut cursor = node.walk();
398            for child in node.named_children(&mut cursor) {
399                let Ok(word) = child.utf8_text(source.as_bytes()) else {
400                    return false;
401                };
402                if child.kind() == "variable_assignment" {
403                    return false;
404                }
405                if child != name
406                    && child.kind() == "word"
407                    && (is_literal_path_glob(word)
408                        || (matches!(name_text, "grep" | "egrep" | "fgrep" | "rg") && is_literal_grep_filter(word)))
409                    && matches!(name_text, "rg" | "grep" | "egrep" | "fgrep" | "ls" | "cat" | "head" | "tail" | "wc")
410                {
411                    // Classification sees a path operand; expansion cannot
412                    // produce flags, while static mutating options stay visible.
413                    words.push(word.to_owned());
414                } else if contains_dynamic_shell_syntax(word) {
415                    // Only these builtins cannot turn a dynamic argument into
416                    // an option that writes or executes code. Keep arguments
417                    // quoted so expansion cannot alter their dimensionality.
418                    if !matches!(name_text, "echo" | "test") || !word.starts_with('"') {
419                        return false;
420                    }
421                    words.push("dynamic-argument".to_owned());
422                } else {
423                    let Ok(parts) = shell_words::split(word) else {
424                        return false;
425                    };
426                    words.extend(parts);
427                }
428            }
429            if crate::tools::command_args::has_unsafe_readonly_options(&words)
430                || (!is_verification_invocation(&words)
431                    && !command_words_are_readonly(&words)
432                    && !is_literal_timer(&words))
433            {
434                return false;
435            }
436        }
437        "file_redirect" => {
438            // Exact AST spans, never substring replacement: a filename such
439            // as /dev/null.backup must not be mistaken for descriptor plumbing.
440            return matches!(text, "2>&1" | "1>&2") || (cfg!(unix) && text == "2>/dev/null");
441        }
442        "word" | "regex" => {
443            return !contains_dynamic_shell_syntax(text) || is_literal_path_glob(text) || is_literal_grep_filter(text);
444        }
445        "raw_string" | "string_content" | "comment" | "number" | "variable_name" | "special_variable_name" => {
446            return true;
447        }
448        "simple_expansion" => return true,
449        "expansion" => {
450            // Support the literal prefix/suffix removal used by link probes;
451            // other parameter operators and arithmetic remain unproven.
452            if text.contains([':', '=', '+', '?', '!']) {
453                return false;
454            }
455        }
456        "program"
457        | "list"
458        | "pipeline"
459        | "for_statement"
460        | "do_group"
461        | "if_statement"
462        | "elif_clause"
463        | "else_clause"
464        | "while_statement"
465        | "command_name"
466        | "string"
467        | "concatenation"
468        | "command_substitution"
469        | "redirected_statement" => {}
470        _ if !node.is_named() => {
471            return matches!(
472                text,
473                "&&" | "||"
474                    | ";"
475                    | "|"
476                    | "for"
477                    | "in"
478                    | "do"
479                    | "done"
480                    | "if"
481                    | "then"
482                    | "elif"
483                    | "else"
484                    | "fi"
485                    | "while"
486                    | "until"
487                    | "\""
488                    | "'"
489                    | "$("
490                    | ")"
491                    | "`"
492                    | "$"
493                    | "${"
494                    | "}"
495                    | "#"
496                    | "##"
497                    | "%"
498                    | "%%"
499            );
500        }
501        _ => return false,
502    }
503    let mut cursor = node.walk();
504    node.children(&mut cursor).all(|child| nonmutating_shell_node(child, source))
505}
506
507#[cfg(test)]
508mod tests;