Skip to main content

lean_ctx/core/
command_cwd.rs

1//! Which directory a command's segments actually run in (GH #1661, #1662).
2//!
3//! A tool call carries one `cwd`, but the command it runs may move: `cd repo &&
4//! grep -rn … .` walks a tree the call never named, and `cd "$SCRATCH" && curl
5//! -o shot.png …` writes to a directory that is sanctioned for exactly that.
6//! Judging either against the call's `cwd` alone gets the answer wrong — too
7//! lenient in the first case, too strict in the second.
8//!
9//! Only a plain `cd <literal>` segment is followed, and only where it is
10//! certain to have run before the next command (#1850). Everything else that
11//! can move the shell — a variable, a substitution, `pushd`/`popd`, a `cd`
12//! inside a subshell, a brace group, a loop or a function, a `cd` that may be
13//! skipped (`a || cd x`) or may fail (`cd missing; …`) — leaves the directory
14//! unknown, and an unknown directory is reported as such rather than guessed
15//! at. The write guard relies on that: judging a later command against a
16//! directory it does not run in is how a redirect lands in the project.
17
18use std::path::{Path, PathBuf};
19
20use super::shell_allowlist::Separator;
21
22/// One command segment together with the directory it runs in.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct SegmentCwd {
25    pub segment: String,
26    /// `None` once a `cd` has moved somewhere this cannot resolve statically,
27    /// or when more than one directory is possible.
28    pub cwd: Option<PathBuf>,
29}
30
31/// Split `command` into segments, tracking `cd` as it goes.
32///
33/// Segmentation is delegated to the shell tokenizer so this never disagrees
34/// with the allowlist about where one command ends and the next begins.
35pub fn segments_with_cwd(command: &str, base: Option<&Path>) -> Vec<SegmentCwd> {
36    track(command, base).0
37}
38
39/// The directory in effect once every segment has run.
40pub fn final_cwd(command: &str, base: Option<&Path>) -> Option<PathBuf> {
41    track(command, base).1
42}
43
44/// A `cd` that may not be in effect: it can fail (its target does not exist
45/// yet) or be skipped (`a && cd x`, `a || cd x`). Commands reached from it only
46/// through `&&` — and the pipelines among them — run in `moved`; anything that
47/// can also be reached when the `cd` did not happen runs in either directory.
48struct Pending {
49    moved: Option<PathBuf>,
50    /// Where the shell is if this `cd` did not take effect.
51    old: Option<PathBuf>,
52    /// Behind `||`: a successful left side skips the `cd` entirely.
53    skippable: bool,
54    /// `cd x || …`: the next segment is the fallback, which runs only if the
55    /// `cd` did not take effect.
56    fallback: bool,
57}
58
59impl Pending {
60    fn either(self) -> Option<PathBuf> {
61        merge(self.moved, self.old.as_deref())
62    }
63}
64
65fn track(command: &str, base: Option<&Path>) -> (Vec<SegmentCwd>, Option<PathBuf>) {
66    let segments = super::shell_allowlist::segments_with_separators(command);
67    // `CDPATH` reroutes a relative `cd sub` to wherever it finds `sub` first.
68    let cdpath = std::env::var_os("CDPATH").is_some_and(|v| !v.is_empty())
69        || segments.iter().any(|(s, _)| s.contains("CDPATH"));
70
71    // The directory the next segment starts in.
72    let mut cwd: Option<PathBuf> = base.map(Path::to_path_buf);
73    // Where the current and-or list started: `a && cd x &` runs the whole list
74    // in a background subshell, so nothing in it moves what comes after.
75    let mut list_base = cwd.clone();
76    let mut pending: Option<Pending> = None;
77    let mut prev: Option<Separator> = None;
78    let mut out = Vec::with_capacity(segments.len());
79
80    for (segment, sep) in segments {
81        // Every segment runs where it starts — a `cd` included: its own
82        // redirect is opened before it moves, and a failed `cd` stays put.
83        let here = cwd.clone();
84        let mut own = here.clone();
85
86        if let Some(p) = pending.take_if(|p| p.fallback) {
87            // `cd x || exit 1; …` — past the fallback, only a working `cd` is
88            // left. A skippable `cd` is not: `a || cd x || exit` exits on neither
89            // path when `a` succeeds.
90            cwd = if exits(&segment) && !p.skippable {
91                p.moved
92            } else if cd_target(&segment).is_some() || moves_opaquely(&segment) {
93                None
94            } else {
95                p.either()
96            };
97        } else if let Some(target) = cd_target(&segment) {
98            let moved = if cdpath && is_cdpath_candidate(target) {
99                None
100            } else {
101                resolve_cd(here.as_deref(), target)
102            };
103            // With an uncertain `cd` still open (`cd a && cd b`), not taking
104            // this one leaves the shell in `a` *or* where `a` started.
105            let old = match pending.take() {
106                Some(p) => merge(here.clone(), p.old.as_deref()),
107                None => here.clone(),
108            };
109            let runs_unconditionally = matches!(
110                prev,
111                None | Some(Separator::Sequence | Separator::Background)
112            );
113            if prev == Some(Separator::Pipe) || sep == Some(Separator::Pipe) {
114                // A pipeline element runs in a subshell — in bash. zsh runs the
115                // last one in the current shell, so neither reading is safe.
116                cwd = merge(moved, old.as_deref());
117            } else if runs_unconditionally && moved.as_deref().is_some_and(Path::is_dir) {
118                // Runs, and into a directory that exists: it takes effect.
119                cwd = moved;
120            } else {
121                let skippable = prev == Some(Separator::Or);
122                let p = Pending {
123                    moved,
124                    old,
125                    skippable,
126                    fallback: sep == Some(Separator::Or),
127                };
128                cwd = match sep {
129                    Some(Separator::Or) => p.old.clone(),
130                    Some(Separator::Sequence) => merge(p.moved.clone(), p.old.as_deref()),
131                    _ if skippable => merge(p.moved.clone(), p.old.as_deref()),
132                    _ => p.moved.clone(),
133                };
134                if matches!(sep, Some(Separator::Or | Separator::And) | None) {
135                    pending = Some(p);
136                }
137            }
138        } else {
139            if moves_opaquely(&segment) {
140                own = None;
141                // A subshell `( … )` cannot move what follows it; anything else
142                // (a brace group, a loop body, a function, `pushd`) can.
143                if !segment.starts_with('(') {
144                    cwd = None;
145                    pending = None;
146                }
147            }
148            // Leaving the `&&` chain of an uncertain `cd`: what comes next can
149            // also be reached when that `cd` did not happen.
150            if let Some(p) = pending.take() {
151                match sep {
152                    Some(Separator::And | Separator::Pipe) | None => pending = Some(p),
153                    Some(Separator::Or | Separator::Sequence | Separator::Background) => {
154                        cwd = p.either();
155                    }
156                }
157            }
158        }
159
160        out.push(SegmentCwd { segment, cwd: own });
161        match sep {
162            Some(Separator::Background) => {
163                cwd.clone_from(&list_base);
164                pending = None;
165            }
166            Some(Separator::Sequence) => list_base.clone_from(&cwd),
167            _ => {}
168        }
169        prev = sep;
170    }
171    (out, cwd)
172}
173
174/// One directory when both possibilities agree, otherwise unknown.
175fn merge(a: Option<PathBuf>, b: Option<&Path>) -> Option<PathBuf> {
176    if a.as_deref() == b { a } else { None }
177}
178
179/// A `cd x || exit` fallback: nothing after it runs unless the `cd` worked.
180fn exits(segment: &str) -> bool {
181    matches!(segment.split_whitespace().next(), Some("exit" | "return"))
182}
183
184/// A relative name `CDPATH` would look up (`./x` and `../x` bypass it).
185fn is_cdpath_candidate(target: &str) -> bool {
186    let t = target.trim_matches(['"', '\'']);
187    !(t.starts_with('/')
188        || t.starts_with('~')
189        || t.starts_with("./")
190        || t.starts_with("../")
191        || t == "."
192        || t == ".."
193        || Path::new(t).is_absolute())
194}
195
196/// Whether a segment that is not a plain `cd <literal>` may still change the
197/// directory: `pushd`, `popd`, `cd` after `do`/`then`/`builtin`/`command`, or
198/// any of them inside a subshell, brace group, substitution or function body.
199/// Deliberately broad — a false positive only makes the directory unknown.
200fn moves_opaquely(segment: &str) -> bool {
201    segment
202        .split(|c: char| c.is_whitespace() || "(){};&|`".contains(c))
203        .any(|word| matches!(word, "cd" | "pushd" | "popd" | "chdir"))
204}
205
206/// The literal argument of a segment that is exactly `cd <path>`.
207fn cd_target(segment: &str) -> Option<&str> {
208    let mut words = segment.split_whitespace();
209    if words.next()? != "cd" {
210        return None;
211    }
212    let target = words.next()?;
213    if words.next().is_some() {
214        // `cd a b` is not something to reason about.
215        return None;
216    }
217    Some(target)
218}
219
220/// Apply one `cd`, or give up on knowing the directory.
221///
222/// `cd` with no resolvable target is not "stay here": it moves somewhere this
223/// cannot see. Returning `None` keeps callers from judging a later segment
224/// against a directory it does not run in.
225fn resolve_cd(from: Option<&Path>, target: &str) -> Option<PathBuf> {
226    let unquoted = target.trim_matches(['"', '\'']);
227    if unquoted.is_empty() || unquoted.contains('$') || unquoted.contains('`') || unquoted == "-" {
228        return None;
229    }
230    // `cd ~` and `cd ~/x` are the shell's expansion, not a relative path.
231    if let Some(rest) = unquoted.strip_prefix('~') {
232        let home = std::env::var_os("HOME").map(PathBuf::from)?;
233        return Some(join_in(&home, rest.trim_start_matches('/')));
234    }
235    // This is shell text, so `/tmp` is an absolute POSIX path even on Windows,
236    // where `Path::is_absolute` says otherwise. Agents write Unix paths there
237    // routinely (Git Bash, WSL, generated commands) — the same reason
238    // `is_unix_scratch_prefix` exists (#1467). Treating them as relative made a
239    // `cd /tmp` resolve to nothing on Windows, and the guard then judged the
240    // download target against no directory at all.
241    if unquoted.starts_with('/') {
242        return Some(PathBuf::from(normalize_posix(unquoted)));
243    }
244    let path = Path::new(unquoted);
245    if path.is_absolute() {
246        return Some(normalize(path));
247    }
248    Some(join_in(from?, unquoted))
249}
250
251/// Join `rel` under `base`, keeping a POSIX-rooted base POSIX.
252///
253/// `Path::join` would splice a backslash into `/tmp` on Windows, and the
254/// scratch-prefix checks match on `/tmp/`.
255pub fn join_in(base: &Path, rel: &str) -> PathBuf {
256    let base_str = base.to_string_lossy();
257    if base_str.starts_with('/') {
258        return PathBuf::from(normalize_posix(&format!(
259            "{}/{rel}",
260            base_str.trim_end_matches('/')
261        )));
262    }
263    normalize(&base.join(rel))
264}
265
266/// Resolve `.` and `..` in a POSIX path textually, on any platform.
267fn normalize_posix(path: &str) -> String {
268    let mut out: Vec<&str> = Vec::new();
269    for part in path.split('/') {
270        match part {
271            "" | "." => {}
272            ".." => {
273                out.pop();
274            }
275            other => out.push(other),
276        }
277    }
278    format!("/{}", out.join("/"))
279}
280
281/// Resolve `.` and `..` textually. The directory may not exist yet, so this
282/// deliberately does not touch the filesystem.
283fn normalize(path: &Path) -> PathBuf {
284    use std::path::Component;
285    let mut out = PathBuf::new();
286    for component in path.components() {
287        match component {
288            Component::CurDir => {}
289            Component::ParentDir => {
290                out.pop();
291            }
292            other => out.push(other),
293        }
294    }
295    out
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn a_leading_cd_moves_the_following_segments() {
304        let segs = segments_with_cwd(
305            "cd /tmp/work && curl -o x.png http://e/x",
306            Some(Path::new("/proj")),
307        );
308        assert_eq!(
309            segs.last().unwrap().cwd.as_deref(),
310            Some(Path::new("/tmp/work"))
311        );
312    }
313
314    #[test]
315    fn without_a_cd_every_segment_keeps_the_call_directory() {
316        let segs = segments_with_cwd("echo a && echo b", Some(Path::new("/proj")));
317        assert!(
318            segs.iter()
319                .all(|s| s.cwd.as_deref() == Some(Path::new("/proj")))
320        );
321    }
322
323    #[test]
324    fn a_relative_cd_is_joined_onto_the_call_directory() {
325        assert_eq!(
326            final_cwd("cd sub/dir && ls", Some(Path::new("/proj"))),
327            Some(PathBuf::from("/proj/sub/dir"))
328        );
329        assert_eq!(
330            final_cwd("cd ../side && ls", Some(Path::new("/proj/here"))),
331            Some(PathBuf::from("/proj/side"))
332        );
333    }
334
335    /// A directory the shell would have to compute is unknown, not the old one
336    /// — judging a later segment against a stale directory is how a guard ends
337    /// up permitting or blocking the wrong thing.
338    #[test]
339    fn an_unresolvable_cd_makes_the_directory_unknown() {
340        assert_eq!(
341            final_cwd("cd \"$TMPDIR\" && ls", Some(Path::new("/proj"))),
342            None
343        );
344        assert_eq!(final_cwd("cd - && ls", Some(Path::new("/proj"))), None);
345    }
346
347    /// A Unix path in shell text stays a Unix path on Windows too (#1467).
348    /// This is the case that broke CI: `cd /tmp` resolved to nothing there, so
349    /// the download guard judged `shot.png` against no directory at all.
350    #[test]
351    fn a_unix_path_in_shell_text_is_absolute_on_every_platform() {
352        assert_eq!(
353            final_cwd("cd /tmp && curl -o shot.png https://e/x", None),
354            Some(PathBuf::from("/tmp"))
355        );
356        assert_eq!(
357            final_cwd("cd /private/tmp/session/../session && ls", None),
358            Some(PathBuf::from("/private/tmp/session"))
359        );
360        assert_eq!(
361            join_in(Path::new("/tmp/work"), "sub/shot.png"),
362            PathBuf::from("/tmp/work/sub/shot.png"),
363            "and joins with a forward slash, which the scratch prefixes match on"
364        );
365    }
366
367    #[test]
368    fn no_base_and_no_cd_is_unknown() {
369        assert_eq!(final_cwd("ls -la", None), None);
370    }
371
372    fn cwds(command: &str) -> Vec<Option<PathBuf>> {
373        segments_with_cwd(command, Some(Path::new("/proj")))
374            .into_iter()
375            .map(|s| s.cwd)
376            .collect()
377    }
378
379    const MISSING: &str = "/lean-ctx-1850-does-not-exist";
380
381    /// A `cd` runs where it starts: its own redirect is opened before it moves.
382    #[test]
383    fn a_cd_segment_runs_in_the_directory_before_it() {
384        assert_eq!(cwds("cd /tmp && ls")[0], Some(PathBuf::from("/proj")));
385    }
386
387    /// #1850: `cd x && a; b` — if the `cd` fails, `a` is skipped but `b` still
388    /// runs, in the old directory. Past the `;` both are possible.
389    #[test]
390    fn a_cd_that_may_fail_does_not_carry_past_a_sequence() {
391        let got = cwds(&format!("cd {MISSING} && true; echo x"));
392        assert_eq!(got[1], Some(PathBuf::from(MISSING)), "reached only via &&");
393        assert_eq!(got[2], None);
394    }
395
396    #[test]
397    fn a_cd_that_may_be_skipped_leaves_the_directory_unknown() {
398        assert_eq!(cwds("false && cd /tmp; echo x")[2], None);
399        assert_eq!(cwds("true || cd /tmp && echo x")[2], None);
400        assert_eq!(cwds("cd /tmp | cat; echo x")[2], None, "a pipeline element");
401    }
402
403    /// `cd a && cd .` must not merge the two possibilities into one directory
404    /// just because both `cd`s name the same place.
405    #[test]
406    fn a_second_cd_does_not_make_a_failed_first_one_certain() {
407        assert_eq!(cwds(&format!("cd {MISSING} && cd . ; echo x"))[2], None);
408    }
409
410    #[test]
411    fn cd_or_exit_leaves_only_the_moved_directory() {
412        let got = cwds(&format!("cd {MISSING} || exit 1; echo x"));
413        assert_eq!(got[1], Some(PathBuf::from("/proj")), "the fallback");
414        assert_eq!(got[2], Some(PathBuf::from(MISSING)));
415    }
416
417    /// `&` runs the whole and-or list in a background subshell.
418    #[test]
419    fn a_backgrounded_list_does_not_move_what_follows() {
420        assert_eq!(
421            cwds("cd /tmp && echo a & echo b")[2],
422            Some(PathBuf::from("/proj"))
423        );
424    }
425
426    #[test]
427    fn opaque_movers_make_the_directory_unknown() {
428        for command in [
429            "pushd /tmp && echo x",
430            "builtin cd /tmp && echo x",
431            "{ cd /tmp; } && echo x",
432        ] {
433            assert_eq!(cwds(command).last(), Some(&None), "{command}");
434        }
435        let subshell = cwds("(cd /tmp) && echo x");
436        assert_eq!(subshell[0], None, "its own directory is not followed");
437        assert_eq!(
438            subshell[1],
439            Some(PathBuf::from("/proj")),
440            "but it cannot move the parent shell"
441        );
442    }
443
444    #[test]
445    fn cdpath_makes_a_relative_cd_unknown() {
446        assert_eq!(cwds("CDPATH=/elsewhere; cd sub && ls")[2], None);
447        assert_eq!(
448            cwds("CDPATH=/elsewhere; cd ./sub && ls")[2],
449            Some(PathBuf::from("/proj/sub")),
450            "`./` bypasses CDPATH"
451        );
452    }
453}