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
13/// Validate without knowing where the command will run.
14///
15/// A relative redirect target cannot be placed, so it is refused — the
16/// conservative reading. Callers that know the working directory should use
17/// [`validate_command_in_cwd`] instead, which resolves the destination first.
18pub(crate) fn validate_command_with_write_allow_paths(
19    command: &str,
20    write_allow_paths: &[String],
21    project_root: Option<&str>,
22) -> Option<String> {
23    validate_command_in_cwd(command, write_allow_paths, project_root, None)
24}
25
26/// The capture rule as the guard applies it, shared by the redirect and `tee`
27/// refusals so the two cannot drift apart. #1946: both used to call the rule
28/// "output capture into a project path", but a destination outside the
29/// project — and outside every root — is refused just the same. A caller who
30/// took that wording at its word tried another non-project path and was
31/// refused again with the identical text.
32const CAPTURE_RULE: &str = "The rule: output capture (`>`, `>>`, `| tee`) may only go to a \
33     scratch path (/tmp, /var/tmp, $TMPDIR) or a directory listed in `write_allow_paths` in \
34     config.toml. Every other destination is refused, inside the project or not, and the \
35     project root stays refused even when listed. Commands that do not capture output are \
36     not restricted.";
37
38/// Why the capture rule exists, shared by every write refusal (#1992). The
39/// refusals used to say ctx_shell's compression could land in the file as
40/// markers. That stopped being true with #1303 (v3.9.14): the child shell
41/// performs the redirect, so the file receives the command's own bytes and
42/// only the MCP return channel is compressed. A caller who knew their output
43/// was tiny plain text read the old rationale as a risk that did not apply to
44/// them and retried with `raw=true` or a smaller command — neither changes
45/// the verdict, because the reason is the write path, not the bytes.
46const WRITE_REASON: &str = "Files you keep are written with ctx_patch or the native Write/Edit \
47     tool, so the read-before-write gate and the edit checks apply to them; ctx_shell does not \
48     write them through output capture. This is unconditional: the redirect itself is not \
49     compressed, so a smaller command or `raw=true` does not change the verdict.";
50
51/// Validate against the directory the command will actually run in (#1811).
52///
53/// The write guard classifies the *destination*, so a relative redirect target
54/// has to be placed before it can be judged. Without a `cwd` it cannot be, and
55/// every relative target was refused — which made `cwd=<scratch> … > probe.txt`
56/// fail while the identical absolute path succeeded, under a message promising
57/// that the destination decides.
58pub(crate) fn validate_command_in_cwd(
59    command: &str,
60    write_allow_paths: &[String],
61    project_root: Option<&str>,
62    cwd: Option<&str>,
63) -> Option<String> {
64    if command.len() > MAX_COMMAND_BYTES {
65        return Some(format!(
66            "ERROR: Command too large ({} bytes, limit {}). \
67             If you're writing file content, use the native Write/Edit tool instead. \
68             ctx_shell is for reading command output only (git, cargo, npm, etc.).",
69            command.len(),
70            MAX_COMMAND_BYTES
71        ));
72    }
73
74    // #931: strip heredoc bodies before the redirect scanner — a `>` inside a
75    // heredoc body is opaque data, not a file-write redirect.
76    let cmd_no_heredoc = crate::core::shell_allowlist::strip_all_heredoc_bodies(command);
77    // #1850: a relative target lands where its own command runs, and a `cd`
78    // earlier in the line moves that. Judging every target against the call's
79    // `cwd` blocked `cd /tmp && echo x > out.txt` and let `cd <project> && echo
80    // x > f` from a scratch cwd write straight into the project. Each segment
81    // is judged against its own directory; where that cannot be known, a
82    // relative target is refused.
83    let segments = segments_in_cwd(&cmd_no_heredoc, cwd);
84    // #1768: the rule is the destination, not the size of the payload. The
85    // refusal used to justify itself with "MCP protocol corruption on large
86    // payloads" while the guard allows a megabyte into /tmp and blocks two
87    // bytes into a project file — so the stated reason argued *against* the
88    // verdict in both directions, and steered callers to retry smaller (no
89    // effect) or to avoid the sanctioned scratch capture. #1992: the
90    // compression-marker rationale that replaced it was stale too — see
91    // WRITE_REASON for the reason that holds.
92    if let Some(target) = segments.iter().find_map(|(segment, here)| {
93        disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
94    }) {
95        return Some(format!(
96            "ERROR: ctx_shell refuses the redirect into `{target}` — the destination decides, \
97             not the size or content of the output. {WRITE_REASON} {CAPTURE_RULE} \
98             Write the file with ctx_patch or the native Write tool, or capture to a scratch \
99             path.{}",
100            relative_target_note(&target)
101        ));
102    }
103
104    // #989: tee detection must run on heredoc-stripped text to avoid false
105    // positives when the word "tee" appears in heredoc/quoted payloads.
106    //
107    // #1671: the rule is the destination, not the pipe. The message used to say
108    // "tee without pipe" and then state that piped tee is allowed — so it
109    // rejected a command and, in the next sentence, described that exact
110    // command as permitted. A reviewer read it, concluded the block was correct
111    // because an alternative was offered, and closed a review with no findings.
112    // Naming the pipe also sent callers off to restructure their pipeline,
113    // which cannot help: `… | tee FILE | wc -l` is judged identically.
114    if let Some(target) = segments.iter().find_map(|(segment, here)| {
115        disallowed_tee_target(segment, write_allow_paths, project_root, here.as_deref())
116    }) {
117        return Some(format!(
118            "ERROR: ctx_shell refuses `tee {target}`. Piping makes no difference: the \
119             destination decides. {WRITE_REASON} {CAPTURE_RULE} \
120             Write the file with ctx_patch or the native Write tool, or tee to a scratch \
121             path.{}",
122            relative_target_note(&target)
123        ));
124    }
125
126    if is_heredoc_file_write(command, &segments, write_allow_paths, project_root) {
127        return Some(format!(
128            "ERROR: ctx_shell detected a heredoc writing to a file. {WRITE_REASON} \
129             Create the file with ctx_patch (op=create) or the native Write tool. \
130             Note: heredocs for input piping (e.g. psql <<EOF) are allowed."
131        ));
132    }
133
134    // #1672: on the heredoc-stripped text, for the same reason as #931 and
135    // #989 above. A download flag inside a heredoc *body* is opaque data — a
136    // commit message, a doc, a fixture — and refusing the call for it blocks
137    // writing about the guard at all. This detector was simply never switched
138    // over when the other two were.
139    if let Some(reason) = download_to_file_reason(&cmd_no_heredoc) {
140        return Some(format!(
141            "ERROR: ctx_shell detected a file download/write ({reason}). \
142             Download flags write a file without a redirect, so the capture rule applies \
143             to them as well (GH #391). \
144             For text, fetch to stdout: curl <url> / wget -qO- <url>. \
145             For a binary (image, PDF, archive) neither stdout nor the editor's Write \
146             tool can carry the bytes — download to an absolute scratch path instead, \
147             e.g. curl -sL -o /tmp/shot.png <url>, which is permitted (GH #1661). \
148             The target must be a literal path, $TMPDIR, or a variable this same command \
149             set to a literal earlier (D=/tmp/x; curl -o $D/f); any other variable cannot \
150             be resolved here and is refused."
151        ));
152    }
153
154    None
155}
156
157/// How a relative target is placed — said when one is refused, because the
158/// answer is usually to say where it should go (#1850).
159fn relative_target_note(target: &str) -> &'static str {
160    let t = target
161        .trim_start_matches(['>', '&', '|'])
162        .trim_matches(['"', '\'']);
163    if t.starts_with('/') || std::path::Path::new(t).is_absolute() {
164        return "";
165    }
166    " A relative target is placed in the directory its own command runs in: the call's \
167     `cwd`, moved by a plain `cd <dir> &&` before it. Where that directory cannot be \
168     known — a `cd` through a variable, `pushd`, a subshell, a `cd` that may not have \
169     run — a relative target is refused; give an absolute path."
170}
171
172/// Each segment of the heredoc-stripped command with the directory it runs in,
173/// as a string for the path checks. An empty `cwd` is no `cwd`.
174fn segments_in_cwd(command: &str, cwd: Option<&str>) -> Vec<(String, Option<String>)> {
175    let base = cwd
176        .filter(|c| !c.trim().is_empty())
177        .map(std::path::Path::new);
178    crate::core::command_cwd::segments_with_cwd(command, base)
179        .into_iter()
180        .map(|s| {
181            let here = s.cwd.map(|p| p.to_string_lossy().into_owned());
182            (s.segment, here)
183        })
184        .collect()
185}
186
187/// Well-known Unix scratch prefixes that agents use on every platform.
188/// On Windows, `/tmp/foo` is not a real absolute path, but Git Bash, WSL,
189/// and agent-generated commands routinely target it.  (#1467)
190fn is_unix_scratch_prefix(path: &str) -> bool {
191    for prefix in ["/tmp", "/var/tmp", "/private/tmp", "/dev/null"] {
192        if path == prefix || path.starts_with(&format!("{prefix}/")) {
193            return true;
194        }
195    }
196    false
197}
198
199/// Detects download/copy tools writing directly to files via their own flags.
200/// Returns true when a path targets a scratch/temp location outside the
201/// project, where file downloads are safe (#1021).
202fn is_scratch_path(path: &str) -> bool {
203    if is_unix_scratch_prefix(path) {
204        return true;
205    }
206    if let Ok(tmpdir) = std::env::var("TMPDIR")
207        && !tmpdir.is_empty()
208        && std::path::Path::new(path).starts_with(tmpdir.as_str())
209    {
210        return true;
211    }
212    // Windows: %TEMP% / std::env::temp_dir()
213    let tmp = std::env::temp_dir();
214    if std::path::Path::new(path).starts_with(&tmp) {
215        return true;
216    }
217    false
218}
219
220/// (`curl -o`, `wget` default mode, `dd of=`) — the redirect-free equivalent of
221/// `> file`, reported as a `validate_command` bypass in GH #391.
222fn download_to_file_reason(command: &str) -> Option<String> {
223    // #1661: the scratch carve-out is written in absolute paths, but agents
224    // reach a scratch directory the way a person would — `cd <scratchpad> &&
225    // curl -o shot.png …`. Judged as the bare string `shot.png`, a target that
226    // lands squarely inside the sanctioned directory looked like a project
227    // write and was blocked, leaving no in-tool way to fetch a binary at all.
228    // Segments are paired with the directory they actually run in so a relative
229    // target is judged where it lands.
230    //
231    // #1953: likewise a target spelled through a variable the same command set
232    // to a literal (`D=/tmp/x; curl -o $D/f`) is judged where it lands; any
233    // other variable stays unresolved and is refused as before.
234    let segments = crate::core::command_cwd::segments_with_cwd(command, None);
235    let known_vars = literal_assignments_before_each_segment(command, segments.len());
236    for (index, seg_cwd) in segments.into_iter().enumerate() {
237        let seg = seg_cwd.segment;
238        let here = seg_cwd.cwd;
239        let vars = &known_vars[index];
240        let resolve = |path: &str| -> String {
241            let expanded = expand_leading_variable(path, vars);
242            let path = expanded.as_deref().unwrap_or(path);
243            let p = std::path::Path::new(path);
244            // `starts_with('/')`: shell text, so a Unix-absolute target is
245            // absolute on Windows too, where `is_absolute` disagrees (#1467).
246            if p.is_absolute() || path.starts_with('/') {
247                return path.to_string();
248            }
249            // Without a known directory the target stays unresolved, which the
250            // scratch check then rejects — the guard errs closed.
251            match here.as_deref() {
252                Some(dir) => crate::core::command_cwd::join_in(dir, path)
253                    .to_string_lossy()
254                    .into_owned(),
255                None => path.to_string(),
256            }
257        };
258        let tokens = crate::core::shell_allowlist::shell_tokenize(seg.trim());
259        let Some(first) = tokens.first() else {
260            continue;
261        };
262        let base = first.rsplit('/').next().unwrap_or(first);
263        match base {
264            "curl" => {
265                let tokens_slice = &tokens[1..];
266                for (i, tok) in tokens_slice.iter().enumerate() {
267                    let target: Option<&str> = if tok == "--output" {
268                        tokens_slice.get(i + 1).map(String::as_str)
269                    } else if let Some(val) = tok.strip_prefix("--output=") {
270                        Some(val)
271                    } else if tok == "--output-dir" {
272                        tokens_slice.get(i + 1).map(String::as_str)
273                    } else if let Some(val) = tok.strip_prefix("--output-dir=") {
274                        Some(val)
275                    } else if tok.starts_with('-')
276                        && !tok.starts_with("--")
277                        && tok[1..].contains('o')
278                    {
279                        // -o <file>: next token is the path
280                        tokens_slice.get(i + 1).map(String::as_str)
281                    } else if tok == "--remote-name"
282                        || tok == "--remote-name-all"
283                        || (tok.starts_with('-')
284                            && !tok.starts_with("--")
285                            && tok[1..].contains('O'))
286                    {
287                        Some(".")
288                    } else {
289                        None
290                    };
291                    if let Some(path) = target {
292                        if is_scratch_path(&resolve(path)) {
293                            continue;
294                        }
295                        return Some(format!("curl {tok}"));
296                    }
297                }
298            }
299            "wget" => {
300                // wget writes a file BY DEFAULT; only stdout/no-download modes pass.
301                let to_stdout = tokens[1..].iter().enumerate().any(|(i, tok)| {
302                    tok == "--output-document=-"
303                        || tok == "-O-"
304                        || (tok.starts_with('-') && !tok.starts_with("--") && tok.ends_with("O-"))
305                        || ((tok == "-O" || tok == "--output-document")
306                            && tokens.get(i + 2).map(std::string::String::as_str) == Some("-"))
307                        || tok == "--spider"
308                });
309                if !to_stdout {
310                    return Some(
311                        "wget downloads to a file by default; use wget -qO- <url> for stdout"
312                            .to_string(),
313                    );
314                }
315            }
316            "dd" => {
317                for tok in &tokens[1..] {
318                    if tok.starts_with("of=") && !tok.starts_with("of=/dev/null") {
319                        return Some(format!("dd {tok}"));
320                    }
321                }
322            }
323            _ => {}
324        }
325    }
326    None
327}
328
329/// For each segment, the variables known to hold a literal value when that
330/// segment starts (#1953).
331///
332/// Only a standalone `NAME=value` / `export NAME=value` segment that certainly
333/// runs in the current shell counts: not behind `&&`/`||` (it may be skipped),
334/// not in a pipeline or the background (a subshell, so nothing propagates).
335/// A value is literal only without `$`, a backtick or a leading `~`. Any
336/// segment that can rebind variables some other way (`read`, `for`, `eval`,
337/// `source`, …) forgets everything known so far. Where this cannot follow the
338/// shell it knows less, and an unknown variable leaves the target refused.
339fn literal_assignments_before_each_segment(
340    command: &str,
341    segment_count: usize,
342) -> Vec<std::collections::HashMap<String, String>> {
343    use crate::core::shell_allowlist::Separator;
344
345    let separated = crate::core::shell_allowlist::segments_with_separators(command);
346    if separated.len() != segment_count {
347        // Both come from the same scanner; if they ever disagree, resolve nothing.
348        return vec![std::collections::HashMap::new(); segment_count];
349    }
350    let mut known = std::collections::HashMap::new();
351    let mut prev: Option<Separator> = None;
352    let mut before_each = Vec::with_capacity(segment_count);
353    for (segment, sep) in separated {
354        before_each.push(known.clone());
355        let tokens = crate::core::shell_allowlist::shell_tokenize(&segment);
356        let words: &[String] = match tokens.first().map(String::as_str) {
357            Some("export") => &tokens[1..],
358            _ => &tokens,
359        };
360        let assignments: Option<Vec<(&str, &str)>> = words
361            .iter()
362            .map(|word| {
363                let (name, value) = word.split_once('=')?;
364                let valid_name = name
365                    .chars()
366                    .next()
367                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
368                    && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
369                valid_name.then_some((name, value))
370            })
371            .collect();
372        match assignments {
373            Some(pairs) if !pairs.is_empty() => {
374                let in_current_shell = matches!(prev, None | Some(Separator::Sequence))
375                    && matches!(sep, None | Some(Separator::Sequence | Separator::And));
376                for (name, value) in pairs {
377                    let literal = !value.contains(['$', '`']) && !value.starts_with('~');
378                    if in_current_shell && literal {
379                        known.insert(name.to_string(), value.to_string());
380                    } else {
381                        known.remove(name);
382                    }
383                }
384            }
385            _ => {
386                let rebinds = matches!(
387                    tokens.first().map(String::as_str),
388                    Some(
389                        "read"
390                            | "for"
391                            | "select"
392                            | "eval"
393                            | "source"
394                            | "."
395                            | "unset"
396                            | "declare"
397                            | "typeset"
398                            | "local"
399                            | "readonly"
400                            | "export"
401                            | "mapfile"
402                            | "readarray"
403                            | "getopts"
404                            | "printf"
405                    )
406                );
407                if rebinds {
408                    known.clear();
409                }
410            }
411        }
412        prev = sep;
413    }
414    before_each
415}
416
417/// Expand a target that starts with `$NAME` or `${NAME}` from `known`, or from
418/// the environment for `$TMPDIR` — the scratch variable the guard itself
419/// honours. `None` when the target starts with no variable or an unknown one.
420fn expand_leading_variable(
421    path: &str,
422    known: &std::collections::HashMap<String, String>,
423) -> Option<String> {
424    let rest = path.strip_prefix('$')?;
425    let (name, tail) = if let Some(braced) = rest.strip_prefix('{') {
426        let (name, tail) = braced.split_once('}')?;
427        (name, tail)
428    } else {
429        let end = rest
430            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
431            .unwrap_or(rest.len());
432        rest.split_at(end)
433    };
434    if name.is_empty() || !(tail.is_empty() || tail.starts_with('/')) {
435        return None;
436    }
437    let value = match known.get(name) {
438        Some(value) => value.clone(),
439        None if name == "TMPDIR" => std::env::var("TMPDIR").ok().filter(|v| !v.is_empty())?,
440        None => return None,
441    };
442    Some(format!("{value}{tail}"))
443}
444
445/// Returns true only for heredocs that redirect to files (the dangerous pattern).
446/// Legitimate heredoc uses (input piping, inline scripts) are allowed through.
447/// `segments` is the heredoc-stripped command with each segment's directory.
448fn is_heredoc_file_write(
449    command: &str,
450    segments: &[(String, Option<String>)],
451    write_allow_paths: &[String],
452    project_root: Option<&str>,
453) -> bool {
454    let has_heredoc = command.contains("<<");
455    if !has_heredoc {
456        return false;
457    }
458    let cmd_lower = command.to_lowercase();
459    let heredoc_patterns = ["<<eof", "<<'eof'", "<<\"eof\"", "<<end", "<<'end'"];
460    let has_known_heredoc = heredoc_patterns.iter().any(|p| cmd_lower.contains(p));
461    if !has_known_heredoc {
462        return false;
463    }
464    // #931: the segments come from the heredoc-stripped text, so `>` / `>>`
465    // inside the body are not mistaken for file-write redirects.
466    segments.iter().any(|(segment, here)| {
467        disallowed_write_redirect_target(segment, write_allow_paths, project_root, here.as_deref())
468            .is_some()
469    })
470}
471
472/// Detects shell redirect operators (`>` or `>>`) that write to files.
473/// Ignores `>` inside quotes, after a backslash escape (`\"` must not toggle
474/// quote state, `\>` is a literal), `2>` (stderr), `/dev/null`, and
475/// comparison operators.
476/// #848: temp directory targets are read-back, not persistent writes.
477/// #848/#989: targets that are NOT persistent project-file writes.
478/// Redirecting to temp dirs, /dev/* devices, or paths containing shell
479/// variables (which we cannot resolve at parse time) is output capture,
480/// not file authoring.
481pub fn is_temp_redirect_target(target: &str) -> bool {
482    let write_allow_paths = crate::core::config::default_shell_write_allow_paths();
483    // No cwd here: this public helper judges a target in isolation, so a
484    // relative one stays unplaceable and therefore not allowed (#1811).
485    is_write_allowed_redirect_target(target, &write_allow_paths, None, None)
486}
487
488fn is_write_allowed_redirect_target(
489    target: &str,
490    write_allow_paths: &[String],
491    project_root: Option<&str>,
492    cwd: Option<&str>,
493) -> bool {
494    // `>|` is the noclobber-override form of `>`; the `|` is not part of the path.
495    let t = target.trim_start_matches(['>', '&', '|']);
496    // #1142: agents quote scratch paths (`> "$TMPDIR/x.log"`, `> "/private/tmp/x"`);
497    // strip quotes so quoted and unquoted targets are judged identically.
498    let t = t.trim_matches(['"', '\'']);
499    if t.starts_with('$') || t.starts_with("${") {
500        // Preserve #989's escape hatch for harness-provided scratch paths.
501        return true;
502    }
503
504    // On Windows, agents often use Unix-style /tmp paths (Git Bash, WSL,
505    // or Claude generating Unix commands).  `/tmp/foo` is not absolute per
506    // std::path on Windows, so check well-known scratch prefixes before
507    // the is_absolute gate.  (#1467)
508    if is_unix_scratch_prefix(t) {
509        return true;
510    }
511
512    // #1811: a relative target is a destination like any other — it just needs
513    // placing first. The guard used to refuse every relative target outright,
514    // so `cwd=<scratch> … > probe.txt` was blocked while the identical
515    // `> <scratch>/probe.txt` was allowed, and the refusal said "the
516    // destination decides" about a destination it had not resolved.
517    //
518    // Resolving narrows as often as it widens: a relative target under a
519    // project cwd now resolves *into* the project and is refused on the same
520    // rule as an absolute one, instead of by accident of its spelling.
521    //
522    // `cwd` is the directory the target's own command runs in — the call's
523    // `cwd` moved by any `cd` before it (#1850, `command_cwd`), or `None` when
524    // that cannot be known, which refuses a relative target below.
525    let path = std::path::Path::new(t);
526    let resolved_input;
527    let path = if path.is_absolute() {
528        path
529    } else if let Some(base) = cwd.filter(|c| !c.trim().is_empty()) {
530        resolved_input = std::path::Path::new(base).join(path);
531        resolved_input.as_path()
532    } else {
533        return false;
534    };
535    let resolved = resolve_path_for_comparison(path);
536    if project_root.is_some_and(|root| {
537        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(root)))
538    }) {
539        return false;
540    }
541    write_allow_paths.iter().any(|allowed| {
542        resolved.starts_with(resolve_path_for_comparison(std::path::Path::new(allowed)))
543    })
544}
545
546fn resolve_path_for_comparison(path: &std::path::Path) -> std::path::PathBuf {
547    use std::path::{Component, PathBuf};
548
549    let mut normalized = PathBuf::new();
550    for component in path.components() {
551        match component {
552            Component::CurDir => {}
553            Component::ParentDir => {
554                normalized.pop();
555            }
556            other => normalized.push(other.as_os_str()),
557        }
558    }
559
560    let mut unresolved = Vec::new();
561    let mut existing = normalized.clone();
562    while !existing.exists() {
563        let Some(name) = existing.file_name() else {
564            break;
565        };
566        unresolved.push(name.to_os_string());
567        if !existing.pop() {
568            break;
569        }
570    }
571    let mut resolved = crate::core::pathutil::canonicalize_secure_or_self(&existing);
572    for component in unresolved.iter().rev() {
573        resolved.push(component);
574    }
575    resolved
576}
577
578fn tee_targets(command: &str) -> Vec<String> {
579    crate::core::shell_allowlist::extract_all_commands_pub(command)
580        .into_iter()
581        .filter_map(|segment| {
582            let tokens = crate::core::shell_allowlist::shell_tokenize(segment.trim());
583            let first = tokens.first()?;
584            if first.rsplit('/').next().unwrap_or(first) != "tee" {
585                return None;
586            }
587            let mut after_separator = false;
588            Some(
589                tokens
590                    .iter()
591                    .skip(1)
592                    .find(|token| {
593                        if *token == "--" {
594                            after_separator = true;
595                            return false;
596                        }
597                        after_separator || !token.starts_with('-')
598                    })
599                    .cloned()
600                    .unwrap_or_default(),
601            )
602        })
603        .collect()
604}
605
606/// The first `tee` destination that is not a permitted write target.
607///
608/// Returns the path so the refusal can name it (#1671). The rule is entirely
609/// about the destination — whether the `tee` is piped makes no difference — and
610/// a message that cannot name the destination ends up describing some other
611/// rule instead.
612fn disallowed_tee_target(
613    command: &str,
614    write_allow_paths: &[String],
615    project_root: Option<&str>,
616    cwd: Option<&str>,
617) -> Option<String> {
618    tee_targets(command).into_iter().find(|target| {
619        !target.is_empty()
620            && !is_write_allowed_redirect_target(target, write_allow_paths, project_root, cwd)
621    })
622}
623
624/// True when the command redirects into a path it may not write.
625///
626/// Test-only convenience: every production caller needs the offending target
627/// for its message and goes to [`disallowed_write_redirect_target`] directly
628/// (#1768). The assertions here only care about the verdict, and reading
629/// `.is_some()` into every one of them would obscure what they pin.
630#[cfg(test)]
631fn has_file_write_redirect(
632    command: &str,
633    write_allow_paths: &[String],
634    project_root: Option<&str>,
635) -> bool {
636    // No cwd: these assertions pin the target-spelling rules, where a relative
637    // target is unplaceable and therefore refused (#1811). The cwd-resolution
638    // behaviour has its own tests that call the public entry point.
639    disallowed_write_redirect_target(command, write_allow_paths, project_root, None).is_some()
640}
641
642/// The first redirect target that is **not** write-allowed, or `None` when the
643/// command writes nowhere it may not.
644///
645/// Returns the target rather than a bare verdict so the refusal can name what
646/// tripped it (#1768) — the same reason [`disallowed_tee_target`] exists. A
647/// guard that states a rule the caller cannot map onto their own command gets
648/// read as something else (there, "piping"; here, "large payloads"), and every
649/// such misreading sends the caller somewhere that cannot help.
650fn disallowed_write_redirect_target(
651    command: &str,
652    write_allow_paths: &[String],
653    project_root: Option<&str>,
654    cwd: Option<&str>,
655) -> Option<String> {
656    let bytes = command.as_bytes();
657    let len = bytes.len();
658    let mut i = 0;
659    let mut in_single_quote = false;
660    let mut in_double_quote = false;
661
662    while i < len {
663        let c = bytes[i];
664        if c == b'\\' && !in_single_quote {
665            // A backslash escapes the next byte (POSIX: outside quotes and
666            // inside double quotes; inside single quotes it is literal).
667            // Without this, an escaped quote like `\"` toggled the quote
668            // state and literal `>` in quoted prose (e.g. `(root: <root>)`
669            // in a gh --body string) read as a redirect (#903).
670            i += 2;
671            continue;
672        }
673        if c == b'\'' && !in_double_quote {
674            in_single_quote = !in_single_quote;
675        } else if c == b'"' && !in_single_quote {
676            in_double_quote = !in_double_quote;
677        } else if c == b'>' && !in_single_quote && !in_double_quote {
678            if i > 0 && bytes[i - 1] == b'2' {
679                i += 1;
680                continue;
681            }
682            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
683                i + 2
684            } else {
685                i + 1
686            };
687            // The redirect *operator* can carry one more character: `>|`
688            // overrides noclobber and `>&` duplicates a descriptor. Neither
689            // belongs to the target word, so strip it before reading the word
690            // and re-attach `&` for the fd check below.
691            let rest = command[target_start..].trim_start();
692            let (rest, fd_dup) = match rest.strip_prefix('|') {
693                Some(r) => (r, false),
694                None => match rest.strip_prefix('&') {
695                    Some(r) => (r, true),
696                    None => (rest, false),
697                },
698            };
699            // The word ends at whitespace *or* at a shell metacharacter
700            // (#1659). Stopping only at whitespace made the verdict depend on
701            // where the redirect sat: `echo a 1>/dev/null` read the target as
702            // `/dev/null` and was allowed, while `echo a 1>/dev/null; echo b`
703            // read `/dev/null;` — semicolon included, since it is not
704            // whitespace — missed the /dev/null exemption, and was blocked as a
705            // file write. `&&` happened to work only because a space precedes
706            // it. Same redirect, same shell semantics, opposite verdicts.
707            //
708            // `(` is deliberately not a terminator: it would reduce the
709            // process-substitution target `>(cmd)` to an empty word, and an
710            // empty word falls through unblocked.
711            let word: String = rest
712                .chars()
713                .take_while(|c| !c.is_whitespace() && !matches!(c, ';' | '&' | '|' | ')' | '<'))
714                .collect();
715            let target = if fd_dup { format!("&{word}") } else { word };
716            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
717                i += 1;
718                continue;
719            }
720            // #1142: `>&1` / `>&2` duplicate a file descriptor — no file involved.
721            // (`2>&1` is already skipped by the `2>` case above.)
722            if let Some(fd) = target.strip_prefix('&')
723                && !fd.is_empty()
724                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
725            {
726                i += 1;
727                continue;
728            }
729            // #848: allow redirects to temp directories — agents capture
730            // build output for grepping, not writing persistent files.
731            if is_write_allowed_redirect_target(&target, write_allow_paths, project_root, cwd) {
732                i += 1;
733                continue;
734            }
735            if !target.is_empty() {
736                return Some(target);
737            }
738        }
739        i += 1;
740    }
741    None
742}
743
744/// On Windows cmd.exe, `;` is not a valid command separator.
745/// Convert `cmd1; cmd2` to `cmd1 && cmd2` when running under cmd.exe.
746pub fn normalize_command_for_shell(command: &str) -> String {
747    if !cfg!(windows) {
748        return command.to_string();
749    }
750    let (_, flag) = crate::shell::shell_and_flag();
751    if flag != "/C" {
752        return command.to_string();
753    }
754    let bytes = command.as_bytes();
755    let mut result = Vec::with_capacity(bytes.len() + 16);
756    let mut in_single = false;
757    let mut in_double = false;
758    for (i, &b) in bytes.iter().enumerate() {
759        if b == b'\'' && !in_double {
760            in_single = !in_single;
761        } else if b == b'"' && !in_single {
762            in_double = !in_double;
763        } else if b == b';' && !in_single && !in_double {
764            result.extend_from_slice(b" && ");
765            continue;
766        }
767        result.push(b);
768        let _ = i;
769    }
770    String::from_utf8(result).unwrap_or_else(|_| command.to_string())
771}
772
773/// Compresses shell command output using the unified compression pipeline.
774/// Delegates to the same exit-code-aware logic used by the CLI, so a failed
775/// command (`exit_code != 0`) is preserved verbatim and successful output is
776/// compressed consistently (excluded_commands, structural routing, terse). #810.
777pub fn handle(command: &str, output: &str, exit_code: i32, _crp_mode: CrpMode) -> String {
778    crate::shell::compress::engine::compress_for_outcome(command, output, exit_code)
779}
780
781pub fn handle_with_context(
782    command: &str,
783    output: &str,
784    exit_code: i32,
785    crp_mode: CrpMode,
786    project_root: Option<&str>,
787) -> String {
788    let mut result = handle(command, output, exit_code, crp_mode);
789
790    {
791        if let Some(root) = project_root {
792            let estimated_tokens = result.len() / 4;
793            if estimated_tokens > 500 {
794                let kernel_budget = 100;
795                if let Some(enrichment) =
796                    crate::core::context_kernel::bridge::kernel_enrich(command, root, kernel_budget)
797                    && !enrichment.blocks.is_empty()
798                {
799                    result.push_str("\n--- kernel context ---\n");
800                    result.push_str(&enrichment.blocks);
801                }
802            }
803        }
804    }
805
806    result
807}
808
809#[cfg(test)]
810mod kernel_tests {
811    use super::handle_with_context;
812    use crate::tools::CrpMode;
813
814    #[test]
815    fn handle_with_context_does_not_panic_on_short_output() {
816        let result = handle_with_context("ls", "file.txt", 0, CrpMode::Tdd, Some("/tmp"));
817        assert!(!result.is_empty());
818    }
819}
820
821#[cfg(test)]
822fn is_search_command(command: &str) -> bool {
823    let cmd = command.trim_start();
824    cmd.starts_with("grep ")
825        || cmd.starts_with("rg ")
826        || cmd.starts_with("find ")
827        || cmd.starts_with("fd ")
828        || cmd.starts_with("ag ")
829        || cmd.starts_with("ack ")
830}
831
832#[cfg(test)]
833fn generic_compress(output: &str) -> String {
834    let output = crate::core::compressor::strip_ansi(output);
835    let lines: Vec<&str> = output
836        .lines()
837        .filter(|l| {
838            let t = l.trim();
839            !t.is_empty()
840        })
841        .collect();
842
843    if lines.len() <= 20 {
844        return lines.join("\n");
845    }
846
847    let show_count = (lines.len() / 3).min(30);
848    let half = show_count / 2;
849    let first = &lines[..half];
850    let last = &lines[lines.len() - half..];
851    let omitted = lines.len() - (half * 2);
852    format!(
853        "{}\n[truncated: showing {}/{} lines, {} omitted. Use raw=true for full output.]\n{}",
854        first.join("\n"),
855        half * 2,
856        lines.len(),
857        omitted,
858        last.join("\n")
859    )
860}
861
862/// Detects OAuth device code flow output that must not be compressed.
863/// Uses a two-tier approach: strong signals match alone (very specific to
864/// device code flows), weak signals require a URL/domain in the same output.
865pub fn contains_auth_flow(output: &str) -> bool {
866    let lower = output.to_lowercase();
867
868    const STRONG_SIGNALS: &[&str] = &[
869        "devicelogin",
870        "deviceauth",
871        "device_code",
872        "device code",
873        "device-code",
874        "verification_uri",
875        "user_code",
876        "one-time code",
877    ];
878
879    if STRONG_SIGNALS.iter().any(|s| lower.contains(s)) {
880        return true;
881    }
882
883    const WEAK_SIGNALS: &[&str] = &[
884        "enter the code",
885        "enter this code",
886        "enter code:",
887        "use the code",
888        "use a web browser to open",
889        "open the page",
890        "authenticate by visiting",
891        "sign in with the code",
892        "sign in using a code",
893        "verification code",
894        "authorize this device",
895        "waiting for authentication",
896        "waiting for login",
897        "waiting for you to authenticate",
898        "open your browser",
899        "open in your browser",
900    ];
901
902    let has_weak_signal = WEAK_SIGNALS.iter().any(|s| lower.contains(s));
903    if !has_weak_signal {
904        return false;
905    }
906
907    lower.contains("http://") || lower.contains("https://")
908}
909
910#[cfg(test)]
911mod tests;