vtcode_core/tools/tool_intent/activity/
verifier.rs1use super::*;
2
3fn make_like_verification_targets(words: &[String]) -> bool {
4 let mut saw_target = false;
5 for word in words.iter().skip(1) {
6 let lower = word.to_ascii_lowercase();
7 if lower.starts_with('-') || lower.contains('=') {
8 continue;
9 }
10 if !matches!(lower.as_str(), "test" | "tests" | "check" | "checks" | "lint" | "verify" | "validate") {
11 return false;
12 }
13 saw_target = true;
14 }
15 saw_target
16}
17
18fn python_verification_arguments(arguments: &[String]) -> bool {
19 let mut arguments = arguments.iter();
21 let target = arguments.find(|word| {
22 !matches!(word.as_str(), "-I" | "-E" | "-s" | "-S" | "-B" | "-O" | "-OO" | "-q" | "-u" | "-b" | "-bb" | "-v")
23 });
24 match target.map(String::as_str) {
25 Some("-m") => arguments.next().is_some_and(|module| module == "pytest"),
26 Some(script) => {
27 ["scripts/check_markdown.py", "scripts/check_docs_links.py"]
31 .iter()
32 .any(|known| Path::new(script).ends_with(known))
33 && arguments.all(|argument| !argument.starts_with('-'))
34 }
35 None => false,
36 }
37}
38
39pub(super) fn is_verification_invocation(words: &[String]) -> bool {
40 if crate::tools::command_args::command_uses_source_repair(words)
43 || crate::tools::command_args::environment_prefix_has_injection_keys(words)
44 {
45 return false;
46 }
47 let command_words = crate::tools::command_args::command_words_after_environment_prefix(words);
48 let first = command_words.first().map(String::as_str).unwrap_or_default();
49 let second = command_words.get(1).map(|word| word.to_ascii_lowercase());
50 let third = command_words.get(2).map(|word| word.to_ascii_lowercase());
51 let program = Path::new(first)
52 .file_name()
53 .and_then(|name| name.to_str())
54 .unwrap_or(first)
55 .to_ascii_lowercase();
56
57 match program.as_str() {
58 "markdownlint-cli2" => command_words.get(1..).is_some_and(markdownlint_arguments_verify),
59 "npx" => {
60 let package_index = command_words
61 .iter()
62 .enumerate()
63 .skip(1)
64 .find(|(_, word)| {
65 !matches!(word.as_str(), "--yes" | "-y" | "--no-install")
66 && !word.strip_prefix("--loglevel=").is_some_and(|level| {
67 matches!(
68 level,
69 "silent" | "error" | "warn" | "notice" | "http" | "info" | "verbose" | "silly"
70 )
71 })
72 })
73 .map(|(index, _)| index);
74 package_index.is_some_and(|index| {
75 let Some(package) = command_words.get(index) else {
76 return false;
77 };
78 let is_markdownlint = package == "markdownlint-cli2"
79 || package.strip_prefix("markdownlint-cli2@").is_some_and(|version| {
80 version.split('.').count() == 3
81 && version
82 .split('.')
83 .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
84 });
85 is_markdownlint && command_words.get(index + 1..).is_some_and(markdownlint_arguments_verify)
86 })
87 }
88 "cargo" => {
89 if second.as_deref() == Some("fmt") {
90 return words.iter().any(|word| word == "--check");
93 }
94 matches!(second.as_deref(), Some("check" | "build" | "clippy" | "test"))
95 || (second.as_deref() == Some("nextest") && third.as_deref() == Some("run"))
96 }
97 "go" => matches!(second.as_deref(), Some("test" | "build")),
98 "npm" | "pnpm" | "yarn" => {
99 matches!(second.as_deref(), Some("test" | "build" | "lint" | "check"))
100 || (second.as_deref() == Some("run")
101 && matches!(third.as_deref(), Some("test" | "build" | "lint" | "check")))
102 }
103 "bun" | "bunx" => {
104 matches!(second.as_deref(), Some("test"))
105 || (second.as_deref() == Some("run")
106 && matches!(third.as_deref(), Some("test" | "build" | "lint" | "check")))
107 }
108 "deno" => matches!(second.as_deref(), Some("test" | "lint" | "check")),
109 "make" | "gmake" | "just" => make_like_verification_targets(command_words),
110 "uv" => {
111 let Some(arguments) = crate::tools::command_args::uv_run_command_words(command_words) else {
112 return false;
113 };
114 let mut arguments = arguments.iter();
115 let target = arguments.next();
116 match target.map(String::as_str) {
117 Some("pytest") => true,
118 Some("ruff") => arguments.next().is_some_and(|argument| argument == "check"),
119 Some("python" | "python3") => python_verification_arguments(arguments.as_slice()),
120 _ => false,
121 }
122 }
123 "ruff" => {
124 if second.as_deref() == Some("format") {
125 return words.iter().any(|word| word == "--check");
126 }
127 matches!(second.as_deref(), Some("check" | "lint"))
128 }
129 "tsc" => {
130 words.iter().any(|word| word == "--noEmit")
132 }
133 "eslint" => {
134 !words.iter().any(|word| word == "--fix" || word == "--fix-dry-run")
136 }
137 "rustc" | "pytest" | "xcodebuild" | "gradle" | "gradlew" => true,
138 "python" | "python3" => python_verification_arguments(&command_words[1..]),
139 _ if first.ends_with("/scripts/check.sh") || first.ends_with("/scripts/check-dev.sh") => true,
140 _ => false,
141 }
142}
143
144fn markdownlint_arguments_verify(arguments: &[String]) -> bool {
145 !arguments.is_empty()
146 && !arguments.iter().any(|argument| {
147 matches!(argument.as_str(), "--fix" | "-f" | "--help" | "-h" | "--version" | "-v")
148 || argument.starts_with("--fix=")
149 })
150}
151
152pub(super) fn contains_verification_invocation(command: &str) -> bool {
153 static_shell_command_words(command)
154 .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
155}
156
157pub fn shell_command_contains_verifier(args: &Value) -> bool {
161 let Some(command) = shell_command_text_with_args(args) else {
162 return false;
163 };
164 super::super::readonly::parse_shell_command_words(&command)
165 .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
166}
167
168pub fn shell_command_is_output_search(args: &Value) -> bool {
175 let Some(command) = shell_command_text_with_args(args) else {
176 return false;
177 };
178 let Some(segments) = static_shell_command_words(&command) else {
179 return false;
180 };
181 let mut saw_search = false;
182 for words in &segments {
183 if !command_words_are_readonly(words) || is_verification_invocation(words) {
184 return false;
185 }
186 let words = crate::tools::command_args::command_words_after_environment_prefix(words);
187 if command_words_are_grep_search(words) {
188 if grep_words_request_quiet_output(words) {
189 return false;
190 }
191 saw_search = true;
192 }
193 }
194 saw_search
195}
196
197fn grep_words_request_quiet_output(words: &[String]) -> bool {
198 let is_rg = words
199 .first()
200 .and_then(|word| Path::new(word).file_name())
201 .is_some_and(|name| name == "rg");
202 let mut arguments = words.iter().skip(1);
203 let mut quiet = false;
204 while let Some(argument) = arguments.next() {
205 match argument.as_str() {
206 "--" => break,
207 "--quiet" | "--silent" => quiet = true,
208 "--no-quiet" if is_rg => quiet = false,
209 _ if argument.starts_with("--") => {
210 let takes_value = matches!(
212 argument.as_str(),
213 "--regexp"
214 | "--file"
215 | "--after-context"
216 | "--before-context"
217 | "--context"
218 | "--max-count"
219 | "--include"
220 | "--exclude"
221 | "--exclude-from"
222 | "--exclude-dir"
223 | "--label"
224 | "--directories"
225 | "--devices"
226 ) || (is_rg
227 && matches!(
228 argument.as_str(),
229 "--glob"
230 | "--iglob"
231 | "--ignore-file"
232 | "--pre-glob"
233 | "--type"
234 | "--type-not"
235 | "--type-add"
236 | "--type-clear"
237 | "--replace"
238 | "--encoding"
239 | "--engine"
240 | "--color"
241 | "--colors"
242 | "--threads"
243 | "--max-depth"
244 | "--max-columns"
245 | "--max-filesize"
246 | "--dfa-size-limit"
247 | "--regex-size-limit"
248 | "--context-separator"
249 | "--field-context-separator"
250 | "--field-match-separator"
251 | "--hyperlink-format"
252 | "--path-separator"
253 | "--sort"
254 | "--sortr"
255 | "--generate"
256 ));
257 if takes_value {
258 arguments.next();
259 }
260 }
261 _ if argument.starts_with('-') => {
262 let mut flags = argument.chars().skip(1).peekable();
263 while let Some(flag) = flags.next() {
264 if flag == 'q' {
265 quiet = true;
266 }
267 let takes_value = matches!(flag, 'e' | 'f' | 'A' | 'B' | 'C' | 'm' | 'd')
268 || (is_rg && matches!(flag, 'g' | 't' | 'T' | 'r' | 'E' | 'j' | 'M'))
269 || (!is_rg && flag == 'D');
270 if takes_value {
271 if flags.peek().is_none() {
272 arguments.next();
273 }
274 break;
275 }
276 }
277 }
278 _ => {}
279 }
280 }
281 quiet
282}
283
284pub fn shell_command_is_standalone_grep_search(args: &Value) -> bool {
288 let Some(command) = shell_command_text_with_args(args) else {
289 return false;
290 };
291 let Some(segments) = static_shell_command_words(&command) else {
292 return false;
293 };
294 let [words] = segments.as_slice() else {
295 return false;
296 };
297 shell_words::split(&command).is_ok_and(|raw_words| raw_words == *words)
298 && command_words_are_readonly(words)
299 && command_words_are_grep_search(words)
300}
301
302fn command_words_are_grep_search(words: &[String]) -> bool {
303 let words = crate::tools::command_args::command_words_after_environment_prefix(words);
304 let program = words
305 .first()
306 .and_then(|word| Path::new(word).file_name())
307 .and_then(|name| name.to_str());
308 matches!(program, Some("rg" | "grep" | "egrep" | "fgrep"))
309}
310
311const PRE_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
315 (&["Cargo.toml"], "cargo check --locked"),
316 (&["go.mod"], "go test ./..."),
317 (&["deno.json", "deno.jsonc"], "deno test"),
318 (&["bun.lockb", "bun.lock"], "bun test"),
319];
320
321const POST_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
324 (&["pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini"], "pytest -q"),
325 (&["Makefile", "makefile"], "make test"),
326 (&["justfile", "Justfile"], "just test"),
327];
328
329fn verifier_for_markers(workspace_root: &Path, markers: &[(&[&str], &str)]) -> Option<String> {
331 markers.iter().find_map(|(files, verifier)| {
332 files
333 .iter()
334 .any(|file| workspace_root.join(file).is_file())
335 .then(|| (*verifier).to_string())
336 })
337}
338
339fn default_verifier_for_node_workspace(workspace_root: &Path) -> Option<String> {
344 let package_json = workspace_root.join("package.json");
345 if !package_json.is_file() {
346 return None;
347 }
348 if let Ok(content) = std::fs::read_to_string(&package_json)
349 && let Ok(parsed) = serde_json::from_str::<Value>(&content)
350 && let Some(scripts) = parsed.get("scripts").and_then(Value::as_object)
351 {
352 for (script, command) in [
353 ("test", "npm test"),
354 ("check", "npm run check"),
355 ("lint", "npm run lint"),
356 ("build", "npm run build"),
357 ] {
358 if scripts.contains_key(script) {
359 return Some(command.to_string());
360 }
361 }
362 }
363 Some("npm test".to_string())
364}
365
366pub fn default_verifier_for_workspace(workspace_root: &Path) -> Option<String> {
382 if let Some(verifier) = verifier_for_markers(workspace_root, PRE_NODE_VERIFIER_MARKERS) {
383 return Some(verifier);
384 }
385 if let Some(verifier) = default_verifier_for_node_workspace(workspace_root) {
386 return Some(verifier);
387 }
388 verifier_for_markers(workspace_root, POST_NODE_VERIFIER_MARKERS)
390}
391
392pub 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.";
396
397pub const GENERIC_VERIFIER_DESCRIPTION: &str =
403 "your project's build/test/lint command (e.g. `cargo check --locked`, `go test ./...`, `npm test`, or `pytest -q`)";
404
405pub fn verifier_reference(default_verifier: Option<&str>) -> String {
410 match default_verifier.map(str::trim).filter(|command| !command.is_empty()) {
411 Some(command) => format!("`{command}`"),
412 None => GENERIC_VERIFIER_DESCRIPTION.to_string(),
413 }
414}
415
416pub fn verification_recovery_directive(default_verifier: Option<&str>, attempt: u8, max_attempts: u8) -> String {
421 let verifier = verifier_reference(default_verifier);
422 format!(
423 "Verification recovery ({attempt}/{max_attempts}): completion is unverified. Continue implementation and repair reported failures; edits remain available. \
424 Validate a failing generated assertion against the original request before changing code; explicitly correct erroneous tracker verify metadata without weakening user criteria. Then run only missing checks, starting with {verifier} via `exec_command`, standalone or as a pure `&&` chain of verifiers. \
425 {VERIFIER_SHELL_FORM_NOTE} Reuse fresh passes; successful completion requires all mandatory checks."
426 )
427}
428
429pub fn shell_command_is_admitted_verification_attempt(args: &Value) -> bool {
444 let Some(command) = shell_command_text_with_args(args) else {
445 return false;
446 };
447 if crate::tools::command_args::contains_dynamic_shell_syntax(&command) {
448 return false;
449 }
450 if command.starts_with(VERIFIER_PIPEFAIL_PREFIX) {
451 return pipefail_verifier_pipeline(&command).is_some();
452 }
453 let segments =
454 static_shell_command_words(&command).or_else(|| static_shell_command_words_with_output_plumbing(&command));
455 let Some(segments) = segments else {
456 return false;
457 };
458 if segments.is_empty() {
459 return false;
460 }
461 let mut saw_verification = false;
462 for words in &segments {
463 if is_verification_invocation(words) {
464 saw_verification = true;
465 } else if !command_words_are_readonly(words) {
466 return false;
467 }
468 }
469 saw_verification
470}
471
472pub(super) fn has_logical_sequencing(words: &[String]) -> bool {
473 words.iter().any(|word| matches!(word.as_str(), "&&" | "||" | ";"))
474}
475
476fn split_top_level_pipes(command: &str) -> Option<Vec<&str>> {
483 if !command.contains('|') {
484 return None;
485 }
486 let mut stages = Vec::new();
487 let mut start = 0;
488 let mut saw_pipe = false;
489 let mut in_single_quote = false;
490 let mut in_double_quote = false;
491 let mut chars = command.char_indices().peekable();
492 while let Some((index, character)) = chars.next() {
493 if character == '\\' && !in_single_quote {
497 chars.next();
498 continue;
499 }
500 if character == '\'' && !in_double_quote {
501 in_single_quote = !in_single_quote;
502 continue;
503 }
504 if character == '"' && !in_single_quote {
505 in_double_quote = !in_double_quote;
506 continue;
507 }
508 if in_single_quote || in_double_quote {
509 continue;
510 }
511 if character == '|' {
512 saw_pipe = true;
513 stages.push(&command[start..index]);
514 start = index + character.len_utf8();
515 }
516 }
517 if !saw_pipe {
518 return None;
519 }
520 stages.push(&command[start..]);
521 Some(stages)
522}
523
524fn is_pure_truncation_stage(stage: &str) -> bool {
530 let trimmed = stage.trim();
531 if trimmed.is_empty() {
532 return false;
533 }
534 let mut in_single_quote = false;
539 let mut in_double_quote = false;
540 let mut chars = trimmed.chars().peekable();
541 while let Some(character) = chars.next() {
542 if character == '\\' && !in_single_quote {
543 chars.next();
544 continue;
545 }
546 if character == '\'' && !in_double_quote {
547 in_single_quote = !in_single_quote;
548 continue;
549 }
550 if character == '"' && !in_single_quote {
551 in_double_quote = !in_double_quote;
552 continue;
553 }
554 if in_single_quote || in_double_quote {
555 continue;
556 }
557 if matches!(character, ';' | '&' | '<' | '>' | '\n' | '|') {
558 return false;
559 }
560 }
561 let words = match shell_words::split(trimmed) {
562 Ok(words) => words,
563 Err(_) => return false,
564 };
565 let Some(parsed) = NonEmptySlice::from_slice(&words) else {
566 return false;
567 };
568 let program = Path::new(parsed.first())
569 .file_name()
570 .and_then(|name| name.to_str())
571 .unwrap_or(parsed.first().as_str())
572 .to_ascii_lowercase();
573 matches!(program.as_str(), "head" | "tail")
574}
575
576pub fn rewrite_truncation_only_verifier(args: &Value) -> Option<String> {
606 use crate::config::constants::tools as tool_names;
607
608 let command = shell_command_text_with_args(args)?;
609 if !shell_command_is_admitted_verification_attempt(args) {
610 return None;
611 }
612 let stages = split_top_level_pipes(&command)?;
613 let (head, tails) = stages.split_first()?;
614 let head = head.trim();
615 if head.is_empty() || tails.iter().any(|stage| !is_pure_truncation_stage(stage)) {
616 return None;
617 }
618 let head_args = serde_json::json!({"cmd": head});
619 if !matches!(classify_shell_activity(tool_names::EXEC_COMMAND, &head_args), ShellActivity::Verification) {
620 return None;
621 }
622 Some(head.to_string())
623}
624
625const VERIFIER_PIPEFAIL_PREFIX: &str = "set -o pipefail && ";
627
628pub(crate) fn pipefail_verifier_pipeline(command: &str) -> Option<&str> {
631 let pipeline = command.strip_prefix(VERIFIER_PIPEFAIL_PREFIX)?;
632 if crate::tools::command_args::contains_dynamic_shell_syntax(pipeline) {
633 return None;
634 }
635 verifier_pipeline_head(pipeline).map(|_| pipeline)
636}
637
638fn verifier_pipeline_head(command: &str) -> Option<&str> {
640 let stages = split_top_level_pipes(command)?;
641 let (head, tails) = stages.split_first()?;
642 let head = head.trim();
643 let head_args = serde_json::json!({"cmd": head});
644 if classify_shell_activity(crate::config::constants::tools::EXEC_COMMAND, &head_args) != ShellActivity::Verification
645 {
646 return None;
647 }
648 for stage in tails {
651 let segments = static_shell_command_words(stage)?;
652 if segments.len() != 1 || !segments.first().is_some_and(|words| command_words_are_readonly(words)) {
653 return None;
654 }
655 }
656 Some(head)
657}
658
659pub(super) fn rewrite_verifier_pipeline(args: &Value) -> Option<String> {
664 if let Some(standalone) = rewrite_truncation_only_verifier(args) {
665 return Some(standalone);
666 }
667 let command = shell_command_text_with_args(args)?;
668 if command.starts_with(VERIFIER_PIPEFAIL_PREFIX)
669 || !shell_command_is_admitted_verification_attempt(args)
670 || verifier_pipeline_head(&command).is_none()
671 {
672 return None;
673 }
674 Some(format!("{VERIFIER_PIPEFAIL_PREFIX}{command}"))
675}