1use 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
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub enum ShellActivity {
21 Inspection,
23 Verification,
25 Mutation,
27}
28
29fn make_like_verification_targets(words: &[String]) -> bool {
30 let mut saw_target = false;
31 for word in words.iter().skip(1) {
32 let lower = word.to_ascii_lowercase();
33 if lower.starts_with('-') || lower.contains('=') {
34 continue;
35 }
36 if !matches!(lower.as_str(), "test" | "tests" | "check" | "checks" | "lint" | "verify" | "validate") {
37 return false;
38 }
39 saw_target = true;
40 }
41 saw_target
42}
43
44fn python_verification_arguments(arguments: &[String]) -> bool {
45 let mut arguments = arguments.iter();
47 let target = arguments.find(|word| {
48 !matches!(word.as_str(), "-I" | "-E" | "-s" | "-S" | "-B" | "-O" | "-OO" | "-q" | "-u" | "-b" | "-bb" | "-v")
49 });
50 match target.map(String::as_str) {
51 Some("-m") => arguments.next().is_some_and(|module| module == "pytest"),
52 Some(script) => {
53 ["scripts/check_markdown.py", "scripts/check_docs_links.py"]
54 .iter()
55 .any(|known| Path::new(script).ends_with(known))
56 && arguments.next().is_none()
57 }
58 None => false,
59 }
60}
61
62fn is_verification_invocation(words: &[String]) -> bool {
63 if crate::tools::command_args::command_uses_source_repair(words)
66 || crate::tools::command_args::environment_prefix_has_injection_keys(words)
67 {
68 return false;
69 }
70 let command_words = crate::tools::command_args::command_words_after_environment_prefix(words);
71 let first = command_words.first().map(String::as_str).unwrap_or_default();
72 let second = command_words.get(1).map(|word| word.to_ascii_lowercase());
73 let third = command_words.get(2).map(|word| word.to_ascii_lowercase());
74 let program = Path::new(first)
75 .file_name()
76 .and_then(|name| name.to_str())
77 .unwrap_or(first)
78 .to_ascii_lowercase();
79
80 match program.as_str() {
81 "markdownlint-cli2" => command_words.get(1..).is_some_and(markdownlint_arguments_verify),
82 "npx" => {
83 let package_index = command_words
84 .iter()
85 .enumerate()
86 .skip(1)
87 .find(|(_, word)| {
88 !matches!(word.as_str(), "--yes" | "-y" | "--no-install")
89 && !word.strip_prefix("--loglevel=").is_some_and(|level| {
90 matches!(
91 level,
92 "silent" | "error" | "warn" | "notice" | "http" | "info" | "verbose" | "silly"
93 )
94 })
95 })
96 .map(|(index, _)| index);
97 package_index.is_some_and(|index| {
98 let Some(package) = command_words.get(index) else {
99 return false;
100 };
101 let is_markdownlint = package == "markdownlint-cli2"
102 || package.strip_prefix("markdownlint-cli2@").is_some_and(|version| {
103 version.split('.').count() == 3
104 && version
105 .split('.')
106 .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
107 });
108 is_markdownlint && command_words.get(index + 1..).is_some_and(markdownlint_arguments_verify)
109 })
110 }
111 "cargo" => {
112 if second.as_deref() == Some("fmt") {
113 return words.iter().any(|word| word == "--check");
116 }
117 matches!(second.as_deref(), Some("check" | "build" | "clippy" | "test"))
118 || (second.as_deref() == Some("nextest") && third.as_deref() == Some("run"))
119 }
120 "go" => matches!(second.as_deref(), Some("test" | "build")),
121 "npm" | "pnpm" | "yarn" => {
122 matches!(second.as_deref(), Some("test" | "build" | "lint" | "check"))
123 || (second.as_deref() == Some("run")
124 && matches!(third.as_deref(), Some("test" | "build" | "lint" | "check")))
125 }
126 "bun" | "bunx" => {
127 matches!(second.as_deref(), Some("test"))
128 || (second.as_deref() == Some("run")
129 && matches!(third.as_deref(), Some("test" | "build" | "lint" | "check")))
130 }
131 "deno" => matches!(second.as_deref(), Some("test" | "lint" | "check")),
132 "make" | "gmake" | "just" => make_like_verification_targets(command_words),
133 "uv" => {
134 let Some(arguments) = crate::tools::command_args::uv_run_command_words(command_words) else {
135 return false;
136 };
137 let mut arguments = arguments.iter();
138 let target = arguments.next();
139 match target.map(String::as_str) {
140 Some("pytest") => true,
141 Some("ruff") => arguments.next().is_some_and(|argument| argument == "check"),
142 Some("python" | "python3") => python_verification_arguments(arguments.as_slice()),
143 _ => false,
144 }
145 }
146 "ruff" => {
147 if second.as_deref() == Some("format") {
148 return words.iter().any(|word| word == "--check");
149 }
150 matches!(second.as_deref(), Some("check" | "lint"))
151 }
152 "tsc" => {
153 words.iter().any(|word| word == "--noEmit")
155 }
156 "eslint" => {
157 !words.iter().any(|word| word == "--fix" || word == "--fix-dry-run")
159 }
160 "rustc" | "pytest" | "xcodebuild" | "gradle" | "gradlew" => true,
161 "python" | "python3" => python_verification_arguments(&command_words[1..]),
162 _ if first.ends_with("/scripts/check.sh") || first.ends_with("/scripts/check-dev.sh") => true,
163 _ => false,
164 }
165}
166
167fn markdownlint_arguments_verify(arguments: &[String]) -> bool {
168 !arguments.is_empty()
169 && !arguments.iter().any(|argument| {
170 matches!(argument.as_str(), "--fix" | "-f" | "--help" | "-h" | "--version" | "-v")
171 || argument.starts_with("--fix=")
172 })
173}
174
175fn contains_verification_invocation(command: &str) -> bool {
176 static_shell_command_words(command)
177 .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
178}
179
180pub fn shell_command_contains_verifier(args: &Value) -> bool {
184 let Some(command) = shell_command_text_with_args(args) else {
185 return false;
186 };
187 super::readonly::parse_shell_command_words(&command)
188 .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
189}
190
191pub fn shell_command_is_output_search(args: &Value) -> bool {
198 let Some(command) = shell_command_text_with_args(args) else {
199 return false;
200 };
201 let Some(segments) = static_shell_command_words(&command) else {
202 return false;
203 };
204 let mut saw_search = false;
205 for words in &segments {
206 if !command_words_are_readonly(words) || is_verification_invocation(words) {
207 return false;
208 }
209 let words = crate::tools::command_args::command_words_after_environment_prefix(words);
210 if command_words_are_grep_search(words) {
211 if grep_words_request_quiet_output(words) {
212 return false;
213 }
214 saw_search = true;
215 }
216 }
217 saw_search
218}
219
220fn grep_words_request_quiet_output(words: &[String]) -> bool {
221 let is_rg = words
222 .first()
223 .and_then(|word| Path::new(word).file_name())
224 .is_some_and(|name| name == "rg");
225 let mut arguments = words.iter().skip(1);
226 let mut quiet = false;
227 while let Some(argument) = arguments.next() {
228 match argument.as_str() {
229 "--" => break,
230 "--quiet" | "--silent" => quiet = true,
231 "--no-quiet" if is_rg => quiet = false,
232 _ if argument.starts_with("--") => {
233 let takes_value = matches!(
235 argument.as_str(),
236 "--regexp"
237 | "--file"
238 | "--after-context"
239 | "--before-context"
240 | "--context"
241 | "--max-count"
242 | "--include"
243 | "--exclude"
244 | "--exclude-from"
245 | "--exclude-dir"
246 | "--label"
247 | "--directories"
248 | "--devices"
249 ) || (is_rg
250 && matches!(
251 argument.as_str(),
252 "--glob"
253 | "--iglob"
254 | "--ignore-file"
255 | "--pre-glob"
256 | "--type"
257 | "--type-not"
258 | "--type-add"
259 | "--type-clear"
260 | "--replace"
261 | "--encoding"
262 | "--engine"
263 | "--color"
264 | "--colors"
265 | "--threads"
266 | "--max-depth"
267 | "--max-columns"
268 | "--max-filesize"
269 | "--dfa-size-limit"
270 | "--regex-size-limit"
271 | "--context-separator"
272 | "--field-context-separator"
273 | "--field-match-separator"
274 | "--hyperlink-format"
275 | "--path-separator"
276 | "--sort"
277 | "--sortr"
278 | "--generate"
279 ));
280 if takes_value {
281 arguments.next();
282 }
283 }
284 _ if argument.starts_with('-') => {
285 let mut flags = argument.chars().skip(1).peekable();
286 while let Some(flag) = flags.next() {
287 if flag == 'q' {
288 quiet = true;
289 }
290 let takes_value = matches!(flag, 'e' | 'f' | 'A' | 'B' | 'C' | 'm' | 'd')
291 || (is_rg && matches!(flag, 'g' | 't' | 'T' | 'r' | 'E' | 'j' | 'M'))
292 || (!is_rg && flag == 'D');
293 if takes_value {
294 if flags.peek().is_none() {
295 arguments.next();
296 }
297 break;
298 }
299 }
300 }
301 _ => {}
302 }
303 }
304 quiet
305}
306
307pub fn shell_command_is_standalone_grep_search(args: &Value) -> bool {
311 let Some(command) = shell_command_text_with_args(args) else {
312 return false;
313 };
314 let Some(segments) = static_shell_command_words(&command) else {
315 return false;
316 };
317 let [words] = segments.as_slice() else {
318 return false;
319 };
320 shell_words::split(&command).is_ok_and(|raw_words| raw_words == *words)
321 && command_words_are_readonly(words)
322 && command_words_are_grep_search(words)
323}
324
325fn command_words_are_grep_search(words: &[String]) -> bool {
326 let words = crate::tools::command_args::command_words_after_environment_prefix(words);
327 let program = words
328 .first()
329 .and_then(|word| Path::new(word).file_name())
330 .and_then(|name| name.to_str());
331 matches!(program, Some("rg" | "grep" | "egrep" | "fgrep"))
332}
333
334const PRE_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
338 (&["Cargo.toml"], "cargo check --locked"),
339 (&["go.mod"], "go test ./..."),
340 (&["deno.json", "deno.jsonc"], "deno test"),
341 (&["bun.lockb", "bun.lock"], "bun test"),
342];
343
344const POST_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
347 (&["pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini"], "pytest -q"),
348 (&["Makefile", "makefile"], "make test"),
349 (&["justfile", "Justfile"], "just test"),
350];
351
352fn verifier_for_markers(workspace_root: &Path, markers: &[(&[&str], &str)]) -> Option<String> {
354 markers.iter().find_map(|(files, verifier)| {
355 files
356 .iter()
357 .any(|file| workspace_root.join(file).is_file())
358 .then(|| (*verifier).to_string())
359 })
360}
361
362fn default_verifier_for_node_workspace(workspace_root: &Path) -> Option<String> {
367 let package_json = workspace_root.join("package.json");
368 if !package_json.is_file() {
369 return None;
370 }
371 if let Ok(content) = std::fs::read_to_string(&package_json)
372 && let Ok(parsed) = serde_json::from_str::<Value>(&content)
373 && let Some(scripts) = parsed.get("scripts").and_then(Value::as_object)
374 {
375 for (script, command) in [
376 ("test", "npm test"),
377 ("check", "npm run check"),
378 ("lint", "npm run lint"),
379 ("build", "npm run build"),
380 ] {
381 if scripts.contains_key(script) {
382 return Some(command.to_string());
383 }
384 }
385 }
386 Some("npm test".to_string())
387}
388
389pub fn default_verifier_for_workspace(workspace_root: &Path) -> Option<String> {
405 if let Some(verifier) = verifier_for_markers(workspace_root, PRE_NODE_VERIFIER_MARKERS) {
406 return Some(verifier);
407 }
408 if let Some(verifier) = default_verifier_for_node_workspace(workspace_root) {
409 return Some(verifier);
410 }
411 verifier_for_markers(workspace_root, POST_NODE_VERIFIER_MARKERS)
413}
414
415pub const VERIFIER_SHELL_FORM_NOTE: &str = "Cap output with `max_output_tokens`. Pure `head`/`tail` verifier tails run standalone; static read-only filtering pipelines run with fail-closed `pipefail`. Only terminal exit 0 clears the gate; `;`, `||`, dynamic syntax, and mutating tails do not qualify.";
419
420pub const GENERIC_VERIFIER_DESCRIPTION: &str =
426 "your project's build/test/lint command (e.g. `cargo check --locked`, `go test ./...`, `npm test`, or `pytest -q`)";
427
428pub fn verifier_reference(default_verifier: Option<&str>) -> String {
433 match default_verifier.map(str::trim).filter(|command| !command.is_empty()) {
434 Some(command) => format!("`{command}`"),
435 None => GENERIC_VERIFIER_DESCRIPTION.to_string(),
436 }
437}
438
439pub fn verification_recovery_directive(default_verifier: Option<&str>, attempt: u8, max_attempts: u8) -> String {
444 let verifier = verifier_reference(default_verifier);
445 format!(
446 "Verification recovery ({attempt}/{max_attempts}): completion is unverified. Continue implementation and repair reported failures; edits remain available. \
447 Then run only missing checks, starting with {verifier} via `exec_command`, standalone or as a pure `&&` chain of verifiers. \
448 {VERIFIER_SHELL_FORM_NOTE} Reuse fresh passes; successful completion requires all mandatory checks."
449 )
450}
451
452pub fn shell_command_is_admitted_verification_attempt(args: &Value) -> bool {
467 let Some(command) = shell_command_text_with_args(args) else {
468 return false;
469 };
470 if crate::tools::command_args::contains_dynamic_shell_syntax(&command) {
471 return false;
472 }
473 if command.starts_with(VERIFIER_PIPEFAIL_PREFIX) {
474 return pipefail_verifier_pipeline(&command).is_some();
475 }
476 let segments =
477 static_shell_command_words(&command).or_else(|| static_shell_command_words_with_output_plumbing(&command));
478 let Some(segments) = segments else {
479 return false;
480 };
481 if segments.is_empty() {
482 return false;
483 }
484 let mut saw_verification = false;
485 for words in &segments {
486 if is_verification_invocation(words) {
487 saw_verification = true;
488 } else if !command_words_are_readonly(words) {
489 return false;
490 }
491 }
492 saw_verification
493}
494
495fn has_logical_sequencing(words: &[String]) -> bool {
496 words.iter().any(|word| matches!(word.as_str(), "&&" | "||" | ";"))
497}
498
499fn split_top_level_pipes(command: &str) -> Option<Vec<&str>> {
506 if !command.contains('|') {
507 return None;
508 }
509 let mut stages = Vec::new();
510 let mut start = 0;
511 let mut saw_pipe = false;
512 let mut in_single_quote = false;
513 let mut in_double_quote = false;
514 let mut chars = command.char_indices().peekable();
515 while let Some((index, character)) = chars.next() {
516 if character == '\\' && !in_single_quote {
520 chars.next();
521 continue;
522 }
523 if character == '\'' && !in_double_quote {
524 in_single_quote = !in_single_quote;
525 continue;
526 }
527 if character == '"' && !in_single_quote {
528 in_double_quote = !in_double_quote;
529 continue;
530 }
531 if in_single_quote || in_double_quote {
532 continue;
533 }
534 if character == '|' {
535 saw_pipe = true;
536 stages.push(&command[start..index]);
537 start = index + character.len_utf8();
538 }
539 }
540 if !saw_pipe {
541 return None;
542 }
543 stages.push(&command[start..]);
544 Some(stages)
545}
546
547fn is_pure_truncation_stage(stage: &str) -> bool {
553 let trimmed = stage.trim();
554 if trimmed.is_empty() {
555 return false;
556 }
557 let mut in_single_quote = false;
562 let mut in_double_quote = false;
563 let mut chars = trimmed.chars().peekable();
564 while let Some(character) = chars.next() {
565 if character == '\\' && !in_single_quote {
566 chars.next();
567 continue;
568 }
569 if character == '\'' && !in_double_quote {
570 in_single_quote = !in_single_quote;
571 continue;
572 }
573 if character == '"' && !in_single_quote {
574 in_double_quote = !in_double_quote;
575 continue;
576 }
577 if in_single_quote || in_double_quote {
578 continue;
579 }
580 if matches!(character, ';' | '&' | '<' | '>' | '\n' | '|') {
581 return false;
582 }
583 }
584 let words = match shell_words::split(trimmed) {
585 Ok(words) => words,
586 Err(_) => return false,
587 };
588 let Some(parsed) = NonEmptySlice::from_slice(&words) else {
589 return false;
590 };
591 let program = Path::new(parsed.first())
592 .file_name()
593 .and_then(|name| name.to_str())
594 .unwrap_or(parsed.first().as_str())
595 .to_ascii_lowercase();
596 matches!(program.as_str(), "head" | "tail")
597}
598
599pub fn rewrite_truncation_only_verifier(args: &Value) -> Option<String> {
629 use crate::config::constants::tools as tool_names;
630
631 let command = shell_command_text_with_args(args)?;
632 if !shell_command_is_admitted_verification_attempt(args) {
633 return None;
634 }
635 let stages = split_top_level_pipes(&command)?;
636 let (head, tails) = stages.split_first()?;
637 let head = head.trim();
638 if head.is_empty() || tails.iter().any(|stage| !is_pure_truncation_stage(stage)) {
639 return None;
640 }
641 let head_args = serde_json::json!({"cmd": head});
642 if !matches!(classify_shell_activity(tool_names::EXEC_COMMAND, &head_args), ShellActivity::Verification) {
643 return None;
644 }
645 Some(head.to_string())
646}
647
648const VERIFIER_PIPEFAIL_PREFIX: &str = "set -o pipefail && ";
650
651pub(crate) fn pipefail_verifier_pipeline(command: &str) -> Option<&str> {
654 let pipeline = command.strip_prefix(VERIFIER_PIPEFAIL_PREFIX)?;
655 if crate::tools::command_args::contains_dynamic_shell_syntax(pipeline) {
656 return None;
657 }
658 verifier_pipeline_head(pipeline).map(|_| pipeline)
659}
660
661fn verifier_pipeline_head(command: &str) -> Option<&str> {
663 let stages = split_top_level_pipes(command)?;
664 let (head, tails) = stages.split_first()?;
665 let head = head.trim();
666 let head_args = serde_json::json!({"cmd": head});
667 if classify_shell_activity(crate::config::constants::tools::EXEC_COMMAND, &head_args) != ShellActivity::Verification
668 {
669 return None;
670 }
671 for stage in tails {
674 let segments = static_shell_command_words(stage)?;
675 if segments.len() != 1 || !segments.first().is_some_and(|words| command_words_are_readonly(words)) {
676 return None;
677 }
678 }
679 Some(head)
680}
681
682fn rewrite_verifier_pipeline(args: &Value) -> Option<String> {
687 if let Some(standalone) = rewrite_truncation_only_verifier(args) {
688 return Some(standalone);
689 }
690 let command = shell_command_text_with_args(args)?;
691 if command.starts_with(VERIFIER_PIPEFAIL_PREFIX)
692 || !shell_command_is_admitted_verification_attempt(args)
693 || verifier_pipeline_head(&command).is_none()
694 {
695 return None;
696 }
697 Some(format!("{VERIFIER_PIPEFAIL_PREFIX}{command}"))
698}
699
700pub fn shell_args_as_executed<'a>(tool_name: &str, args: &'a Value) -> std::borrow::Cow<'a, Value> {
712 if !super::is_command_run_tool_call(tool_name, args) {
713 return std::borrow::Cow::Borrowed(args);
714 }
715 let Some(rewritten) = rewrite_verifier_pipeline(args) else {
716 return std::borrow::Cow::Borrowed(args);
717 };
718 let mut executed = args.clone();
719 match executed.as_object_mut() {
720 Some(payload) => {
721 if payload.get("raw_command").is_some_and(Value::is_string) {
722 payload.insert("raw_command".to_string(), Value::String(rewritten.clone()));
723 }
724 payload.remove("args");
727 payload.insert("command".to_string(), Value::String(rewritten));
728 std::borrow::Cow::Owned(executed)
729 }
730 None => std::borrow::Cow::Borrowed(args),
731 }
732}
733
734fn is_known_inspection(words: &[String]) -> bool {
735 if words
736 .iter()
737 .any(|word| matches!(word.as_str(), ">" | ">>" | "|" | "&&" | ";" | "||"))
738 {
739 return false;
740 }
741 command_words_are_readonly(words)
742}
743
744fn classify_provable_shell_sequence(command: &str) -> Option<ShellActivity> {
745 let (segments, has_output_plumbing) = if let Some(segments) = static_shell_command_words(command) {
746 (segments, false)
747 } else {
748 (static_shell_command_words_with_output_plumbing(command)?, true)
749 };
750 if has_output_plumbing && segments.len() != 1 {
751 return None;
752 }
753 let has_multiple_segments = segments.len() > 1;
754 let mut saw_verification = false;
755
756 for words in segments {
757 if is_verification_invocation(&words) {
758 saw_verification = true;
759 } else if !command_words_are_readonly(&words) {
760 return None;
761 }
762 }
763
764 if has_output_plumbing && !saw_verification {
765 return None;
766 }
767
768 if saw_verification && has_multiple_segments {
779 if shell_uses_only_and_chaining(command) {
780 return Some(ShellActivity::Verification);
781 }
782 return Some(ShellActivity::Mutation);
783 }
784
785 Some(if saw_verification {
786 ShellActivity::Verification
787 } else {
788 ShellActivity::Inspection
789 })
790}
791
792fn has_shell_sequence(command: &str) -> bool {
793 static_shell_command_words(command).is_none_or(|segments| segments.len() > 1)
794}
795
796fn shell_uses_only_and_chaining(command: &str) -> bool {
806 let chars: Vec<char> = command.chars().collect();
807 let mut index = 0;
808 let mut in_single_quote = false;
809 let mut in_double_quote = false;
810
811 while index < chars.len() {
812 let character = chars[index];
813 if character == '\\' && !in_single_quote && index + 1 < chars.len() {
818 index += 2;
819 continue;
820 }
821 if character == '\'' && !in_double_quote {
822 in_single_quote = !in_single_quote;
823 index += 1;
824 continue;
825 }
826 if character == '"' && !in_single_quote {
827 in_double_quote = !in_double_quote;
828 index += 1;
829 continue;
830 }
831 if in_single_quote || in_double_quote {
832 index += 1;
833 continue;
834 }
835 match character {
836 ';' | '\n' | '|' | '!' | '(' | ')' => return false,
839 '&' => {
840 let next_is_and = chars.get(index + 1) == Some(&'&');
841 if !next_is_and {
842 return false;
843 }
844 let third = chars.get(index + 2);
848 if third == Some(&'&') || third == Some(&'|') {
849 return false;
850 }
851 index += 2;
852 continue;
853 }
854 _ => {}
855 }
856 index += 1;
857 }
858
859 true
860}
861
862pub(crate) fn shell_command_covers_required_check(command: &str, required: &str) -> bool {
865 if !shell_uses_only_and_chaining(command) || !shell_uses_only_and_chaining(required) {
866 return false;
867 }
868 let Some(segments) = static_shell_command_words(command) else {
869 return false;
870 };
871 let Some(required_segments) = static_shell_command_words(required) else {
872 return false;
873 };
874 if segments.iter().any(|words| {
875 words.first().is_some_and(|word| word == "cd")
876 || (!is_verification_invocation(words) && !command_words_are_readonly(words))
877 }) {
878 return false;
879 }
880 segments
881 .windows(required_segments.len())
882 .any(|window| window == required_segments)
883}
884
885#[must_use]
894pub fn classify_shell_activity(tool_name: &str, args: &Value) -> ShellActivity {
895 let command = shell_command_text_with_args(args);
896 if command.is_none() && crate::tools::command_args::raw_command_text(args).is_some() {
897 return ShellActivity::Mutation;
898 }
899 if command.as_deref().and_then(pipefail_verifier_pipeline).is_some() {
900 return ShellActivity::Verification;
901 }
902 let words = crate::tools::command_args::command_words(args).ok().flatten();
903 let has_unclassified_shell_sequence = command.as_deref().is_some_and(has_shell_sequence);
904
905 if let Some(activity) = command.as_deref().and_then(classify_provable_shell_sequence) {
906 return activity;
907 }
908 if has_unclassified_shell_sequence {
911 return ShellActivity::Mutation;
912 }
913
914 let intent = super::classify_tool_intent(tool_name, args);
915
916 if !has_unclassified_shell_sequence && words.as_deref().is_some_and(is_known_inspection) {
917 return ShellActivity::Inspection;
918 }
919
920 let starts_with_verification = words.as_deref().is_some_and(is_verification_invocation);
921 let contains_verification =
922 starts_with_verification || command.as_deref().is_some_and(contains_verification_invocation);
923 if !intent.mutating {
924 return if contains_verification {
925 ShellActivity::Verification
926 } else {
927 ShellActivity::Inspection
928 };
929 }
930
931 if starts_with_verification
932 && !has_unclassified_shell_sequence
933 && !words.as_deref().is_some_and(has_logical_sequencing)
934 {
935 ShellActivity::Verification
936 } else {
937 ShellActivity::Mutation
938 }
939}
940
941fn is_literal_timer(words: &[String]) -> bool {
942 let seconds = match words {
943 [program, seconds] if program == "sleep" => Some(seconds.as_str()),
944 [program, flag, code] if matches!(program.as_str(), "python" | "python3") && flag == "-c" => code
945 .strip_prefix("import time; time.sleep(")
946 .and_then(|code| code.strip_suffix(')')),
947 _ => None,
948 };
949 seconds.is_some_and(|seconds| {
950 !seconds.is_empty()
951 && seconds.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.')
952 && seconds
953 .parse::<f64>()
954 .is_ok_and(|seconds| seconds.is_finite() && seconds >= 0.0)
955 })
956}
957
958#[must_use]
962pub fn exec_mutation_should_incur_debt(command: &str, output: &Value) -> bool {
963 if exec_output_has_changes(output) {
964 return true;
965 }
966 let mut parser = tree_sitter::Parser::new();
967 if parser.set_language(&tree_sitter_bash::LANGUAGE.into()).is_err() {
968 return true;
969 }
970 let Some(tree) = parser.parse(command, None) else {
971 return true;
972 };
973 let root = tree.root_node();
974 root.has_error() || root.named_child_count() == 0 || !nonmutating_shell_node(root, command)
975}
976
977pub(crate) fn exec_output_has_changes(output: &Value) -> bool {
978 output
979 .get("modified_files")
980 .and_then(Value::as_array)
981 .is_some_and(|files| !files.is_empty())
982 || crate::tools::file_ops::diff_output_has_effective_change(output) == Some(true)
983}
984
985fn is_literal_path_glob(word: &str) -> bool {
989 let Some((prefix, _)) = word.split_once('/') else {
990 return false;
991 };
992 !prefix.starts_with('-')
993 && !prefix.contains(['*', '?', '[', ']'])
994 && word.contains(['*', '?'])
995 && !word.contains(['[', ']'])
996 && !word
997 .chars()
998 .any(|character| character.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(character))
999}
1000
1001fn nonmutating_shell_node(node: tree_sitter::Node<'_>, source: &str) -> bool {
1004 use crate::command_safety::shell_parser::contains_dynamic_shell_syntax;
1005 let Ok(text) = node.utf8_text(source.as_bytes()) else {
1006 return false;
1007 };
1008 match node.kind() {
1009 "command" => {
1010 let Some(name) = node.child_by_field_name("name") else {
1011 return false;
1012 };
1013 let Ok(name_text) = name.utf8_text(source.as_bytes()) else {
1014 return false;
1015 };
1016 if contains_dynamic_shell_syntax(name_text) {
1017 return false;
1018 }
1019 let mut words = Vec::new();
1020 let mut cursor = node.walk();
1021 for child in node.named_children(&mut cursor) {
1022 let Ok(word) = child.utf8_text(source.as_bytes()) else {
1023 return false;
1024 };
1025 if child.kind() == "variable_assignment" {
1026 return false;
1027 }
1028 if child != name
1029 && child.kind() == "word"
1030 && is_literal_path_glob(word)
1031 && matches!(name_text, "rg" | "grep" | "egrep" | "fgrep" | "ls" | "cat" | "head" | "tail" | "wc")
1032 {
1033 words.push(word.to_owned());
1036 } else if contains_dynamic_shell_syntax(word) {
1037 if !matches!(name_text, "echo" | "test") || !word.starts_with('"') {
1041 return false;
1042 }
1043 words.push("dynamic-argument".to_owned());
1044 } else {
1045 let Ok(parts) = shell_words::split(word) else {
1046 return false;
1047 };
1048 words.extend(parts);
1049 }
1050 }
1051 if crate::tools::command_args::has_unsafe_readonly_options(&words)
1052 || (!is_verification_invocation(&words)
1053 && !command_words_are_readonly(&words)
1054 && !is_literal_timer(&words))
1055 {
1056 return false;
1057 }
1058 }
1059 "file_redirect" => {
1060 return matches!(text, "2>&1" | "1>&2") || (cfg!(unix) && text == "2>/dev/null");
1063 }
1064 "word" | "regex" => return !contains_dynamic_shell_syntax(text) || is_literal_path_glob(text),
1065 "raw_string" | "string_content" | "comment" | "number" | "variable_name" | "special_variable_name" => {
1066 return true;
1067 }
1068 "simple_expansion" => return true,
1069 "expansion" => {
1070 if text.contains([':', '=', '+', '?', '!']) {
1073 return false;
1074 }
1075 }
1076 "program"
1077 | "list"
1078 | "pipeline"
1079 | "for_statement"
1080 | "do_group"
1081 | "if_statement"
1082 | "elif_clause"
1083 | "else_clause"
1084 | "while_statement"
1085 | "command_name"
1086 | "string"
1087 | "concatenation"
1088 | "command_substitution"
1089 | "redirected_statement" => {}
1090 _ if !node.is_named() => {
1091 return matches!(
1092 text,
1093 "&&" | "||"
1094 | ";"
1095 | "|"
1096 | "for"
1097 | "in"
1098 | "do"
1099 | "done"
1100 | "if"
1101 | "then"
1102 | "elif"
1103 | "else"
1104 | "fi"
1105 | "while"
1106 | "until"
1107 | "\""
1108 | "'"
1109 | "$("
1110 | ")"
1111 | "`"
1112 | "$"
1113 | "${"
1114 | "}"
1115 | "#"
1116 | "##"
1117 | "%"
1118 | "%%"
1119 );
1120 }
1121 _ => return false,
1122 }
1123 let mut cursor = node.walk();
1124 node.children(&mut cursor).all(|child| nonmutating_shell_node(child, source))
1125}
1126
1127#[cfg(test)]
1128mod tests {
1129 use serde_json::json;
1130
1131 use super::*;
1132 use crate::config::constants::tools;
1133 use crate::tools::tool_intent::is_readonly_command_session_command;
1134
1135 fn exec_command(command: &str) -> Value {
1136 json!({"cmd": command})
1137 }
1138
1139 #[test]
1140 fn literal_timers_do_not_create_mutation_debt_but_arbitrary_python_does() {
1141 let output = serde_json::json!({"exit_code":0});
1142 for command in [
1143 "python3 -c 'import time; time.sleep(0.01)'",
1144 "python -c 'import time; time.sleep(5)'",
1145 "sleep 30",
1146 "sleep 120",
1147 "sleep 0.01",
1148 ] {
1149 assert!(!exec_mutation_should_incur_debt(command, &output), "{command}");
1150 assert!(exec_mutation_should_incur_debt(command, &serde_json::json!({"modified_files":["src/lib.rs"]})));
1151 }
1152 for command in [
1153 "python3 -c 'import time; time.sleep(1); open(\"x\",\"w\")'",
1154 "python3 -c 'import time; time.sleep(float(\"nan\"))'",
1155 "python3 -c 'print(1)'",
1156 "python3 timer.py",
1157 "sleep $DELAY",
1158 "sleep 1 > timer.log",
1159 "sleep -1",
1160 "python3 -c 'import time; time.sleep(-1)'",
1161 "PYTHONSTARTUP=script.py python3 -c 'import time; time.sleep(1)'",
1162 "python3 -c 'import time; time.sleep(1)' > timer.log",
1163 ] {
1164 assert!(exec_mutation_should_incur_debt(command, &output), "{command}");
1165 }
1166 }
1167
1168 #[test]
1169 fn source_repair_commands_create_debt_instead_of_verifying() {
1170 for command in [
1171 "cargo clippy --fix --allow-dirty",
1172 "env LD_PRELOAD=./rewrite.so cargo clippy",
1173 "cargo +nightly clippy --fix",
1174 "cargo fix --allow-dirty",
1175 "ruff check --fix .",
1176 "ruff check --fix-only .",
1177 "ruff check --add-noqa .",
1178 "ruff check --add-ignore=reason .",
1179 "uv run --frozen --offline ruff check --fix .",
1180 "cargo clippy --fix && cargo check",
1181 "ruff check --fix . | head -20",
1182 "ruff check --fix --exclude --diff .",
1184 ] {
1185 let args = exec_command(command);
1186 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Mutation, "{command}");
1187 assert!(!shell_command_is_admitted_verification_attempt(&args), "{command}");
1188 assert!(exec_mutation_should_incur_debt(command, &json!({"exit_code": 0})), "{command}");
1189 }
1190 for command in [
1191 "cargo clippy --locked",
1192 "cargo nextest run fix",
1193 "ruff check --no-fix .",
1194 "ruff check --diff .",
1195 "uv run --frozen --offline ruff check --no-fix .",
1196 ] {
1197 let args = exec_command(command);
1198 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Verification, "{command}");
1199 assert!(shell_command_is_admitted_verification_attempt(&args), "{command}");
1200 assert!(!exec_mutation_should_incur_debt(command, &json!({"exit_code": 0})), "{command}");
1201 }
1202 }
1203
1204 #[test]
1205 fn compiler_artifact_writes_remain_eligible_verification() {
1206 let command = "rustc --crate-type lib sample.rs -o checked.rlib";
1207 let args = exec_command(command);
1208 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Verification);
1209 assert!(shell_command_is_admitted_verification_attempt(&args));
1210 assert!(exec_mutation_should_incur_debt(command, &json!({"exit_code":0})));
1213 }
1214
1215 #[test]
1216 fn verifier_diagnostics_recognize_masked_status_without_granting_admission() {
1217 for command in [
1218 "npx markdownlint-cli2 README.md; echo \"lint exit: $?\"",
1219 "cargo check; echo $?",
1220 "python3 scripts/check_markdown.py; echo \"lint exit: $?\"",
1221 "cargo check --locked || true",
1222 "cargo check; rm marker",
1223 ] {
1224 let args = exec_command(command);
1225 assert!(shell_command_contains_verifier(&args), "{command}");
1226 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Mutation);
1227 }
1228 let masked = exec_command("npx markdownlint-cli2 README.md; echo \"lint exit: $?\"");
1229 assert!(!shell_command_is_admitted_verification_attempt(&masked));
1230 assert_eq!(shell_args_as_executed(tools::EXEC_COMMAND, &masked).as_ref(), &masked);
1231 for args in [
1232 exec_command("echo 'cargo check; echo $?'"),
1233 exec_command("grep 'cargo check' README.md"),
1234 exec_command("npx markdownlint-cli2 --fix README.md"),
1235 json!({"cmd":"cargo check; true", "raw_command":"echo hello"}),
1236 json!({"cmd":"npx markdownlint-cli2", "args":["--fix", "README.md"]}),
1237 ] {
1238 assert!(!shell_command_contains_verifier(&args), "{args}");
1239 }
1240 }
1241
1242 #[test]
1243 fn markdownlint_verification_preserves_command_boundaries() {
1244 for command in [
1245 "markdownlint-cli2 README.md",
1246 "npx --yes markdownlint-cli2 README.md",
1247 "npx --no-install markdownlint-cli2@0.23.3 README.md",
1248 "npx --yes --loglevel=error markdownlint-cli2@0.23.3 --config .markdownlint-cli2.jsonc ':README.md'",
1249 "npx -y markdownlint-cli2 README.md && cargo check --locked",
1250 "python3 scripts/check_markdown.py",
1251 "python ./scripts/check_markdown.py",
1252 "python3 scripts/check_docs_links.py",
1253 "python ./scripts/check_docs_links.py",
1254 ] {
1255 assert!(shell_command_is_admitted_verification_attempt(&exec_command(command)), "{command}");
1256 assert_eq!(
1257 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1258 ShellActivity::Verification,
1259 "{command}"
1260 );
1261 }
1262 for command in [
1263 "markdownlint-cli2 --fix README.md",
1264 "npx --yes markdownlint-cli2 -f README.md",
1265 "npx --yes markdownlint-cli2 --fix=true README.md",
1266 "markdownlint-cli2 --version",
1267 "npx --package evil markdownlint-cli2 README.md",
1268 "npx --loglevel=error --package evil markdownlint-cli2 README.md",
1269 "npx --loglevel=error markdownlint-cli2 --fix README.md",
1270 "npx --loglevel=unknown markdownlint-cli2 README.md",
1271 "npx markdownlint-cli2@evil README.md",
1272 "npx markdownlint-cli2 README.md && rm README.md",
1273 "python3 scripts/check_markdown.py --fix",
1274 "python3 scripts/check_markdown.py --list",
1275 "python3 scripts/check_markdown.py --help",
1276 "python3 other/check_markdown.py",
1277 "python3 scripts/check_docs_links.py --help",
1278 "python3 other/check_docs_links.py",
1279 ] {
1280 assert!(!shell_command_is_admitted_verification_attempt(&exec_command(command)), "{command}");
1281 }
1282 assert_ne!(
1283 classify_shell_activity(tools::EXEC_COMMAND, &exec_command("npx markdownlint-cli2 README.md | grep error")),
1284 ShellActivity::Verification
1285 );
1286 }
1287
1288 #[test]
1289 fn output_search_recognizes_static_search_pipelines() {
1290 for command in [
1291 "rg --files --hidden -g '.markdownlint*'",
1292 "rg --files --hidden | rg -i 'markdownlint' | sed -n '1,15p'",
1293 "git ls-files | grep -i markdownlint | head -10",
1294 "LANG=C /usr/bin/grep -n missing README.md",
1295 "rg -- '-q' README.md",
1296 "rg -e -query src | head -10",
1297 "grep -ne-query README.md",
1298 "rg --regexp --quiet src",
1299 "rg -g '-q*' missing src",
1300 "rg '-g-q*' missing src",
1301 "rg -q --no-quiet missing src",
1302 ] {
1303 assert!(shell_command_is_output_search(&exec_command(command)), "{command}");
1304 }
1305 assert!(shell_command_is_output_search(&json!({"command": ["rg", "missing", "src"]})));
1306 }
1307
1308 #[test]
1309 fn output_search_excludes_quiet_probes_and_unproven_commands() {
1310 for command in [
1311 "rg -q pattern src",
1312 "grep -nq pattern README.md",
1313 "rg --quiet pattern src | head -10",
1314 "grep --silent pattern README.md",
1315 "rg -e -query -q src",
1316 "grep -nqe-query README.md",
1317 "rg --regexp --quiet --quiet src",
1318 "rg -q --no-quiet -q missing src",
1319 "echo 'rg missing'",
1320 "cat empty.txt",
1321 "cargo check | rg error",
1322 "rg missing src; touch result.txt",
1323 "rg missing $(pwd)",
1324 "rg missing src > result.txt",
1325 "rg --pre 'touch result.txt' missing src",
1326 ] {
1327 assert!(!shell_command_is_output_search(&exec_command(command)), "{command}");
1328 }
1329 assert!(!shell_command_is_output_search(&json!({})));
1330 }
1331
1332 #[test]
1333 fn output_search_distinguishes_separator_values_from_quiet_flags() {
1334 for option in [
1335 "--context-separator",
1336 "--field-context-separator",
1337 "--field-match-separator",
1338 ] {
1339 let command = format!("rg {option} -q missing src | head -10");
1340 assert!(shell_command_is_output_search(&exec_command(&command)), "{command}");
1341 let quiet_command = format!("rg {option} -q --quiet missing src | head -10");
1342 assert!(!shell_command_is_output_search(&exec_command(&quiet_command)), "{quiet_command}");
1343 }
1344 }
1345
1346 #[test]
1347 fn standalone_grep_search_preserves_exit_status_ownership() {
1348 for command in [
1349 "rg missing src",
1350 "grep -q missing README.md",
1351 "LANG=C /usr/bin/grep -n missing README.md",
1352 "rg 'a|b' src",
1353 "fgrep missing README.md",
1354 ] {
1355 assert!(shell_command_is_standalone_grep_search(&exec_command(command)), "{command}");
1356 }
1357 assert!(shell_command_is_standalone_grep_search(&json!({"command": ["rg", "missing", "src"]})));
1358 for command in [
1359 "rg missing src; false",
1360 "rg missing src && false",
1361 "rg missing src | grep other",
1362 "! rg missing src",
1363 "(rg missing src)",
1364 "echo '/rg missing'; false",
1365 "rg missing src 2>/dev/null",
1366 "rg missing src 2>&1",
1367 "rg missing $(pwd)",
1368 "rg --pre 'false' missing src",
1369 ] {
1370 assert!(!shell_command_is_standalone_grep_search(&exec_command(command)), "{command}");
1371 }
1372 }
1373
1374 #[test]
1375 fn admitted_verification_attempt_allows_truncation_but_blocks_smuggled_mutations() {
1376 for command in [
1377 "cargo check --locked 2>&1 | head -c 4000",
1378 "cargo check --locked",
1379 "cargo nextest run 2>&1 | head -c 4000",
1380 ] {
1381 assert!(
1382 shell_command_is_admitted_verification_attempt(&exec_command(command)),
1383 "expected admission: {command}"
1384 );
1385 }
1386 for command in [
1387 "cargo check && rm -rf target",
1388 "cargo check; rm foo.txt",
1389 "cargo check || rm foo.txt",
1390 "cargo check && cargo test && rm foo.txt",
1391 "sed -i '' 's/old/new/' README.md",
1392 "echo $(date)",
1393 "cargo check > build.log && rm foo.txt",
1394 ] {
1395 assert!(
1396 !shell_command_is_admitted_verification_attempt(&exec_command(command)),
1397 "expected block: {command}"
1398 );
1399 }
1400 assert!(!shell_command_is_admitted_verification_attempt(&json!({})));
1401 }
1402
1403 #[test]
1404 fn logged_compound_inspection_commands_are_not_mutations() {
1405 for command in [
1406 "cat README.md && printf '\\n--- git status ---\\n' && git status --short",
1407 "wc -l README.md; rg -n '^#' README.md",
1408 "git diff --stat; find docs -maxdepth 2 -type f | sort | head -40",
1409 ] {
1410 assert_eq!(
1411 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1412 ShellActivity::Inspection,
1413 "{command}"
1414 );
1415 }
1416 }
1417
1418 #[cfg(unix)]
1419 #[test]
1420 fn captured_read_commands_with_output_suppression_are_inspection() {
1421 for command in [
1422 r#"sed -n '1,180p' README.md; sed -n '280,350p' README.md; sed -n '389,411p' README.md; printf '\n--- repo metadata ---\n'; git log -1 --format='%h %s'; sed -n '1,100p' Cargo.toml; rg -n '^version\s*=|rust-version|workspace\.package' Cargo.toml crates -g Cargo.toml | head -40"#,
1423 r#"sed -n '1,120p' crates/codegen/vtcode-core/src/tools/tool_intent/activity.rs; printf '\n--- readonly policy ---\n'; rg -n 'READONLY_UNIFIED_EXEC_COMMANDS|command_words_are_readonly' crates/codegen/vtcode-core/src/tools/tool_intent/readonly.rs; printf '\n--- recent commits ---\n'; git log -5 --oneline; printf '\n--- command arguments ---\n'; sed -n '1,180p' crates/codegen/vtcode-core/src/tools/command_args.rs"#,
1424 r###"git diff --stat; find docs -maxdepth 2 -type f | sort | head -40; rg -n "vtcode init|vtcode models|full-auto|run-debug|cargo install" docs/user-guide docs/installation docs/development 2>/dev/null | head -50"###,
1425 ] {
1426 assert_eq!(
1427 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1428 ShellActivity::Inspection,
1429 "{command}"
1430 );
1431 }
1432 }
1433
1434 #[cfg(unix)]
1435 #[test]
1436 fn printf_output_safety_guards_remain_mutations() {
1437 for command in [
1438 "printf 'captured output\\n' > output.txt",
1439 "printf '%s\\n' \"$(git status --short)\"",
1440 "printf '%s\\n' `git status --short`",
1441 "printf '\\n--- inspection ---\\n' && rm output.txt",
1442 ] {
1443 let args = exec_command(command);
1444 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Mutation, "{command}");
1445 assert!(!is_readonly_command_session_command(&args), "unexpected readonly command: {command}");
1446 }
1447 }
1448
1449 #[test]
1450 fn git_diff_check_chain_remains_inspection() {
1451 assert_eq!(
1452 classify_shell_activity(
1453 tools::EXEC_COMMAND,
1454 &exec_command("git diff --check && git status --short && git diff --stat"),
1455 ),
1456 ShellActivity::Inspection
1457 );
1458 }
1459
1460 #[test]
1461 fn verification_detection_skips_environment_prefixes() {
1462 for command in [
1463 "env RUSTFLAGS=-Dwarnings cargo check",
1464 "RUSTFLAGS=-Dwarnings env cargo check",
1465 "env -u PATH cargo check",
1466 "env -C /tmp cargo check",
1467 ] {
1468 assert_eq!(
1469 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1470 ShellActivity::Verification,
1471 "{command}"
1472 );
1473 }
1474 }
1475
1476 #[test]
1477 fn ambiguous_or_mutating_compounds_remain_mutations() {
1478 for command in [
1479 "git diff --stat; python3 -c 'open(\"out\", \"w\").write(\"x\")'",
1480 "cat README.md; sed -i '' 's/a/b/' README.md",
1481 "sed --in-place= README.md",
1482 "git diff --output=out",
1483 "git diff '--output=out'",
1484 "git diff -o out",
1485 "git diff -oout",
1486 "git log --output=out",
1487 "git show --textconv",
1488 "git -c core.fsmonitor=touch status",
1492 "find . -fprint output.txt",
1493 "find . -fprintf output.txt '%p'",
1494 "rg --hostname-bin sh pattern",
1495 "rg --search-zip pattern",
1496 "rg -z pattern",
1497 "sort -o generated.txt README.md",
1498 "sort --compress-program=sh README.md",
1499 "date -s now",
1500 "awk -i inplace '{print}' README.md",
1501 "sed -n 's/a/b/e' README.md",
1502 "fd --exec sh -c 'touch output'",
1503 "tree -o output.txt",
1504 "ast-grep -r 'README.md'",
1505 "sed -n -fmalicious.sed -e '1p' src/main.rs",
1506 "sed -I '' 's/a/b/' src/main.rs",
1507 "sed -n '1p\nw leaked.txt' src/main.rs",
1508 "cargo check & rm output",
1509 "cargo check > build.log | rm output",
1510 "cargo check | head -40 > build.log",
1511 "cargo check | echo x > output.log",
1512 "cargo check | head -40",
1513 "cargo check > build.log &",
1514 "env -S 'cargo check'",
1515 "echo x > output.log && cargo check",
1516 "cargo check < build-input.log",
1517 "cat README.md > copied.txt",
1518 "git diff --check; rm output",
1519 "cat README.md\nrm output",
1520 ] {
1521 assert_eq!(
1522 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1523 ShellActivity::Mutation,
1524 "{command}"
1525 );
1526 }
1527 }
1528
1529 #[test]
1530 fn quoted_output_text_does_not_change_inspection_classification() {
1531 for command in ["echo 'git diff --output=out'", "printf 'sort -o out input'"] {
1532 assert_eq!(
1533 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1534 ShellActivity::Inspection,
1535 "{command}"
1536 );
1537 }
1538 }
1539
1540 #[test]
1541 fn cargo_fmt_check_is_verification_but_plain_fmt_is_not() {
1542 for command in [
1543 "cargo fmt --check",
1544 "cargo fmt --all -- --check",
1545 "cargo fmt -- --check",
1546 ] {
1547 assert_eq!(
1548 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1549 ShellActivity::Verification,
1550 "{command}"
1551 );
1552 assert!(
1553 shell_command_is_admitted_verification_attempt(&exec_command(command)),
1554 "expected admission: {command}"
1555 );
1556 }
1557 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &exec_command("cargo fmt")), ShellActivity::Mutation);
1560 assert!(!shell_command_is_admitted_verification_attempt(&exec_command("cargo fmt")));
1561 }
1562
1563 #[test]
1564 fn pure_and_chained_verifiers_are_verification() {
1565 for command in [
1566 "cargo fmt --all -- --check && cargo check --locked",
1567 "cargo check --locked && cargo nextest run --locked -p vtcode-ui",
1568 "cargo check --locked && cargo clippy --locked -p vtcode-ui -- -D warnings",
1569 "git diff --check && cargo check --locked",
1570 ] {
1571 assert_eq!(
1572 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1573 ShellActivity::Verification,
1574 "{command}"
1575 );
1576 assert!(
1577 shell_command_is_admitted_verification_attempt(&exec_command(command)),
1578 "expected admission: {command}"
1579 );
1580 }
1581 }
1582
1583 #[test]
1584 fn non_and_chained_verifiers_remain_mutations() {
1585 for command in [
1586 "cargo check --locked; cargo nextest run --locked -p vtcode-ui",
1587 "cargo check --locked || cargo nextest run --locked -p vtcode-ui",
1588 "cargo check --locked | head -40",
1589 "cargo check --locked && cargo nextest run --locked -p vtcode-ui | head -40",
1590 "cargo check --locked &",
1591 ] {
1592 assert_eq!(
1593 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1594 ShellActivity::Mutation,
1595 "{command}"
1596 );
1597 }
1598 }
1599
1600 #[test]
1601 fn expanded_verifiers_classify_as_verification() {
1602 for command in [
1603 "bun test",
1604 "bun run test",
1605 "deno lint",
1606 "deno check mod.ts",
1607 "make test",
1608 "make lint",
1609 "just verify",
1610 "ruff check src/",
1611 "ruff format --check",
1612 "tsc --noEmit",
1613 "eslint src/",
1614 "python3 -m pytest",
1615 "uv run pytest",
1616 "npm run lint",
1617 ] {
1618 assert_eq!(
1619 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1620 ShellActivity::Verification,
1621 "{command}"
1622 );
1623 }
1624 for command in [
1625 "make clean",
1626 "make test clean",
1627 "just fmt",
1628 "tsc",
1629 "eslint --fix src/",
1630 "ruff format src/",
1631 "bun install",
1632 "uv sync",
1633 ] {
1634 assert_eq!(
1635 classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1636 ShellActivity::Mutation,
1637 "{command}"
1638 );
1639 }
1640 }
1641
1642 #[test]
1643 fn escaped_quotes_fail_closed_instead_of_hiding_operators() {
1644 assert!(!shell_uses_only_and_chaining("cargo check --locked \\\"; echo ok"));
1648 assert!(!shell_uses_only_and_chaining("echo \\\" ; cargo check --locked && echo done"));
1649 assert!(shell_uses_only_and_chaining("echo \"a\\\"b\" && cargo check --locked"));
1651 assert!(shell_uses_only_and_chaining("echo \"path\" && cargo fmt --check"));
1652 assert!(shell_uses_only_and_chaining("echo 'a\\b' && cargo check --locked"));
1654 }
1655
1656 #[test]
1657 fn default_verifier_prefers_manifest_priority_order() {
1658 let dir = tempfile::tempdir().expect("tempdir");
1659 assert_eq!(default_verifier_for_workspace(dir.path()), None);
1660
1661 std::fs::write(dir.path().join("justfile"), "test:\n\techo ok\n").expect("justfile");
1662 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("just test"));
1663 std::fs::write(dir.path().join("pyproject.toml"), "[tool.pytest]\n").expect("pyproject");
1664 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("pytest -q"));
1665 std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"test":"vitest"}}"#).expect("package.json");
1666 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm test"));
1667 std::fs::write(dir.path().join("go.mod"), "module example\n").expect("go.mod");
1668 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("go test ./..."));
1669 std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").expect("Cargo.toml");
1670 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("cargo check --locked"));
1671 }
1672
1673 #[test]
1674 fn default_verifier_marker_aliases_and_tier_priority() {
1675 for (marker, expected) in [
1679 ("Justfile", "just test"),
1680 ("makefile", "make test"),
1681 ("bun.lock", "bun test"),
1682 ("deno.jsonc", "deno test"),
1683 ] {
1684 let dir = tempfile::tempdir().expect("tempdir");
1685 std::fs::write(dir.path().join(marker), "x\n").expect(marker);
1686 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some(expected), "{marker}");
1687 }
1688 let dir = tempfile::tempdir().expect("tempdir");
1690 std::fs::write(dir.path().join("bun.lockb"), "x\n").expect("bun.lockb");
1691 std::fs::write(dir.path().join("deno.json"), "{}\n").expect("deno.json");
1692 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("deno test"));
1693 std::fs::write(dir.path().join("go.mod"), "module example\n").expect("go.mod");
1694 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("go test ./..."));
1695 let dir = tempfile::tempdir().expect("tempdir");
1697 std::fs::write(dir.path().join("pyproject.toml"), "[tool.pytest]\n").expect("pyproject");
1698 std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"test":"vitest"}}"#).expect("package.json");
1699 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm test"));
1700 let dir = tempfile::tempdir().expect("tempdir");
1702 std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"start":"serve"}}"#).expect("package.json");
1703 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm test"));
1704 }
1705
1706 #[test]
1707 fn default_verifier_reads_npm_script_fallbacks() {
1708 let dir = tempfile::tempdir().expect("tempdir");
1709 std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"lint":"eslint ."}}"#).expect("package.json");
1710 assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm run lint"));
1711 }
1712
1713 #[test]
1714 fn verification_recovery_directive_names_concrete_command() {
1715 let directive = verification_recovery_directive(Some("go test ./..."), 1, 2);
1716 assert!(directive.contains("go test ./..."));
1717 assert!(directive.contains("1/2"));
1718 assert!(directive.contains("edits remain available"));
1719 assert!(directive.contains("only missing checks"));
1720 assert!(!directive.contains("mutations are blocked"));
1721 assert!(directive.contains("max_output_tokens"));
1722 assert!(directive.contains(VERIFIER_SHELL_FORM_NOTE));
1723 assert!(directive.contains("tails run standalone"));
1724 assert!(directive.contains("fail-closed `pipefail`"));
1725 let fallback = verification_recovery_directive(None, 2, 2);
1726 assert!(fallback.contains(GENERIC_VERIFIER_DESCRIPTION));
1727 assert!(fallback.contains("2/2"));
1728 }
1729
1730 #[test]
1731 fn verifier_reference_names_resolved_command_or_generic_description() {
1732 assert_eq!(verifier_reference(Some("go test ./...")), "`go test ./...`");
1733 assert_eq!(verifier_reference(Some(" npm test ")), "`npm test`");
1734 for missing in [None, Some(""), Some(" ")] {
1735 let reference = verifier_reference(missing);
1736 assert_eq!(reference, GENERIC_VERIFIER_DESCRIPTION);
1737 assert!(!reference.starts_with('`'), "no single command is named: {reference}");
1738 for ecosystem in ["cargo check --locked", "go test ./...", "npm test", "pytest -q"] {
1739 assert!(reference.contains(ecosystem), "missing {ecosystem}: {reference}");
1740 }
1741 }
1742 }
1743
1744 #[test]
1745 fn truncation_only_verifier_rewrites_to_standalone_prefix() {
1746 for (command, expected) in [
1747 ("cargo check --locked 2>&1 | head -c 4000", "cargo check --locked 2>&1"),
1748 ("cargo check --locked -p vtcode 2>&1 | tail -20", "cargo check --locked -p vtcode 2>&1"),
1749 ("cargo nextest run 2>&1 | tail -15", "cargo nextest run 2>&1"),
1750 (
1751 "cargo check --locked && cargo nextest run --locked -p vtcode | tail -5",
1752 "cargo check --locked && cargo nextest run --locked -p vtcode",
1753 ),
1754 ("cargo check | tail -5 | head -20", "cargo check"),
1755 ("RUSTFLAGS=-Dwarnings cargo check | head -20", "RUSTFLAGS=-Dwarnings cargo check"),
1756 ("cargo check > build.log | tail -5", "cargo check > build.log"),
1760 ] {
1761 assert_eq!(
1762 rewrite_truncation_only_verifier(&exec_command(command)).as_deref(),
1763 Some(expected),
1764 "expected rewrite: {command}"
1765 );
1766 }
1767 }
1768
1769 #[test]
1770 fn non_truncation_pipelines_and_mutations_are_never_rewritten() {
1771 for command in [
1775 "cargo check | grep error",
1776 "cargo check | wc -l",
1777 "cargo check | sort | uniq",
1778 "cargo check && rm -rf target | tail -5",
1779 "cargo check; git status | tail -5",
1780 "cargo check || cargo test | tail -5",
1781 "cargo check | tail -5; rm foo.txt",
1782 "cargo check | tail &",
1783 "cargo check",
1784 "echo done | tail -5",
1785 "rg -n 'pattern' src | head -20",
1786 "echo $(date) | tail -5",
1787 ] {
1788 assert_eq!(rewrite_truncation_only_verifier(&exec_command(command)), None, "must not rewrite: {command}");
1789 }
1790 assert_eq!(
1791 rewrite_truncation_only_verifier(&serde_json::json!({"command": ["cargo", "check", "|", "tail"]})),
1792 None,
1793 "array-form commands keep today's behavior"
1794 );
1795 assert_eq!(rewrite_truncation_only_verifier(&serde_json::json!({})), None);
1796 }
1797
1798 #[test]
1799 fn args_as_executed_classify_elided_truncation_verifiers_as_verification() {
1800 for command in [
1801 "cargo check --locked 2>&1 | tail -5",
1802 "cargo nextest run 2>&1 | head -c 4000",
1803 ] {
1804 let typed = exec_command(command);
1805 let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1806 assert!(matches!(executed, std::borrow::Cow::Owned(_)), "expected rewrite: {command}");
1807 assert_eq!(
1808 classify_shell_activity(tools::EXEC_COMMAND, &executed),
1809 ShellActivity::Verification,
1810 "{command}"
1811 );
1812 assert!(matches!(shell_args_as_executed(tools::EXEC_COMMAND, &executed), std::borrow::Cow::Borrowed(_)));
1814 }
1815
1816 let unified = json!({"action": "run", "command": "cargo check 2>&1 | tail -5"});
1817 assert_eq!(shell_args_as_executed(tools::UNIFIED_EXEC, &unified)["command"], "cargo check 2>&1");
1818 }
1819
1820 #[test]
1821 fn verifier_rewrite_keeps_raw_alias_and_appended_arguments_in_sync() {
1822 let command = "cargo check | grep";
1823 let typed = json!({"cmd":command, "raw_command":command, "args":["warning"]});
1824 let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1825 let expected = "set -o pipefail && cargo check | grep warning";
1826 assert_eq!(executed["command"], expected);
1827 assert_eq!(executed["raw_command"], expected);
1828 assert!(executed.get("args").is_none(), "suffix must execute exactly once");
1829 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &executed), ShellActivity::Verification);
1830 assert!(matches!(shell_args_as_executed(tools::EXEC_COMMAND, &executed), std::borrow::Cow::Borrowed(_)));
1831
1832 let truncator = json!({"cmd":"cargo check | head", "args":["-20"]});
1833 assert_eq!(shell_args_as_executed(tools::EXEC_COMMAND, &truncator)["command"], "cargo check");
1834 }
1835
1836 #[test]
1837 fn verifier_pipeline_rejects_conflicting_raw_alias_and_mutating_suffix() {
1838 for typed in [
1839 json!({"cmd":"cargo check | grep marker", "raw_command":"printf marker"}),
1840 json!({"cmd":"cargo check | sort", "args":["-o", "changed.txt"]}),
1841 json!({"cmd":"set -o pipefail && cargo check | sort", "args":["-o", "changed.txt"]}),
1842 json!({"cmd":"cargo check | grep", "args":"invalid"}),
1843 ] {
1844 assert_eq!(rewrite_verifier_pipeline(&typed), None, "{typed}");
1845 assert!(!shell_command_is_admitted_verification_attempt(&typed), "{typed}");
1846 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &typed), ShellActivity::Mutation, "{typed}");
1847 assert!(super::super::classify_tool_intent(tools::EXEC_COMMAND, &typed).mutating, "{typed}");
1848 }
1849 }
1850
1851 #[test]
1852 fn filtered_verifier_pipeline_preserves_filters_and_truthful_status() {
1853 for command in [
1854 "python3 scripts/check_markdown.py 2>&1 | grep -E '^(README|docs/SECURITY)\\.md' | head -20",
1855 "cargo check --locked | grep warning",
1856 "cargo fmt --check && cargo check --locked | wc -l",
1857 ] {
1858 let typed = exec_command(command);
1859 let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1860 assert_eq!(executed["command"], format!("set -o pipefail && {command}"));
1861 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &executed), ShellActivity::Verification);
1862 assert!(shell_command_is_admitted_verification_attempt(&executed));
1863 assert!(matches!(shell_args_as_executed(tools::EXEC_COMMAND, &executed), std::borrow::Cow::Borrowed(_)));
1864 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &typed), ShellActivity::Mutation);
1865 }
1866 for command in [
1867 "cargo check | grep error; true",
1868 "cargo check | grep error || true",
1869 "cargo check | tee source.rs",
1870 "cargo check | sed -i 's/old/new/' source.rs",
1871 "cargo check | grep $(touch marker)",
1872 "cargo check | grep error > hidden.log",
1873 "cargo check | grep error &",
1874 "cargo check && rm source.rs | grep error",
1875 ] {
1876 assert_eq!(rewrite_verifier_pipeline(&exec_command(command)), None, "{command}");
1877 let prefixed = exec_command(&format!("set -o pipefail && {command}"));
1878 assert_ne!(
1879 classify_shell_activity(tools::EXEC_COMMAND, &prefixed),
1880 ShellActivity::Verification,
1881 "{command}"
1882 );
1883 }
1884 }
1885
1886 #[test]
1887 fn args_as_executed_keep_unsafe_joins_and_non_run_calls_as_typed() {
1888 for command in [
1889 "cargo check 2>&1 | grep error; true",
1890 "cargo check; git status",
1891 "cargo check || true",
1892 ] {
1893 let typed = exec_command(command);
1894 let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1895 assert!(matches!(executed, std::borrow::Cow::Borrowed(_)), "must run as typed: {command}");
1896 assert_ne!(
1897 classify_shell_activity(tools::EXEC_COMMAND, &executed),
1898 ShellActivity::Verification,
1899 "{command}"
1900 );
1901 }
1902 let poll = json!({"action": "poll", "session_id": "s1", "command": "cargo check | tail -5"});
1903 assert!(matches!(shell_args_as_executed(tools::UNIFIED_EXEC, &poll), std::borrow::Cow::Borrowed(_)));
1904 let read = json!({"path": "src/lib.rs"});
1905 assert!(matches!(shell_args_as_executed(tools::READ_FILE, &read), std::borrow::Cow::Borrowed(_)));
1906 }
1907
1908 #[test]
1909 fn path_glob_inspections_preserve_debt_without_weakening_admission() {
1910 let clean = json!({"exit_code":0});
1911 for command in [
1912 "rg -n \"MD013|line_length\" docs/development/*.md | head",
1913 "rg -n x ./docs/file?.md | head -20",
1914 "grep -n x docs/*.md",
1915 "cat ./docs/*.md",
1916 "ls docs/*.md",
1917 ] {
1918 assert!(!exec_mutation_should_incur_debt(command, &clean), "{command}");
1919 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)), ShellActivity::Mutation);
1920 assert!(exec_mutation_should_incur_debt(command, &json!({"exit_code":0,"modified_files":["src/lib.rs"]})));
1921 }
1922 for command in [
1923 "rg -n x *",
1924 "rg -n x ./docs/[a-z]*.md",
1925 "rg -n x -docs/*.md",
1926 "rg -n x $dir/*.md",
1927 "rg --pre touch docs/*.md",
1928 "rg --hostname-bin=touch docs/*.md",
1929 "sed docs/*.md",
1930 "sort -o marker docs/*.md",
1931 "./tools/* --version",
1932 "rg x docs/$(touch marker)/*.md",
1933 "rg x docs/*.md > marker",
1934 "rg x docs/*.md; touch marker",
1935 "rg x docs/*.md; if",
1936 "rg x docs*/*.md",
1937 ] {
1938 assert!(exec_mutation_should_incur_debt(command, &clean), "{command}");
1939 }
1940 }
1941
1942 #[test]
1943 fn mutation_accounting_rejects_unproven_shell_forms() {
1944 let output = json!({"exit_code": 0});
1945 for command in [
1946 "echo \"$(touch marker)\"",
1947 "echo \"`touch marker`\"",
1948 "for p in $(echo $(touch marker)); do test -f \"$p\"; done",
1949 "for p in a; do sed -i '' 's/a/b/' README.md; done",
1950 "for p in a; do sort -o README.md README.md; done",
1951 "echo x 2>/dev/null.backup",
1952 "echo x 2>&1>marker",
1953 "cat <(touch marker)",
1954 "$program --version",
1955 "\"$(echo rm)\" marker",
1956 "grep $options README.md",
1957 "if true; then touch marker; fi",
1958 "for p in a; do echo x",
1959 "echo $(",
1960 "echo hi &",
1961 "sed -n '1p' README.md > marker",
1962 "echo ${x:=value}",
1963 ] {
1964 assert!(exec_mutation_should_incur_debt(command, &output), "{command}");
1965 }
1966 for command in [
1967 "echo '>'",
1968 "echo '2>/dev/null.backup'",
1969 "echo \"$(grep -n x README.md)\"",
1970 ] {
1971 assert!(!exec_mutation_should_incur_debt(command, &output), "{command}");
1972 }
1973 }
1974
1975 #[test]
1976 fn dynamic_readonly_inspections_do_not_incur_mutation_debt() {
1977 let clean_output = json!({"success": true, "exit_code": 0});
1978 for command in [
1985 "for p in $(grep -o '](\\./[^)#]*' README.md | sed 's/](//' | sort -u); do test -f \"$p\" || echo \"missing: $p\"; done; echo \"check done\"",
1986 "for p in $(grep -o '](\\./[^)#]*' README.md | sed 's/](\\.\\///' | sort -u); do test -f \"docs/${p#docs/}\" 2>/dev/null || echo \"missing: $p\"; done",
1987 "rg -n 'vinhnx/(VTCode|vtcode)' README.md",
1988 "grep -n '^## ' README.md",
1989 "ls docs/guides/zed-acp.md",
1990 "git diff --stat -- README.md",
1991 "git status --short",
1992 "npx markdownlint-cli2 README.md",
1993 "cargo check --locked",
1994 ] {
1995 let expected = if command.starts_with("npx markdownlint") || command.starts_with("cargo check") {
1996 ShellActivity::Verification
1997 } else if command.starts_with("for") {
1998 ShellActivity::Mutation
1999 } else {
2000 ShellActivity::Inspection
2001 };
2002 assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)), expected, "{command}");
2003 assert!(!exec_mutation_should_incur_debt(command, &clean_output), "{command}");
2004 }
2005 assert!(!exec_mutation_should_incur_debt(
2007 "for p in $(grep -o 'x' README.md); do test -f \"$p\" || echo \"missing: $p\"; done",
2008 &clean_output,
2009 ));
2010 assert!(!exec_mutation_should_incur_debt("rg -n 'x' README.md", &clean_output));
2011 assert!(!exec_mutation_should_incur_debt("grep -n 'x' README.md", &clean_output));
2012 assert!(!exec_mutation_should_incur_debt("git status --short", &clean_output));
2013 assert!(exec_mutation_should_incur_debt(
2015 "for p in $(grep -o 'x' README.md); do test -f \"$p\" || echo \"missing: $p\"; done",
2016 &json!({"success": true, "exit_code": 0, "modified_files": ["README.md"]}),
2017 ));
2018 assert!(exec_mutation_should_incur_debt("echo hi > README.md", &clean_output));
2020 assert!(exec_mutation_should_incur_debt("for f in a b; do echo x > \"$f\"; done", &clean_output));
2021 assert!(exec_mutation_should_incur_debt("rm -rf target", &clean_output));
2023 assert!(exec_mutation_should_incur_debt("rm $f", &clean_output));
2025 assert!(!exec_mutation_should_incur_debt("rg -n 'x' README.md 2>&1", &clean_output));
2027 assert!(exec_mutation_should_incur_debt("npx markdownlint-cli2 --fix README.md", &clean_output));
2030 assert!(!exec_mutation_should_incur_debt("npx markdownlint-cli2 README.md", &clean_output));
2031 assert!(exec_mutation_should_incur_debt("cargo fmt", &clean_output));
2032 assert!(!exec_mutation_should_incur_debt("cargo fmt --check", &clean_output));
2033 assert!(exec_mutation_should_incur_debt("tsc", &clean_output));
2034 assert!(!exec_mutation_should_incur_debt("tsc --noEmit", &clean_output));
2035 assert!(exec_mutation_should_incur_debt("git diff $x", &clean_output));
2037 assert!(exec_mutation_should_incur_debt("git checkout $x", &clean_output));
2038 assert!(!exec_mutation_should_incur_debt("grep -n 'x' README.md; echo \"exit:$?\"", &clean_output,));
2040 }
2041}