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        "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                // `cargo fmt` without `--check` reformats the worktree (mutation).
91                // With `--check` it is a read-only lint verification.
92                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            // Bare `tsc` emits output (mutation). Only `--noEmit` type-checks.
131            words.iter().any(|word| word == "--noEmit")
132        }
133        "eslint" => {
134            // `eslint --fix` rewrites the worktree (mutation).
135            !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
157/// Recognize a verifier for diagnostic feedback, including status-masking tails
158/// such as `; echo $?` that cannot pass static verification admission.
159/// This heuristic grants no permissions, verification credit, or repair edits.
160pub 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
168/// Whether a command inspects search results that normally produce output.
169///
170/// Used only for progress accounting: an empty read-only search pipeline can
171/// exit successfully when its final filter masks the search's no-match status.
172/// Quiet/existence probes intentionally return no text and are excluded. This
173/// predicate grants no execution permissions and never verifies mutations.
174pub 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                // Values can look like options, including patterns such as `-query`.
211                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
284/// Whether exit code 1 belongs to a standalone grep-style search.
285/// Compound commands, shell wrappers and redirected diagnostics cannot prove
286/// the search's no-match status, even when their visible output is empty.
287pub 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
311/// Project markers checked in priority order before the Node tier: each
312/// entry names the files that select its verifier. First tier with any
313/// marker present wins, matching the previous sequential `if` chain.
314const 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
321/// Project markers checked after the Node tier (`package.json` is resolved
322/// separately at its priority position for script sniffing).
323const 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
329/// First verifier whose tier has any marker file under `workspace_root`.
330fn 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
339/// Node verifier with `package.json` script sniffing: `test` runs directly,
340/// other known scripts run via `npm run`, and a missing/unreadable script
341/// map falls back to `npm test` so the directive never names a command that
342/// does not exist. Returns `None` when there is no `package.json`.
343fn 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
366/// Detect a project-appropriate default verifier for autonomous recovery.
367///
368/// Inspects well-known project markers under `workspace_root` and returns a
369/// concrete standalone verification command the agent can run via
370/// `exec_command` (no pipes, no `;`/`||` joins). Priority follows the
371/// existing `is_verification_invocation` coverage: Rust → Go → Deno/Bun →
372/// Node → Python → Make/Just. Returns `None` when no marker is found so
373/// callers can fall back to the generic verifier examples.
374///
375/// This is intentionally synchronous and allocation-light (existence checks
376/// plus one small `package.json` read): it runs on the turn hot path when
377/// the anti-blind-editing gate needs an actionable recovery directive.
378/// Codex-style harness-managed verification (Stop-hook test gates,
379/// auto-review) shows that naming the exact command — rather than listing
380/// examples — is what unblocks long-running autonomous work.
381pub 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    // No recognised project marker; callers fall back to generic examples.
389    verifier_for_markers(workspace_root, POST_NODE_VERIFIER_MARKERS)
390}
391
392/// Which shell forms of a verifier clear the anti-blind-editing gate. Shared
393/// by the recovery directive and the blocked-mutation `next_action` so the
394/// two surfaces cannot drift.
395pub 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
397/// Stand-in for the verifier when no project command was detected or
398/// configured. It lists examples across ecosystems instead of naming one
399/// command, because a single concrete fallback (such as a Cargo command in a
400/// Go or Node workspace) would direct the model to a verifier that does not
401/// exist.
402pub 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
405/// How harness text names the verifier to run: the resolved command in
406/// backticks, or [`GENERIC_VERIFIER_DESCRIPTION`] when none was resolved.
407/// `default_verifier` should come from [`default_verifier_for_workspace`] or
408/// the harness override resolution built on it.
409pub 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
416/// Build the actionable verification-recovery directive with a concrete
417/// command. `default_verifier` should come from
418/// [`default_verifier_for_workspace`]; when `None`, the generic examples are
419/// kept so the directive never names a command that does not exist.
420pub 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
429/// Return whether a shell tool call is an admitted truncation-only verification
430/// attempt while the anti-blind-editing gate is pending.
431///
432/// Piped verifiers (e.g. `cargo check 2>&1 | head -c 4000`) must be allowed to
433/// run so the model can see the failure; otherwise the generic "cap output
434/// with `| head`" guidance deadlocks on `Mutation blocked until verification`.
435/// Only a truthful successful verifier clears the gate; this helper only
436/// decides admission, never clearance.
437///
438/// Fail-closed smuggling guard: every parsed shell segment must be a
439/// verification invocation or an allow-listed readonly command. A chained
440/// mutation such as `cargo check && rm -rf target` therefore stays blocked
441/// instead of riding through on the verifier prefix. Unparseable (dynamic)
442/// shell syntax also stays blocked.
443pub 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
476/// Split a command on top-level `|` operators, tracking single/double quotes
477/// and backslash escapes with the same discipline as
478/// [`shell_uses_only_and_chaining`]. Returns the pipe-separated stages in
479/// order, or `None` when no top-level pipe exists. `||` is not special-cased:
480/// it yields an empty stage, which stage validation rejects — fail-closed
481/// without a second operator table to keep in sync.
482fn 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        // Outside single quotes a backslash escapes the next character for the
494        // shell, so `\|` is a literal pipe, not a stage separator. Consume the
495        // pair to stay aligned with the shell (mirrors the `&&`-chain scanner).
496        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
524/// Whether a pipeline tail stage is a pure output truncator: a bare `head` or
525/// `tail` invocation (any flags) with no shell operators of its own. Anything
526/// else (`grep`, `wc`, `sort`, redirects, backgrounding, chaining) keeps its
527/// pipeline semantics and must not be elided — dropping it would discard work
528/// the caller asked for or change what the exit status means.
529fn is_pure_truncation_stage(stage: &str) -> bool {
530    let trimmed = stage.trim();
531    if trimmed.is_empty() {
532        return false;
533    }
534    // A truncator stage is one simple command: reject any operator that would
535    // indicate chaining, backgrounding, redirection, or nesting. The scan is
536    // quote-aware so quoted flag values (e.g. `--sep=';'`) do not false-reject;
537    // an unaware scan could only over-reject, which stays fail-closed.
538    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
576/// Rewrite a truncation-only piped verifier (`cargo check 2>&1 | head -c 4000`)
577/// to its standalone verifier prefix so the observed exit status is the
578/// verifier's, not the truncator's.
579///
580/// A pipeline's status belongs to its tail: running `cargo check | tail`
581/// reports `tail`'s success even when the build fails, and the model reads
582/// that exit 0 as "verified" while the anti-blind gate (correctly) stays
583/// pending — a deadlock manufactured by shell exit-status semantics, observed
584/// in real sessions. Eliding the truncator (output stays capped via
585/// `max_output_tokens`) makes the status truthful in one round trip.
586///
587/// Fail-closed gates, all required:
588/// - the full command is an admitted verification attempt (no dynamic
589///   syntax; every segment independently verification-or-readonly), so shapes
590///   like `cargo check | tail; rm …` can never reach the rewrite;
591/// - the head classifies as [`ShellActivity::Verification`] on its own, so
592///   `;`/`||`/background joins and smuggled mutations behind a verifier
593///   prefix are rejected (only standalone verifiers and pure `&&` verifier
594///   chains pass, whose `&&` exit status is truthful; output redirects such
595///   as `> build.log` are preserved verbatim in the head and do not mask the
596///   status, so they rewrite safely);
597/// - every tail stage is a pure `is_pure_truncation_stage` truncator, so
598///   `grep`/`wc`/`sort` tails (whose filtering is real work) are preserved.
599///
600/// Returns the standalone verifier text, or `None` when the command must run
601/// (or be rejected) exactly as typed. Only commands whose raw text carries a
602/// top-level `|` are candidates; array and indexed spellings re-quote
603/// operators when joined, so they never present a top-level pipe and keep
604/// today's behavior.
605pub 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
625// `&&` fails closed when the selected shell does not support pipefail.
626const VERIFIER_PIPEFAIL_PREFIX: &str = "set -o pipefail && ";
627
628/// The exact status-only shell setup, with the entire verifier pipeline validated.
629/// Command policy still checks every executable and explicit deny rule.
630pub(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
638/// Validate a static pipeline without granting execution or mutation permissions.
639fn 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    // Tail stages must be independently static and read-only. Logical joins,
649    // unsafe redirections, substitutions, and mutations cannot ride behind it.
650    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
659/// Preserve filtering while making pipeline success depend on every stage.
660/// Pure truncator pipelines retain the existing standalone rewrite to avoid
661/// SIGPIPE from early-closing head/tail. Other static read-only tails use
662/// pipefail; failures (including no matches or SIGPIPE) never clear the gate.
663pub(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}