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 Ok(tree) = crate::command_safety::shell_parser::BashTree::parse(command) else {
308 return true;
309 };
310 let root = tree.root();
311 tree.has_error() || root.named_children().is_empty() || !nonmutating_shell_node(root)
312}
313
314pub(crate) fn exec_output_has_changes(output: &Value) -> bool {
315 output
316 .get("modified_files")
317 .and_then(Value::as_array)
318 .is_some_and(|files| !files.is_empty())
319 || crate::tools::file_ops::diff_output_has_effective_change(output) == Some(true)
320}
321
322fn is_literal_path_glob(word: &str) -> bool {
326 let prefix = match word.split_once('/') {
327 Some((prefix, _)) => prefix,
328 None if word.starts_with('.') => ".",
329 None => return false,
330 };
331 !prefix.starts_with('-')
332 && !prefix.contains(['*', '?', '[', ']'])
333 && word.contains(['*', '?'])
334 && !word.contains(['[', ']'])
335 && !word
336 .chars()
337 .any(|character| character.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(character))
338}
339
340fn is_literal_grep_filter(word: &str) -> bool {
343 let Some((option, pattern)) = word.split_once('=') else {
344 return false;
345 };
346 matches!(option, "--include" | "--exclude" | "--exclude-dir")
347 && !pattern.is_empty()
348 && !pattern.chars().any(|c| c.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(c))
349}
350
351fn is_quoted_variable_file_test(text: &str) -> bool {
354 let Some(expression) = text.strip_prefix('[').and_then(|s| s.strip_suffix(']')) else {
355 return false;
356 };
357 let Some(operand) = expression.trim().strip_prefix("-f ") else {
358 return false;
359 };
360 let Some(variable) = operand
361 .trim()
362 .strip_prefix('"')
363 .and_then(|s| s.strip_suffix('"'))
364 .and_then(|s| s.strip_prefix('$'))
365 else {
366 return false;
367 };
368 let mut chars = variable.chars();
369 chars.next().is_some_and(|ch| ch == '_' || ch.is_ascii_alphabetic())
370 && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
371}
372
373fn nonmutating_shell_node(node: crate::command_safety::shell_parser::BashNode<'_>) -> bool {
376 use crate::command_safety::shell_parser::contains_dynamic_shell_syntax;
377 let text = node.text();
378 match node.kind() {
379 "test_command" => return is_quoted_variable_file_test(text),
380 "command" => {
381 let Some(name) = node.field("name") else {
382 return false;
383 };
384 let name_text = name.text();
385 if contains_dynamic_shell_syntax(name_text) {
386 return false;
387 }
388 let mut words = Vec::new();
389 for child in node.named_children() {
390 let word = child.text();
391 if child.kind() == "variable_assignment" {
392 return false;
393 }
394 if child.start_byte() != name.start_byte()
395 && child.kind() == "word"
396 && (is_literal_path_glob(word)
397 || (matches!(name_text, "grep" | "egrep" | "fgrep" | "rg") && is_literal_grep_filter(word)))
398 && matches!(name_text, "rg" | "grep" | "egrep" | "fgrep" | "ls" | "cat" | "head" | "tail" | "wc")
399 {
400 words.push(word.to_owned());
403 } else if contains_dynamic_shell_syntax(word) {
404 if !matches!(name_text, "echo" | "test") || !word.starts_with('"') {
408 return false;
409 }
410 words.push("dynamic-argument".to_owned());
411 } else {
412 let Ok(parts) = shell_words::split(word) else {
413 return false;
414 };
415 words.extend(parts);
416 }
417 }
418 if crate::tools::command_args::has_unsafe_readonly_options(&words)
419 || (!is_verification_invocation(&words)
420 && !command_words_are_readonly(&words)
421 && !is_literal_timer(&words))
422 {
423 return false;
424 }
425 }
426 "file_redirect" => {
427 return matches!(text, "2>&1" | "1>&2") || (cfg!(unix) && text == "2>/dev/null");
430 }
431 "word" | "regex" => {
432 return !contains_dynamic_shell_syntax(text) || is_literal_path_glob(text) || is_literal_grep_filter(text);
433 }
434 "raw_string" | "string_content" | "comment" | "number" | "variable_name" | "special_variable_name" => {
435 return true;
436 }
437 "simple_expansion" => return true,
438 "expansion" => {
439 if text.contains([':', '=', '+', '?', '!']) {
442 return false;
443 }
444 }
445 "program"
446 | "list"
447 | "pipeline"
448 | "for_statement"
449 | "do_group"
450 | "if_statement"
451 | "elif_clause"
452 | "else_clause"
453 | "while_statement"
454 | "command_name"
455 | "string"
456 | "concatenation"
457 | "command_substitution"
458 | "redirected_statement" => {}
459 _ if !node.is_named() => {
460 return matches!(
461 text,
462 "&&" | "||"
463 | ";"
464 | "|"
465 | "for"
466 | "in"
467 | "do"
468 | "done"
469 | "if"
470 | "then"
471 | "elif"
472 | "else"
473 | "fi"
474 | "while"
475 | "until"
476 | "\""
477 | "'"
478 | "$("
479 | ")"
480 | "`"
481 | "$"
482 | "${"
483 | "}"
484 | "#"
485 | "##"
486 | "%"
487 | "%%"
488 );
489 }
490 _ => return false,
491 }
492 node.children().iter().all(|child| nonmutating_shell_node(*child))
493}
494
495#[cfg(test)]
496mod tests;