Skip to main content

vtcode_core/tools/tool_intent/
activity.rs

1//! Shell activity classification for progress accounting and output previews.
2//!
3//! Mutation safety remains owned by [`super::classify_tool_intent`]. This
4//! module adds the narrower distinction between repository inspection and
5//! verification without duplicating that safety decision in binary consumers.
6
7use std::path::Path;
8
9use serde_json::Value;
10use vtcode_commons::validation::NonEmptySlice;
11
12use crate::tools::command_args::shell_command_text_with_args;
13
14use super::readonly::{
15    command_words_are_readonly, static_shell_command_words, static_shell_command_words_with_output_plumbing,
16};
17
18/// Progress semantics for a command invocation.
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub enum ShellActivity {
21    /// Read-only repository or environment inspection.
22    Inspection,
23    /// A build, test, lint, or compile command that verifies work.
24    Verification,
25    /// A command that may mutate state and is not primarily verification.
26    Mutation,
27}
28
29fn make_like_verification_targets(words: &[String]) -> bool {
30    let mut saw_target = false;
31    for word in words.iter().skip(1) {
32        let lower = word.to_ascii_lowercase();
33        if lower.starts_with('-') || lower.contains('=') {
34            continue;
35        }
36        if !matches!(lower.as_str(), "test" | "tests" | "check" | "checks" | "lint" | "verify" | "validate") {
37            return false;
38        }
39        saw_target = true;
40    }
41    saw_target
42}
43
44fn python_verification_arguments(arguments: &[String]) -> bool {
45    // Python executes the first target, not later verifier-like tokens.
46    let mut arguments = arguments.iter();
47    let target = arguments.find(|word| {
48        !matches!(word.as_str(), "-I" | "-E" | "-s" | "-S" | "-B" | "-O" | "-OO" | "-q" | "-u" | "-b" | "-bb" | "-v")
49    });
50    match target.map(String::as_str) {
51        Some("-m") => arguments.next().is_some_and(|module| module == "pytest"),
52        Some(script) => {
53            ["scripts/check_markdown.py", "scripts/check_docs_links.py"]
54                .iter()
55                .any(|known| Path::new(script).ends_with(known))
56                && arguments.next().is_none()
57        }
58        None => false,
59    }
60}
61
62fn is_verification_invocation(words: &[String]) -> bool {
63    // Verifiers may emit build artifacts; reject source-repair modes without
64    // applying the stricter inspection-only output restrictions to compilers.
65    if crate::tools::command_args::command_uses_source_repair(words)
66        || crate::tools::command_args::environment_prefix_has_injection_keys(words)
67    {
68        return false;
69    }
70    let command_words = crate::tools::command_args::command_words_after_environment_prefix(words);
71    let first = command_words.first().map(String::as_str).unwrap_or_default();
72    let second = command_words.get(1).map(|word| word.to_ascii_lowercase());
73    let third = command_words.get(2).map(|word| word.to_ascii_lowercase());
74    let program = Path::new(first)
75        .file_name()
76        .and_then(|name| name.to_str())
77        .unwrap_or(first)
78        .to_ascii_lowercase();
79
80    match program.as_str() {
81        "markdownlint-cli2" => command_words.get(1..).is_some_and(markdownlint_arguments_verify),
82        "npx" => {
83            let package_index = command_words
84                .iter()
85                .enumerate()
86                .skip(1)
87                .find(|(_, word)| {
88                    !matches!(word.as_str(), "--yes" | "-y" | "--no-install")
89                        && !word.strip_prefix("--loglevel=").is_some_and(|level| {
90                            matches!(
91                                level,
92                                "silent" | "error" | "warn" | "notice" | "http" | "info" | "verbose" | "silly"
93                            )
94                        })
95                })
96                .map(|(index, _)| index);
97            package_index.is_some_and(|index| {
98                let Some(package) = command_words.get(index) else {
99                    return false;
100                };
101                let is_markdownlint = package == "markdownlint-cli2"
102                    || package.strip_prefix("markdownlint-cli2@").is_some_and(|version| {
103                        version.split('.').count() == 3
104                            && version
105                                .split('.')
106                                .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
107                    });
108                is_markdownlint && command_words.get(index + 1..).is_some_and(markdownlint_arguments_verify)
109            })
110        }
111        "cargo" => {
112            if second.as_deref() == Some("fmt") {
113                // `cargo fmt` without `--check` reformats the worktree (mutation).
114                // With `--check` it is a read-only lint verification.
115                return words.iter().any(|word| word == "--check");
116            }
117            matches!(second.as_deref(), Some("check" | "build" | "clippy" | "test"))
118                || (second.as_deref() == Some("nextest") && third.as_deref() == Some("run"))
119        }
120        "go" => matches!(second.as_deref(), Some("test" | "build")),
121        "npm" | "pnpm" | "yarn" => {
122            matches!(second.as_deref(), Some("test" | "build" | "lint" | "check"))
123                || (second.as_deref() == Some("run")
124                    && matches!(third.as_deref(), Some("test" | "build" | "lint" | "check")))
125        }
126        "bun" | "bunx" => {
127            matches!(second.as_deref(), Some("test"))
128                || (second.as_deref() == Some("run")
129                    && matches!(third.as_deref(), Some("test" | "build" | "lint" | "check")))
130        }
131        "deno" => matches!(second.as_deref(), Some("test" | "lint" | "check")),
132        "make" | "gmake" | "just" => make_like_verification_targets(command_words),
133        "uv" => {
134            let Some(arguments) = crate::tools::command_args::uv_run_command_words(command_words) else {
135                return false;
136            };
137            let mut arguments = arguments.iter();
138            let target = arguments.next();
139            match target.map(String::as_str) {
140                Some("pytest") => true,
141                Some("ruff") => arguments.next().is_some_and(|argument| argument == "check"),
142                Some("python" | "python3") => python_verification_arguments(arguments.as_slice()),
143                _ => false,
144            }
145        }
146        "ruff" => {
147            if second.as_deref() == Some("format") {
148                return words.iter().any(|word| word == "--check");
149            }
150            matches!(second.as_deref(), Some("check" | "lint"))
151        }
152        "tsc" => {
153            // Bare `tsc` emits output (mutation). Only `--noEmit` type-checks.
154            words.iter().any(|word| word == "--noEmit")
155        }
156        "eslint" => {
157            // `eslint --fix` rewrites the worktree (mutation).
158            !words.iter().any(|word| word == "--fix" || word == "--fix-dry-run")
159        }
160        "rustc" | "pytest" | "xcodebuild" | "gradle" | "gradlew" => true,
161        "python" | "python3" => python_verification_arguments(&command_words[1..]),
162        _ if first.ends_with("/scripts/check.sh") || first.ends_with("/scripts/check-dev.sh") => true,
163        _ => false,
164    }
165}
166
167fn markdownlint_arguments_verify(arguments: &[String]) -> bool {
168    !arguments.is_empty()
169        && !arguments.iter().any(|argument| {
170            matches!(argument.as_str(), "--fix" | "-f" | "--help" | "-h" | "--version" | "-v")
171                || argument.starts_with("--fix=")
172        })
173}
174
175fn 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::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
495fn 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 = !in_single_quote;
525            continue;
526        }
527        if character == '"' && !in_single_quote {
528            in_double_quote = !in_double_quote;
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 = !in_single_quote;
571            continue;
572        }
573        if character == '"' && !in_single_quote {
574            in_double_quote = !in_double_quote;
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.
686fn 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}
699
700/// Shell-call arguments as the execution kernel runs them.
701///
702/// The kernel applies `rewrite_verifier_pipeline` to every
703/// command-run call before execution, so the process that runs (and whose
704/// exit status the outcome reports) is the standalone verifier, not the typed
705/// pipeline. Static filtering pipelines instead enable pipefail. Gate
706/// bookkeeping must classify that same command; classifying the
707/// typed pipeline would call a truthful `cargo check 2>&1 | tail -5` success a
708/// mutation and leave the gate pending. Arguments the kernel runs unchanged
709/// (already-normalized arguments included, since the rewrite is idempotent)
710/// are borrowed as-is.
711pub fn shell_args_as_executed<'a>(tool_name: &str, args: &'a Value) -> std::borrow::Cow<'a, Value> {
712    if !super::is_command_run_tool_call(tool_name, args) {
713        return std::borrow::Cow::Borrowed(args);
714    }
715    let Some(rewritten) = rewrite_verifier_pipeline(args) else {
716        return std::borrow::Cow::Borrowed(args);
717    };
718    let mut executed = args.clone();
719    match executed.as_object_mut() {
720        Some(payload) => {
721            if payload.get("raw_command").is_some_and(Value::is_string) {
722                payload.insert("raw_command".to_string(), Value::String(rewritten.clone()));
723            }
724            // The rewrite already includes the suffix (or elides its truncator).
725            // Keeping args would append it a second time at launch.
726            payload.remove("args");
727            payload.insert("command".to_string(), Value::String(rewritten));
728            std::borrow::Cow::Owned(executed)
729        }
730        None => std::borrow::Cow::Borrowed(args),
731    }
732}
733
734fn is_known_inspection(words: &[String]) -> bool {
735    if words
736        .iter()
737        .any(|word| matches!(word.as_str(), ">" | ">>" | "|" | "&&" | ";" | "||"))
738    {
739        return false;
740    }
741    command_words_are_readonly(words)
742}
743
744fn classify_provable_shell_sequence(command: &str) -> Option<ShellActivity> {
745    let (segments, has_output_plumbing) = if let Some(segments) = static_shell_command_words(command) {
746        (segments, false)
747    } else {
748        (static_shell_command_words_with_output_plumbing(command)?, true)
749    };
750    if has_output_plumbing && segments.len() != 1 {
751        return None;
752    }
753    let has_multiple_segments = segments.len() > 1;
754    let mut saw_verification = false;
755
756    for words in segments {
757        if is_verification_invocation(&words) {
758            saw_verification = true;
759        } else if !command_words_are_readonly(&words) {
760            return None;
761        }
762    }
763
764    if has_output_plumbing && !saw_verification {
765        return None;
766    }
767
768    // Shell execution does not guarantee that a pipeline or logical chain's
769    // final status reflects every verification stage. Do not let a successful
770    // downstream command clear the anti-blind checkpoint after an earlier
771    // verifier failed.
772    //
773    // Exception: a pure `&&` chain of verification (or readonly) segments
774    // short-circuits on first failure, so its exit status does represent every
775    // stage. `cargo fmt --check && cargo check --locked && cargo nextest run`
776    // must clear the gate; `;`, `||`, `|`, and background `&` still mask
777    // failures and stay `Mutation`.
778    if saw_verification && has_multiple_segments {
779        if shell_uses_only_and_chaining(command) {
780            return Some(ShellActivity::Verification);
781        }
782        return Some(ShellActivity::Mutation);
783    }
784
785    Some(if saw_verification {
786        ShellActivity::Verification
787    } else {
788        ShellActivity::Inspection
789    })
790}
791
792fn has_shell_sequence(command: &str) -> bool {
793    static_shell_command_words(command).is_none_or(|segments| segments.len() > 1)
794}
795
796/// Quote-aware check that a shell command chains segments only with `&&`.
797///
798/// Returns `false` when an unquoted `;`, newline, `||`, single `&`
799/// (background), or `|` (pipeline) is present, since those operators let a
800/// downstream success mask an earlier verifier failure. `&&` short-circuits,
801/// so a pure `&&` chain of verifiers has a faithful aggregate exit status and
802/// may clear the anti-blind-editing gate. Backslash escapes outside single
803/// quotes are honored, so a shell-literal `\"` cannot open a phantom quote
804/// state that hides a later live operator.
805fn shell_uses_only_and_chaining(command: &str) -> bool {
806    let chars: Vec<char> = command.chars().collect();
807    let mut index = 0;
808    let mut in_single_quote = false;
809    let mut in_double_quote = false;
810
811    while index < chars.len() {
812        let character = chars[index];
813        // Outside single quotes a backslash escapes the next character for the
814        // shell: `\"` is a literal quote (no quote-state change) and `\;` is an
815        // inert character, not an operator. Skip the pair so the scanner stays
816        // aligned with the shell and fails closed.
817        if character == '\\' && !in_single_quote && index + 1 < chars.len() {
818            index += 2;
819            continue;
820        }
821        if character == '\'' && !in_double_quote {
822            in_single_quote = !in_single_quote;
823            index += 1;
824            continue;
825        }
826        if character == '"' && !in_single_quote {
827            in_double_quote = !in_double_quote;
828            index += 1;
829            continue;
830        }
831        if in_single_quote || in_double_quote {
832            index += 1;
833            continue;
834        }
835        match character {
836            // Token extraction walks nested commands and drops negation;
837            // neither shape proves each check actually returned success.
838            ';' | '\n' | '|' | '!' | '(' | ')' => return false,
839            '&' => {
840                let next_is_and = chars.get(index + 1) == Some(&'&');
841                if !next_is_and {
842                    return false;
843                }
844                // A `||`-style `|` was already rejected above; `&&` consumes
845                // both characters. `|||`, `&&&`, and similar malformed
846                // sequences fail closed.
847                let third = chars.get(index + 2);
848                if third == Some(&'&') || third == Some(&'|') {
849                    return false;
850                }
851                index += 2;
852                continue;
853            }
854            _ => {}
855        }
856        index += 1;
857    }
858
859    true
860}
861
862/// Match required checks within a statically proven, status-preserving chain.
863/// This is evidence accounting only; execution and permission gates still apply.
864pub(crate) fn shell_command_covers_required_check(command: &str, required: &str) -> bool {
865    if !shell_uses_only_and_chaining(command) || !shell_uses_only_and_chaining(required) {
866        return false;
867    }
868    let Some(segments) = static_shell_command_words(command) else {
869        return false;
870    };
871    let Some(required_segments) = static_shell_command_words(required) else {
872        return false;
873    };
874    if segments.iter().any(|words| {
875        words.first().is_some_and(|word| word == "cd")
876            || (!is_verification_invocation(words) && !command_words_are_readonly(words))
877    }) {
878        return false;
879    }
880    segments
881        .windows(required_segments.len())
882        .any(|window| window == required_segments)
883}
884
885/// Classify a shell call without weakening the authoritative mutation guard.
886///
887/// Standalone output plumbing such as `2>&1` or `> build.log` does not turn a
888/// primary verification command into a mutation for progress accounting.
889/// Pipelines and `;`/`||` chains remain mutations because their final
890/// status does not reliably represent every verification stage. Pure `&&`
891/// chains of verification-or-readonly segments are `Verification` since `&&`
892/// short-circuits on first failure.
893#[must_use]
894pub fn classify_shell_activity(tool_name: &str, args: &Value) -> ShellActivity {
895    let command = shell_command_text_with_args(args);
896    if command.is_none() && crate::tools::command_args::raw_command_text(args).is_some() {
897        return ShellActivity::Mutation;
898    }
899    if command.as_deref().and_then(pipefail_verifier_pipeline).is_some() {
900        return ShellActivity::Verification;
901    }
902    let words = crate::tools::command_args::command_words(args).ok().flatten();
903    let has_unclassified_shell_sequence = command.as_deref().is_some_and(has_shell_sequence);
904
905    if let Some(activity) = command.as_deref().and_then(classify_provable_shell_sequence) {
906        return activity;
907    }
908    // A failed sequence proof cannot fall back to the original tool intent:
909    // appended arguments may make an otherwise read-only tail mutate state.
910    if has_unclassified_shell_sequence {
911        return ShellActivity::Mutation;
912    }
913
914    let intent = super::classify_tool_intent(tool_name, args);
915
916    if !has_unclassified_shell_sequence && words.as_deref().is_some_and(is_known_inspection) {
917        return ShellActivity::Inspection;
918    }
919
920    let starts_with_verification = words.as_deref().is_some_and(is_verification_invocation);
921    let contains_verification =
922        starts_with_verification || command.as_deref().is_some_and(contains_verification_invocation);
923    if !intent.mutating {
924        return if contains_verification {
925            ShellActivity::Verification
926        } else {
927            ShellActivity::Inspection
928        };
929    }
930
931    if starts_with_verification
932        && !has_unclassified_shell_sequence
933        && !words.as_deref().is_some_and(has_logical_sequencing)
934    {
935        ShellActivity::Verification
936    } else {
937        ShellActivity::Mutation
938    }
939}
940
941fn is_literal_timer(words: &[String]) -> bool {
942    let seconds = match words {
943        [program, seconds] if program == "sleep" => Some(seconds.as_str()),
944        [program, flag, code] if matches!(program.as_str(), "python" | "python3") && flag == "-c" => code
945            .strip_prefix("import time; time.sleep(")
946            .and_then(|code| code.strip_suffix(')')),
947        _ => None,
948    };
949    seconds.is_some_and(|seconds| {
950        !seconds.is_empty()
951            && seconds.bytes().all(|byte| byte.is_ascii_digit() || byte == b'.')
952            && seconds
953                .parse::<f64>()
954                .is_ok_and(|seconds| seconds.is_finite() && seconds >= 0.0)
955    })
956}
957
958/// Whether an exec result creates workspace mutation debt. This is accounting
959/// only: permission and admission still use the stricter static classifiers.
960/// Unknown syntax or commands retain debt; changed-file evidence always wins.
961#[must_use]
962pub fn exec_mutation_should_incur_debt(command: &str, output: &Value) -> bool {
963    if exec_output_has_changes(output) {
964        return true;
965    }
966    let mut parser = tree_sitter::Parser::new();
967    if parser.set_language(&tree_sitter_bash::LANGUAGE.into()).is_err() {
968        return true;
969    }
970    let Some(tree) = parser.parse(command, None) else {
971        return true;
972    };
973    let root = tree.root_node();
974    root.has_error() || root.named_child_count() == 0 || !nonmutating_shell_node(root, command)
975}
976
977pub(crate) fn exec_output_has_changes(output: &Value) -> bool {
978    output
979        .get("modified_files")
980        .and_then(Value::as_array)
981        .is_some_and(|files| !files.is_empty())
982        || crate::tools::file_ops::diff_output_has_effective_change(output) == Some(true)
983}
984
985/// Path-prefixed globs cannot expand into options. Keep this narrower than
986/// general expansion: variables, substitutions, bare globs and dynamic heads
987/// remain unproven, and the parent command still checks program/options.
988fn is_literal_path_glob(word: &str) -> bool {
989    let Some((prefix, _)) = word.split_once('/') else {
990        return false;
991    };
992    !prefix.starts_with('-')
993        && !prefix.contains(['*', '?', '[', ']'])
994        && word.contains(['*', '?'])
995        && !word.contains(['[', ']'])
996        && !word
997            .chars()
998            .any(|character| character.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(character))
999}
1000
1001/// Inline grep filters remain one option even when the literal pattern has globs.
1002/// This is accounting proof only; shell admission is unchanged.
1003fn is_literal_grep_filter(word: &str) -> bool {
1004    let Some((option, pattern)) = word.split_once('=') else {
1005        return false;
1006    };
1007    matches!(option, "--include" | "--exclude" | "--exclude-dir")
1008        && !pattern.is_empty()
1009        && !pattern.chars().any(|c| c.is_whitespace() || "\"'$`\\{}()<>&;|~!".contains(c))
1010}
1011
1012/// Walk every supported node, including commands nested in substitutions.
1013/// Unlike command extraction, this proof must never discard unknown syntax.
1014fn nonmutating_shell_node(node: tree_sitter::Node<'_>, source: &str) -> bool {
1015    use crate::command_safety::shell_parser::contains_dynamic_shell_syntax;
1016    let Ok(text) = node.utf8_text(source.as_bytes()) else {
1017        return false;
1018    };
1019    match node.kind() {
1020        "command" => {
1021            let Some(name) = node.child_by_field_name("name") else {
1022                return false;
1023            };
1024            let Ok(name_text) = name.utf8_text(source.as_bytes()) else {
1025                return false;
1026            };
1027            if contains_dynamic_shell_syntax(name_text) {
1028                return false;
1029            }
1030            let mut words = Vec::new();
1031            let mut cursor = node.walk();
1032            for child in node.named_children(&mut cursor) {
1033                let Ok(word) = child.utf8_text(source.as_bytes()) else {
1034                    return false;
1035                };
1036                if child.kind() == "variable_assignment" {
1037                    return false;
1038                }
1039                if child != name
1040                    && child.kind() == "word"
1041                    && (is_literal_path_glob(word)
1042                        || (matches!(name_text, "grep" | "egrep" | "fgrep" | "rg") && is_literal_grep_filter(word)))
1043                    && matches!(name_text, "rg" | "grep" | "egrep" | "fgrep" | "ls" | "cat" | "head" | "tail" | "wc")
1044                {
1045                    // Classification sees a path operand; expansion cannot
1046                    // produce flags, while static mutating options stay visible.
1047                    words.push(word.to_owned());
1048                } else if contains_dynamic_shell_syntax(word) {
1049                    // Only these builtins cannot turn a dynamic argument into
1050                    // an option that writes or executes code. Keep arguments
1051                    // quoted so expansion cannot alter their dimensionality.
1052                    if !matches!(name_text, "echo" | "test") || !word.starts_with('"') {
1053                        return false;
1054                    }
1055                    words.push("dynamic-argument".to_owned());
1056                } else {
1057                    let Ok(parts) = shell_words::split(word) else {
1058                        return false;
1059                    };
1060                    words.extend(parts);
1061                }
1062            }
1063            if crate::tools::command_args::has_unsafe_readonly_options(&words)
1064                || (!is_verification_invocation(&words)
1065                    && !command_words_are_readonly(&words)
1066                    && !is_literal_timer(&words))
1067            {
1068                return false;
1069            }
1070        }
1071        "file_redirect" => {
1072            // Exact AST spans, never substring replacement: a filename such
1073            // as /dev/null.backup must not be mistaken for descriptor plumbing.
1074            return matches!(text, "2>&1" | "1>&2") || (cfg!(unix) && text == "2>/dev/null");
1075        }
1076        "word" | "regex" => {
1077            return !contains_dynamic_shell_syntax(text) || is_literal_path_glob(text) || is_literal_grep_filter(text);
1078        }
1079        "raw_string" | "string_content" | "comment" | "number" | "variable_name" | "special_variable_name" => {
1080            return true;
1081        }
1082        "simple_expansion" => return true,
1083        "expansion" => {
1084            // Support the literal prefix/suffix removal used by link probes;
1085            // other parameter operators and arithmetic remain unproven.
1086            if text.contains([':', '=', '+', '?', '!']) {
1087                return false;
1088            }
1089        }
1090        "program"
1091        | "list"
1092        | "pipeline"
1093        | "for_statement"
1094        | "do_group"
1095        | "if_statement"
1096        | "elif_clause"
1097        | "else_clause"
1098        | "while_statement"
1099        | "command_name"
1100        | "string"
1101        | "concatenation"
1102        | "command_substitution"
1103        | "redirected_statement" => {}
1104        _ if !node.is_named() => {
1105            return matches!(
1106                text,
1107                "&&" | "||"
1108                    | ";"
1109                    | "|"
1110                    | "for"
1111                    | "in"
1112                    | "do"
1113                    | "done"
1114                    | "if"
1115                    | "then"
1116                    | "elif"
1117                    | "else"
1118                    | "fi"
1119                    | "while"
1120                    | "until"
1121                    | "\""
1122                    | "'"
1123                    | "$("
1124                    | ")"
1125                    | "`"
1126                    | "$"
1127                    | "${"
1128                    | "}"
1129                    | "#"
1130                    | "##"
1131                    | "%"
1132                    | "%%"
1133            );
1134        }
1135        _ => return false,
1136    }
1137    let mut cursor = node.walk();
1138    node.children(&mut cursor).all(|child| nonmutating_shell_node(child, source))
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143    use serde_json::json;
1144
1145    use super::*;
1146    use crate::config::constants::tools;
1147    use crate::tools::tool_intent::is_readonly_command_session_command;
1148
1149    fn exec_command(command: &str) -> Value {
1150        json!({"cmd": command})
1151    }
1152
1153    #[test]
1154    fn literal_timers_do_not_create_mutation_debt_but_arbitrary_python_does() {
1155        let output = serde_json::json!({"exit_code":0});
1156        for command in [
1157            "python3 -c 'import time; time.sleep(0.01)'",
1158            "python -c 'import time; time.sleep(5)'",
1159            "sleep 30",
1160            "sleep 120",
1161            "sleep 0.01",
1162        ] {
1163            assert!(!exec_mutation_should_incur_debt(command, &output), "{command}");
1164            assert!(exec_mutation_should_incur_debt(command, &serde_json::json!({"modified_files":["src/lib.rs"]})));
1165        }
1166        for command in [
1167            "python3 -c 'import time; time.sleep(1); open(\"x\",\"w\")'",
1168            "python3 -c 'import time; time.sleep(float(\"nan\"))'",
1169            "python3 -c 'print(1)'",
1170            "python3 timer.py",
1171            "sleep $DELAY",
1172            "sleep 1 > timer.log",
1173            "sleep -1",
1174            "python3 -c 'import time; time.sleep(-1)'",
1175            "PYTHONSTARTUP=script.py python3 -c 'import time; time.sleep(1)'",
1176            "python3 -c 'import time; time.sleep(1)' > timer.log",
1177        ] {
1178            assert!(exec_mutation_should_incur_debt(command, &output), "{command}");
1179        }
1180    }
1181
1182    #[test]
1183    fn source_repair_commands_create_debt_instead_of_verifying() {
1184        for command in [
1185            "cargo clippy --fix --allow-dirty",
1186            "env LD_PRELOAD=./rewrite.so cargo clippy",
1187            "cargo +nightly clippy --fix",
1188            "cargo fix --allow-dirty",
1189            "ruff check --fix .",
1190            "ruff check --fix-only .",
1191            "ruff check --add-noqa .",
1192            "ruff check --add-ignore=reason .",
1193            "uv run --frozen --offline ruff check --fix .",
1194            "cargo clippy --fix && cargo check",
1195            "ruff check --fix . | head -20",
1196            // Do not treat an operand value as a safe preview flag.
1197            "ruff check --fix --exclude --diff .",
1198        ] {
1199            let args = exec_command(command);
1200            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Mutation, "{command}");
1201            assert!(!shell_command_is_admitted_verification_attempt(&args), "{command}");
1202            assert!(exec_mutation_should_incur_debt(command, &json!({"exit_code": 0})), "{command}");
1203        }
1204        for command in [
1205            "cargo clippy --locked",
1206            "cargo nextest run fix",
1207            "ruff check --no-fix .",
1208            "ruff check --diff .",
1209            "uv run --frozen --offline ruff check --no-fix .",
1210        ] {
1211            let args = exec_command(command);
1212            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Verification, "{command}");
1213            assert!(shell_command_is_admitted_verification_attempt(&args), "{command}");
1214            assert!(!exec_mutation_should_incur_debt(command, &json!({"exit_code": 0})), "{command}");
1215        }
1216    }
1217
1218    #[test]
1219    fn compiler_artifact_writes_remain_eligible_verification() {
1220        let command = "rustc --crate-type lib sample.rs -o checked.rlib";
1221        let args = exec_command(command);
1222        assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Verification);
1223        assert!(shell_command_is_admitted_verification_attempt(&args));
1224        // The inspection proof still sees a write; verifier eligibility owns
1225        // the build-artifact exemption, not the read-only permission boundary.
1226        assert!(exec_mutation_should_incur_debt(command, &json!({"exit_code":0})));
1227    }
1228
1229    #[test]
1230    fn verifier_diagnostics_recognize_masked_status_without_granting_admission() {
1231        for command in [
1232            "npx markdownlint-cli2 README.md; echo \"lint exit: $?\"",
1233            "cargo check; echo $?",
1234            "python3 scripts/check_markdown.py; echo \"lint exit: $?\"",
1235            "cargo check --locked || true",
1236            "cargo check; rm marker",
1237        ] {
1238            let args = exec_command(command);
1239            assert!(shell_command_contains_verifier(&args), "{command}");
1240            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Mutation);
1241        }
1242        let masked = exec_command("npx markdownlint-cli2 README.md; echo \"lint exit: $?\"");
1243        assert!(!shell_command_is_admitted_verification_attempt(&masked));
1244        assert_eq!(shell_args_as_executed(tools::EXEC_COMMAND, &masked).as_ref(), &masked);
1245        for args in [
1246            exec_command("echo 'cargo check; echo $?'"),
1247            exec_command("grep 'cargo check' README.md"),
1248            exec_command("npx markdownlint-cli2 --fix README.md"),
1249            json!({"cmd":"cargo check; true", "raw_command":"echo hello"}),
1250            json!({"cmd":"npx markdownlint-cli2", "args":["--fix", "README.md"]}),
1251        ] {
1252            assert!(!shell_command_contains_verifier(&args), "{args}");
1253        }
1254    }
1255
1256    #[test]
1257    fn markdownlint_verification_preserves_command_boundaries() {
1258        for command in [
1259            "markdownlint-cli2 README.md",
1260            "npx --yes markdownlint-cli2 README.md",
1261            "npx --no-install markdownlint-cli2@0.23.3 README.md",
1262            "npx --yes --loglevel=error markdownlint-cli2@0.23.3 --config .markdownlint-cli2.jsonc ':README.md'",
1263            "npx -y markdownlint-cli2 README.md && cargo check --locked",
1264            "python3 scripts/check_markdown.py",
1265            "python ./scripts/check_markdown.py",
1266            "python3 scripts/check_docs_links.py",
1267            "python ./scripts/check_docs_links.py",
1268        ] {
1269            assert!(shell_command_is_admitted_verification_attempt(&exec_command(command)), "{command}");
1270            assert_eq!(
1271                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1272                ShellActivity::Verification,
1273                "{command}"
1274            );
1275        }
1276        for command in [
1277            "markdownlint-cli2 --fix README.md",
1278            "npx --yes markdownlint-cli2 -f README.md",
1279            "npx --yes markdownlint-cli2 --fix=true README.md",
1280            "markdownlint-cli2 --version",
1281            "npx --package evil markdownlint-cli2 README.md",
1282            "npx --loglevel=error --package evil markdownlint-cli2 README.md",
1283            "npx --loglevel=error markdownlint-cli2 --fix README.md",
1284            "npx --loglevel=unknown markdownlint-cli2 README.md",
1285            "npx markdownlint-cli2@evil README.md",
1286            "npx markdownlint-cli2 README.md && rm README.md",
1287            "python3 scripts/check_markdown.py --fix",
1288            "python3 scripts/check_markdown.py --list",
1289            "python3 scripts/check_markdown.py --help",
1290            "python3 other/check_markdown.py",
1291            "python3 scripts/check_docs_links.py --help",
1292            "python3 other/check_docs_links.py",
1293        ] {
1294            assert!(!shell_command_is_admitted_verification_attempt(&exec_command(command)), "{command}");
1295        }
1296        assert_ne!(
1297            classify_shell_activity(tools::EXEC_COMMAND, &exec_command("npx markdownlint-cli2 README.md | grep error")),
1298            ShellActivity::Verification
1299        );
1300    }
1301
1302    #[test]
1303    fn output_search_recognizes_static_search_pipelines() {
1304        for command in [
1305            "rg --files --hidden -g '.markdownlint*'",
1306            "rg --files --hidden | rg -i 'markdownlint' | sed -n '1,15p'",
1307            "git ls-files | grep -i markdownlint | head -10",
1308            "LANG=C /usr/bin/grep -n missing README.md",
1309            "rg -- '-q' README.md",
1310            "rg -e -query src | head -10",
1311            "grep -ne-query README.md",
1312            "rg --regexp --quiet src",
1313            "rg -g '-q*' missing src",
1314            "rg '-g-q*' missing src",
1315            "rg -q --no-quiet missing src",
1316        ] {
1317            assert!(shell_command_is_output_search(&exec_command(command)), "{command}");
1318        }
1319        assert!(shell_command_is_output_search(&json!({"command": ["rg", "missing", "src"]})));
1320    }
1321
1322    #[test]
1323    fn output_search_excludes_quiet_probes_and_unproven_commands() {
1324        for command in [
1325            "rg -q pattern src",
1326            "grep -nq pattern README.md",
1327            "rg --quiet pattern src | head -10",
1328            "grep --silent pattern README.md",
1329            "rg -e -query -q src",
1330            "grep -nqe-query README.md",
1331            "rg --regexp --quiet --quiet src",
1332            "rg -q --no-quiet -q missing src",
1333            "echo 'rg missing'",
1334            "cat empty.txt",
1335            "cargo check | rg error",
1336            "rg missing src; touch result.txt",
1337            "rg missing $(pwd)",
1338            "rg missing src > result.txt",
1339            "rg --pre 'touch result.txt' missing src",
1340        ] {
1341            assert!(!shell_command_is_output_search(&exec_command(command)), "{command}");
1342        }
1343        assert!(!shell_command_is_output_search(&json!({})));
1344    }
1345
1346    #[test]
1347    fn output_search_distinguishes_separator_values_from_quiet_flags() {
1348        for option in [
1349            "--context-separator",
1350            "--field-context-separator",
1351            "--field-match-separator",
1352        ] {
1353            let command = format!("rg {option} -q missing src | head -10");
1354            assert!(shell_command_is_output_search(&exec_command(&command)), "{command}");
1355            let quiet_command = format!("rg {option} -q --quiet missing src | head -10");
1356            assert!(!shell_command_is_output_search(&exec_command(&quiet_command)), "{quiet_command}");
1357        }
1358    }
1359
1360    #[test]
1361    fn standalone_grep_search_preserves_exit_status_ownership() {
1362        for command in [
1363            "rg missing src",
1364            "grep -q missing README.md",
1365            "LANG=C /usr/bin/grep -n missing README.md",
1366            "rg 'a|b' src",
1367            "fgrep missing README.md",
1368        ] {
1369            assert!(shell_command_is_standalone_grep_search(&exec_command(command)), "{command}");
1370        }
1371        assert!(shell_command_is_standalone_grep_search(&json!({"command": ["rg", "missing", "src"]})));
1372        for command in [
1373            "rg missing src; false",
1374            "rg missing src && false",
1375            "rg missing src | grep other",
1376            "! rg missing src",
1377            "(rg missing src)",
1378            "echo '/rg missing'; false",
1379            "rg missing src 2>/dev/null",
1380            "rg missing src 2>&1",
1381            "rg missing $(pwd)",
1382            "rg --pre 'false' missing src",
1383        ] {
1384            assert!(!shell_command_is_standalone_grep_search(&exec_command(command)), "{command}");
1385        }
1386    }
1387
1388    #[test]
1389    fn admitted_verification_attempt_allows_truncation_but_blocks_smuggled_mutations() {
1390        for command in [
1391            "cargo check --locked 2>&1 | head -c 4000",
1392            "cargo check --locked",
1393            "cargo nextest run 2>&1 | head -c 4000",
1394        ] {
1395            assert!(
1396                shell_command_is_admitted_verification_attempt(&exec_command(command)),
1397                "expected admission: {command}"
1398            );
1399        }
1400        for command in [
1401            "cargo check && rm -rf target",
1402            "cargo check; rm foo.txt",
1403            "cargo check || rm foo.txt",
1404            "cargo check && cargo test && rm foo.txt",
1405            "sed -i '' 's/old/new/' README.md",
1406            "echo $(date)",
1407            "cargo check > build.log && rm foo.txt",
1408        ] {
1409            assert!(
1410                !shell_command_is_admitted_verification_attempt(&exec_command(command)),
1411                "expected block: {command}"
1412            );
1413        }
1414        assert!(!shell_command_is_admitted_verification_attempt(&json!({})));
1415    }
1416
1417    #[test]
1418    fn logged_compound_inspection_commands_are_not_mutations() {
1419        for command in [
1420            "cat README.md && printf '\\n--- git status ---\\n' && git status --short",
1421            "wc -l README.md; rg -n '^#' README.md",
1422            "git diff --stat; find docs -maxdepth 2 -type f | sort | head -40",
1423        ] {
1424            assert_eq!(
1425                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1426                ShellActivity::Inspection,
1427                "{command}"
1428            );
1429        }
1430    }
1431
1432    #[cfg(unix)]
1433    #[test]
1434    fn captured_read_commands_with_output_suppression_are_inspection() {
1435        for command in [
1436            r#"sed -n '1,180p' README.md; sed -n '280,350p' README.md; sed -n '389,411p' README.md; printf '\n--- repo metadata ---\n'; git log -1 --format='%h %s'; sed -n '1,100p' Cargo.toml; rg -n '^version\s*=|rust-version|workspace\.package' Cargo.toml crates -g Cargo.toml | head -40"#,
1437            r#"sed -n '1,120p' crates/codegen/vtcode-core/src/tools/tool_intent/activity.rs; printf '\n--- readonly policy ---\n'; rg -n 'READONLY_UNIFIED_EXEC_COMMANDS|command_words_are_readonly' crates/codegen/vtcode-core/src/tools/tool_intent/readonly.rs; printf '\n--- recent commits ---\n'; git log -5 --oneline; printf '\n--- command arguments ---\n'; sed -n '1,180p' crates/codegen/vtcode-core/src/tools/command_args.rs"#,
1438            r###"git diff --stat; find docs -maxdepth 2 -type f | sort | head -40; rg -n "vtcode init|vtcode models|full-auto|run-debug|cargo install" docs/user-guide docs/installation docs/development 2>/dev/null | head -50"###,
1439        ] {
1440            assert_eq!(
1441                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1442                ShellActivity::Inspection,
1443                "{command}"
1444            );
1445        }
1446    }
1447
1448    #[cfg(unix)]
1449    #[test]
1450    fn printf_output_safety_guards_remain_mutations() {
1451        for command in [
1452            "printf 'captured output\\n' > output.txt",
1453            "printf '%s\\n' \"$(git status --short)\"",
1454            "printf '%s\\n' `git status --short`",
1455            "printf '\\n--- inspection ---\\n' && rm output.txt",
1456        ] {
1457            let args = exec_command(command);
1458            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &args), ShellActivity::Mutation, "{command}");
1459            assert!(!is_readonly_command_session_command(&args), "unexpected readonly command: {command}");
1460        }
1461    }
1462
1463    #[test]
1464    fn git_diff_check_chain_remains_inspection() {
1465        assert_eq!(
1466            classify_shell_activity(
1467                tools::EXEC_COMMAND,
1468                &exec_command("git diff --check && git status --short && git diff --stat"),
1469            ),
1470            ShellActivity::Inspection
1471        );
1472    }
1473
1474    #[test]
1475    fn verification_detection_skips_environment_prefixes() {
1476        for command in [
1477            "env RUSTFLAGS=-Dwarnings cargo check",
1478            "RUSTFLAGS=-Dwarnings env cargo check",
1479            "env -u PATH cargo check",
1480            "env -C /tmp cargo check",
1481        ] {
1482            assert_eq!(
1483                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1484                ShellActivity::Verification,
1485                "{command}"
1486            );
1487        }
1488    }
1489
1490    #[test]
1491    fn ambiguous_or_mutating_compounds_remain_mutations() {
1492        for command in [
1493            "git diff --stat; python3 -c 'open(\"out\", \"w\").write(\"x\")'",
1494            "cat README.md; sed -i '' 's/a/b/' README.md",
1495            "sed --in-place= README.md",
1496            "git diff --output=out",
1497            "git diff '--output=out'",
1498            "git diff -o out",
1499            "git diff -oout",
1500            "git log --output=out",
1501            "git show --textconv",
1502            // `-C <dir> <read-only sub>` is an Inspection now (the redirect
1503            // only changes which repository is read); config injection stays
1504            // a Mutation.
1505            "git -c core.fsmonitor=touch status",
1506            "find . -fprint output.txt",
1507            "find . -fprintf output.txt '%p'",
1508            "rg --hostname-bin sh pattern",
1509            "rg --search-zip pattern",
1510            "rg -z pattern",
1511            "sort -o generated.txt README.md",
1512            "sort --compress-program=sh README.md",
1513            "date -s now",
1514            "awk -i inplace '{print}' README.md",
1515            "sed -n 's/a/b/e' README.md",
1516            "fd --exec sh -c 'touch output'",
1517            "tree -o output.txt",
1518            "ast-grep -r 'README.md'",
1519            "sed -n -fmalicious.sed -e '1p' src/main.rs",
1520            "sed -I '' 's/a/b/' src/main.rs",
1521            "sed -n '1p\nw leaked.txt' src/main.rs",
1522            "cargo check & rm output",
1523            "cargo check > build.log | rm output",
1524            "cargo check | head -40 > build.log",
1525            "cargo check | echo x > output.log",
1526            "cargo check | head -40",
1527            "cargo check > build.log &",
1528            "env -S 'cargo check'",
1529            "echo x > output.log && cargo check",
1530            "cargo check < build-input.log",
1531            "cat README.md > copied.txt",
1532            "git diff --check; rm output",
1533            "cat README.md\nrm output",
1534        ] {
1535            assert_eq!(
1536                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1537                ShellActivity::Mutation,
1538                "{command}"
1539            );
1540        }
1541    }
1542
1543    #[test]
1544    fn quoted_output_text_does_not_change_inspection_classification() {
1545        for command in ["echo 'git diff --output=out'", "printf 'sort -o out input'"] {
1546            assert_eq!(
1547                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1548                ShellActivity::Inspection,
1549                "{command}"
1550            );
1551        }
1552    }
1553
1554    #[test]
1555    fn cargo_fmt_check_is_verification_but_plain_fmt_is_not() {
1556        for command in [
1557            "cargo fmt --check",
1558            "cargo fmt --all -- --check",
1559            "cargo fmt -- --check",
1560        ] {
1561            assert_eq!(
1562                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1563                ShellActivity::Verification,
1564                "{command}"
1565            );
1566            assert!(
1567                shell_command_is_admitted_verification_attempt(&exec_command(command)),
1568                "expected admission: {command}"
1569            );
1570        }
1571        // Plain `cargo fmt` rewrites the worktree: it must stay a mutation and
1572        // must not ride through the verification gate.
1573        assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &exec_command("cargo fmt")), ShellActivity::Mutation);
1574        assert!(!shell_command_is_admitted_verification_attempt(&exec_command("cargo fmt")));
1575    }
1576
1577    #[test]
1578    fn pure_and_chained_verifiers_are_verification() {
1579        for command in [
1580            "cargo fmt --all -- --check && cargo check --locked",
1581            "cargo check --locked && cargo nextest run --locked -p vtcode-ui",
1582            "cargo check --locked && cargo clippy --locked -p vtcode-ui -- -D warnings",
1583            "git diff --check && cargo check --locked",
1584        ] {
1585            assert_eq!(
1586                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1587                ShellActivity::Verification,
1588                "{command}"
1589            );
1590            assert!(
1591                shell_command_is_admitted_verification_attempt(&exec_command(command)),
1592                "expected admission: {command}"
1593            );
1594        }
1595    }
1596
1597    #[test]
1598    fn non_and_chained_verifiers_remain_mutations() {
1599        for command in [
1600            "cargo check --locked; cargo nextest run --locked -p vtcode-ui",
1601            "cargo check --locked || cargo nextest run --locked -p vtcode-ui",
1602            "cargo check --locked | head -40",
1603            "cargo check --locked && cargo nextest run --locked -p vtcode-ui | head -40",
1604            "cargo check --locked &",
1605        ] {
1606            assert_eq!(
1607                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1608                ShellActivity::Mutation,
1609                "{command}"
1610            );
1611        }
1612    }
1613
1614    #[test]
1615    fn expanded_verifiers_classify_as_verification() {
1616        for command in [
1617            "bun test",
1618            "bun run test",
1619            "deno lint",
1620            "deno check mod.ts",
1621            "make test",
1622            "make lint",
1623            "just verify",
1624            "ruff check src/",
1625            "ruff format --check",
1626            "tsc --noEmit",
1627            "eslint src/",
1628            "python3 -m pytest",
1629            "uv run pytest",
1630            "npm run lint",
1631        ] {
1632            assert_eq!(
1633                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1634                ShellActivity::Verification,
1635                "{command}"
1636            );
1637        }
1638        for command in [
1639            "make clean",
1640            "make test clean",
1641            "just fmt",
1642            "tsc",
1643            "eslint --fix src/",
1644            "ruff format src/",
1645            "bun install",
1646            "uv sync",
1647        ] {
1648            assert_eq!(
1649                classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)),
1650                ShellActivity::Mutation,
1651                "{command}"
1652            );
1653        }
1654    }
1655
1656    #[test]
1657    fn escaped_quotes_fail_closed_instead_of_hiding_operators() {
1658        // A backslash-escaped quote is a literal for the shell, so the trailing
1659        // `;` is a live separator: the aggregate exit status can mask a failed
1660        // verifier, and the chain must not classify as pure `&&`.
1661        assert!(!shell_uses_only_and_chaining("cargo check --locked \\\"; echo ok"));
1662        assert!(!shell_uses_only_and_chaining("echo \\\" ; cargo check --locked && echo done"));
1663        // Escaped quotes inside real double quotes stay inert.
1664        assert!(shell_uses_only_and_chaining("echo \"a\\\"b\" && cargo check --locked"));
1665        assert!(shell_uses_only_and_chaining("echo \"path\" && cargo fmt --check"));
1666        // Backslash is literal inside single quotes.
1667        assert!(shell_uses_only_and_chaining("echo 'a\\b' && cargo check --locked"));
1668    }
1669
1670    #[test]
1671    fn default_verifier_prefers_manifest_priority_order() {
1672        let dir = tempfile::tempdir().expect("tempdir");
1673        assert_eq!(default_verifier_for_workspace(dir.path()), None);
1674
1675        std::fs::write(dir.path().join("justfile"), "test:\n\techo ok\n").expect("justfile");
1676        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("just test"));
1677        std::fs::write(dir.path().join("pyproject.toml"), "[tool.pytest]\n").expect("pyproject");
1678        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("pytest -q"));
1679        std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"test":"vitest"}}"#).expect("package.json");
1680        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm test"));
1681        std::fs::write(dir.path().join("go.mod"), "module example\n").expect("go.mod");
1682        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("go test ./..."));
1683        std::fs::write(dir.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").expect("Cargo.toml");
1684        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("cargo check --locked"));
1685    }
1686
1687    #[test]
1688    fn default_verifier_marker_aliases_and_tier_priority() {
1689        // Every table row resolves, including alternate spellings — a
1690        // dropped alias in the marker table must fail here, not in a
1691        // live session. Each fixture names a different row.
1692        for (marker, expected) in [
1693            ("Justfile", "just test"),
1694            ("makefile", "make test"),
1695            ("bun.lock", "bun test"),
1696            ("deno.jsonc", "deno test"),
1697        ] {
1698            let dir = tempfile::tempdir().expect("tempdir");
1699            std::fs::write(dir.path().join(marker), "x\n").expect(marker);
1700            assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some(expected), "{marker}");
1701        }
1702        // Cross-tier priority: earlier tiers win over later ones.
1703        let dir = tempfile::tempdir().expect("tempdir");
1704        std::fs::write(dir.path().join("bun.lockb"), "x\n").expect("bun.lockb");
1705        std::fs::write(dir.path().join("deno.json"), "{}\n").expect("deno.json");
1706        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("deno test"));
1707        std::fs::write(dir.path().join("go.mod"), "module example\n").expect("go.mod");
1708        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("go test ./..."));
1709        // The Node tier (script sniffing) sits between Bun and Python.
1710        let dir = tempfile::tempdir().expect("tempdir");
1711        std::fs::write(dir.path().join("pyproject.toml"), "[tool.pytest]\n").expect("pyproject");
1712        std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"test":"vitest"}}"#).expect("package.json");
1713        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm test"));
1714        // Unrecognized scripts keep the `npm test` fallback.
1715        let dir = tempfile::tempdir().expect("tempdir");
1716        std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"start":"serve"}}"#).expect("package.json");
1717        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm test"));
1718    }
1719
1720    #[test]
1721    fn default_verifier_reads_npm_script_fallbacks() {
1722        let dir = tempfile::tempdir().expect("tempdir");
1723        std::fs::write(dir.path().join("package.json"), r#"{"scripts":{"lint":"eslint ."}}"#).expect("package.json");
1724        assert_eq!(default_verifier_for_workspace(dir.path()).as_deref(), Some("npm run lint"));
1725    }
1726
1727    #[test]
1728    fn verification_recovery_directive_names_concrete_command() {
1729        let directive = verification_recovery_directive(Some("go test ./..."), 1, 2);
1730        assert!(directive.contains("go test ./..."));
1731        assert!(directive.contains("1/2"));
1732        assert!(directive.contains("edits remain available"));
1733        assert!(directive.contains("only missing checks"));
1734        assert!(!directive.contains("mutations are blocked"));
1735        assert!(directive.contains("max_output_tokens"));
1736        assert!(directive.contains(VERIFIER_SHELL_FORM_NOTE));
1737        assert!(directive.contains("tails run standalone"));
1738        assert!(directive.contains("fail-closed `pipefail`"));
1739        let fallback = verification_recovery_directive(None, 2, 2);
1740        assert!(fallback.contains(GENERIC_VERIFIER_DESCRIPTION));
1741        assert!(fallback.contains("2/2"));
1742    }
1743
1744    #[test]
1745    fn verifier_reference_names_resolved_command_or_generic_description() {
1746        assert_eq!(verifier_reference(Some("go test ./...")), "`go test ./...`");
1747        assert_eq!(verifier_reference(Some("  npm test ")), "`npm test`");
1748        for missing in [None, Some(""), Some("   ")] {
1749            let reference = verifier_reference(missing);
1750            assert_eq!(reference, GENERIC_VERIFIER_DESCRIPTION);
1751            assert!(!reference.starts_with('`'), "no single command is named: {reference}");
1752            for ecosystem in ["cargo check --locked", "go test ./...", "npm test", "pytest -q"] {
1753                assert!(reference.contains(ecosystem), "missing {ecosystem}: {reference}");
1754            }
1755        }
1756    }
1757
1758    #[test]
1759    fn truncation_only_verifier_rewrites_to_standalone_prefix() {
1760        for (command, expected) in [
1761            ("cargo check --locked 2>&1 | head -c 4000", "cargo check --locked 2>&1"),
1762            ("cargo check --locked -p vtcode 2>&1 | tail -20", "cargo check --locked -p vtcode 2>&1"),
1763            ("cargo nextest run 2>&1 | tail -15", "cargo nextest run 2>&1"),
1764            (
1765                "cargo check --locked && cargo nextest run --locked -p vtcode | tail -5",
1766                "cargo check --locked && cargo nextest run --locked -p vtcode",
1767            ),
1768            ("cargo check | tail -5 | head -20", "cargo check"),
1769            ("RUSTFLAGS=-Dwarnings cargo check | head -20", "RUSTFLAGS=-Dwarnings cargo check"),
1770            // File-output redirects are preserved verbatim in the head slice
1771            // (only the status-masking pipe tail is elided), and `>` does not
1772            // mask the exit status — so the rewrite stays truthful here too.
1773            ("cargo check > build.log | tail -5", "cargo check > build.log"),
1774        ] {
1775            assert_eq!(
1776                rewrite_truncation_only_verifier(&exec_command(command)).as_deref(),
1777                Some(expected),
1778                "expected rewrite: {command}"
1779            );
1780        }
1781    }
1782
1783    #[test]
1784    fn non_truncation_pipelines_and_mutations_are_never_rewritten() {
1785        // Filtering tails do real work; dropping them would discard evidence.
1786        // Smuggled mutations, joins, redirects, and array forms must run (or
1787        // be rejected) exactly as typed — the rewrite must stay silent.
1788        for command in [
1789            "cargo check | grep error",
1790            "cargo check | wc -l",
1791            "cargo check | sort | uniq",
1792            "cargo check && rm -rf target | tail -5",
1793            "cargo check; git status | tail -5",
1794            "cargo check || cargo test | tail -5",
1795            "cargo check | tail -5; rm foo.txt",
1796            "cargo check | tail &",
1797            "cargo check",
1798            "echo done | tail -5",
1799            "rg -n 'pattern' src | head -20",
1800            "echo $(date) | tail -5",
1801        ] {
1802            assert_eq!(rewrite_truncation_only_verifier(&exec_command(command)), None, "must not rewrite: {command}");
1803        }
1804        assert_eq!(
1805            rewrite_truncation_only_verifier(&serde_json::json!({"command": ["cargo", "check", "|", "tail"]})),
1806            None,
1807            "array-form commands keep today's behavior"
1808        );
1809        assert_eq!(rewrite_truncation_only_verifier(&serde_json::json!({})), None);
1810    }
1811
1812    #[test]
1813    fn args_as_executed_classify_elided_truncation_verifiers_as_verification() {
1814        for command in [
1815            "cargo check --locked 2>&1 | tail -5",
1816            "cargo nextest run 2>&1 | head -c 4000",
1817        ] {
1818            let typed = exec_command(command);
1819            let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1820            assert!(matches!(executed, std::borrow::Cow::Owned(_)), "expected rewrite: {command}");
1821            assert_eq!(
1822                classify_shell_activity(tools::EXEC_COMMAND, &executed),
1823                ShellActivity::Verification,
1824                "{command}"
1825            );
1826            // Idempotent: the executed form runs unchanged on a second pass.
1827            assert!(matches!(shell_args_as_executed(tools::EXEC_COMMAND, &executed), std::borrow::Cow::Borrowed(_)));
1828        }
1829
1830        let unified = json!({"action": "run", "command": "cargo check 2>&1 | tail -5"});
1831        assert_eq!(shell_args_as_executed(tools::UNIFIED_EXEC, &unified)["command"], "cargo check 2>&1");
1832    }
1833
1834    #[test]
1835    fn verifier_rewrite_keeps_raw_alias_and_appended_arguments_in_sync() {
1836        let command = "cargo check | grep";
1837        let typed = json!({"cmd":command, "raw_command":command, "args":["warning"]});
1838        let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1839        let expected = "set -o pipefail && cargo check | grep warning";
1840        assert_eq!(executed["command"], expected);
1841        assert_eq!(executed["raw_command"], expected);
1842        assert!(executed.get("args").is_none(), "suffix must execute exactly once");
1843        assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &executed), ShellActivity::Verification);
1844        assert!(matches!(shell_args_as_executed(tools::EXEC_COMMAND, &executed), std::borrow::Cow::Borrowed(_)));
1845
1846        let truncator = json!({"cmd":"cargo check | head", "args":["-20"]});
1847        assert_eq!(shell_args_as_executed(tools::EXEC_COMMAND, &truncator)["command"], "cargo check");
1848    }
1849
1850    #[test]
1851    fn verifier_pipeline_rejects_conflicting_raw_alias_and_mutating_suffix() {
1852        for typed in [
1853            json!({"cmd":"cargo check | grep marker", "raw_command":"printf marker"}),
1854            json!({"cmd":"cargo check | sort", "args":["-o", "changed.txt"]}),
1855            json!({"cmd":"set -o pipefail && cargo check | sort", "args":["-o", "changed.txt"]}),
1856            json!({"cmd":"cargo check | grep", "args":"invalid"}),
1857        ] {
1858            assert_eq!(rewrite_verifier_pipeline(&typed), None, "{typed}");
1859            assert!(!shell_command_is_admitted_verification_attempt(&typed), "{typed}");
1860            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &typed), ShellActivity::Mutation, "{typed}");
1861            assert!(super::super::classify_tool_intent(tools::EXEC_COMMAND, &typed).mutating, "{typed}");
1862        }
1863    }
1864
1865    #[test]
1866    fn filtered_verifier_pipeline_preserves_filters_and_truthful_status() {
1867        for command in [
1868            "python3 scripts/check_markdown.py 2>&1 | grep -E '^(README|docs/SECURITY)\\.md' | head -20",
1869            "cargo check --locked | grep warning",
1870            "cargo fmt --check && cargo check --locked | wc -l",
1871        ] {
1872            let typed = exec_command(command);
1873            let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1874            assert_eq!(executed["command"], format!("set -o pipefail && {command}"));
1875            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &executed), ShellActivity::Verification);
1876            assert!(shell_command_is_admitted_verification_attempt(&executed));
1877            assert!(matches!(shell_args_as_executed(tools::EXEC_COMMAND, &executed), std::borrow::Cow::Borrowed(_)));
1878            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &typed), ShellActivity::Mutation);
1879        }
1880        for command in [
1881            "cargo check | grep error; true",
1882            "cargo check | grep error || true",
1883            "cargo check | tee source.rs",
1884            "cargo check | sed -i 's/old/new/' source.rs",
1885            "cargo check | grep $(touch marker)",
1886            "cargo check | grep error > hidden.log",
1887            "cargo check | grep error &",
1888            "cargo check && rm source.rs | grep error",
1889        ] {
1890            assert_eq!(rewrite_verifier_pipeline(&exec_command(command)), None, "{command}");
1891            let prefixed = exec_command(&format!("set -o pipefail && {command}"));
1892            assert_ne!(
1893                classify_shell_activity(tools::EXEC_COMMAND, &prefixed),
1894                ShellActivity::Verification,
1895                "{command}"
1896            );
1897        }
1898    }
1899
1900    #[test]
1901    fn args_as_executed_keep_unsafe_joins_and_non_run_calls_as_typed() {
1902        for command in [
1903            "cargo check 2>&1 | grep error; true",
1904            "cargo check; git status",
1905            "cargo check || true",
1906        ] {
1907            let typed = exec_command(command);
1908            let executed = shell_args_as_executed(tools::EXEC_COMMAND, &typed);
1909            assert!(matches!(executed, std::borrow::Cow::Borrowed(_)), "must run as typed: {command}");
1910            assert_ne!(
1911                classify_shell_activity(tools::EXEC_COMMAND, &executed),
1912                ShellActivity::Verification,
1913                "{command}"
1914            );
1915        }
1916        let poll = json!({"action": "poll", "session_id": "s1", "command": "cargo check | tail -5"});
1917        assert!(matches!(shell_args_as_executed(tools::UNIFIED_EXEC, &poll), std::borrow::Cow::Borrowed(_)));
1918        let read = json!({"path": "src/lib.rs"});
1919        assert!(matches!(shell_args_as_executed(tools::READ_FILE, &read), std::borrow::Cow::Borrowed(_)));
1920    }
1921
1922    #[test]
1923    fn path_glob_inspections_preserve_debt_without_weakening_admission() {
1924        let clean = json!({"exit_code":0});
1925        for command in [
1926            "rg -n \"MD013|line_length\" docs/development/*.md | head",
1927            "rg -n x ./docs/file?.md | head -20",
1928            "grep -n x docs/*.md",
1929            r#"grep -rn "default_webmcp\|WebmcpConfig" crates/codegen/vtcode-config/src --include=*.rs | head -10"#,
1930            "grep -rn x src --exclude=*.lock --exclude-dir=target*",
1931            "egrep x --include=*.rs src",
1932            "fgrep x --exclude=*.md src",
1933            "cat ./docs/*.md",
1934            "ls docs/*.md",
1935        ] {
1936            assert!(!exec_mutation_should_incur_debt(command, &clean), "{command}");
1937            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)), ShellActivity::Mutation);
1938            assert!(exec_mutation_should_incur_debt(command, &json!({"exit_code":0,"modified_files":["src/lib.rs"]})));
1939        }
1940        for command in [
1941            "grep --include=$(touch marker) x src",
1942            "grep --exclude-dir=$directory x src",
1943            "grep --include=*.rs x src > marker",
1944            "grep --include=*.rs x src; touch marker",
1945            "rg --pre=touch --include=*.rs x src",
1946            "unknown --include=*.rs x src",
1947            "rg -n x *",
1948            "rg -n x ./docs/[a-z]*.md",
1949            "rg -n x -docs/*.md",
1950            "rg -n x $dir/*.md",
1951            "rg --pre touch docs/*.md",
1952            "rg --hostname-bin=touch docs/*.md",
1953            "sed docs/*.md",
1954            "sort -o marker docs/*.md",
1955            "./tools/* --version",
1956            "rg x docs/$(touch marker)/*.md",
1957            "rg x docs/*.md > marker",
1958            "rg x docs/*.md; touch marker",
1959            "rg x docs/*.md; if",
1960            "rg x docs*/*.md",
1961        ] {
1962            assert!(exec_mutation_should_incur_debt(command, &clean), "{command}");
1963        }
1964    }
1965
1966    #[test]
1967    fn mutation_accounting_rejects_unproven_shell_forms() {
1968        let output = json!({"exit_code": 0});
1969        for command in [
1970            "echo \"$(touch marker)\"",
1971            "echo \"`touch marker`\"",
1972            "for p in $(echo $(touch marker)); do test -f \"$p\"; done",
1973            "for p in a; do sed -i '' 's/a/b/' README.md; done",
1974            "for p in a; do sort -o README.md README.md; done",
1975            "echo x 2>/dev/null.backup",
1976            "echo x 2>&1>marker",
1977            "cat <(touch marker)",
1978            "$program --version",
1979            "\"$(echo rm)\" marker",
1980            "grep $options README.md",
1981            "if true; then touch marker; fi",
1982            "for p in a; do echo x",
1983            "echo $(",
1984            "echo hi &",
1985            "sed -n '1p' README.md > marker",
1986            "echo ${x:=value}",
1987        ] {
1988            assert!(exec_mutation_should_incur_debt(command, &output), "{command}");
1989        }
1990        for command in [
1991            "echo '>'",
1992            "echo '2>/dev/null.backup'",
1993            "echo \"$(grep -n x README.md)\"",
1994        ] {
1995            assert!(!exec_mutation_should_incur_debt(command, &output), "{command}");
1996        }
1997    }
1998
1999    #[test]
2000    fn dynamic_readonly_inspections_do_not_incur_mutation_debt() {
2001        let clean_output = json!({"success": true, "exit_code": 0});
2002        // Session-vtcode-20261015T142625Z: `for` loops over grep results with
2003        // `test -f` exited 0 with no writes, bumped the completion generation,
2004        // invalidated tracker evidence, and looped harness auto-verification
2005        // on `rg` inspections instead of ending the turn. Admission stays
2006        // fail-closed (still Mutation, still blocked when pending); accounting
2007        // must not create new debt.
2008        for command in [
2009            "for p in $(grep -o '](\\./[^)#]*' README.md | sed 's/](//' | sort -u); do test -f \"$p\" || echo \"missing: $p\"; done; echo \"check done\"",
2010            "for p in $(grep -o '](\\./[^)#]*' README.md | sed 's/](\\.\\///' | sort -u); do test -f \"docs/${p#docs/}\" 2>/dev/null || echo \"missing: $p\"; done",
2011            "rg -n 'vinhnx/(VTCode|vtcode)' README.md",
2012            "grep -n '^## ' README.md",
2013            "ls docs/guides/zed-acp.md",
2014            "git diff --stat -- README.md",
2015            "git status --short",
2016            "npx markdownlint-cli2 README.md",
2017            "cargo check --locked",
2018        ] {
2019            let expected = if command.starts_with("npx markdownlint") || command.starts_with("cargo check") {
2020                ShellActivity::Verification
2021            } else if command.starts_with("for") {
2022                ShellActivity::Mutation
2023            } else {
2024                ShellActivity::Inspection
2025            };
2026            assert_eq!(classify_shell_activity(tools::EXEC_COMMAND, &exec_command(command)), expected, "{command}");
2027            assert!(!exec_mutation_should_incur_debt(command, &clean_output), "{command}");
2028        }
2029        // Dynamic `for`/`test` inspections: no debt without writes.
2030        assert!(!exec_mutation_should_incur_debt(
2031            "for p in $(grep -o 'x' README.md); do test -f \"$p\" || echo \"missing: $p\"; done",
2032            &clean_output,
2033        ));
2034        assert!(!exec_mutation_should_incur_debt("rg -n 'x' README.md", &clean_output));
2035        assert!(!exec_mutation_should_incur_debt("grep -n 'x' README.md", &clean_output));
2036        assert!(!exec_mutation_should_incur_debt("git status --short", &clean_output));
2037        // Concrete evidence still counts.
2038        assert!(exec_mutation_should_incur_debt(
2039            "for p in $(grep -o 'x' README.md); do test -f \"$p\" || echo \"missing: $p\"; done",
2040            &json!({"success": true, "exit_code": 0, "modified_files": ["README.md"]}),
2041        ));
2042        // Shell redirection is a potential write.
2043        assert!(exec_mutation_should_incur_debt("echo hi > README.md", &clean_output));
2044        assert!(exec_mutation_should_incur_debt("for f in a b; do echo x > \"$f\"; done", &clean_output));
2045        // Static mutating base still counts (fail-closed for `rm`, etc.).
2046        assert!(exec_mutation_should_incur_debt("rm -rf target", &clean_output));
2047        // Dynamic mutating base with variable still counts.
2048        assert!(exec_mutation_should_incur_debt("rm $f", &clean_output));
2049        // Stderr plumbing alone is not a file write.
2050        assert!(!exec_mutation_should_incur_debt("rg -n 'x' README.md 2>&1", &clean_output));
2051        // Shared classifiers decide verifier-shaped commands: mutating
2052        // variants count, clean checks do not. Asymmetric pairs.
2053        assert!(exec_mutation_should_incur_debt("npx markdownlint-cli2 --fix README.md", &clean_output));
2054        assert!(!exec_mutation_should_incur_debt("npx markdownlint-cli2 README.md", &clean_output));
2055        assert!(exec_mutation_should_incur_debt("cargo fmt", &clean_output));
2056        assert!(!exec_mutation_should_incur_debt("cargo fmt --check", &clean_output));
2057        assert!(exec_mutation_should_incur_debt("tsc", &clean_output));
2058        assert!(!exec_mutation_should_incur_debt("tsc --noEmit", &clean_output));
2059        // Unresolved options stay unproven even for inspection subcommands.
2060        assert!(exec_mutation_should_incur_debt("git diff $x", &clean_output));
2061        assert!(exec_mutation_should_incur_debt("git checkout $x", &clean_output));
2062        // Dynamic chains of inspections with exit-echo tails stay debt-free.
2063        assert!(!exec_mutation_should_incur_debt("grep -n 'x' README.md; echo \"exit:$?\"", &clean_output,));
2064    }
2065}