vtcode_core/tools/tool_intent/activity/
mod.rs1use 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
32pub enum ShellActivity {
33 Inspection,
35 Verification,
37 Mutation,
39}
40
41pub 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 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 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
137fn 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 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 ';' | '\n' | '|' | '!' | '(' | ')' => return false,
180 '&' => {
181 let next_is_and = chars.get(index + 1) == Some(&'&');
182 if !next_is_and {
183 return false;
184 }
185 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
203pub(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#[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 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#[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
326fn is_literal_path_glob(word: &str) -> bool {
330 let Some((prefix, _)) = word.split_once('/') else {
331 return false;
332 };
333 !prefix.starts_with('-')
334 && !prefix.contains(['*', '?', '[', ']'])
335 && word.contains(['*', '?'])
336 && !word.contains(['[', ']'])
337 && !word
338 .chars()
339 .any(|character| character.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(character))
340}
341
342fn is_literal_grep_filter(word: &str) -> bool {
345 let Some((option, pattern)) = word.split_once('=') else {
346 return false;
347 };
348 matches!(option, "--include" | "--exclude" | "--exclude-dir")
349 && !pattern.is_empty()
350 && !pattern.chars().any(|c| c.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(c))
351}
352
353fn nonmutating_shell_node(node: tree_sitter::Node<'_>, source: &str) -> bool {
356 use crate::command_safety::shell_parser::contains_dynamic_shell_syntax;
357 let Ok(text) = node.utf8_text(source.as_bytes()) else {
358 return false;
359 };
360 match node.kind() {
361 "command" => {
362 let Some(name) = node.child_by_field_name("name") else {
363 return false;
364 };
365 let Ok(name_text) = name.utf8_text(source.as_bytes()) else {
366 return false;
367 };
368 if contains_dynamic_shell_syntax(name_text) {
369 return false;
370 }
371 let mut words = Vec::new();
372 let mut cursor = node.walk();
373 for child in node.named_children(&mut cursor) {
374 let Ok(word) = child.utf8_text(source.as_bytes()) else {
375 return false;
376 };
377 if child.kind() == "variable_assignment" {
378 return false;
379 }
380 if child != name
381 && child.kind() == "word"
382 && (is_literal_path_glob(word)
383 || (matches!(name_text, "grep" | "egrep" | "fgrep" | "rg") && is_literal_grep_filter(word)))
384 && matches!(name_text, "rg" | "grep" | "egrep" | "fgrep" | "ls" | "cat" | "head" | "tail" | "wc")
385 {
386 words.push(word.to_owned());
389 } else if contains_dynamic_shell_syntax(word) {
390 if !matches!(name_text, "echo" | "test") || !word.starts_with('"') {
394 return false;
395 }
396 words.push("dynamic-argument".to_owned());
397 } else {
398 let Ok(parts) = shell_words::split(word) else {
399 return false;
400 };
401 words.extend(parts);
402 }
403 }
404 if crate::tools::command_args::has_unsafe_readonly_options(&words)
405 || (!is_verification_invocation(&words)
406 && !command_words_are_readonly(&words)
407 && !is_literal_timer(&words))
408 {
409 return false;
410 }
411 }
412 "file_redirect" => {
413 return matches!(text, "2>&1" | "1>&2") || (cfg!(unix) && text == "2>/dev/null");
416 }
417 "word" | "regex" => {
418 return !contains_dynamic_shell_syntax(text) || is_literal_path_glob(text) || is_literal_grep_filter(text);
419 }
420 "raw_string" | "string_content" | "comment" | "number" | "variable_name" | "special_variable_name" => {
421 return true;
422 }
423 "simple_expansion" => return true,
424 "expansion" => {
425 if text.contains([':', '=', '+', '?', '!']) {
428 return false;
429 }
430 }
431 "program"
432 | "list"
433 | "pipeline"
434 | "for_statement"
435 | "do_group"
436 | "if_statement"
437 | "elif_clause"
438 | "else_clause"
439 | "while_statement"
440 | "command_name"
441 | "string"
442 | "concatenation"
443 | "command_substitution"
444 | "redirected_statement" => {}
445 _ if !node.is_named() => {
446 return matches!(
447 text,
448 "&&" | "||"
449 | ";"
450 | "|"
451 | "for"
452 | "in"
453 | "do"
454 | "done"
455 | "if"
456 | "then"
457 | "elif"
458 | "else"
459 | "fi"
460 | "while"
461 | "until"
462 | "\""
463 | "'"
464 | "$("
465 | ")"
466 | "`"
467 | "$"
468 | "${"
469 | "}"
470 | "#"
471 | "##"
472 | "%"
473 | "%%"
474 );
475 }
476 _ => return false,
477 }
478 let mut cursor = node.walk();
479 node.children(&mut cursor).all(|child| nonmutating_shell_node(child, source))
480}
481
482#[cfg(test)]
483mod tests;