Skip to main content

vtcode_core/tools/tool_intent/activity/
verifier.rs

1use 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    // Python executes the first target, not later verifier-like tokens.
20    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            // The known lint scripts stay read-only under trailing path
28            // operands (`check_markdown.py README.md`); any flag keeps the
29            // conservative rejection so `--fix`/`--list`/`--help` never verify.
30            ["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    // Verifiers may emit build artifacts; reject source-repair modes without
41    // applying the stricter inspection-only output restrictions to compilers.
42    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        // The repo's own gates run `bun x`; the `npx` form stays so lint
60        // runs on npm-based foreign repos still count as verification.
61        "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                // `cargo fmt` without `--check` reformats the worktree (mutation).
94                // With `--check` it is a read-only lint verification.
95                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            // Mirrors the `bun x` package slot above so `bunx markdownlint-cli2`
108            // guidance is credited as verification. Runner flags are skipped
109            // before locating the package name.
110            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            // Bare `tsc` emits output (mutation). Only `--noEmit` type-checks.
145            words.iter().any(|word| word == "--noEmit")
146        }
147        "eslint" => {
148            // `eslint --fix` rewrites the worktree (mutation).
149            !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
166/// Whether `bun test` or `bun run <test|build|lint|check>` runs a suite.
167fn 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
172/// Whether the located `bun x`/`npx` package slot names pinned markdownlint
173/// with verifying trailing arguments.
174fn 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
195/// Recognize a verifier for diagnostic feedback, including status-masking tails
196/// such as `; echo $?` that cannot pass static verification admission.
197/// This heuristic grants no permissions, verification credit, or repair edits.
198pub 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
206/// Whether a command inspects search results that normally produce output.
207///
208/// Used only for progress accounting: an empty read-only search pipeline can
209/// exit successfully when its final filter masks the search's no-match status.
210/// Quiet/existence probes intentionally return no text and are excluded. This
211/// predicate grants no execution permissions and never verifies mutations.
212pub 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                // Values can look like options, including patterns such as `-query`.
249                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
322/// Whether exit code 1 belongs to a standalone grep-style search.
323/// Compound commands, shell wrappers and redirected diagnostics cannot prove
324/// the search's no-match status, even when their visible output is empty.
325pub 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
349/// Project markers checked in priority order before the Node tier: each
350/// entry names the files that select its verifier. First tier with any
351/// marker present wins, matching the previous sequential `if` chain.
352const 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
359/// Project markers checked after the Node tier (`package.json` is resolved
360/// separately at its priority position for script sniffing).
361const 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
367/// First verifier whose tier has any marker file under `workspace_root`.
368fn 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
377/// Node verifier with `package.json` script sniffing: `test` runs directly,
378/// other known scripts run via `npm run`, and a missing/unreadable script
379/// map falls back to `npm test` so the directive never names a command that
380/// does not exist. Returns `None` when there is no `package.json`.
381fn 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
404/// Detect a project-appropriate default verifier for autonomous recovery.
405///
406/// Inspects well-known project markers under `workspace_root` and returns a
407/// concrete standalone verification command the agent can run via
408/// `exec_command` (no pipes, no `;`/`||` joins). Priority follows the
409/// existing `is_verification_invocation` coverage: Rust → Go → Deno/Bun →
410/// Node → Python → Make/Just. Returns `None` when no marker is found so
411/// callers can fall back to the generic verifier examples.
412///
413/// This is intentionally synchronous and allocation-light (existence checks
414/// plus one small `package.json` read): it runs on the turn hot path when
415/// the anti-blind-editing gate needs an actionable recovery directive.
416/// Codex-style harness-managed verification (Stop-hook test gates,
417/// auto-review) shows that naming the exact command — rather than listing
418/// examples — is what unblocks long-running autonomous work.
419pub 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    // No recognised project marker; callers fall back to generic examples.
427    verifier_for_markers(workspace_root, POST_NODE_VERIFIER_MARKERS)
428}
429
430/// Which shell forms of a verifier clear the anti-blind-editing gate. Shared
431/// by the recovery directive and the blocked-mutation `next_action` so the
432/// two surfaces cannot drift.
433pub 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
435/// Stand-in for the verifier when no project command was detected or
436/// configured. It lists examples across ecosystems instead of naming one
437/// command, because a single concrete fallback (such as a Cargo command in a
438/// Go or Node workspace) would direct the model to a verifier that does not
439/// exist.
440pub 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
443/// How harness text names the verifier to run: the resolved command in
444/// backticks, or [`GENERIC_VERIFIER_DESCRIPTION`] when none was resolved.
445/// `default_verifier` should come from [`default_verifier_for_workspace`] or
446/// the harness override resolution built on it.
447pub 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
454/// Build the actionable verification-recovery directive with a concrete
455/// command. `default_verifier` should come from
456/// [`default_verifier_for_workspace`]; when `None`, the generic examples are
457/// kept so the directive never names a command that does not exist.
458pub 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
467/// Return whether a shell tool call is an admitted truncation-only verification
468/// attempt while the anti-blind-editing gate is pending.
469///
470/// Piped verifiers (e.g. `cargo check 2>&1 | head -c 4000`) must be allowed to
471/// run so the model can see the failure; otherwise the generic "cap output
472/// with `| head`" guidance deadlocks on `Mutation blocked until verification`.
473/// Only a truthful successful verifier clears the gate; this helper only
474/// decides admission, never clearance.
475///
476/// Fail-closed smuggling guard: every parsed shell segment must be a
477/// verification invocation or an allow-listed readonly command. A chained
478/// mutation such as `cargo check && rm -rf target` therefore stays blocked
479/// instead of riding through on the verifier prefix. Unparseable (dynamic)
480/// shell syntax also stays blocked.
481pub 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
514/// Split a command on top-level `|` operators, tracking single/double quotes
515/// and backslash escapes with the same discipline as
516/// [`shell_uses_only_and_chaining`]. Returns the pipe-separated stages in
517/// order, or `None` when no top-level pipe exists. `||` is not special-cased:
518/// it yields an empty stage, which stage validation rejects — fail-closed
519/// without a second operator table to keep in sync.
520fn 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        // Outside single quotes a backslash escapes the next character for the
532        // shell, so `\|` is a literal pipe, not a stage separator. Consume the
533        // pair to stay aligned with the shell (mirrors the `&&`-chain scanner).
534        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
562/// Whether a pipeline tail stage is a pure output truncator: a bare `head` or
563/// `tail` invocation (any flags) with no shell operators of its own. Anything
564/// else (`grep`, `wc`, `sort`, redirects, backgrounding, chaining) keeps its
565/// pipeline semantics and must not be elided — dropping it would discard work
566/// the caller asked for or change what the exit status means.
567fn is_pure_truncation_stage(stage: &str) -> bool {
568    let trimmed = stage.trim();
569    if trimmed.is_empty() {
570        return false;
571    }
572    // A truncator stage is one simple command: reject any operator that would
573    // indicate chaining, backgrounding, redirection, or nesting. The scan is
574    // quote-aware so quoted flag values (e.g. `--sep=';'`) do not false-reject;
575    // an unaware scan could only over-reject, which stays fail-closed.
576    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
614/// Rewrite a truncation-only piped verifier (`cargo check 2>&1 | head -c 4000`)
615/// to its standalone verifier prefix so the observed exit status is the
616/// verifier's, not the truncator's.
617///
618/// A pipeline's status belongs to its tail: running `cargo check | tail`
619/// reports `tail`'s success even when the build fails, and the model reads
620/// that exit 0 as "verified" while the anti-blind gate (correctly) stays
621/// pending — a deadlock manufactured by shell exit-status semantics, observed
622/// in real sessions. Eliding the truncator (output stays capped via
623/// `max_output_tokens`) makes the status truthful in one round trip.
624///
625/// Fail-closed gates, all required:
626/// - the full command is an admitted verification attempt (no dynamic
627///   syntax; every segment independently verification-or-readonly), so shapes
628///   like `cargo check | tail; rm …` can never reach the rewrite;
629/// - the head classifies as [`ShellActivity::Verification`] on its own, so
630///   `;`/`||`/background joins and smuggled mutations behind a verifier
631///   prefix are rejected (only standalone verifiers and pure `&&` verifier
632///   chains pass, whose `&&` exit status is truthful; output redirects such
633///   as `> build.log` are preserved verbatim in the head and do not mask the
634///   status, so they rewrite safely);
635/// - every tail stage is a pure `is_pure_truncation_stage` truncator, so
636///   `grep`/`wc`/`sort` tails (whose filtering is real work) are preserved.
637///
638/// Returns the standalone verifier text, or `None` when the command must run
639/// (or be rejected) exactly as typed. Only commands whose raw text carries a
640/// top-level `|` are candidates; array and indexed spellings re-quote
641/// operators when joined, so they never present a top-level pipe and keep
642/// today's behavior.
643pub 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
663// `&&` fails closed when the selected shell does not support pipefail.
664const VERIFIER_PIPEFAIL_PREFIX: &str = "set -o pipefail && ";
665
666/// The exact status-only shell setup, with the entire verifier pipeline validated.
667/// Command policy still checks every executable and explicit deny rule.
668pub(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
676/// Validate a static pipeline without granting execution or mutation permissions.
677fn 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    // Tail stages must be independently static and read-only. Logical joins,
687    // unsafe redirections, substitutions, and mutations cannot ride behind it.
688    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
697/// Preserve filtering while making pipeline success depend on every stage.
698/// Pure truncator pipelines retain the existing standalone rewrite to avoid
699/// SIGPIPE from early-closing head/tail. Other static read-only tails use
700/// pipefail; failures (including no matches or SIGPIPE) never clear the gate.
701pub(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}