use std::path::Path;
use serde_json::Value;
use vtcode_commons::validation::NonEmptySlice;
use crate::tools::command_args::shell_command_text_with_args;
use super::readonly::{
command_words_are_readonly, static_shell_command_words, static_shell_command_words_with_output_plumbing,
};
mod verifier;
pub(crate) use verifier::pipefail_verifier_pipeline;
pub use verifier::{
GENERIC_VERIFIER_DESCRIPTION, VERIFIER_SHELL_FORM_NOTE, default_verifier_for_workspace,
rewrite_truncation_only_verifier, shell_command_contains_verifier, shell_command_is_admitted_verification_attempt,
shell_command_is_output_search, shell_command_is_standalone_grep_search, verification_recovery_directive,
verifier_reference,
};
use verifier::{
contains_verification_invocation, has_logical_sequencing, is_verification_invocation, rewrite_verifier_pipeline,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ShellActivity {
Inspection,
Verification,
Mutation,
}
pub fn shell_args_as_executed<'a>(tool_name: &str, args: &'a Value) -> std::borrow::Cow<'a, Value> {
if !super::is_command_run_tool_call(tool_name, args) {
return std::borrow::Cow::Borrowed(args);
}
let Some(rewritten) = rewrite_verifier_pipeline(args) else {
return std::borrow::Cow::Borrowed(args);
};
let mut executed = args.clone();
match executed.as_object_mut() {
Some(payload) => {
if payload.get("raw_command").is_some_and(Value::is_string) {
payload.insert("raw_command".to_string(), Value::String(rewritten.clone()));
}
payload.remove("args");
payload.insert("command".to_string(), Value::String(rewritten));
std::borrow::Cow::Owned(executed)
}
None => std::borrow::Cow::Borrowed(args),
}
}
fn is_known_inspection(words: &[String]) -> bool {
if words
.iter()
.any(|word| matches!(word.as_str(), ">" | ">>" | "|" | "&&" | ";" | "||"))
{
return false;
}
command_words_are_readonly(words)
}
fn classify_provable_shell_sequence(command: &str) -> Option<ShellActivity> {
let (segments, has_output_plumbing) = if let Some(segments) = static_shell_command_words(command) {
(segments, false)
} else {
(static_shell_command_words_with_output_plumbing(command)?, true)
};
if has_output_plumbing && segments.len() != 1 {
return None;
}
let has_multiple_segments = segments.len() > 1;
let mut saw_verification = false;
for words in segments {
if is_verification_invocation(&words) {
saw_verification = true;
} else if !command_words_are_readonly(&words) {
return None;
}
}
if has_output_plumbing && !saw_verification {
return None;
}
if saw_verification && has_multiple_segments {
if shell_uses_only_and_chaining(command) {
return Some(ShellActivity::Verification);
}
return Some(ShellActivity::Mutation);
}
Some(if saw_verification {
ShellActivity::Verification
} else {
ShellActivity::Inspection
})
}
fn has_shell_sequence(command: &str) -> bool {
static_shell_command_words(command).is_none_or(|segments| segments.len() > 1)
}
fn shell_uses_only_and_chaining(command: &str) -> bool {
let chars: Vec<char> = command.chars().collect();
let mut index = 0;
let mut in_single_quote = false;
let mut in_double_quote = false;
while index < chars.len() {
let character = chars[index];
if character == '\\' && !in_single_quote && index + 1 < chars.len() {
index += 2;
continue;
}
if character == '\'' && !in_double_quote {
in_single_quote = !in_single_quote;
index += 1;
continue;
}
if character == '"' && !in_single_quote {
in_double_quote = !in_double_quote;
index += 1;
continue;
}
if in_single_quote || in_double_quote {
index += 1;
continue;
}
match character {
';' | '\n' | '|' | '!' | '(' | ')' => return false,
'&' => {
let next_is_and = chars.get(index + 1) == Some(&'&');
if !next_is_and {
return false;
}
let third = chars.get(index + 2);
if third == Some(&'&') || third == Some(&'|') {
return false;
}
index += 2;
continue;
}
_ => {}
}
index += 1;
}
true
}
pub(crate) fn shell_command_covers_required_check(command: &str, required: &str) -> bool {
if !shell_uses_only_and_chaining(command) || !shell_uses_only_and_chaining(required) {
return false;
}
let Some(segments) = static_shell_command_words(command) else {
return false;
};
let Some(required_segments) = static_shell_command_words(required) else {
return false;
};
if segments.iter().any(|words| {
words.first().is_some_and(|word| word == "cd")
|| (!is_verification_invocation(words) && !command_words_are_readonly(words))
}) {
return false;
}
segments
.windows(required_segments.len())
.any(|window| window == required_segments)
}
#[must_use]
pub fn classify_shell_activity(tool_name: &str, args: &Value) -> ShellActivity {
let command = shell_command_text_with_args(args);
if command.is_none() && crate::tools::command_args::raw_command_text(args).is_some() {
return ShellActivity::Mutation;
}
if command.as_deref().and_then(pipefail_verifier_pipeline).is_some() {
return ShellActivity::Verification;
}
let words = crate::tools::command_args::command_words(args).ok().flatten();
let has_unclassified_shell_sequence = command.as_deref().is_some_and(has_shell_sequence);
if let Some(activity) = command.as_deref().and_then(classify_provable_shell_sequence) {
return activity;
}
if has_unclassified_shell_sequence {
return ShellActivity::Mutation;
}
let intent = super::classify_tool_intent(tool_name, args);
if !has_unclassified_shell_sequence && words.as_deref().is_some_and(is_known_inspection) {
return ShellActivity::Inspection;
}
let starts_with_verification = words.as_deref().is_some_and(is_verification_invocation);
let contains_verification =
starts_with_verification || command.as_deref().is_some_and(contains_verification_invocation);
if !intent.mutating {
return if contains_verification {
ShellActivity::Verification
} else {
ShellActivity::Inspection
};
}
if starts_with_verification
&& !has_unclassified_shell_sequence
&& !words.as_deref().is_some_and(has_logical_sequencing)
{
ShellActivity::Verification
} else {
ShellActivity::Mutation
}
}
fn is_literal_timer(words: &[String]) -> bool {
let seconds = match words {
[program, seconds] if program == "sleep" => Some(seconds.as_str()),
[program, flag, code] if matches!(program.as_str(), "python" | "python3") && flag == "-c" => code
.strip_prefix("import time; time.sleep(")
.and_then(|code| code.strip_suffix(')')),
_ => None,
};
seconds.is_some_and(|seconds| {
!seconds.is_empty()
&& seconds.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.')
&& seconds
.parse::<f64>()
.is_ok_and(|seconds| seconds.is_finite() && seconds >= 0.0)
})
}
#[must_use]
pub fn exec_mutation_should_incur_debt(command: &str, output: &Value) -> bool {
if exec_output_has_changes(output) {
return true;
}
let mut parser = tree_sitter::Parser::new();
if parser.set_language(&tree_sitter_bash::LANGUAGE.into()).is_err() {
return true;
}
let Some(tree) = parser.parse(command, None) else {
return true;
};
let root = tree.root_node();
root.has_error() || root.named_child_count() == 0 || !nonmutating_shell_node(root, command)
}
pub(crate) fn exec_output_has_changes(output: &Value) -> bool {
output
.get("modified_files")
.and_then(Value::as_array)
.is_some_and(|files| !files.is_empty())
|| crate::tools::file_ops::diff_output_has_effective_change(output) == Some(true)
}
fn is_literal_path_glob(word: &str) -> bool {
let Some((prefix, _)) = word.split_once('/') else {
return false;
};
!prefix.starts_with('-')
&& !prefix.contains(['*', '?', '[', ']'])
&& word.contains(['*', '?'])
&& !word.contains(['[', ']'])
&& !word
.chars()
.any(|character| character.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(character))
}
fn is_literal_grep_filter(word: &str) -> bool {
let Some((option, pattern)) = word.split_once('=') else {
return false;
};
matches!(option, "--include" | "--exclude" | "--exclude-dir")
&& !pattern.is_empty()
&& !pattern.chars().any(|c| c.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(c))
}
fn nonmutating_shell_node(node: tree_sitter::Node<'_>, source: &str) -> bool {
use crate::command_safety::shell_parser::contains_dynamic_shell_syntax;
let Ok(text) = node.utf8_text(source.as_bytes()) else {
return false;
};
match node.kind() {
"command" => {
let Some(name) = node.child_by_field_name("name") else {
return false;
};
let Ok(name_text) = name.utf8_text(source.as_bytes()) else {
return false;
};
if contains_dynamic_shell_syntax(name_text) {
return false;
}
let mut words = Vec::new();
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
let Ok(word) = child.utf8_text(source.as_bytes()) else {
return false;
};
if child.kind() == "variable_assignment" {
return false;
}
if child != name
&& child.kind() == "word"
&& (is_literal_path_glob(word)
|| (matches!(name_text, "grep" | "egrep" | "fgrep" | "rg") && is_literal_grep_filter(word)))
&& matches!(name_text, "rg" | "grep" | "egrep" | "fgrep" | "ls" | "cat" | "head" | "tail" | "wc")
{
words.push(word.to_owned());
} else if contains_dynamic_shell_syntax(word) {
if !matches!(name_text, "echo" | "test") || !word.starts_with('"') {
return false;
}
words.push("dynamic-argument".to_owned());
} else {
let Ok(parts) = shell_words::split(word) else {
return false;
};
words.extend(parts);
}
}
if crate::tools::command_args::has_unsafe_readonly_options(&words)
|| (!is_verification_invocation(&words)
&& !command_words_are_readonly(&words)
&& !is_literal_timer(&words))
{
return false;
}
}
"file_redirect" => {
return matches!(text, "2>&1" | "1>&2") || (cfg!(unix) && text == "2>/dev/null");
}
"word" | "regex" => {
return !contains_dynamic_shell_syntax(text) || is_literal_path_glob(text) || is_literal_grep_filter(text);
}
"raw_string" | "string_content" | "comment" | "number" | "variable_name" | "special_variable_name" => {
return true;
}
"simple_expansion" => return true,
"expansion" => {
if text.contains([':', '=', '+', '?', '!']) {
return false;
}
}
"program"
| "list"
| "pipeline"
| "for_statement"
| "do_group"
| "if_statement"
| "elif_clause"
| "else_clause"
| "while_statement"
| "command_name"
| "string"
| "concatenation"
| "command_substitution"
| "redirected_statement" => {}
_ if !node.is_named() => {
return matches!(
text,
"&&" | "||"
| ";"
| "|"
| "for"
| "in"
| "do"
| "done"
| "if"
| "then"
| "elif"
| "else"
| "fi"
| "while"
| "until"
| "\""
| "'"
| "$("
| ")"
| "`"
| "$"
| "${"
| "}"
| "#"
| "##"
| "%"
| "%%"
);
}
_ => return false,
}
let mut cursor = node.walk();
node.children(&mut cursor).all(|child| nonmutating_shell_node(child, source))
}
#[cfg(test)]
mod tests;