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