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