use std::io::{self, IsTerminal};
use std::process::{Command, Stdio};
use crate::core::config;
pub fn exec_argv(args: &[String]) -> i32 {
if args.is_empty() {
return 127;
}
let joined = super::super::platform::join_command(args);
if let Some(u) = super::super::agent_wrapper::unwrap_agent_wrapper(&joined) {
return exec(&u.rebuild());
}
if let Some(code) = allowlist_gate(&joined) {
return code;
}
if super::super::reentry::should_pass_through() {
return exec_direct(args);
}
let cfg = config::Config::load();
let policy = super::super::output_policy::classify(&joined, &cfg.excluded_commands);
if policy.is_protected() {
let code = exec_direct(args);
crate::core::tool_lifecycle::record_shell_command(0, 0);
return code;
}
let code = exec_direct(args);
crate::core::tool_lifecycle::record_shell_command(0, 0);
code
}
fn exec_direct(args: &[String]) -> i32 {
let mut cmd = Command::new(&args[0]);
cmd.args(&args[1..])
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
super::super::reentry::mark_child(&mut cmd);
super::super::platform::apply_utf8_locale(&mut cmd);
let status = cmd.status();
match status {
Ok(s) => s.code().unwrap_or(1),
Err(e) => {
tracing::error!("lean-ctx: failed to execute: {e}");
127
}
}
}
fn allowlist_must_enforce() -> bool {
let hook_child = crate::core::runtime_flags::hook_child_enabled();
let warn_only = std::env::var("LEAN_CTX_ALLOWLIST_WARN_ONLY")
.is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
allowlist_must_enforce_inner(hook_child, warn_only, io::stderr().is_terminal())
}
fn allowlist_must_enforce_inner(hook_child: bool, warn_only: bool, stderr_is_tty: bool) -> bool {
if hook_child {
return true;
}
if warn_only {
return false;
}
!stderr_is_tty
}
fn stdout_is_regular_file() -> bool {
#[cfg(unix)]
{
use std::os::unix::io::{AsRawFd, FromRawFd};
let fd = io::stdout().as_raw_fd();
let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_fd(fd) });
file.metadata().is_ok_and(|m| m.is_file())
}
#[cfg(windows)]
{
use std::os::windows::io::{AsRawHandle, FromRawHandle};
let handle = io::stdout().as_raw_handle();
let file = std::mem::ManuallyDrop::new(unsafe { std::fs::File::from_raw_handle(handle) });
file.metadata().is_ok_and(|m| m.is_file())
}
#[cfg(not(any(unix, windows)))]
{
false
}
}
fn command_has_file_redirect(cmd: &str) -> bool {
let bytes = cmd.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut in_single_quote = false;
let mut in_double_quote = false;
while i < len {
let c = bytes[i];
if c == b'\\' && !in_single_quote {
i += 2;
continue;
}
if c == b'\'' && !in_double_quote {
in_single_quote = !in_single_quote;
} else if c == b'"' && !in_single_quote {
in_double_quote = !in_double_quote;
} else if c == b'>' && !in_single_quote && !in_double_quote {
if i > 0 && bytes[i - 1] == b'2' {
i += 1;
continue;
}
let target_start = if i + 1 < len && bytes[i + 1] == b'>' {
i + 2
} else {
i + 1
};
let target: String = cmd[target_start..]
.trim_start()
.chars()
.take_while(|c| !c.is_whitespace())
.collect();
if target == "/dev/null" || target == "/dev/stdout" || target == "/dev/stderr" {
i += 1;
continue;
}
if let Some(fd) = target.strip_prefix('&')
&& !fd.is_empty()
&& (fd == "-" || fd.chars().all(|c| c.is_ascii_digit()))
{
i += 1;
continue;
}
if !target.is_empty() {
return true;
}
}
i += 1;
}
false
}
fn allowlist_gate(command: &str) -> Option<i32> {
if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(command) {
if allowlist_must_enforce() {
eprintln!("{msg}");
eprintln!(
"lean-ctx: command blocked by shell allowlist. \
Allow it permanently: lean-ctx allow <cmd> — or set \
LEAN_CTX_ALLOWLIST_WARN_ONLY=1 to downgrade to a warning."
);
return Some(126);
}
if io::stderr().is_terminal() {
tracing::debug!("[CLI] Command would be blocked in MCP mode: {msg}");
} else {
tracing::warn!("[CLI] Command would be blocked in MCP mode: {msg}");
}
}
None
}
pub fn exec(command: &str) -> i32 {
let unwrapped = super::super::agent_wrapper::unwrap_agent_wrapper(command).map(|u| u.rebuild());
let mut collapsed_nested = false;
let collapsed;
let command = unwrapped.as_deref().unwrap_or(command);
let command = if let Some(c) = collapse_nested_lean_ctx_exec(command) {
collapsed_nested = true;
collapsed = c;
collapsed.as_str()
} else {
command
};
if let Some(code) = allowlist_gate(command) {
return code;
}
let (shell, shell_flag) = super::super::platform::shell_and_flag();
let command = crate::tools::ctx_shell::normalize_command_for_shell(command);
let command = command.as_str();
if super::super::reentry::is_disabled() {
return exec_inherit(command, &shell, &shell_flag);
}
if should_delegate_wrapped_to_shell_default(collapsed_nested) {
return exec_shell_default(command, &shell, &shell_flag);
}
let cfg = config::Config::load();
let force_compress = crate::core::runtime_flags::compress_enabled();
let raw_mode = crate::core::runtime_flags::raw_enabled();
if raw_mode {
return exec_inherit_tracked(command, &shell, &shell_flag);
}
let policy = super::super::output_policy::classify(command, &cfg.excluded_commands);
if policy == super::super::output_policy::OutputPolicy::Passthrough {
return exec_inherit_tracked(command, &shell, &shell_flag);
}
if policy == super::super::output_policy::OutputPolicy::Verbatim && !force_compress {
return exec_inherit_tracked(command, &shell, &shell_flag);
}
if !force_compress {
if io::stdout().is_terminal() {
return exec_inherit_tracked(command, &shell, &shell_flag);
}
let code = exec_inherit(command, &shell, &shell_flag);
crate::core::tool_lifecycle::record_shell_command(0, 0);
return code;
}
if stdout_is_regular_file() {
return exec_inherit_tracked(command, &shell, &shell_flag);
}
if command_has_file_redirect(command) {
return exec_inherit_tracked(command, &shell, &shell_flag);
}
super::super::pipeline::exec_buffered(command, &shell, &shell_flag, &cfg)
}
fn collapse_nested_lean_ctx_exec(command: &str) -> Option<String> {
let mut current = command.trim().to_string();
let mut changed = false;
while let Some(next) = strip_one_lean_ctx_exec(¤t) {
if next == current {
break;
}
current = next;
changed = true;
}
changed.then_some(current)
}
fn should_delegate_wrapped_to_shell_default(collapsed_nested: bool) -> bool {
super::super::reentry::is_wrapped() && !collapsed_nested
}
fn strip_one_lean_ctx_exec(command: &str) -> Option<String> {
let words = split_simple_shell_words(command)?;
if words.len() < 3 || !is_lean_ctx_bin(&words[0].value) {
return None;
}
if words[1].value != "-c" && words[1].value != "exec" {
return None;
}
if words[2..].iter().any(|w| {
matches!(
w.value.as_str(),
"|" | "||" | "&" | "&&" | ";" | "<" | ">" | ">>"
)
}) {
return None;
}
if words.len() == 3 {
Some(words[2].value.trim().to_string())
} else {
Some(command[words[2].start..].trim().to_string())
}
}
fn is_lean_ctx_bin(word: &str) -> bool {
std::path::Path::new(word)
.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name == "lean-ctx" || name == "lean-ctx.exe")
}
struct SimpleShellWord {
value: String,
start: usize,
}
fn split_simple_shell_words(command: &str) -> Option<Vec<SimpleShellWord>> {
let mut words = Vec::new();
let mut current = String::new();
let mut current_start: Option<usize> = None;
let mut chars = command.char_indices().peekable();
let mut quote: Option<char> = None;
while let Some((idx, ch)) = chars.next() {
match quote {
Some('\'') if ch == '\'' => quote = None,
Some('"') if ch == '"' => quote = None,
None if ch == '\'' || ch == '"' => {
current_start.get_or_insert(idx);
quote = Some(ch);
}
Some('"') | None if ch == '\\' => {
current_start.get_or_insert(idx);
if let Some((_, next)) = chars.next() {
current.push(next);
}
}
None if ch.is_whitespace() => {
if let Some(start) = current_start.take() {
words.push(SimpleShellWord {
value: std::mem::take(&mut current),
start,
});
}
}
Some(_) | None => {
current_start.get_or_insert(idx);
current.push(ch);
}
}
}
if quote.is_some() {
return None;
}
if let Some(start) = current_start {
words.push(SimpleShellWord {
value: current,
start,
});
}
(!words.is_empty()).then_some(words)
}
fn exec_inherit(command: &str, shell: &str, shell_flag: &str) -> i32 {
let mut cmd = Command::new(shell);
cmd.arg(shell_flag)
.arg(command)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
super::super::reentry::mark_child(&mut cmd);
super::super::platform::apply_utf8_locale(&mut cmd);
super::super::platform::apply_profile_free_env(&mut cmd);
let status = cmd.status();
match status {
Ok(s) => s.code().unwrap_or(1),
Err(e) => {
tracing::error!("lean-ctx: failed to execute: {e}");
127
}
}
}
fn exec_shell_default(command: &str, shell: &str, shell_flag: &str) -> i32 {
let mut cmd = Command::new(shell);
cmd.arg(shell_flag)
.arg(command)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());
super::super::reentry::clear_shell_default_markers(&mut cmd);
super::super::platform::apply_utf8_locale(&mut cmd);
super::super::platform::apply_profile_free_env(&mut cmd);
let status = cmd.status();
match status {
Ok(s) => s.code().unwrap_or(1),
Err(e) => {
eprintln!("lean-ctx: failed to execute '{command}': {e}");
127
}
}
}
fn exec_inherit_tracked(command: &str, shell: &str, shell_flag: &str) -> i32 {
let code = exec_inherit(command, shell, shell_flag);
crate::core::tool_lifecycle::record_shell_command(0, 0);
code
}
pub(crate) const STDERR_LABEL: &str = "--- stderr ---";
pub(crate) fn combine_streams(stdout: &str, stderr: &str, exit_code: i32) -> String {
match (stdout.is_empty(), stderr.is_empty()) {
(_, true) => stdout.to_string(),
(true, false) => stderr.to_string(),
(false, false) if exit_code != 0 => format!("{stdout}\n{STDERR_LABEL}\n{stderr}"),
(false, false) => format!("{stdout}\n{stderr}"),
}
}
#[cfg(test)]
mod nested_lean_ctx_exec_tests;
#[cfg(test)]
mod exec_tests {
#[test]
fn combine_streams_labels_stderr_on_failure() {
let out = super::combine_streams("build ok", "linker: undefined symbol", 1);
assert_eq!(
out,
format!(
"build ok\n{}\nlinker: undefined symbol",
super::STDERR_LABEL
)
);
}
#[test]
fn combine_streams_plain_join_on_success() {
let out = super::combine_streams("step 1", "warning: noop", 0);
assert_eq!(out, "step 1\nwarning: noop");
assert!(!out.contains(super::STDERR_LABEL));
}
#[test]
fn combine_streams_single_stream_is_unchanged() {
assert_eq!(super::combine_streams("only stdout", "", 1), "only stdout");
assert_eq!(super::combine_streams("", "only stderr", 1), "only stderr");
}
#[test]
fn exec_direct_runs_true() {
let code = super::exec_direct(&["true".to_string()]);
assert_eq!(code, 0);
}
#[test]
fn exec_direct_runs_false() {
let code = super::exec_direct(&["false".to_string()]);
assert_ne!(code, 0);
}
#[test]
fn exec_direct_preserves_args_with_special_chars() {
let code = super::exec_direct(&[
"echo".to_string(),
"hello world".to_string(),
"it's here".to_string(),
"a \"quoted\" thing".to_string(),
]);
assert_eq!(code, 0);
}
#[test]
fn exec_direct_nonexistent_returns_127() {
let code = super::exec_direct(&["__nonexistent_binary_12345__".to_string()]);
assert_eq!(code, 127);
}
#[test]
fn exec_argv_empty_returns_127() {
let code = super::exec_argv(&[]);
assert_eq!(code, 127);
}
#[test]
fn exec_argv_runs_simple_command() {
let _lock = crate::core::data_dir::test_env_lock();
crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
let code = super::exec_argv(&["true".to_string()]);
assert_eq!(code, 0);
}
#[test]
fn exec_argv_passes_through_when_disabled() {
let _lock = crate::core::data_dir::test_env_lock();
crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
crate::test_env::set_var("LEAN_CTX_DISABLED", "1");
let code = super::exec_argv(&["true".to_string()]);
crate::test_env::remove_var("LEAN_CTX_DISABLED");
assert_eq!(code, 0);
}
#[test]
fn exec_argv_enforces_allowlist_for_disallowed_command() {
let _lock = crate::core::data_dir::test_env_lock();
crate::test_env::remove_var("LEAN_CTX_ACTIVE");
crate::test_env::remove_var("LEAN_CTX_DISABLED");
crate::test_env::remove_var("LEAN_CTX_ALLOWLIST_WARN_ONLY");
crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "git");
let code = super::exec_argv(&["xxd".to_string()]);
crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
assert_eq!(
code, 126,
"non-allowlisted command must be blocked on the -t track path"
);
}
#[test]
fn exec_argv_allows_allowlisted_command() {
let _lock = crate::core::data_dir::test_env_lock();
crate::test_env::remove_var("LEAN_CTX_ACTIVE");
crate::test_env::remove_var("LEAN_CTX_DISABLED");
crate::test_env::set_var("LEAN_CTX_HOOK_CHILD", "1");
crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "true");
let code = super::exec_argv(&["true".to_string()]);
crate::test_env::remove_var("LEAN_CTX_HOOK_CHILD");
crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
assert_eq!(code, 0, "allowlisted command must run on the -t track path");
}
#[test]
fn allowlist_enforces_in_hook_child_mode() {
assert!(super::allowlist_must_enforce_inner(true, false, true));
assert!(super::allowlist_must_enforce_inner(true, true, true));
}
#[test]
fn allowlist_enforces_for_non_interactive_callers() {
assert!(super::allowlist_must_enforce_inner(false, false, false));
}
#[test]
fn allowlist_warns_for_interactive_humans() {
assert!(!super::allowlist_must_enforce_inner(false, false, true));
}
#[test]
fn allowlist_warn_only_opt_out_downgrades_non_interactive() {
assert!(!super::allowlist_must_enforce_inner(false, true, false));
assert!(super::allowlist_must_enforce_inner(true, true, false));
}
#[test]
fn redirect_to_file_detected() {
assert!(super::command_has_file_redirect("git show HEAD:f > out.md"));
assert!(super::command_has_file_redirect("git diff >> changes.log"));
assert!(super::command_has_file_redirect(
"git status > /tmp/status.txt"
));
}
#[test]
fn no_redirect_not_detected() {
assert!(!super::command_has_file_redirect("git status"));
assert!(!super::command_has_file_redirect("cargo test --lib"));
}
#[test]
fn dev_null_not_detected_as_redirect() {
assert!(!super::command_has_file_redirect("cargo test > /dev/null"));
assert!(!super::command_has_file_redirect("cmd > /dev/stdout"));
assert!(!super::command_has_file_redirect("cmd > /dev/stderr"));
}
#[test]
fn stderr_redirect_not_detected() {
assert!(!super::command_has_file_redirect(
"cargo test 2> errors.log"
));
assert!(!super::command_has_file_redirect("cargo test 2>/dev/null"));
}
#[test]
fn fd_dup_not_detected() {
assert!(!super::command_has_file_redirect("cargo test 2>&1"));
assert!(!super::command_has_file_redirect("cmd >&2"));
}
#[test]
fn quoted_redirect_not_detected() {
assert!(!super::command_has_file_redirect("echo 'a > b'"));
assert!(!super::command_has_file_redirect("echo \"a > b\""));
assert!(!super::command_has_file_redirect(
"gh pr create --body 'see > details'"
));
}
#[test]
fn escaped_redirect_not_detected() {
assert!(!super::command_has_file_redirect("echo a \\> b"));
}
}