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 "bun" => {
62 if second.as_deref() == Some("x") {
63 let package_index = command_words
64 .iter()
65 .enumerate()
66 .skip(2)
67 .find(|(_, word)| !matches!(word.as_str(), "--no-install" | "--silent"))
68 .map(|(index, _)| index);
69 markdownlint_package_verifies(command_words, package_index)
70 } else {
71 bun_test_or_run_verifies(second.as_deref(), third.as_deref())
72 }
73 }
74 "npx" => {
75 let package_index = command_words
76 .iter()
77 .enumerate()
78 .skip(1)
79 .find(|(_, word)| {
80 !matches!(word.as_str(), "--yes" | "-y" | "--no-install")
81 && !word.strip_prefix("--loglevel=").is_some_and(|level| {
82 matches!(
83 level,
84 "silent" | "error" | "warn" | "notice" | "http" | "info" | "verbose" | "silly"
85 )
86 })
87 })
88 .map(|(index, _)| index);
89 markdownlint_package_verifies(command_words, package_index)
90 }
91 "cargo" => {
92 if second.as_deref() == Some("fmt") {
93 return words.iter().any(|word| word == "--check");
96 }
97 matches!(second.as_deref(), Some("check" | "build" | "clippy" | "test"))
98 || (second.as_deref() == Some("nextest") && third.as_deref() == Some("run"))
99 }
100 "go" => matches!(second.as_deref(), Some("test" | "build")),
101 "npm" | "pnpm" | "yarn" => {
102 matches!(second.as_deref(), Some("test" | "build" | "lint" | "check"))
103 || (second.as_deref() == Some("run")
104 && matches!(third.as_deref(), Some("test" | "build" | "lint" | "check")))
105 }
106 "bunx" => {
107 let package_index = command_words
111 .iter()
112 .enumerate()
113 .skip(1)
114 .find(|(_, word)| {
115 !matches!(word.as_str(), "--no-install" | "--silent" | "--verbose" | "--bun")
116 && !word.starts_with('-')
117 })
118 .map(|(index, _)| index);
119 markdownlint_package_verifies(command_words, package_index)
120 || bun_test_or_run_verifies(second.as_deref(), third.as_deref())
121 }
122 "deno" => matches!(second.as_deref(), Some("test" | "lint" | "check")),
123 "make" | "gmake" | "just" => make_like_verification_targets(command_words),
124 "uv" => {
125 let Some(arguments) = crate::tools::command_args::uv_run_command_words(command_words) else {
126 return false;
127 };
128 let mut arguments = arguments.iter();
129 let target = arguments.next();
130 match target.map(String::as_str) {
131 Some("pytest") => true,
132 Some("ruff") => arguments.next().is_some_and(|argument| argument == "check"),
133 Some("python" | "python3") => python_verification_arguments(arguments.as_slice()),
134 _ => false,
135 }
136 }
137 "ruff" => {
138 if second.as_deref() == Some("format") {
139 return words.iter().any(|word| word == "--check");
140 }
141 matches!(second.as_deref(), Some("check" | "lint"))
142 }
143 "tsc" => {
144 words.iter().any(|word| word == "--noEmit")
146 }
147 "eslint" => {
148 !words.iter().any(|word| word == "--fix" || word == "--fix-dry-run")
150 }
151 "rustc" | "pytest" | "xcodebuild" | "gradle" | "gradlew" => true,
152 "python" | "python3" => python_verification_arguments(&command_words[1..]),
153 _ if first.ends_with("/scripts/check.sh") || first.ends_with("/scripts/check-dev.sh") => true,
154 _ => false,
155 }
156}
157
158fn markdownlint_arguments_verify(arguments: &[String]) -> bool {
159 !arguments.is_empty()
160 && !arguments.iter().any(|argument| {
161 matches!(argument.as_str(), "--fix" | "-f" | "--help" | "-h" | "--version" | "-v")
162 || argument.starts_with("--fix=")
163 })
164}
165
166fn bun_test_or_run_verifies(second: Option<&str>, third: Option<&str>) -> bool {
168 matches!(second, Some("test"))
169 || (second == Some("run") && matches!(third, Some("test" | "build" | "lint" | "check")))
170}
171
172fn markdownlint_package_verifies(command_words: &[String], package_index: Option<usize>) -> bool {
175 package_index.is_some_and(|index| {
176 let Some(package) = command_words.get(index) else {
177 return false;
178 };
179 let is_markdownlint = package == "markdownlint-cli2"
180 || package.strip_prefix("markdownlint-cli2@").is_some_and(|version| {
181 version.split('.').count() == 3
182 && version
183 .split('.')
184 .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
185 });
186 is_markdownlint && command_words.get(index + 1..).is_some_and(markdownlint_arguments_verify)
187 })
188}
189
190pub(super) fn contains_verification_invocation(command: &str) -> bool {
191 static_shell_command_words(command)
192 .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
193}
194
195pub fn shell_command_contains_verifier(args: &Value) -> bool {
199 let Some(command) = shell_command_text_with_args(args) else {
200 return false;
201 };
202 super::super::readonly::parse_shell_command_words(&command)
203 .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
204}
205
206pub fn shell_command_is_output_search(args: &Value) -> bool {
213 let Some(command) = shell_command_text_with_args(args) else {
214 return false;
215 };
216 let Some(segments) = static_shell_command_words(&command) else {
217 return false;
218 };
219 let mut saw_search = false;
220 for words in &segments {
221 if !command_words_are_readonly(words) || is_verification_invocation(words) {
222 return false;
223 }
224 let words = crate::tools::command_args::command_words_after_environment_prefix(words);
225 if command_words_are_grep_search(words) {
226 if grep_words_request_quiet_output(words) {
227 return false;
228 }
229 saw_search = true;
230 }
231 }
232 saw_search
233}
234
235fn grep_words_request_quiet_output(words: &[String]) -> bool {
236 let is_rg = words
237 .first()
238 .and_then(|word| Path::new(word).file_name())
239 .is_some_and(|name| name == "rg");
240 let mut arguments = words.iter().skip(1);
241 let mut quiet = false;
242 while let Some(argument) = arguments.next() {
243 match argument.as_str() {
244 "--" => break,
245 "--quiet" | "--silent" => quiet = true,
246 "--no-quiet" if is_rg => quiet = false,
247 _ if argument.starts_with("--") => {
248 let takes_value = matches!(
250 argument.as_str(),
251 "--regexp"
252 | "--file"
253 | "--after-context"
254 | "--before-context"
255 | "--context"
256 | "--max-count"
257 | "--include"
258 | "--exclude"
259 | "--exclude-from"
260 | "--exclude-dir"
261 | "--label"
262 | "--directories"
263 | "--devices"
264 ) || (is_rg
265 && matches!(
266 argument.as_str(),
267 "--glob"
268 | "--iglob"
269 | "--ignore-file"
270 | "--pre-glob"
271 | "--type"
272 | "--type-not"
273 | "--type-add"
274 | "--type-clear"
275 | "--replace"
276 | "--encoding"
277 | "--engine"
278 | "--color"
279 | "--colors"
280 | "--threads"
281 | "--max-depth"
282 | "--max-columns"
283 | "--max-filesize"
284 | "--dfa-size-limit"
285 | "--regex-size-limit"
286 | "--context-separator"
287 | "--field-context-separator"
288 | "--field-match-separator"
289 | "--hyperlink-format"
290 | "--path-separator"
291 | "--sort"
292 | "--sortr"
293 | "--generate"
294 ));
295 if takes_value {
296 arguments.next();
297 }
298 }
299 _ if argument.starts_with('-') => {
300 let mut flags = argument.chars().skip(1).peekable();
301 while let Some(flag) = flags.next() {
302 if flag == 'q' {
303 quiet = true;
304 }
305 let takes_value = matches!(flag, 'e' | 'f' | 'A' | 'B' | 'C' | 'm' | 'd')
306 || (is_rg && matches!(flag, 'g' | 't' | 'T' | 'r' | 'E' | 'j' | 'M'))
307 || (!is_rg && flag == 'D');
308 if takes_value {
309 if flags.peek().is_none() {
310 arguments.next();
311 }
312 break;
313 }
314 }
315 }
316 _ => {}
317 }
318 }
319 quiet
320}
321
322pub fn shell_command_is_standalone_grep_search(args: &Value) -> bool {
326 let Some(command) = shell_command_text_with_args(args) else {
327 return false;
328 };
329 let Some(segments) = static_shell_command_words(&command) else {
330 return false;
331 };
332 let [words] = segments.as_slice() else {
333 return false;
334 };
335 shell_words::split(&command).is_ok_and(|raw_words| raw_words == *words)
336 && command_words_are_readonly(words)
337 && command_words_are_grep_search(words)
338}
339
340fn command_words_are_grep_search(words: &[String]) -> bool {
341 let words = crate::tools::command_args::command_words_after_environment_prefix(words);
342 let program = words
343 .first()
344 .and_then(|word| Path::new(word).file_name())
345 .and_then(|name| name.to_str());
346 matches!(program, Some("rg" | "grep" | "egrep" | "fgrep"))
347}
348
349const PRE_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
353 (&["Cargo.toml"], "cargo check --locked"),
354 (&["go.mod"], "go test ./..."),
355 (&["deno.json", "deno.jsonc"], "deno test"),
356 (&["bun.lockb", "bun.lock"], "bun test"),
357];
358
359const POST_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
362 (&["pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini"], "pytest -q"),
363 (&["Makefile", "makefile"], "make test"),
364 (&["justfile", "Justfile"], "just test"),
365];
366
367fn verifier_for_markers(workspace_root: &Path, markers: &[(&[&str], &str)]) -> Option<String> {
369 markers.iter().find_map(|(files, verifier)| {
370 files
371 .iter()
372 .any(|file| workspace_root.join(file).is_file())
373 .then(|| (*verifier).to_string())
374 })
375}
376
377fn default_verifier_for_node_workspace(workspace_root: &Path) -> Option<String> {
382 let package_json = workspace_root.join("package.json");
383 if !package_json.is_file() {
384 return None;
385 }
386 if let Ok(content) = std::fs::read_to_string(&package_json)
387 && let Ok(parsed) = serde_json::from_str::<Value>(&content)
388 && let Some(scripts) = parsed.get("scripts").and_then(Value::as_object)
389 {
390 for (script, command) in [
391 ("test", "npm test"),
392 ("check", "npm run check"),
393 ("lint", "npm run lint"),
394 ("build", "npm run build"),
395 ] {
396 if scripts.contains_key(script) {
397 return Some(command.to_string());
398 }
399 }
400 }
401 Some("npm test".to_string())
402}
403
404pub fn default_verifier_for_workspace(workspace_root: &Path) -> Option<String> {
420 if let Some(verifier) = verifier_for_markers(workspace_root, PRE_NODE_VERIFIER_MARKERS) {
421 return Some(verifier);
422 }
423 if let Some(verifier) = default_verifier_for_node_workspace(workspace_root) {
424 return Some(verifier);
425 }
426 verifier_for_markers(workspace_root, POST_NODE_VERIFIER_MARKERS)
428}
429
430pub 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.";
434
435pub const GENERIC_VERIFIER_DESCRIPTION: &str =
441 "your project's build/test/lint command (e.g. `cargo check --locked`, `go test ./...`, `npm test`, or `pytest -q`)";
442
443pub fn verifier_reference(default_verifier: Option<&str>) -> String {
448 match default_verifier.map(str::trim).filter(|command| !command.is_empty()) {
449 Some(command) => format!("`{command}`"),
450 None => GENERIC_VERIFIER_DESCRIPTION.to_string(),
451 }
452}
453
454pub fn verification_recovery_directive(default_verifier: Option<&str>, attempt: u8, max_attempts: u8) -> String {
459 let verifier = verifier_reference(default_verifier);
460 format!(
461 "Verification recovery ({attempt}/{max_attempts}): completion is unverified. Continue implementation and repair reported failures; edits remain available. \
462 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. \
463 {VERIFIER_SHELL_FORM_NOTE} Reuse fresh passes; successful completion requires all mandatory checks."
464 )
465}
466
467pub fn shell_command_is_admitted_verification_attempt(args: &Value) -> bool {
482 let Some(command) = shell_command_text_with_args(args) else {
483 return false;
484 };
485 if crate::tools::command_args::contains_dynamic_shell_syntax(&command) {
486 return false;
487 }
488 if command.starts_with(VERIFIER_PIPEFAIL_PREFIX) {
489 return pipefail_verifier_pipeline(&command).is_some();
490 }
491 let segments =
492 static_shell_command_words(&command).or_else(|| static_shell_command_words_with_output_plumbing(&command));
493 let Some(segments) = segments else {
494 return false;
495 };
496 if segments.is_empty() {
497 return false;
498 }
499 let mut saw_verification = false;
500 for words in &segments {
501 if is_verification_invocation(words) {
502 saw_verification = true;
503 } else if !command_words_are_readonly(words) {
504 return false;
505 }
506 }
507 saw_verification
508}
509
510pub(super) fn has_logical_sequencing(words: &[String]) -> bool {
511 words.iter().any(|word| matches!(word.as_str(), "&&" | "||" | ";"))
512}
513
514fn split_top_level_pipes(command: &str) -> Option<Vec<&str>> {
521 if !command.contains('|') {
522 return None;
523 }
524 let mut stages = Vec::new();
525 let mut start = 0;
526 let mut saw_pipe = false;
527 let mut in_single_quote = false;
528 let mut in_double_quote = false;
529 let mut chars = command.char_indices().peekable();
530 while let Some((index, character)) = chars.next() {
531 if character == '\\' && !in_single_quote {
535 chars.next();
536 continue;
537 }
538 if character == '\'' && !in_double_quote {
539 in_single_quote.toggle();
540 continue;
541 }
542 if character == '"' && !in_single_quote {
543 in_double_quote.toggle();
544 continue;
545 }
546 if in_single_quote || in_double_quote {
547 continue;
548 }
549 if character == '|' {
550 saw_pipe = true;
551 stages.push(&command[start..index]);
552 start = index + character.len_utf8();
553 }
554 }
555 if !saw_pipe {
556 return None;
557 }
558 stages.push(&command[start..]);
559 Some(stages)
560}
561
562fn is_pure_truncation_stage(stage: &str) -> bool {
568 let trimmed = stage.trim();
569 if trimmed.is_empty() {
570 return false;
571 }
572 let mut in_single_quote = false;
577 let mut in_double_quote = false;
578 let mut chars = trimmed.chars().peekable();
579 while let Some(character) = chars.next() {
580 if character == '\\' && !in_single_quote {
581 chars.next();
582 continue;
583 }
584 if character == '\'' && !in_double_quote {
585 in_single_quote.toggle();
586 continue;
587 }
588 if character == '"' && !in_single_quote {
589 in_double_quote.toggle();
590 continue;
591 }
592 if in_single_quote || in_double_quote {
593 continue;
594 }
595 if matches!(character, ';' | '&' | '<' | '>' | '\n' | '|') {
596 return false;
597 }
598 }
599 let words = match shell_words::split(trimmed) {
600 Ok(words) => words,
601 Err(_) => return false,
602 };
603 let Some(parsed) = NonEmptySlice::from_slice(&words) else {
604 return false;
605 };
606 let program = Path::new(parsed.first())
607 .file_name()
608 .and_then(|name| name.to_str())
609 .unwrap_or(parsed.first().as_str())
610 .to_ascii_lowercase();
611 matches!(program.as_str(), "head" | "tail")
612}
613
614pub fn rewrite_truncation_only_verifier(args: &Value) -> Option<String> {
644 use crate::config::constants::tools as tool_names;
645
646 let command = shell_command_text_with_args(args)?;
647 if !shell_command_is_admitted_verification_attempt(args) {
648 return None;
649 }
650 let stages = split_top_level_pipes(&command)?;
651 let (head, tails) = stages.split_first()?;
652 let head = head.trim();
653 if head.is_empty() || tails.iter().any(|stage| !is_pure_truncation_stage(stage)) {
654 return None;
655 }
656 let head_args = serde_json::json!({"cmd": head});
657 if !matches!(classify_shell_activity(tool_names::EXEC_COMMAND, &head_args), ShellActivity::Verification) {
658 return None;
659 }
660 Some(head.to_string())
661}
662
663const VERIFIER_PIPEFAIL_PREFIX: &str = "set -o pipefail && ";
665
666pub(crate) fn pipefail_verifier_pipeline(command: &str) -> Option<&str> {
669 let pipeline = command.strip_prefix(VERIFIER_PIPEFAIL_PREFIX)?;
670 if crate::tools::command_args::contains_dynamic_shell_syntax(pipeline) {
671 return None;
672 }
673 verifier_pipeline_head(pipeline).map(|_| pipeline)
674}
675
676fn verifier_pipeline_head(command: &str) -> Option<&str> {
678 let stages = split_top_level_pipes(command)?;
679 let (head, tails) = stages.split_first()?;
680 let head = head.trim();
681 let head_args = serde_json::json!({"cmd": head});
682 if classify_shell_activity(crate::config::constants::tools::EXEC_COMMAND, &head_args) != ShellActivity::Verification
683 {
684 return None;
685 }
686 for stage in tails {
689 let segments = static_shell_command_words(stage)?;
690 if segments.len() != 1 || !segments.first().is_some_and(|words| command_words_are_readonly(words)) {
691 return None;
692 }
693 }
694 Some(head)
695}
696
697pub(super) fn rewrite_verifier_pipeline(args: &Value) -> Option<String> {
702 if let Some(standalone) = rewrite_truncation_only_verifier(args) {
703 return Some(standalone);
704 }
705 let command = shell_command_text_with_args(args)?;
706 if command.starts_with(VERIFIER_PIPEFAIL_PREFIX)
707 || !shell_command_is_admitted_verification_attempt(args)
708 || verifier_pipeline_head(&command).is_none()
709 {
710 return None;
711 }
712 Some(format!("{VERIFIER_PIPEFAIL_PREFIX}{command}"))
713}