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" => bun_test_or_run_verifies(second.as_deref(), third.as_deref()),
107        "deno" => matches!(second.as_deref(), Some("test" | "lint" | "check")),
108        "make" | "gmake" | "just" => make_like_verification_targets(command_words),
109        "uv" => {
110            let Some(arguments) = crate::tools::command_args::uv_run_command_words(command_words) else {
111                return false;
112            };
113            let mut arguments = arguments.iter();
114            let target = arguments.next();
115            match target.map(String::as_str) {
116                Some("pytest") => true,
117                Some("ruff") => arguments.next().is_some_and(|argument| argument == "check"),
118                Some("python" | "python3") => python_verification_arguments(arguments.as_slice()),
119                _ => false,
120            }
121        }
122        "ruff" => {
123            if second.as_deref() == Some("format") {
124                return words.iter().any(|word| word == "--check");
125            }
126            matches!(second.as_deref(), Some("check" | "lint"))
127        }
128        "tsc" => {
129            // Bare `tsc` emits output (mutation). Only `--noEmit` type-checks.
130            words.iter().any(|word| word == "--noEmit")
131        }
132        "eslint" => {
133            // `eslint --fix` rewrites the worktree (mutation).
134            !words.iter().any(|word| word == "--fix" || word == "--fix-dry-run")
135        }
136        "rustc" | "pytest" | "xcodebuild" | "gradle" | "gradlew" => true,
137        "python" | "python3" => python_verification_arguments(&command_words[1..]),
138        _ if first.ends_with("/scripts/check.sh") || first.ends_with("/scripts/check-dev.sh") => true,
139        _ => false,
140    }
141}
142
143fn markdownlint_arguments_verify(arguments: &[String]) -> bool {
144    !arguments.is_empty()
145        && !arguments.iter().any(|argument| {
146            matches!(argument.as_str(), "--fix" | "-f" | "--help" | "-h" | "--version" | "-v")
147                || argument.starts_with("--fix=")
148        })
149}
150
151/// Whether `bun test` or `bun run <test|build|lint|check>` runs a suite.
152fn bun_test_or_run_verifies(second: Option<&str>, third: Option<&str>) -> bool {
153    matches!(second, Some("test"))
154        || (second == Some("run") && matches!(third, Some("test" | "build" | "lint" | "check")))
155}
156
157/// Whether the located `bun x`/`npx` package slot names pinned markdownlint
158/// with verifying trailing arguments.
159fn markdownlint_package_verifies(command_words: &[String], package_index: Option<usize>) -> bool {
160    package_index.is_some_and(|index| {
161        let Some(package) = command_words.get(index) else {
162            return false;
163        };
164        let is_markdownlint = package == "markdownlint-cli2"
165            || package.strip_prefix("markdownlint-cli2@").is_some_and(|version| {
166                version.split('.').count() == 3
167                    && version
168                        .split('.')
169                        .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
170            });
171        is_markdownlint && command_words.get(index + 1..).is_some_and(markdownlint_arguments_verify)
172    })
173}
174
175pub(super) fn contains_verification_invocation(command: &str) -> bool {
176    static_shell_command_words(command)
177        .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
178}
179
180/// Recognize a verifier for diagnostic feedback, including status-masking tails
181/// such as `; echo $?` that cannot pass static verification admission.
182/// This heuristic grants no permissions, verification credit, or repair edits.
183pub fn shell_command_contains_verifier(args: &Value) -> bool {
184    let Some(command) = shell_command_text_with_args(args) else {
185        return false;
186    };
187    super::super::readonly::parse_shell_command_words(&command)
188        .is_some_and(|commands| commands.iter().any(|words| is_verification_invocation(words)))
189}
190
191/// Whether a command inspects search results that normally produce output.
192///
193/// Used only for progress accounting: an empty read-only search pipeline can
194/// exit successfully when its final filter masks the search's no-match status.
195/// Quiet/existence probes intentionally return no text and are excluded. This
196/// predicate grants no execution permissions and never verifies mutations.
197pub fn shell_command_is_output_search(args: &Value) -> bool {
198    let Some(command) = shell_command_text_with_args(args) else {
199        return false;
200    };
201    let Some(segments) = static_shell_command_words(&command) else {
202        return false;
203    };
204    let mut saw_search = false;
205    for words in &segments {
206        if !command_words_are_readonly(words) || is_verification_invocation(words) {
207            return false;
208        }
209        let words = crate::tools::command_args::command_words_after_environment_prefix(words);
210        if command_words_are_grep_search(words) {
211            if grep_words_request_quiet_output(words) {
212                return false;
213            }
214            saw_search = true;
215        }
216    }
217    saw_search
218}
219
220fn grep_words_request_quiet_output(words: &[String]) -> bool {
221    let is_rg = words
222        .first()
223        .and_then(|word| Path::new(word).file_name())
224        .is_some_and(|name| name == "rg");
225    let mut arguments = words.iter().skip(1);
226    let mut quiet = false;
227    while let Some(argument) = arguments.next() {
228        match argument.as_str() {
229            "--" => break,
230            "--quiet" | "--silent" => quiet = true,
231            "--no-quiet" if is_rg => quiet = false,
232            _ if argument.starts_with("--") => {
233                // Values can look like options, including patterns such as `-query`.
234                let takes_value = matches!(
235                    argument.as_str(),
236                    "--regexp"
237                        | "--file"
238                        | "--after-context"
239                        | "--before-context"
240                        | "--context"
241                        | "--max-count"
242                        | "--include"
243                        | "--exclude"
244                        | "--exclude-from"
245                        | "--exclude-dir"
246                        | "--label"
247                        | "--directories"
248                        | "--devices"
249                ) || (is_rg
250                    && matches!(
251                        argument.as_str(),
252                        "--glob"
253                            | "--iglob"
254                            | "--ignore-file"
255                            | "--pre-glob"
256                            | "--type"
257                            | "--type-not"
258                            | "--type-add"
259                            | "--type-clear"
260                            | "--replace"
261                            | "--encoding"
262                            | "--engine"
263                            | "--color"
264                            | "--colors"
265                            | "--threads"
266                            | "--max-depth"
267                            | "--max-columns"
268                            | "--max-filesize"
269                            | "--dfa-size-limit"
270                            | "--regex-size-limit"
271                            | "--context-separator"
272                            | "--field-context-separator"
273                            | "--field-match-separator"
274                            | "--hyperlink-format"
275                            | "--path-separator"
276                            | "--sort"
277                            | "--sortr"
278                            | "--generate"
279                    ));
280                if takes_value {
281                    arguments.next();
282                }
283            }
284            _ if argument.starts_with('-') => {
285                let mut flags = argument.chars().skip(1).peekable();
286                while let Some(flag) = flags.next() {
287                    if flag == 'q' {
288                        quiet = true;
289                    }
290                    let takes_value = matches!(flag, 'e' | 'f' | 'A' | 'B' | 'C' | 'm' | 'd')
291                        || (is_rg && matches!(flag, 'g' | 't' | 'T' | 'r' | 'E' | 'j' | 'M'))
292                        || (!is_rg && flag == 'D');
293                    if takes_value {
294                        if flags.peek().is_none() {
295                            arguments.next();
296                        }
297                        break;
298                    }
299                }
300            }
301            _ => {}
302        }
303    }
304    quiet
305}
306
307/// Whether exit code 1 belongs to a standalone grep-style search.
308/// Compound commands, shell wrappers and redirected diagnostics cannot prove
309/// the search's no-match status, even when their visible output is empty.
310pub fn shell_command_is_standalone_grep_search(args: &Value) -> bool {
311    let Some(command) = shell_command_text_with_args(args) else {
312        return false;
313    };
314    let Some(segments) = static_shell_command_words(&command) else {
315        return false;
316    };
317    let [words] = segments.as_slice() else {
318        return false;
319    };
320    shell_words::split(&command).is_ok_and(|raw_words| raw_words == *words)
321        && command_words_are_readonly(words)
322        && command_words_are_grep_search(words)
323}
324
325fn command_words_are_grep_search(words: &[String]) -> bool {
326    let words = crate::tools::command_args::command_words_after_environment_prefix(words);
327    let program = words
328        .first()
329        .and_then(|word| Path::new(word).file_name())
330        .and_then(|name| name.to_str());
331    matches!(program, Some("rg" | "grep" | "egrep" | "fgrep"))
332}
333
334/// Project markers checked in priority order before the Node tier: each
335/// entry names the files that select its verifier. First tier with any
336/// marker present wins, matching the previous sequential `if` chain.
337const PRE_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
338    (&["Cargo.toml"], "cargo check --locked"),
339    (&["go.mod"], "go test ./..."),
340    (&["deno.json", "deno.jsonc"], "deno test"),
341    (&["bun.lockb", "bun.lock"], "bun test"),
342];
343
344/// Project markers checked after the Node tier (`package.json` is resolved
345/// separately at its priority position for script sniffing).
346const POST_NODE_VERIFIER_MARKERS: &[(&[&str], &str)] = &[
347    (&["pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini"], "pytest -q"),
348    (&["Makefile", "makefile"], "make test"),
349    (&["justfile", "Justfile"], "just test"),
350];
351
352/// First verifier whose tier has any marker file under `workspace_root`.
353fn verifier_for_markers(workspace_root: &Path, markers: &[(&[&str], &str)]) -> Option<String> {
354    markers.iter().find_map(|(files, verifier)| {
355        files
356            .iter()
357            .any(|file| workspace_root.join(file).is_file())
358            .then(|| (*verifier).to_string())
359    })
360}
361
362/// Node verifier with `package.json` script sniffing: `test` runs directly,
363/// other known scripts run via `npm run`, and a missing/unreadable script
364/// map falls back to `npm test` so the directive never names a command that
365/// does not exist. Returns `None` when there is no `package.json`.
366fn default_verifier_for_node_workspace(workspace_root: &Path) -> Option<String> {
367    let package_json = workspace_root.join("package.json");
368    if !package_json.is_file() {
369        return None;
370    }
371    if let Ok(content) = std::fs::read_to_string(&package_json)
372        && let Ok(parsed) = serde_json::from_str::<Value>(&content)
373        && let Some(scripts) = parsed.get("scripts").and_then(Value::as_object)
374    {
375        for (script, command) in [
376            ("test", "npm test"),
377            ("check", "npm run check"),
378            ("lint", "npm run lint"),
379            ("build", "npm run build"),
380        ] {
381            if scripts.contains_key(script) {
382                return Some(command.to_string());
383            }
384        }
385    }
386    Some("npm test".to_string())
387}
388
389/// Detect a project-appropriate default verifier for autonomous recovery.
390///
391/// Inspects well-known project markers under `workspace_root` and returns a
392/// concrete standalone verification command the agent can run via
393/// `exec_command` (no pipes, no `;`/`||` joins). Priority follows the
394/// existing `is_verification_invocation` coverage: Rust → Go → Deno/Bun →
395/// Node → Python → Make/Just. Returns `None` when no marker is found so
396/// callers can fall back to the generic verifier examples.
397///
398/// This is intentionally synchronous and allocation-light (existence checks
399/// plus one small `package.json` read): it runs on the turn hot path when
400/// the anti-blind-editing gate needs an actionable recovery directive.
401/// Codex-style harness-managed verification (Stop-hook test gates,
402/// auto-review) shows that naming the exact command — rather than listing
403/// examples — is what unblocks long-running autonomous work.
404pub fn default_verifier_for_workspace(workspace_root: &Path) -> Option<String> {
405    if let Some(verifier) = verifier_for_markers(workspace_root, PRE_NODE_VERIFIER_MARKERS) {
406        return Some(verifier);
407    }
408    if let Some(verifier) = default_verifier_for_node_workspace(workspace_root) {
409        return Some(verifier);
410    }
411    // No recognised project marker; callers fall back to generic examples.
412    verifier_for_markers(workspace_root, POST_NODE_VERIFIER_MARKERS)
413}
414
415/// Which shell forms of a verifier clear the anti-blind-editing gate. Shared
416/// by the recovery directive and the blocked-mutation `next_action` so the
417/// two surfaces cannot drift.
418pub const VERIFIER_SHELL_FORM_NOTE: &str = "Cap output with `max_output_tokens`. Pure `head`/`tail` verifier tails run standalone; static read-only filtering pipelines run with fail-closed `pipefail`. Only terminal exit 0 clears the gate; `;`, `||`, dynamic syntax, and mutating tails do not qualify.";
419
420/// Stand-in for the verifier when no project command was detected or
421/// configured. It lists examples across ecosystems instead of naming one
422/// command, because a single concrete fallback (such as a Cargo command in a
423/// Go or Node workspace) would direct the model to a verifier that does not
424/// exist.
425pub const GENERIC_VERIFIER_DESCRIPTION: &str =
426    "your project's build/test/lint command (e.g. `cargo check --locked`, `go test ./...`, `npm test`, or `pytest -q`)";
427
428/// How harness text names the verifier to run: the resolved command in
429/// backticks, or [`GENERIC_VERIFIER_DESCRIPTION`] when none was resolved.
430/// `default_verifier` should come from [`default_verifier_for_workspace`] or
431/// the harness override resolution built on it.
432pub fn verifier_reference(default_verifier: Option<&str>) -> String {
433    match default_verifier.map(str::trim).filter(|command| !command.is_empty()) {
434        Some(command) => format!("`{command}`"),
435        None => GENERIC_VERIFIER_DESCRIPTION.to_string(),
436    }
437}
438
439/// Build the actionable verification-recovery directive with a concrete
440/// command. `default_verifier` should come from
441/// [`default_verifier_for_workspace`]; when `None`, the generic examples are
442/// kept so the directive never names a command that does not exist.
443pub fn verification_recovery_directive(default_verifier: Option<&str>, attempt: u8, max_attempts: u8) -> String {
444    let verifier = verifier_reference(default_verifier);
445    format!(
446        "Verification recovery ({attempt}/{max_attempts}): completion is unverified. Continue implementation and repair reported failures; edits remain available. \
447        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. \
448        {VERIFIER_SHELL_FORM_NOTE} Reuse fresh passes; successful completion requires all mandatory checks."
449    )
450}
451
452/// Return whether a shell tool call is an admitted truncation-only verification
453/// attempt while the anti-blind-editing gate is pending.
454///
455/// Piped verifiers (e.g. `cargo check 2>&1 | head -c 4000`) must be allowed to
456/// run so the model can see the failure; otherwise the generic "cap output
457/// with `| head`" guidance deadlocks on `Mutation blocked until verification`.
458/// Only a truthful successful verifier clears the gate; this helper only
459/// decides admission, never clearance.
460///
461/// Fail-closed smuggling guard: every parsed shell segment must be a
462/// verification invocation or an allow-listed readonly command. A chained
463/// mutation such as `cargo check && rm -rf target` therefore stays blocked
464/// instead of riding through on the verifier prefix. Unparseable (dynamic)
465/// shell syntax also stays blocked.
466pub fn shell_command_is_admitted_verification_attempt(args: &Value) -> bool {
467    let Some(command) = shell_command_text_with_args(args) else {
468        return false;
469    };
470    if crate::tools::command_args::contains_dynamic_shell_syntax(&command) {
471        return false;
472    }
473    if command.starts_with(VERIFIER_PIPEFAIL_PREFIX) {
474        return pipefail_verifier_pipeline(&command).is_some();
475    }
476    let segments =
477        static_shell_command_words(&command).or_else(|| static_shell_command_words_with_output_plumbing(&command));
478    let Some(segments) = segments else {
479        return false;
480    };
481    if segments.is_empty() {
482        return false;
483    }
484    let mut saw_verification = false;
485    for words in &segments {
486        if is_verification_invocation(words) {
487            saw_verification = true;
488        } else if !command_words_are_readonly(words) {
489            return false;
490        }
491    }
492    saw_verification
493}
494
495pub(super) fn has_logical_sequencing(words: &[String]) -> bool {
496    words.iter().any(|word| matches!(word.as_str(), "&&" | "||" | ";"))
497}
498
499/// Split a command on top-level `|` operators, tracking single/double quotes
500/// and backslash escapes with the same discipline as
501/// [`shell_uses_only_and_chaining`]. Returns the pipe-separated stages in
502/// order, or `None` when no top-level pipe exists. `||` is not special-cased:
503/// it yields an empty stage, which stage validation rejects — fail-closed
504/// without a second operator table to keep in sync.
505fn split_top_level_pipes(command: &str) -> Option<Vec<&str>> {
506    if !command.contains('|') {
507        return None;
508    }
509    let mut stages = Vec::new();
510    let mut start = 0;
511    let mut saw_pipe = false;
512    let mut in_single_quote = false;
513    let mut in_double_quote = false;
514    let mut chars = command.char_indices().peekable();
515    while let Some((index, character)) = chars.next() {
516        // Outside single quotes a backslash escapes the next character for the
517        // shell, so `\|` is a literal pipe, not a stage separator. Consume the
518        // pair to stay aligned with the shell (mirrors the `&&`-chain scanner).
519        if character == '\\' && !in_single_quote {
520            chars.next();
521            continue;
522        }
523        if character == '\'' && !in_double_quote {
524            in_single_quote.toggle();
525            continue;
526        }
527        if character == '"' && !in_single_quote {
528            in_double_quote.toggle();
529            continue;
530        }
531        if in_single_quote || in_double_quote {
532            continue;
533        }
534        if character == '|' {
535            saw_pipe = true;
536            stages.push(&command[start..index]);
537            start = index + character.len_utf8();
538        }
539    }
540    if !saw_pipe {
541        return None;
542    }
543    stages.push(&command[start..]);
544    Some(stages)
545}
546
547/// Whether a pipeline tail stage is a pure output truncator: a bare `head` or
548/// `tail` invocation (any flags) with no shell operators of its own. Anything
549/// else (`grep`, `wc`, `sort`, redirects, backgrounding, chaining) keeps its
550/// pipeline semantics and must not be elided — dropping it would discard work
551/// the caller asked for or change what the exit status means.
552fn is_pure_truncation_stage(stage: &str) -> bool {
553    let trimmed = stage.trim();
554    if trimmed.is_empty() {
555        return false;
556    }
557    // A truncator stage is one simple command: reject any operator that would
558    // indicate chaining, backgrounding, redirection, or nesting. The scan is
559    // quote-aware so quoted flag values (e.g. `--sep=';'`) do not false-reject;
560    // an unaware scan could only over-reject, which stays fail-closed.
561    let mut in_single_quote = false;
562    let mut in_double_quote = false;
563    let mut chars = trimmed.chars().peekable();
564    while let Some(character) = chars.next() {
565        if character == '\\' && !in_single_quote {
566            chars.next();
567            continue;
568        }
569        if character == '\'' && !in_double_quote {
570            in_single_quote.toggle();
571            continue;
572        }
573        if character == '"' && !in_single_quote {
574            in_double_quote.toggle();
575            continue;
576        }
577        if in_single_quote || in_double_quote {
578            continue;
579        }
580        if matches!(character, ';' | '&' | '<' | '>' | '\n' | '|') {
581            return false;
582        }
583    }
584    let words = match shell_words::split(trimmed) {
585        Ok(words) => words,
586        Err(_) => return false,
587    };
588    let Some(parsed) = NonEmptySlice::from_slice(&words) else {
589        return false;
590    };
591    let program = Path::new(parsed.first())
592        .file_name()
593        .and_then(|name| name.to_str())
594        .unwrap_or(parsed.first().as_str())
595        .to_ascii_lowercase();
596    matches!(program.as_str(), "head" | "tail")
597}
598
599/// Rewrite a truncation-only piped verifier (`cargo check 2>&1 | head -c 4000`)
600/// to its standalone verifier prefix so the observed exit status is the
601/// verifier's, not the truncator's.
602///
603/// A pipeline's status belongs to its tail: running `cargo check | tail`
604/// reports `tail`'s success even when the build fails, and the model reads
605/// that exit 0 as "verified" while the anti-blind gate (correctly) stays
606/// pending — a deadlock manufactured by shell exit-status semantics, observed
607/// in real sessions. Eliding the truncator (output stays capped via
608/// `max_output_tokens`) makes the status truthful in one round trip.
609///
610/// Fail-closed gates, all required:
611/// - the full command is an admitted verification attempt (no dynamic
612///   syntax; every segment independently verification-or-readonly), so shapes
613///   like `cargo check | tail; rm …` can never reach the rewrite;
614/// - the head classifies as [`ShellActivity::Verification`] on its own, so
615///   `;`/`||`/background joins and smuggled mutations behind a verifier
616///   prefix are rejected (only standalone verifiers and pure `&&` verifier
617///   chains pass, whose `&&` exit status is truthful; output redirects such
618///   as `> build.log` are preserved verbatim in the head and do not mask the
619///   status, so they rewrite safely);
620/// - every tail stage is a pure `is_pure_truncation_stage` truncator, so
621///   `grep`/`wc`/`sort` tails (whose filtering is real work) are preserved.
622///
623/// Returns the standalone verifier text, or `None` when the command must run
624/// (or be rejected) exactly as typed. Only commands whose raw text carries a
625/// top-level `|` are candidates; array and indexed spellings re-quote
626/// operators when joined, so they never present a top-level pipe and keep
627/// today's behavior.
628pub fn rewrite_truncation_only_verifier(args: &Value) -> Option<String> {
629    use crate::config::constants::tools as tool_names;
630
631    let command = shell_command_text_with_args(args)?;
632    if !shell_command_is_admitted_verification_attempt(args) {
633        return None;
634    }
635    let stages = split_top_level_pipes(&command)?;
636    let (head, tails) = stages.split_first()?;
637    let head = head.trim();
638    if head.is_empty() || tails.iter().any(|stage| !is_pure_truncation_stage(stage)) {
639        return None;
640    }
641    let head_args = serde_json::json!({"cmd": head});
642    if !matches!(classify_shell_activity(tool_names::EXEC_COMMAND, &head_args), ShellActivity::Verification) {
643        return None;
644    }
645    Some(head.to_string())
646}
647
648// `&&` fails closed when the selected shell does not support pipefail.
649const VERIFIER_PIPEFAIL_PREFIX: &str = "set -o pipefail && ";
650
651/// The exact status-only shell setup, with the entire verifier pipeline validated.
652/// Command policy still checks every executable and explicit deny rule.
653pub(crate) fn pipefail_verifier_pipeline(command: &str) -> Option<&str> {
654    let pipeline = command.strip_prefix(VERIFIER_PIPEFAIL_PREFIX)?;
655    if crate::tools::command_args::contains_dynamic_shell_syntax(pipeline) {
656        return None;
657    }
658    verifier_pipeline_head(pipeline).map(|_| pipeline)
659}
660
661/// Validate a static pipeline without granting execution or mutation permissions.
662fn verifier_pipeline_head(command: &str) -> Option<&str> {
663    let stages = split_top_level_pipes(command)?;
664    let (head, tails) = stages.split_first()?;
665    let head = head.trim();
666    let head_args = serde_json::json!({"cmd": head});
667    if classify_shell_activity(crate::config::constants::tools::EXEC_COMMAND, &head_args) != ShellActivity::Verification
668    {
669        return None;
670    }
671    // Tail stages must be independently static and read-only. Logical joins,
672    // unsafe redirections, substitutions, and mutations cannot ride behind it.
673    for stage in tails {
674        let segments = static_shell_command_words(stage)?;
675        if segments.len() != 1 || !segments.first().is_some_and(|words| command_words_are_readonly(words)) {
676            return None;
677        }
678    }
679    Some(head)
680}
681
682/// Preserve filtering while making pipeline success depend on every stage.
683/// Pure truncator pipelines retain the existing standalone rewrite to avoid
684/// SIGPIPE from early-closing head/tail. Other static read-only tails use
685/// pipefail; failures (including no matches or SIGPIPE) never clear the gate.
686pub(super) fn rewrite_verifier_pipeline(args: &Value) -> Option<String> {
687    if let Some(standalone) = rewrite_truncation_only_verifier(args) {
688        return Some(standalone);
689    }
690    let command = shell_command_text_with_args(args)?;
691    if command.starts_with(VERIFIER_PIPEFAIL_PREFIX)
692        || !shell_command_is_admitted_verification_attempt(args)
693        || verifier_pipeline_head(&command).is_none()
694    {
695        return None;
696    }
697    Some(format!("{VERIFIER_PIPEFAIL_PREFIX}{command}"))
698}