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/// Execute a command from pre-split argv without going through `sh -c`.
7/// Used by `-t` mode when the shell hook passes `"$@"` — arguments are
8/// already correctly split by the user's shell, so re-serializing them
9/// into a string and re-parsing via `sh -c` would risk mangling complex
10/// quoted arguments (em-dashes, `#`, nested quotes, etc.).
11pub fn exec_argv(args: &[String]) -> i32 {
12    if args.is_empty() {
13        return 127;
14    }
15
16    // Quote-safe join used only for the allowlist/policy *checks*; execution
17    // below still consumes the pre-split argv verbatim (the whole reason `-t`
18    // avoids `sh -c`). Joining first means a single argv element such as
19    // `git status; rm -rf /` is checked as ONE quoted token, never re-parsed.
20    let joined = super::super::platform::join_command(args);
21
22    // #595: unwrap a host command wrapper (eval + cwd snapshot) before any
23    // checks so the real command — not the wrapper — is gated and run. The `-t`
24    // path cannot exec a compound argv, so route the rebuild through `exec`.
25    if let Some(u) = super::super::agent_wrapper::unwrap_agent_wrapper(&joined) {
26        return exec(&u.rebuild());
27    }
28
29    // The `-t` track path is the agent's default shell hook
30    // (`_lc() { lean-ctx -t "$@" }`), so it MUST enforce the same allowlist
31    // boundary as `-c` (see `exec`). Previously it skipped the check entirely,
32    // letting every aliased multi-arg invocation (`_lc git …`) bypass the
33    // restriction that `lean-ctx -c` enforces (GH security audit, finding 1).
34    if let Some(code) = allowlist_gate(&joined) {
35        return code;
36    }
37
38    if super::super::reentry::should_pass_through() {
39        return exec_direct(args);
40    }
41
42    let cfg = config::Config::load();
43    let policy = super::super::output_policy::classify(&joined, &cfg.excluded_commands);
44
45    if policy.is_protected() {
46        let code = exec_direct(args);
47        crate::core::tool_lifecycle::record_shell_command(0, 0);
48        return code;
49    }
50
51    let code = exec_direct(args);
52    crate::core::tool_lifecycle::record_shell_command(0, 0);
53    code
54}
55
56fn exec_direct(args: &[String]) -> i32 {
57    let mut cmd = Command::new(&args[0]);
58    cmd.args(&args[1..])
59        .stdin(Stdio::inherit())
60        .stdout(Stdio::inherit())
61        .stderr(Stdio::inherit());
62    super::super::reentry::mark_child(&mut cmd);
63    super::super::platform::apply_utf8_locale(&mut cmd);
64    let status = cmd.status();
65
66    match status {
67        Ok(s) => s.code().unwrap_or(1),
68        Err(e) => {
69            tracing::error!("lean-ctx: failed to execute: {e}");
70            127
71        }
72    }
73}
74
75/// Decides whether an allowlist violation on the CLI path blocks (exit 126) or
76/// only warns.
77///
78/// Enforced when:
79/// - hook-child mode (`LEAN_CTX_HOOK_CHILD`): lean-ctx is the agent's
80///   command-interception channel and must not be weaker than the MCP path, or
81/// - stderr is not a TTY: a non-interactive caller is an agent or script, and
82///   agent-driven `lean-ctx -c` must enforce the same boundary as ctx_shell.
83///
84/// Warn-only when a human runs `lean-ctx -c` at an interactive terminal (they
85/// can run the command without lean-ctx anyway, so blocking adds friction, not
86/// a boundary) or when `LEAN_CTX_ALLOWLIST_WARN_ONLY=1` explicitly opts out.
87fn allowlist_must_enforce() -> bool {
88    let hook_child = crate::core::runtime_flags::hook_child_enabled();
89    let warn_only = std::env::var("LEAN_CTX_ALLOWLIST_WARN_ONLY")
90        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
91    allowlist_must_enforce_inner(hook_child, warn_only, io::stderr().is_terminal())
92}
93
94/// Pure decision core of [`allowlist_must_enforce`] (unit-testable without
95/// process-global env/TTY state).
96fn allowlist_must_enforce_inner(hook_child: bool, warn_only: bool, stderr_is_tty: bool) -> bool {
97    if hook_child {
98        return true;
99    }
100    if warn_only {
101        return false;
102    }
103    !stderr_is_tty
104}
105
106/// True when this process's stdout is a **regular file** — i.e. the caller
107/// redirected output to a file (`cmd > out`, `cmd >> out`).
108///
109/// Output captured to a file is consumed as *data*, so it must stay byte-faithful:
110/// compression would silently drop/abbreviate lines and corrupt the file
111/// (e.g. `git status --short > files.txt` losing entries). Pipes (agent capture)
112/// and TTYs are NOT regular files and return `false`, so they keep their normal
113/// behavior — this only ever *adds* a verbatim guarantee, never removes one.
114///
115/// Uses only `std`: it wraps the existing stdout descriptor in a `ManuallyDrop`
116/// `File` purely to read its metadata (`fstat` on Unix, `GetFileInformation` on
117/// Windows) without ever closing the real stdout.
118fn stdout_is_regular_file() -> bool {
119    #[cfg(unix)]
120    {
121        use std::os::unix::io::{AsRawFd, FromRawFd};
122        let fd = io::stdout().as_raw_fd();
123        // SAFETY: fd 1 stays valid for the whole process. `ManuallyDrop` prevents
124        // the wrapper's `Drop` from closing stdout; we only read metadata.
125        let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(fd) });
126        file.metadata().is_ok_and(|m| m.is_file())
127    }
128    #[cfg(windows)]
129    {
130        use std::os::windows::io::{AsRawHandle, FromRawHandle};
131        let handle = io::stdout().as_raw_handle();
132        // SAFETY: the stdout handle stays valid for the whole process.
133        // `ManuallyDrop` prevents the wrapper's `Drop` from closing it.
134        let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_handle(handle) });
135        file.metadata().is_ok_and(|m| m.is_file())
136    }
137    #[cfg(not(any(unix, windows)))]
138    {
139        false
140    }
141}
142
143/// Quote-aware check for stdout file redirects (`>`, `>>`) inside a command
144/// string. Returns `true` when the command redirects to a real file (not
145/// `/dev/null`, not `>&N` fd-duplication, not `2>`).
146fn command_has_file_redirect(cmd: &str) -> bool {
147    let bytes = cmd.as_bytes();
148    let len = bytes.len();
149    let mut i = 0;
150    let mut in_single_quote = false;
151    let mut in_double_quote = false;
152
153    while i < len {
154        let c = bytes[i];
155        if c == b'\\' && !in_single_quote {
156            i += 2;
157            continue;
158        }
159        if c == b'\'' && !in_double_quote {
160            in_single_quote = !in_single_quote;
161        } else if c == b'"' && !in_single_quote {
162            in_double_quote = !in_double_quote;
163        } else if c == b'>' && !in_single_quote && !in_double_quote {
164            if i > 0 && bytes[i - 1] == b'2' {
165                i += 1;
166                continue;
167            }
168            let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
169                i + 2
170            } else {
171                i + 1
172            };
173            let target: String = cmd[target_start..]
174                .trim_start()
175                .chars()
176                .take_while(|c| !c.is_whitespace())
177                .collect();
178            if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
179                i += 1;
180                continue;
181            }
182            if let Some(fd) = target.strip_prefix('&')
183                && !fd.is_empty()
184                && (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
185            {
186                i += 1;
187                continue;
188            }
189            if !target.is_empty() {
190                return true;
191            }
192        }
193        i += 1;
194    }
195    false
196}
197
198/// Shared allowlist gate for the CLI shell entrypoints — `-c` (via [`exec`]) and
199/// `-t` (via [`exec_argv`]). Both must apply the SAME boundary so the track path
200/// (the default shell hook) cannot be weaker than the compress path.
201///
202/// Returns `Some(126)` when the command is blocked and the caller must return
203/// that exit code; `None` when execution may proceed (allowed, or warn-only for
204/// an interactive human — see [`allowlist_must_enforce`]).
205fn allowlist_gate(command: &str) -> Option<i32> {
206    if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(command) {
207        if allowlist_must_enforce() {
208            eprintln!("{msg}");
209            eprintln!(
210                "lean-ctx: command blocked by shell allowlist. \
211                 Allow it permanently: lean-ctx allow <cmd> — or set \
212                 LEAN_CTX_ALLOWLIST_WARN_ONLY=1 to downgrade to a warning."
213            );
214            return Some(126);
215        }
216        // Diagnostic, not user feedback: an interactive human at a TTY can run
217        // the command without lean-ctx anyway, and surfacing a WARN in their
218        // plain terminal is exactly the confusion GH #699 reported. Keep the
219        // warning for non-TTY callers (agents that opted into warn-only).
220        if io::stderr().is_terminal() {
221            tracing::debug!("[CLI] Command would be blocked in MCP mode: {msg}");
222        } else {
223            tracing::warn!("[CLI] Command would be blocked in MCP mode: {msg}");
224        }
225    }
226    None
227}
228
229pub fn exec(command: &str) -> i32 {
230    // #595: when the agent wraps its command in host scaffolding
231    // (`… && eval '<cmd>' … && pwd -P >| …-cwd`), look through it so the allowlist
232    // and compression act on the REAL command, not the wrapper — whose `eval` the
233    // allowlist would otherwise hard-block on every single call. The cwd snapshot
234    // is preserved so the host keeps tracking the working directory.
235    let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
236    let mut collapsed_nested = false;
237    let collapsed;
238    let command = unwrapped.as_deref().unwrap_or(command);
239    let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
240        collapsed_nested = true;
241        collapsed = c;
242        collapsed.as_str()
243    } else {
244        command
245    };
246
247    if let Some(code) = allowlist_gate(command) {
248        return code;
249    }
250
251    let (shell, shell_flag) = super::super::platform::shell_and_flag();
252    let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
253    // #1286: keep the zsh preamble (`setopt nonomatch noequals; `) OUT of the
254    // command string used for classification and compression — every
255    // `starts_with("ls ")`/`git`-style pattern matcher silently stopped
256    // matching under zsh (the default macOS shell), degrading pattern
257    // compression to the generic terse fallback. The preamble is applied to
258    // the SPAWNED command only, inside the exec helpers.
259    let command = command.as_str();
260
261    if super::super::reentry::is_disabled() {
262        return exec_inherit(command, &shell, &shell_flag);
263    }
264    if should_delegate_wrapped_to_shell_default(collapsed_nested) {
265        return exec_shell_default(command, &shell, &shell_flag);
266    }
267
268    let cfg = config::Config::load();
269    let force_compress = crate::core::runtime_flags::compress_enabled();
270    let raw_mode = crate::core::runtime_flags::raw_enabled();
271
272    if raw_mode {
273        return exec_inherit_tracked(command, &shell, &shell_flag);
274    }
275
276    let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
277
278    // Passthrough: ALWAYS bypass compression, even with force_compress.
279    if policy == super::super::output_policy::OutputPolicy::Passthrough {
280        return exec_inherit_tracked(command, &shell, &shell_flag);
281    }
282
283    // Verbatim: bypass compression unless force_compress is set,
284    // in which case use buffered path (compress_if_beneficial will
285    // respect the verbatim classification and only size-cap).
286    if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
287        return exec_inherit_tracked(command, &shell, &shell_flag);
288    }
289
290    if !force_compress {
291        if io::stdout().is_terminal() {
292            return exec_inherit_tracked(command, &shell, &shell_flag);
293        }
294        let code = exec_inherit(command, &shell, &shell_flag);
295        crate::core::tool_lifecycle::record_shell_command(0, 0);
296        return code;
297    }
298
299    // Compression is forced (`-c` / LEAN_CTX_COMPRESS, e.g. the agent shell hook).
300    // It must STILL never alter bytes destined for a file: a redirect
301    // (`cmd > out`, `cmd >> out`) means the output is captured as data, not read by
302    // a human or agent. Writing the compressed digest there would silently
303    // drop/abbreviate lines and corrupt the file (e.g. contradictory `git diff`
304    // dumps). Pass redirected-to-file output through verbatim; pipes (agent
305    // capture) and TTYs keep compressing. This is the single choke point, so it
306    // holds for every caller (hook, direct CLI, Pi/MCP bridges).
307    if stdout_is_regular_file() {
308        return exec_inherit_tracked(command, &shell, &shell_flag);
309    }
310
311    // Also bypass compression when the redirect is INSIDE the command string
312    // (e.g., `lean-ctx -c 'git show HEAD:f > out.md'`). In this case lean-ctx's
313    // own stdout is a pipe (to the agent), but the shell child redirects its
314    // stdout to the file. exec_buffered would capture empty/minimal output while
315    // the file gets correct data — but the overhead is wasted and the compressed
316    // empty output confuses agents. Let sh handle it natively. (#1303)
317    if command_has_file_redirect(command) {
318        return exec_inherit_tracked(command, &shell, &shell_flag);
319    }
320
321    super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
322}
323
324fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
325    let mut current = command.trim().to_string();
326    let mut changed = false;
327
328    while let Some(next) = strip_one_lean_ctx_exec(&current) {
329        if next == current {
330            break;
331        }
332        current = next;
333        changed = true;
334    }
335
336    changed.then_some(current)
337}
338
339fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
340    // After collapsing `lean-ctx -c "lean-ctx -c ..."` the current process is the
341    // one compression pass that would otherwise be owned by the shell default.
342    // Delegating again would drop back to raw execution or re-enter the hook.
343    super::super::reentry::is_wrapped() && !collapsed_nested
344}
345
346fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
347    let words = split_simple_shell_words(command)?;
348    if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
349        return None;
350    }
351    if words[1].value != "-c" && words[1].value != "exec" {
352        return None;
353    }
354    if words[2..].iter().any(|w| {
355        matches!(
356            w.value.as_str(),
357            "|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
358        )
359    }) {
360        return None;
361    }
362    if words.len() == 3 {
363        Some(words[2].value.trim().to_string())
364    } else {
365        Some(command[words[2].start..].trim().to_string())
366    }
367}
368
369fn is_lean_ctx_bin(word: &str) -> bool {
370    std::path::Path::new(word)
371        .file_name()
372        .and_then(|name| name.to_str())
373        .is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
374}
375
376struct SimpleShellWord {
377    value: String,
378    start: usize,
379}
380
381fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
382    let mut words = Vec::new();
383    let mut current = String::new();
384    let mut current_start: Option<usize> = None;
385    let mut chars = command.char_indices().peekable();
386    let mut quote: Option<char> = None;
387
388    while let Some((idx, ch)) = chars.next() {
389        match quote {
390            Some('\'') if ch == '\'' => quote = None,
391            Some('"') if ch == '"' => quote = None,
392            None if ch == '\'' || ch == '"' => {
393                current_start.get_or_insert(idx);
394                quote = Some(ch);
395            }
396            Some('"') | None if ch == '\\' => {
397                current_start.get_or_insert(idx);
398                if let Some((_, next)) = chars.next() {
399                    current.push(next);
400                }
401            }
402            None if ch.is_whitespace() => {
403                if let Some(start) = current_start.take() {
404                    words.push(SimpleShellWord {
405                        value: std::mem::take(&mut current),
406                        start,
407                    });
408                }
409            }
410            Some(_) | None => {
411                current_start.get_or_insert(idx);
412                current.push(ch);
413            }
414        }
415    }
416
417    if quote.is_some() {
418        return None;
419    }
420    if let Some(start) = current_start {
421        words.push(SimpleShellWord {
422            value: current,
423            start,
424        });
425    }
426    (!words.is_empty()).then_some(words)
427}
428
429fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
430    // #1286: the zsh preamble is applied at spawn time only, so `command`
431    // stays clean for classification/compression upstream.
432    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
433    let mut cmd = Command::new(shell);
434    cmd.arg(shell_flag)
435        .arg(&spawn_command)
436        .stdin(Stdio::inherit())
437        .stdout(Stdio::inherit())
438        .stderr(Stdio::inherit());
439    super::super::reentry::mark_child(&mut cmd);
440    super::super::platform::apply_utf8_locale(&mut cmd);
441    super::super::platform::apply_profile_free_env(&mut cmd);
442    let status = cmd.status();
443
444    match status {
445        Ok(s) => s.code().unwrap_or(1),
446        Err(e) => {
447            tracing::error!("lean-ctx: failed to execute: {e}");
448            127
449        }
450    }
451}
452
453fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
454    let spawn_command = super::super::platform::zsh_safe_command(command, shell);
455    let mut cmd = Command::new(shell);
456    cmd.arg(shell_flag)
457        .arg(&spawn_command)
458        .stdin(Stdio::inherit())
459        .stdout(Stdio::inherit())
460        .stderr(Stdio::inherit());
461    super::super::reentry::clear_shell_default_markers(&mut cmd);
462    super::super::platform::apply_utf8_locale(&mut cmd);
463    super::super::platform::apply_profile_free_env(&mut cmd);
464    let status = cmd.status();
465
466    match status {
467        Ok(s) => s.code().unwrap_or(1),
468        Err(e) => {
469            eprintln!("lean-ctx: failed to execute '{command}': {e}");
470            127
471        }
472    }
473}
474
475fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
476    let code = exec_inherit(command, shell, shell_flag);
477    crate::core::tool_lifecycle::record_shell_command(0, 0);
478    code
479}
480
481/// Label inserted between stdout and stderr of a FAILED command so the agent can
482/// attribute the error to the right stream instead of guessing — and never has to
483/// re-run the command raw just to locate the failure. See #809 / #812.
484pub(crate) const STDERR_LABEL: &str = "--- stderr ---";
485
486/// Join captured stdout and stderr for display/recovery. On failure (non-zero
487/// exit) with both streams present, a labeled delimiter separates them; success
488/// output keeps the plain `stdout\nstderr` shape (determinism, #498).
489pub(crate) fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
490    match (stdout.is_empty(), stderr.is_empty()) {
491        (_, true) => stdout.to_string(),
492        (true, false) => stderr.to_string(),
493        (false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
494        (false, false) => format!("{stdout}\n{stderr}"),
495    }
496}
497
498// Buffered command execution and output transformation live in `pipeline`.
499
500#[cfg(test)]
501mod nested_lean_ctx_exec_tests;
502
503#[cfg(test)]
504mod exec_tests {
505    #[test]
506    fn combine_streams_labels_stderr_on_failure() {
507        let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
508        assert_eq!(
509            out,
510            format!(
511                "build ok\n{}\nlinker: undefined symbol",
512                super::STDERR_LABEL
513            )
514        );
515    }
516
517    #[test]
518    fn combine_streams_plain_join_on_success() {
519        let out = super::combine_streams("step 1", "warning: noop", 0);
520        assert_eq!(out, "step 1\nwarning: noop");
521        assert!(!out.contains(super::STDERR_LABEL));
522    }
523
524    #[test]
525    fn combine_streams_single_stream_is_unchanged() {
526        assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
527        assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
528    }
529
530    #[test]
531    fn exec_direct_runs_true() {
532        let code = super::exec_direct(&["true".to_string()]);
533        assert_eq!(code, 0);
534    }
535
536    #[test]
537    fn exec_direct_runs_false() {
538        let code = super::exec_direct(&["false".to_string()]);
539        assert_ne!(code, 0);
540    }
541
542    #[test]
543    fn exec_direct_preserves_args_with_special_chars() {
544        let code = super::exec_direct(&[
545            "echo".to_string(),
546            "hello world".to_string(),
547            "it's here".to_string(),
548            "a \"quoted\" thing".to_string(),
549        ]);
550        assert_eq!(code, 0);
551    }
552
553    #[test]
554    fn exec_direct_nonexistent_returns_127() {
555        let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
556        assert_eq!(code, 127);
557    }
558
559    #[test]
560    fn exec_argv_empty_returns_127() {
561        let code = super::exec_argv(&[]);
562        assert_eq!(code, 127);
563    }
564
565    #[test]
566    fn exec_argv_runs_simple_command() {
567        let _lock = crate::core::data_dir::test_env_lock();
568        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
569        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
570        let code = super::exec_argv(&["true".to_string()]);
571        assert_eq!(code, 0);
572    }
573
574    #[test]
575    fn exec_argv_passes_through_when_disabled() {
576        let _lock = crate::core::data_dir::test_env_lock();
577        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
578        crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
579        let code = super::exec_argv(&["true".to_string()]);
580        crate::test_env::remove_var("LEAN_CTX_DISABLED");
581        assert_eq!(code, 0);
582    }
583
584    // Finding 1 (GH security audit): the `-t` track path is the default shell
585    // hook, so it must enforce the allowlist exactly like the `-c` path. A
586    // non-allowlisted command must be blocked (126), not executed.
587    #[test]
588    fn exec_argv_enforces_allowlist_for_disallowed_command() {
589        let _lock = crate::core::data_dir::test_env_lock();
590        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
591        crate::test_env::remove_var("LEAN_CTX_DISABLED");
592        crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
593        // hook-child forces enforcement regardless of the test runner's TTY state.
594        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
595        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
596
597        // #1022: `true` is now a SHELL_BUILTIN (bypasses allowlist).
598        // Use `xxd` which is a real binary and not in the override list.
599        let code = super::exec_argv(&["xxd".to_string()]);
600
601        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
602        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
603
604        assert_eq!(
605            code, 126,
606            "non-allowlisted command must be blocked on the -t track path"
607        );
608    }
609
610    #[test]
611    fn exec_argv_allows_allowlisted_command() {
612        let _lock = crate::core::data_dir::test_env_lock();
613        crate::test_env::remove_var("LEAN_CTX_ACTIVE");
614        crate::test_env::remove_var("LEAN_CTX_DISABLED");
615        crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
616        crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
617
618        let code = super::exec_argv(&["true".to_string()]);
619
620        crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
621        crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
622
623        assert_eq!(code, 0, "allowlisted command must run on the -t track path");
624    }
625    // P0-1 (#413): the CLI allowlist must enforce for agents, warn for humans.
626    #[test]
627    fn allowlist_enforces_in_hook_child_mode() {
628        // Hook-child wins over everything, even an interactive TTY.
629        assert!(super::allowlist_must_enforce_inner(true, false, true));
630        assert!(super::allowlist_must_enforce_inner(true, true, true));
631    }
632
633    #[test]
634    fn allowlist_enforces_for_non_interactive_callers() {
635        // Agent/script invocation: stderr is a pipe → enforce.
636        assert!(super::allowlist_must_enforce_inner(false, false, false));
637    }
638
639    #[test]
640    fn allowlist_warns_for_interactive_humans() {
641        // Human at a TTY → warn-only (they can bypass lean-ctx anyway).
642        assert!(!super::allowlist_must_enforce_inner(false, false, true));
643    }
644
645    #[test]
646    fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
647        // Explicit LEAN_CTX_ALLOWLIST_WARN_ONLY=1 opt-out (but never in hook-child mode).
648        assert!(!super::allowlist_must_enforce_inner(false, true, false));
649        assert!(super::allowlist_must_enforce_inner(true, true, false));
650    }
651
652    // --- #1303: command_has_file_redirect ---
653
654    #[test]
655    fn redirect_to_file_detected() {
656        assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
657        assert!(super::command_has_file_redirect("git diff >> changes.log"));
658        assert!(super::command_has_file_redirect(
659            "git status > /tmp/status.txt"
660        ));
661    }
662
663    #[test]
664    fn no_redirect_not_detected() {
665        assert!(!super::command_has_file_redirect("git status"));
666        assert!(!super::command_has_file_redirect("cargo test --lib"));
667    }
668
669    #[test]
670    fn dev_null_not_detected_as_redirect() {
671        assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
672        assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
673        assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
674    }
675
676    #[test]
677    fn stderr_redirect_not_detected() {
678        assert!(!super::command_has_file_redirect(
679            "cargo test 2> errors.log"
680        ));
681        assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
682    }
683
684    #[test]
685    fn fd_dup_not_detected() {
686        assert!(!super::command_has_file_redirect("cargo test 2>&1"));
687        assert!(!super::command_has_file_redirect("cmd >&2"));
688    }
689
690    #[test]
691    fn quoted_redirect_not_detected() {
692        assert!(!super::command_has_file_redirect("echo 'a > b'"));
693        assert!(!super::command_has_file_redirect("echo \"a > b\""));
694        assert!(!super::command_has_file_redirect(
695            "gh pr create --body 'see > details'"
696        ));
697    }
698
699    #[test]
700    fn escaped_redirect_not_detected() {
701        assert!(!super::command_has_file_redirect("echo a \\> b"));
702    }
703}