Skip to main content

lean_ctx_server/server/
execute.rs

1// SPDX-License-Identifier: Apache-2.0
2use fs2::FileExt;
3use std::io::Read;
4use std::process::Stdio;
5use std::sync::{Arc, Mutex, atomic::AtomicBool, mpsc};
6use std::time::{Duration, Instant};
7
8const READER_RESULT_TIMEOUT: Duration = Duration::from_secs(2);
9
10/// Prefix of the timeout notice this module appends to a killed command.
11const TIMEOUT_MARKER: &str = "ERROR: command timed out after ";
12
13fn is_build_or_test_command(command: &str) -> bool {
14    let tokens: Vec<_> = command
15        .split(|ch: char| ch.is_ascii_whitespace() || matches!(ch, ';' | '&' | '|'))
16        .filter(|token| !token.is_empty())
17        .collect();
18    tokens.windows(2).any(|pair| {
19        let tool = std::path::Path::new(pair[0])
20            .file_name()
21            .and_then(|name| name.to_str())
22            .unwrap_or(pair[0]);
23        (tool == "cargo"
24            && matches!(
25                pair[1],
26                "build" | "check" | "clippy" | "test" | "run" | "bench" | "install" | "fast"
27            ))
28            || (matches!(tool, "npm" | "pnpm" | "yarn" | "bun")
29                && matches!(pair[1], "test" | "build" | "check"))
30            || (tool == "lean-ctx" && pair[1] == "dev-install")
31            || (matches!(tool, "make" | "gmake")
32                && matches!(
33                    pair[1],
34                    "build"
35                        | "check"
36                        | "dev"
37                        | "install"
38                        | "install-release"
39                        | "test"
40                        | "preflight"
41                        | "preflight-fast"
42                ))
43    }) || tokens.windows(3).any(|triple| {
44        matches!(triple[0], "npm" | "pnpm" | "yarn" | "bun")
45            && triple[1] == "run"
46            && matches!(triple[2], "test" | "build" | "check" | "lint" | "typecheck")
47    }) || tokens.iter().any(|token| {
48        std::path::Path::new(token)
49            .file_name()
50            .and_then(|name| name.to_str())
51            .is_some_and(|name| matches!(name, "rustc" | "dev-install.sh" | "install.sh"))
52    })
53}
54
55fn acquire_build_lease(
56    command: &str,
57    cancel: Option<&AtomicBool>,
58) -> Result<Option<lean_ctx::core::file_lock::FlockGuard>, String> {
59    let config = lean_ctx::core::config::Config::load();
60    if !config.agents.serialize_build_commands || !is_build_or_test_command(command) {
61        return Ok(None);
62    }
63    let dir = lean_ctx::core::data_dir::lean_ctx_data_dir()?.join("resources");
64    std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
65    let path = dir.join("build.lock");
66    let file = std::fs::OpenOptions::new()
67        .create(true)
68        .truncate(false)
69        .read(true)
70        .write(true)
71        .open(&path)
72        .map_err(|error| format!("open build lease {}: {error}", path.display()))?;
73    loop {
74        match file.try_lock_exclusive() {
75            Ok(()) => {
76                return Ok(Some(lean_ctx::core::file_lock::FlockGuard::from_locked(
77                    file,
78                )));
79            }
80            Err(error) if lock_is_contended(&error) => {
81                if cancel.is_some_and(|flag| flag.load(std::sync::atomic::Ordering::Acquire)) {
82                    return Err(
83                        "build cancelled while waiting for the machine-wide slot".to_string()
84                    );
85                }
86                std::thread::sleep(Duration::from_millis(100));
87            }
88            Err(error) => {
89                return Err(format!("acquire build lease {}: {error}", path.display()));
90            }
91        }
92    }
93}
94
95fn lock_is_contended(error: &std::io::Error) -> bool {
96    error.kind() == std::io::ErrorKind::WouldBlock
97        || cfg!(windows) && matches!(error.raw_os_error(), Some(32 | 33))
98}
99
100/// The child's own output preceding the timeout marker, or `None` when the
101/// output carries no marker. `Some("")` means the command timed out having
102/// produced nothing recoverable.
103///
104/// Single source of truth for "was anything captured before the timeout?":
105/// `call_tool` decides `isError` with it (#1086) and `ctx_shell` decides
106/// whether the notice is worth archiving (#995). It lives beside the code that
107/// writes the marker because both callers previously re-derived it by matching
108/// the whole output, so enriching the notice broke them silently (#1173).
109pub(crate) fn output_before_timeout_marker(output: &str) -> Option<&str> {
110    output.find(TIMEOUT_MARKER).map(|idx| output[..idx].trim())
111}
112
113#[cfg(test)]
114pub(crate) fn execute_command_in(command: &str, cwd: &str) -> (String, i32) {
115    execute_command_with_env(command, cwd, &std::collections::HashMap::new(), None)
116}
117
118#[cfg(test)]
119pub(crate) fn execute_command_with_env(
120    command: &str,
121    cwd: &str,
122    extra_env: &std::collections::HashMap<String, String>,
123    timeout_ms: Option<u64>,
124) -> (String, i32) {
125    execute_command_with_env_cancellable(command, cwd, extra_env, timeout_ms, None, false, None)
126}
127
128/// Execute a command under the normal shell policy, with an optional cooperative
129/// cancellation signal used by explicit background jobs. The signal is checked
130/// by the same watchdog that enforces `timeout_ms`, so cancellation kills the
131/// complete process tree — the Unix session or the Windows job — rather than
132/// only the shell leader.
133///
134/// `idle_keyed` turns `timeout_ms` into an *idle* budget instead of a wall-clock
135/// one: the clock resets whenever the child produces new bytes (#1113/#1173). A
136/// poll loop emitting a few hundred bytes over ten minutes is not the runaway
137/// this watchdog protects against.
138///
139/// Every job managed by `background_shell` sets it, foreground runs included —
140/// those detach at the soft cap and become exactly such a job. Only the
141/// degraded no-session path runs strict wall-clock. Two bounds keep it honest:
142/// genuinely runaway output hits the byte cap, which freezes the captured
143/// length and so restarts the clock, and `LEAN_CTX_SHELL_BG_MAX_MS` (default
144/// 1h) caps lifetime absolutely.
145pub(crate) struct ShellExecution {
146    pub output: String,
147    pub exit_code: i32,
148    pub completeness: lean_ctx::core::context_admission::OutputCompleteness,
149    /// Q13: what the caller has to be told about the call's processes — a
150    /// fixed, content-free line (`shell::containment`). It is NOT part of
151    /// `output`: whoever delivers the result puts it in front of the text
152    /// with [`with_notice`], after everything that admits, compresses or
153    /// shortens that text, so none of it can drop or alter the line.
154    pub notice: Option<&'static str>,
155}
156
157/// Puts a call's notice, if it has one, in front of the text delivered for
158/// it, as a line of its own. The last step of a delivery, applied once.
159pub(crate) fn with_notice(notice: Option<&'static str>, text: String) -> String {
160    match notice {
161        Some(notice) => format!("{notice}\n{text}"),
162        None => text,
163    }
164}
165
166/// Takes a notice off the front of a result that arrived as plain text (the
167/// protected launcher's supervisor runs the shell and answers with text
168/// only), so that it travels on as the typed field.
169#[cfg(unix)]
170fn split_notice(text: String) -> (Option<&'static str>, String) {
171    match leading_notice(&text) {
172        Some(notice) => {
173            let rest = text.get(notice.len() + 1..).unwrap_or_default().to_string();
174            (Some(notice), rest)
175        }
176        None => (None, text),
177    }
178}
179
180/// The notice a delivered text starts with, as a line of its own.
181#[cfg(unix)]
182pub(crate) fn leading_notice(text: &str) -> Option<&'static str> {
183    use lean_ctx::shell::containment::{END_NOTICE, HELPER_NOTICE, RELEASE_NOTICE, UNCLEAR_NOTICE};
184    [HELPER_NOTICE, END_NOTICE, UNCLEAR_NOTICE, RELEASE_NOTICE]
185        .into_iter()
186        .find(|notice| {
187            text.strip_prefix(notice)
188                .is_some_and(|rest| rest.is_empty() || rest.starts_with('\n'))
189        })
190}
191
192/// No notice exists without process containment.
193#[cfg(not(unix))]
194pub(crate) fn leading_notice(_text: &str) -> Option<&'static str> {
195    None
196}
197
198/// Keeps a call's notice in front of a text that replaced the one it stood
199/// on: the digest of a result too large to deliver inline says nothing about
200/// the call's processes by itself.
201pub(crate) fn keep_notice(notice: Option<&'static str>, text: String) -> String {
202    if leading_notice(&text).is_some() {
203        text
204    } else {
205        with_notice(notice, text)
206    }
207}
208
209impl ShellExecution {
210    fn complete(output: String, exit_code: i32) -> Self {
211        Self {
212            output,
213            exit_code,
214            completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
215            notice: None,
216        }
217    }
218
219    /// A brokered run: the supervisor captured it, so this process cannot
220    /// vouch for the readers. Brokered execution exists on Unix only.
221    #[cfg(unix)]
222    fn unknown_capture(output: String, exit_code: i32) -> Self {
223        Self {
224            output,
225            exit_code,
226            completeness: lean_ctx::core::context_admission::OutputCompleteness {
227                reader_incomplete: true,
228                ..lean_ctx::core::context_admission::OutputCompleteness::complete()
229            },
230            notice: None,
231        }
232    }
233}
234
235/// Hand this executor to the protected supervisor
236/// (`core::protected_execution`), which runs brokered `ctx_shell` commands
237/// with it. The CLI calls this at start-up; the first registration wins.
238#[cfg(unix)]
239pub fn register_protected_shell_runner() {
240    lean_ctx_ext::core::protected_execution::register_shell_runner(
241        execute_command_with_env_cancellable,
242    );
243}
244
245// Production caller: core::protected_execution (via
246// `register_protected_shell_runner`), which is unix-only.
247#[cfg(any(unix, test))]
248pub(crate) fn execute_command_with_env_cancellable(
249    command: &str,
250    cwd: &str,
251    extra_env: &std::collections::HashMap<String, String>,
252    timeout_ms: Option<u64>,
253    cancel: Option<&AtomicBool>,
254    idle_keyed: bool,
255    live: Option<&std::sync::Mutex<String>>,
256) -> (String, i32) {
257    // Kept as a compatibility wrapper. Raw progressive output is no longer
258    // written to caller-owned buffers.
259    let _ = live;
260    let execution = execute_command_with_env_cancellable_captured(
261        command, cwd, extra_env, timeout_ms, cancel, idle_keyed,
262    );
263    // Nothing shortens the text on this path: the notice goes in front here.
264    (
265        with_notice(execution.notice, execution.output),
266        execution.exit_code,
267    )
268}
269
270/// Test seam: every production caller now goes through the cancellable,
271/// detachable path (`background_shell::run_foreground_or_detach_captured`).
272#[cfg(all(test, unix))]
273pub(crate) fn execute_command_with_env_captured(
274    command: &str,
275    cwd: &str,
276    extra_env: &std::collections::HashMap<String, String>,
277    timeout_ms: Option<u64>,
278) -> ShellExecution {
279    execute_command_with_env_cancellable_captured(command, cwd, extra_env, timeout_ms, None, false)
280}
281
282pub(crate) fn execute_command_with_env_cancellable_captured(
283    command: &str,
284    cwd: &str,
285    extra_env: &std::collections::HashMap<String, String>,
286    timeout_ms: Option<u64>,
287    cancel: Option<&AtomicBool>,
288    idle_keyed: bool,
289) -> ShellExecution {
290    // Store isolation for model-directed subprocesses of a protected session.
291    //
292    // macOS refuses a nested `sandbox_apply` under the whole-MCP profile, so
293    // this process cannot wrap its own children in the launcher's rules. The
294    // request goes to the launcher's supervisor instead, which starts the child
295    // from outside that sandbox under the profile the launcher pinned. Decided
296    // *before* the build lease and before any caller-supplied `extra_env`: the
297    // supervisor takes the machine-wide lease itself (taking it on both sides
298    // would deadlock), and a tool call can neither select nor drop the rules. A
299    // protected session that cannot reach its supervisor runs nothing.
300    //
301    // This is the one exec seam `ctx_shell` has — foreground, background and the
302    // interpreter heredoc reroute all arrive here — and the Engine's own
303    // persistence never passes through it.
304    #[cfg(unix)]
305    let protected_prefix: Option<Vec<String>> = {
306        use lean_ctx_ext::core::protected_execution::{Mode, launch_mode, sandbox_prefix};
307        match launch_mode() {
308            Err(error) => return ShellExecution::complete(format!("ERROR: {error}"), 1),
309            Ok(Mode::Brokered(client)) => {
310                let (output, exit_code) = client.shell(
311                    command, cwd, extra_env, timeout_ms, cancel, idle_keyed, None,
312                );
313                let (notice, output) = split_notice(output);
314                return ShellExecution {
315                    notice,
316                    ..ShellExecution::unknown_capture(output, exit_code)
317                };
318            }
319            Ok(Mode::Sandboxed(profile)) => Some(sandbox_prefix(&profile)),
320            Ok(Mode::Direct) => None,
321        }
322    };
323    #[cfg(not(unix))]
324    let protected_prefix = match lean_ctx::core::protected_store::protected_child_prefix() {
325        Ok(prefix) => prefix,
326        Err(error) => return ShellExecution::complete(format!("ERROR: {error}"), 1),
327    };
328
329    let _build_lease = match acquire_build_lease(command, cancel) {
330        Ok(lease) => lease,
331        Err(error) => return ShellExecution::complete(format!("ERROR: {error}"), 130),
332    };
333    let resource_config = lean_ctx::core::config::Config::load().agents;
334    let (shell, flag) = lean_ctx::shell::shell_and_flag();
335    let normalized_cmd = crate::tools::ctx_shell::normalize_command_for_shell(command);
336    let normalized_cmd = lean_ctx::shell::platform::zsh_safe_command(&normalized_cmd, &shell);
337    let dir = std::path::Path::new(cwd);
338    let mut cmd = std::process::Command::new(&shell);
339    if let Some([program, arguments @ ..]) = protected_prefix.as_deref() {
340        cmd = std::process::Command::new(program);
341        cmd.args(arguments).arg(&shell);
342    }
343    if cfg!(windows) && lean_ctx::shell::platform::is_powershell(&shell) {
344        cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass"]);
345    }
346    cmd.arg(&flag)
347        .arg(&normalized_cmd)
348        .env("GIT_TERMINAL_PROMPT", "0")
349        .stdin(Stdio::null());
350    lean_ctx::shell::reentry::mark_child(&mut cmd);
351
352    if !extra_env.contains_key("GIT_PAGER") {
353        cmd.env("GIT_PAGER", "cat");
354    }
355    if !extra_env.contains_key("PAGER") {
356        cmd.env("PAGER", "cat");
357    }
358
359    ensure_utf8_locale(&mut cmd, extra_env);
360    lean_ctx::shell::platform::apply_profile_free_env(&mut cmd);
361
362    // Auto-forward agent runtime env vars (CODEX_THREAD_ID, CLAUDE_*, …) so
363    // session-aware commands run through ctx_shell can see the active session.
364    //   1. From this process's own env — covers agents that pass the vars to the
365    //      MCP server process.
366    //   2. From the captured agent-env store — covers agents like Codex where the
367    //      vars live only in the native agent shell, not the MCP server process
368    //      (#370). Hooks / `lean-ctx -c` capture them; the process env wins on
369    //      conflict, and explicit `extra_env` (below) wins over both.
370    let mut forwarded: std::collections::HashSet<String> = std::collections::HashSet::new();
371    for (key, val) in std::env::vars() {
372        if lean_ctx_ext::core::agent_runtime_env::is_forwardable(&key) {
373            cmd.env(&key, &val);
374            forwarded.insert(key);
375        }
376    }
377    for (key, val) in lean_ctx_ext::core::agent_runtime_env::load() {
378        if !forwarded.contains(&key) {
379            cmd.env(&key, &val);
380        }
381    }
382
383    // Explicit env vars from tool call (highest priority)
384    for (key, val) in extra_env {
385        cmd.env(key, val);
386    }
387    if is_build_or_test_command(command) {
388        if resource_config.cargo_build_jobs > 0 && !extra_env.contains_key("CARGO_BUILD_JOBS") {
389            cmd.env(
390                "CARGO_BUILD_JOBS",
391                resource_config.cargo_build_jobs.to_string(),
392            );
393        }
394        if resource_config.shared_cargo_target
395            && !extra_env.contains_key("CARGO_TARGET_DIR")
396            && let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir()
397        {
398            cmd.env(
399                "CARGO_TARGET_DIR",
400                data_dir.join("build-cache/cargo-target"),
401            );
402        }
403    }
404    if dir.is_dir() {
405        cmd.current_dir(dir);
406    } else {
407        return ShellExecution::complete(
408            format!("ERROR: working directory does not exist or is not a directory: {cwd}"),
409            1,
410        );
411    }
412    let cap = lean_ctx::core::limits::max_shell_bytes();
413
414    // Isolate the shell in its own process group on Unix. A timeout must kill
415    // descendants too; otherwise a child can retain a pipe write-end and make
416    // the caller report an empty result despite bytes already captured (#995).
417    //
418    // A new *session* rather than just a group: it also drops the controlling
419    // terminal. Otherwise an interactive descendant (`zsh -i`, `bash -i`, a
420    // test suite that spawns one) takes the terminal's foreground with
421    // tcsetpgrp, and the agent that launched the MCP server is stopped by
422    // SIGTTIN — "zsh: suspended claude", with mouse reporting still on.
423    // The session leader's pid is its pgid, so the timeout kill is unchanged.
424    //
425    // Q13: on Unix the shell's parent is this process's spawn helper
426    // (`shell::containment`), which starts it with that same `setsid` and
427    // ends its session should this process die during the call. Everything
428    // decided above — command line, environment, directory, sandbox prefix —
429    // is handed over as it is. Without a helper the shell is started here, as
430    // before, and the result says so in its first line.
431    //
432    // Windows has no process group to kill: contain the tree in a job object
433    // instead, so a timeout or cancel ends the `python -` a heredoc started
434    // rather than only its shell (#1920).
435    lean_ctx::shell::process_tree::ProcessTree::prepare(&mut cmd);
436
437    let started = match lean_ctx::shell::process_tree::ShellChild::start(&mut cmd) {
438        Ok(started) => started,
439        Err(e) => return ShellExecution::complete(format!("ERROR: {e}"), 1),
440    };
441    let mut child = started.child;
442    // Stream each pipe into a shared, cap-bounded buffer that the main thread can
443    // read at any time. Crucially this lets a timed-out wait recover the bytes
444    // captured so far instead of discarding all output (#945).
445    let (out_buf, out_done) = spawn_capture(started.stdout, cap);
446    let (err_buf, err_done) = spawn_capture(started.stderr, cap);
447
448    let timeout = command_timeout(command, timeout_ms);
449    let start = Instant::now();
450    let hard_deadline = idle_keyed.then(|| start + streaming_max_lifetime());
451    let mut last_len = 0usize;
452    let mut last_output_at = start;
453    // Named on timeout so a multi-segment pipeline says *which* part hung (#1086).
454    let mut still_running: Vec<String> = Vec::new();
455    let (code, timed_out, cancelled) = loop {
456        match child.try_wait() {
457            Ok(Some(status)) => {
458                break (
459                    lean_ctx::shell::exit_status::exit_code(status),
460                    false,
461                    false,
462                );
463            }
464            Ok(None) => {
465                if cancel.is_some_and(|signal| signal.load(std::sync::atomic::Ordering::Acquire)) {
466                    child.kill();
467                    child.wait();
468                    break (130, false, true);
469                }
470                let idle_for = if idle_keyed {
471                    let len = captured_len(&out_buf) + captured_len(&err_buf);
472                    if len != last_len {
473                        last_len = len;
474                        last_output_at = Instant::now();
475                    }
476                    last_output_at.elapsed()
477                } else {
478                    start.elapsed()
479                };
480                if idle_for >= timeout || hard_deadline.is_some_and(|d| Instant::now() >= d) {
481                    still_running = running_segments(child.id(), &normalized_cmd);
482                    child.kill();
483                    child.wait();
484                    break (124, true, false);
485                }
486                std::thread::sleep(Duration::from_millis(25));
487            }
488            Err(_) => {
489                child.kill();
490                break (1, false, false);
491            }
492        }
493    };
494    // Q13: a shell whose helper went away before its exit was known has no
495    // parent that answers for it; the caller is told with the fixed notice.
496    // Such a call's outcome is not known in full — whether the command ran
497    // at all, or how it ended — so its capture counts as incomplete.
498    let lost_notice = child.lost_notice();
499    // A command that exited on its own keeps what it deliberately left running,
500    // as the Unix session does; a killed tree has nothing left to release. A
501    // release that could not be handed over is said to the caller as well.
502    let release_notice = child.release();
503    let containment_notice = started.notice.or(lost_notice).or(release_notice);
504
505    // Bounded grace period for the readers to reach EOF, but always read the
506    // shared buffers afterwards so output is never silently lost (#945). A reader
507    // that misses the deadline means something still holds the pipe open; we then
508    // surface the partial capture plus an explicit note rather than nothing.
509    let reader_deadline = Instant::now() + READER_RESULT_TIMEOUT;
510    let out_complete = wait_for_reader(&out_done, reader_deadline);
511    let err_complete = wait_for_reader(&err_done, reader_deadline);
512    let (out_bytes, out_trunc, out_read_failed) = snapshot(&out_buf);
513    let (err_bytes, err_trunc, err_read_failed) = snapshot(&err_buf);
514    let reader_incomplete = !out_complete || !err_complete || out_read_failed || err_read_failed;
515    // The legacy decoder may replace invalid UTF-8 bytes. On Windows this also
516    // conservatively flags ACP decoding, whose fallback does not prove lossless.
517    let decode_lossy =
518        std::str::from_utf8(&out_bytes).is_err() || std::str::from_utf8(&err_bytes).is_err();
519
520    let stdout =
521        lean_ctx::shell::resolve_carriage_returns(&lean_ctx::shell::decode_output(&out_bytes));
522    let stderr =
523        lean_ctx::shell::resolve_carriage_returns(&lean_ctx::shell::decode_output(&err_bytes));
524    // On failure both streams are labeled so the agent can attribute the error
525    // (#812); success keeps the plain join.
526    let mut text = lean_ctx::shell::combine_streams(&stdout, &stderr, code);
527
528    if out_trunc || err_trunc {
529        text.push_str(&format!(
530            "\n[truncated: cap={}B stdout={}B stderr={}B]",
531            cap,
532            out_bytes.len(),
533            err_bytes.len()
534        ));
535    }
536    // The command finished but a reader never hit EOF: a leftover process is
537    // holding the pipe open. We still return what was captured; flag it so the
538    // agent knows the tail may be missing instead of seeing a bare exit code
539    // (#945). Suppressed on timeout, which carries its own message below.
540    if reader_incomplete && !timed_out {
541        if !text.is_empty() && !text.ends_with('\n') {
542            text.push('\n');
543        }
544        text.push_str(&format!(
545            "[lean-ctx: output reader still draining after {}s — a background process is likely \
546             holding the pipe open; output above may be partial]",
547            READER_RESULT_TIMEOUT.as_secs()
548        ));
549    }
550    if timed_out {
551        if !text.ends_with('\n') && !text.is_empty() {
552            text.push('\n');
553        }
554        text.push_str(&format!(
555            "{TIMEOUT_MARKER}{}ms{}",
556            timeout.as_millis(),
557            if idle_keyed {
558                " without new output"
559            } else {
560                ""
561            }
562        ));
563        // #1086: for a compound command the captured output is often complete
564        // for every segment but one. Name what is still alive in the child's
565        // process group so the caller can fix that part instead of re-running
566        // the whole pipeline.
567        //
568        // Joined with "; " rather than " | " (#1654): these are processes, not
569        // stages, and a pipe character asserted a relationship the process
570        // table never established — rendering a line that was not runnable and
571        // named a stage the caller never wrote.
572        if !still_running.is_empty() {
573            text.push_str(&format!(
574                "\n[still running at timeout: {}]",
575                still_running.join("; ")
576            ));
577        }
578    }
579    // #1655/#1662: a recursive walk does not read `.gitignore`, so a nested
580    // checkout the other ctx_* tools never see can dominate it. Say so after
581    // the fact — the command's own traversal is left alone.
582    //
583    // Not only on timeout (#1662): `grep -r … | head` is the shape agents
584    // actually type, and it is the shape where the cost hides best. `head`
585    // closes early, the ten visible lines arrive at once, and the walk keeps
586    // running for two more minutes behind a result that already looked
587    // finished. Reported as "no redirect, no hint" — because the only place
588    // this was emitted was a timeout that a fast-looking command never
589    // reached.
590    if let Some(hint) = super::walk_hint::walk_hint(command, cwd) {
591        if !text.is_empty() && !text.ends_with('\n') {
592            text.push('\n');
593        }
594        text.push_str(&hint);
595    }
596    if cancelled {
597        if !text.ends_with('\n') && !text.is_empty() {
598            text.push('\n');
599        }
600        // #1246: a cancel is always caller-requested, so it is not an error.
601        text.push_str("[cancelled: command stopped on request]");
602    }
603
604    ShellExecution {
605        output: text,
606        exit_code: code,
607        // Q13: fixed and content-free; carried beside the text, not in it.
608        notice: containment_notice,
609        completeness: lean_ctx::core::context_admission::OutputCompleteness {
610            truncated: out_trunc || err_trunc,
611            timed_out,
612            reader_incomplete: reader_incomplete || lost_notice.is_some(),
613            cancelled,
614            decode_lossy,
615        },
616    }
617}
618
619/// Shared, cap-bounded capture buffer for one child pipe. The reader thread
620/// appends here as bytes arrive — not only at EOF — so the caller can recover
621/// whatever was read so far even if the reader never reaches EOF, e.g. when a
622/// backgrounded or otherwise-inherited process keeps the pipe's write-end open
623/// after the direct child exits (#945).
624#[derive(Default)]
625struct CaptureBuf {
626    bytes: Vec<u8>,
627    truncated: bool,
628    read_failed: bool,
629}
630
631/// Spawn a reader that streams `pipe` into a shared [`CaptureBuf`] (bounded to
632/// `cap` bytes) and signals completion (EOF or read error) over the returned
633/// channel. The buffer is readable at any time via [`snapshot`], so a timed-out
634/// wait yields partial output instead of nothing.
635fn spawn_capture<R: Read + Send + 'static>(
636    pipe: Option<R>,
637    cap: usize,
638) -> (Arc<Mutex<CaptureBuf>>, mpsc::Receiver<()>) {
639    let shared = Arc::new(Mutex::new(CaptureBuf::default()));
640    let (done_tx, done_rx) = mpsc::channel();
641    let writer = Arc::clone(&shared);
642    std::thread::spawn(move || {
643        if let Some(mut r) = pipe {
644            let mut buf = [0u8; 8192];
645            loop {
646                match r.read(&mut buf) {
647                    Ok(0) => break,
648                    Err(ref error) if error.kind() == std::io::ErrorKind::Interrupted => {}
649                    Err(_) => {
650                        writer
651                            .lock()
652                            .unwrap_or_else(std::sync::PoisonError::into_inner)
653                            .read_failed = true;
654                        break;
655                    }
656                    Ok(n) => {
657                        let mut s = writer
658                            .lock()
659                            .unwrap_or_else(std::sync::PoisonError::into_inner);
660                        if s.bytes.len() < cap {
661                            let remaining = cap - s.bytes.len();
662                            let take = remaining.min(n);
663                            s.bytes.extend_from_slice(&buf[..take]);
664                            if take < n {
665                                s.truncated = true;
666                            }
667                        } else {
668                            s.truncated = true;
669                        }
670                    }
671                }
672            }
673        }
674        let _ = done_tx.send(());
675    });
676    (shared, done_rx)
677}
678
679/// Snapshot a capture buffer (clone bytes + truncation flag) under its lock.
680/// Safe to call while the reader is still writing — yields a consistent prefix.
681fn snapshot(buf: &Arc<Mutex<CaptureBuf>>) -> (Vec<u8>, bool, bool) {
682    let s = buf
683        .lock()
684        .unwrap_or_else(std::sync::PoisonError::into_inner);
685    (s.bytes.clone(), s.truncated, s.read_failed)
686}
687
688/// Bytes captured so far, used as the liveness signal for an idle-keyed
689/// timeout. Cheaper than [`snapshot`], which clones the whole buffer.
690fn captured_len(buf: &Arc<Mutex<CaptureBuf>>) -> usize {
691    buf.lock()
692        .unwrap_or_else(std::sync::PoisonError::into_inner)
693        .bytes
694        .len()
695}
696
697/// Absolute ceiling on an idle-keyed (background) job, so a command that keeps
698/// emitting output forever still cannot outlive the daemon's patience (#1173).
699fn streaming_max_lifetime() -> Duration {
700    Duration::from_millis(
701        std::env::var("LEAN_CTX_SHELL_BG_MAX_MS")
702            .ok()
703            .and_then(|v| v.parse().ok())
704            .filter(|&ms: &u64| ms > 0)
705            .unwrap_or(3_600_000),
706    )
707}
708
709/// One live process in the timed-out child's group.
710#[cfg(unix)]
711struct LiveProc {
712    pid: u32,
713    ppid: u32,
714    args: String,
715}
716
717/// Command lines still alive in the timed-out child's process group (#1086).
718///
719/// These are **processes**, not pipeline segments. The distinction matters
720/// because a segment can spawn its own children into the same group: `go run x`
721/// execs a compiled binary under `$TMPDIR`, which then shows up here alongside
722/// its parent. Rendering the set as `a | b` claimed a pipeline the process
723/// table never established, and pointed the caller at a stage they never wrote
724/// (#1654).
725///
726/// Rows still carrying the *whole* command are the un-exec'd shell wrapper and
727/// say nothing specific, so they are dropped — note the leader is not simply
728/// skipped by pid, because `sh -c 'a; b'` execs into its final segment and so
729/// *is* the leader.
730///
731/// Best-effort: an unavailable or unparsable `ps` yields no attribution.
732#[cfg(unix)]
733fn running_segments(pgid: u32, command: &str) -> Vec<String> {
734    // POSIX-portable field selection; `ps -g` differs between BSD and Linux.
735    // `ppid` is read so a descendant can be labelled as one rather than
736    // presented as a sibling stage.
737    let Ok(out) = std::process::Command::new("ps")
738        .args(["-A", "-o", "pid=,ppid=,pgid=,args="])
739        .output()
740    else {
741        return Vec::new();
742    };
743    let needle = command.split_whitespace().collect::<Vec<_>>().join(" ");
744    let live: Vec<LiveProc> = String::from_utf8_lossy(&out.stdout)
745        .lines()
746        .filter_map(|line| parse_ps_row(line, pgid, &needle))
747        .collect();
748
749    describe_live(&live)
750}
751
752/// Render the live set, marking any process whose parent is also in the set.
753///
754/// A descendant is shown under its parent rather than as a peer, so the caller
755/// can tell "the stage I wrote" from "something that stage started".
756#[cfg(unix)]
757fn describe_live(live: &[LiveProc]) -> Vec<String> {
758    let pids: std::collections::HashSet<u32> = live.iter().map(|p| p.pid).collect();
759    live.iter()
760        .filter(|p| !pids.contains(&p.ppid))
761        .map(|parent| {
762            let kids: Vec<&str> = live
763                .iter()
764                .filter(|c| c.ppid == parent.pid)
765                .map(|c| c.args.as_str())
766                .collect();
767            if kids.is_empty() {
768                parent.args.clone()
769            } else {
770                format!("{} (spawned: {})", parent.args, kids.join(", "))
771            }
772        })
773        .collect()
774}
775
776/// One `pid ppid pgid args` row: `Some(..)` iff it belongs to `pgid` and names
777/// a narrower command than the one we launched. `needle` is the whole command
778/// with runs of whitespace collapsed, matching how `ps` renders `args`.
779#[cfg(unix)]
780fn parse_ps_row(line: &str, pgid: u32, needle: &str) -> Option<LiveProc> {
781    let rest = line.trim_start();
782    let (pid, rest) = rest.split_once(char::is_whitespace)?;
783    let rest = rest.trim_start();
784    let (ppid, rest) = rest.split_once(char::is_whitespace)?;
785    let args = rest
786        .trim_start()
787        .split_once(char::is_whitespace)
788        .and_then(|(row_pgid, args)| {
789            (row_pgid.parse::<u32>().ok()? == pgid).then_some(args.trim())
790        })?;
791    if args.is_empty() || args.contains(needle) {
792        return None;
793    }
794    Some(LiveProc {
795        pid: pid.parse().ok()?,
796        ppid: ppid.parse().ok()?,
797        args: args.chars().take(200).collect(),
798    })
799}
800
801#[cfg(not(unix))]
802fn running_segments(_pgid: u32, _command: &str) -> Vec<String> {
803    // No process groups here, so a descendant cannot be attributed to this run.
804    Vec::new()
805}
806
807/// Block until the reader signals completion or `deadline` passes. Returns true
808/// iff the reader completed (reached EOF) within the deadline.
809fn wait_for_reader(done: &mpsc::Receiver<()>, deadline: Instant) -> bool {
810    let remaining = deadline.saturating_duration_since(Instant::now());
811    done.recv_timeout(remaining).is_ok()
812}
813
814fn ensure_utf8_locale(
815    cmd: &mut std::process::Command,
816    extra_env: &std::collections::HashMap<String, String>,
817) {
818    if extra_env.contains_key("LC_ALL") || extra_env.contains_key("LC_CTYPE") {
819        return;
820    }
821    lean_ctx::shell::platform::apply_utf8_locale(cmd);
822}
823
824fn command_timeout(command: &str, timeout_ms: Option<u64>) -> Duration {
825    // Single source of truth: operator env pin > per-call `timeout_ms` >
826    // per-tier env/config > built-in heavy/normal ceilings. Keeps this path
827    // identical to the interactive hook (`shell::exec::shell_timeout`).
828    lean_ctx::shell::shell_timeout_with_override(command, timeout_ms)
829}
830
831#[cfg(all(test, target_os = "macos"))]
832#[path = "execute_supervised_tests.rs"]
833mod supervised_tests;
834
835#[cfg(all(test, unix))]
836#[path = "execute_containment_tests.rs"]
837mod containment_tests;
838
839#[cfg(test)]
840mod tests {
841    use super::{
842        command_timeout, ensure_utf8_locale, execute_command_in, is_build_or_test_command,
843    };
844
845    #[test]
846    fn resource_broker_build_slot_classifier_is_precise() {
847        for command in [
848            "cargo test --lib",
849            "cargo fast",
850            "cd rust && cargo fast --features dev-tools",
851            "make dev",
852            "make build",
853            "make preflight-fast",
854            "make install-release",
855            "./install.sh --build-only",
856            "bash rust/dev-install.sh --fast",
857            "./rust/dev-install.sh --release",
858            "lean-ctx dev-install",
859            "/opt/bin/lean-ctx dev-install --fast",
860            "cd rust && cargo clippy --all-features",
861            "/opt/bin/cargo build --release",
862            "npm test",
863            "npm run typecheck",
864            "pnpm build",
865            "rustc main.rs",
866        ] {
867            assert!(is_build_or_test_command(command), "{command}");
868        }
869        for command in [
870            "git status",
871            "cargo metadata",
872            "make help",
873            "lean-ctx --version",
874            "npm view lean-ctx",
875            "rg cargo",
876        ] {
877            assert!(!is_build_or_test_command(command), "{command}");
878        }
879    }
880
881    #[test]
882    fn resource_broker_serializes_build_leases() {
883        let isolation = lean_ctx::core::data_dir::isolated_data_dir();
884        // Off by default: a user's builds are never queued behind other sessions.
885        assert!(
886            super::acquire_build_lease("cargo test", None)
887                .expect("lease")
888                .is_none()
889        );
890        std::fs::write(
891            isolation.path().join("config.toml"),
892            "[agents]\nserialize_build_commands = true\n",
893        )
894        .expect("opt in");
895        let first = super::acquire_build_lease("cargo test first", None)
896            .expect("first lease")
897            .expect("build command gets lease");
898        let acquired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
899        let worker_acquired = std::sync::Arc::clone(&acquired);
900        let worker = std::thread::spawn(move || {
901            let _second = super::acquire_build_lease("cargo test second", None)
902                .expect("second lease")
903                .expect("build command gets lease");
904            worker_acquired.store(true, std::sync::atomic::Ordering::Release);
905        });
906        std::thread::sleep(std::time::Duration::from_millis(50));
907        assert!(!acquired.load(std::sync::atomic::Ordering::Acquire));
908        drop(first);
909        worker.join().expect("lease waiter");
910        assert!(acquired.load(std::sync::atomic::Ordering::Acquire));
911    }
912
913    #[test]
914    fn command_timeout_delegates_to_shell_timeout() {
915        // `command_timeout` is a thin alias for `shell::exec::shell_timeout`
916        // (full precedence coverage lives there). Smoke-test the delegation:
917        // heavy beats normal, and the universal MS override pins both.
918        let _lock = lean_ctx::core::data_dir::test_env_lock();
919        let saved = std::env::var("LEAN_CTX_SHELL_TIMEOUT_MS").ok();
920        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
921
922        assert!(
923            command_timeout("cargo install --path .", None) > command_timeout("git status", None)
924        );
925
926        lean_ctx::test_env::set_var("LEAN_CTX_SHELL_TIMEOUT_MS", "5000");
927        assert_eq!(
928            command_timeout("cargo install --path .", None),
929            std::time::Duration::from_secs(5)
930        );
931        assert_eq!(
932            command_timeout("git status", None),
933            std::time::Duration::from_secs(5)
934        );
935
936        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
937        if let Some(v) = saved {
938            lean_ctx::test_env::set_var("LEAN_CTX_SHELL_TIMEOUT_MS", v);
939        }
940    }
941
942    /// The one exec seam: foreground runs, detached background jobs and the
943    /// interpreter-heredoc reroute all build their command here, so covering it
944    /// once covers all three. Synthetic store, isolated data dir — never the
945    /// developer's installed knowledge.
946    #[cfg(target_os = "macos")]
947    #[test]
948    fn the_supervisor_runs_the_shell_under_the_pinned_child_rules() {
949        let _lock = lean_ctx::core::data_dir::test_env_lock();
950        let isolation = lean_ctx::core::data_dir::isolated_data_dir();
951        let fact = isolation.path().join("knowledge/knowledge.json");
952        std::fs::create_dir_all(fact.parent().unwrap()).unwrap();
953        std::fs::write(&fact, "synthetic-provider-fact").unwrap();
954        let work = tempfile::tempdir().unwrap();
955        let cwd = work.path().to_str().unwrap();
956        let read_fact = format!("cat {}", fact.display());
957        let write_fact = format!("printf downgraded > {}", fact.display());
958
959        // Community: the store is an ordinary file, the shell is unwrapped.
960        lean_ctx::core::protected_store::unpin_synthetic_session();
961        let (text, code) = execute_command_in(&read_fact, cwd);
962        assert_eq!(code, 0, "{text}");
963        assert!(text.contains("synthetic-provider-fact"), "{text}");
964
965        let _session = lean_ctx::core::protected_store::pin_synthetic_session(isolation.path())
966            .expect("pinned rules");
967        lean_ctx_ext::core::protected_execution::with_test_supervisor(|| {
968            let (text, code) = execute_command_in(&read_fact, cwd);
969            assert_ne!(code, 0, "{text}");
970            assert!(!text.contains("synthetic-provider-fact"), "{text}");
971            let (text, code) = execute_command_in(&write_fact, cwd);
972            assert_ne!(code, 0, "{text}");
973            // Ordinary project work in the session's own directory is untouched.
974            let (text, code) =
975                execute_command_in("printf 'fn main() {}' > main.rs && cat main.rs", cwd);
976            assert_eq!(code, 0, "{text}");
977            assert!(text.contains("fn main()"), "{text}");
978        });
979        // The Engine keeps persisting from outside the child rules.
980        assert_eq!(
981            std::fs::read_to_string(&fact).unwrap(),
982            "synthetic-provider-fact"
983        );
984        std::fs::write(&fact, "engine-write").unwrap();
985
986        // A protected session whose rules went missing runs nothing at all —
987        // there is no unconfined fallback shell.
988        lean_ctx::test_env::remove_var(lean_ctx::core::protected_store::CHILD_PROFILE_ENV);
989        let (text, code) = execute_command_in("printf ran-unconfined", cwd);
990        assert_ne!(code, 0, "{text}");
991        assert!(text.starts_with("ERROR:"), "{text}");
992        assert!(!text.contains("ran-unconfined"), "{text}");
993    }
994
995    /// #1113/#1173: a poll loop that emits a short line every so often must
996    /// outlive the wall-clock budget — the cap protects against runaway output,
997    /// not against a long-lived monitor. Wall-clock mode still kills it.
998    #[test]
999    #[cfg_attr(windows, ignore)]
1000    fn idle_keyed_timeout_survives_a_trickling_loop() {
1001        let _lock = lean_ctx::core::data_dir::test_env_lock();
1002        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
1003        let env = std::collections::HashMap::new();
1004        // Emits every 100ms for ~900ms under a 400ms budget.
1005        let cmd = "for i in 1 2 3 4 5 6 7 8 9; do printf T; sleep 0.1; done; printf DONE";
1006
1007        let (idle_out, idle_code) = super::execute_command_with_env_cancellable(
1008            cmd,
1009            ".",
1010            &env,
1011            Some(400),
1012            None,
1013            true,
1014            None,
1015        );
1016        assert_eq!(
1017            idle_code, 0,
1018            "output kept resetting the idle clock: {idle_out}"
1019        );
1020        assert!(idle_out.contains("DONE"));
1021
1022        let (wall_out, wall_code) = super::execute_command_with_env_cancellable(
1023            cmd,
1024            ".",
1025            &env,
1026            Some(400),
1027            None,
1028            false,
1029            None,
1030        );
1031        assert_eq!(wall_code, 124, "wall-clock mode must still enforce the cap");
1032        assert!(wall_out.contains("timed out"));
1033    }
1034
1035    /// #1086: a timed-out pipeline names the segment that was still running,
1036    /// so the caller fixes that part instead of re-running everything.
1037    #[test]
1038    #[cfg_attr(windows, ignore)]
1039    fn timeout_names_the_still_running_segment() {
1040        let _lock = lean_ctx::core::data_dir::test_env_lock();
1041        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_TIMEOUT_MS");
1042        let env = std::collections::HashMap::new();
1043        let (out, code) = super::execute_command_with_env_cancellable(
1044            "printf FIRST_OK; sleep 47",
1045            ".",
1046            &env,
1047            Some(600),
1048            None,
1049            false,
1050            None,
1051        );
1052        assert_eq!(code, 124);
1053        assert!(
1054            out.contains("FIRST_OK"),
1055            "partial output must survive: {out}"
1056        );
1057        assert!(
1058            out.contains("still running at timeout") && out.contains("47"),
1059            "the hung segment must be named: {out}"
1060        );
1061    }
1062
1063    #[test]
1064    #[cfg(unix)]
1065    fn ps_row_names_segments_and_drops_the_whole_command() {
1066        // Rows are `pid ppid pgid args`.
1067        let whole = "printf hi; grep -rn needle /repo";
1068        assert_eq!(
1069            super::parse_ps_row(" 4242 4200 4200 grep -rn needle /repo", 4200, whole)
1070                .map(|p| p.args),
1071            Some("grep -rn needle /repo".to_string()),
1072            "a segment must be named"
1073        );
1074        // The un-exec'd shell wrapper still carries the whole command.
1075        assert!(
1076            super::parse_ps_row(
1077                "4200 1 4200 /bin/sh -c printf hi; grep -rn needle /repo",
1078                4200,
1079                whole
1080            )
1081            .is_none()
1082        );
1083        // Another job's process group.
1084        assert!(super::parse_ps_row("4242 4200 9999 sleep 5", 4200, whole).is_none());
1085        assert!(super::parse_ps_row("garbage", 4200, whole).is_none());
1086    }
1087
1088    // --- GH #1654: descendants are not pipeline stages ---
1089
1090    /// The reporter's case. `go run ./x` execs the binary it just compiled,
1091    /// which joins the same process group. Rendering the set as `a | b` claimed
1092    /// a pipeline the process table never established, producing a line that
1093    /// is not runnable and naming a stage the caller never wrote.
1094    #[test]
1095    #[cfg(unix)]
1096    fn a_spawned_child_is_labelled_not_presented_as_a_stage() {
1097        let live = vec![
1098            super::LiveProc {
1099                pid: 100,
1100                ppid: 1,
1101                args: "go run ./ --template x".into(),
1102            },
1103            super::LiveProc {
1104                pid: 101,
1105                ppid: 100,
1106                args: "/var/folders/T/go-build/b001/exe/evcc --template x".into(),
1107            },
1108        ];
1109        let out = super::describe_live(&live);
1110        assert_eq!(out.len(), 1, "the child is not a peer entry: {out:?}");
1111        assert!(out[0].starts_with("go run ./"), "{out:?}");
1112        assert!(
1113            out[0].contains("(spawned: /var/folders/T/go-build/b001/exe/evcc"),
1114            "the descendant is named as one: {out:?}"
1115        );
1116    }
1117
1118    /// Real pipeline siblings share a parent that is *not* in the set (the
1119    /// shell wrapper was dropped for carrying the whole command), so both stay
1120    /// top-level.
1121    #[test]
1122    #[cfg(unix)]
1123    fn genuine_pipeline_siblings_both_stay_top_level() {
1124        let live = vec![
1125            super::LiveProc {
1126                pid: 200,
1127                ppid: 50,
1128                args: "grep -rn needle /repo".into(),
1129            },
1130            super::LiveProc {
1131                pid: 201,
1132                ppid: 50,
1133                args: "head -30".into(),
1134            },
1135        ];
1136        let mut out = super::describe_live(&live);
1137        out.sort();
1138        assert_eq!(out, vec!["grep -rn needle /repo", "head -30"]);
1139    }
1140
1141    /// The rendered separator must not be shell syntax — that was the whole
1142    /// defect. `;` reads as a list; `|` read as a pipeline that did not exist.
1143    #[test]
1144    #[cfg(unix)]
1145    fn the_timeout_line_does_not_imply_a_pipeline() {
1146        let joined = ["a".to_string(), "b".to_string()].join("; ");
1147        assert!(!joined.contains('|'), "no pipe may be invented: {joined}");
1148    }
1149
1150    #[test]
1151    fn ensure_utf8_locale_sets_fallback_when_none_inherited() {
1152        let _env_lock = lean_ctx::core::data_dir::test_env_lock();
1153        let empty: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1154        let mut cmd = std::process::Command::new("true");
1155
1156        // Temporarily unset locale vars to test fallback
1157        let saved = (
1158            std::env::var("LC_ALL").ok(),
1159            std::env::var("LC_CTYPE").ok(),
1160            std::env::var("LANG").ok(),
1161        );
1162        lean_ctx::test_env::remove_var("LC_ALL");
1163        lean_ctx::test_env::remove_var("LC_CTYPE");
1164        lean_ctx::test_env::remove_var("LANG");
1165
1166        ensure_utf8_locale(&mut cmd, &empty);
1167
1168        // Restore
1169        if let Some(v) = saved.0 {
1170            lean_ctx::test_env::set_var("LC_ALL", v);
1171        }
1172        if let Some(v) = saved.1 {
1173            lean_ctx::test_env::set_var("LC_CTYPE", v);
1174        }
1175        if let Some(v) = saved.2 {
1176            lean_ctx::test_env::set_var("LANG", v);
1177        }
1178
1179        // Command internal env isn't inspectable, but we verify the fn doesn't panic
1180        // and the real integration test below checks byte-level correctness.
1181    }
1182
1183    #[test]
1184    fn ensure_utf8_locale_skips_when_extra_env_has_lc_all() {
1185        let mut extra = std::collections::HashMap::new();
1186        extra.insert("LC_ALL".to_string(), "C".to_string());
1187        let mut cmd = std::process::Command::new("true");
1188        ensure_utf8_locale(&mut cmd, &extra);
1189        // Should not panic or override
1190    }
1191
1192    #[test]
1193    #[cfg_attr(windows, ignore)]
1194    fn utf8_bytes_survive_shell_roundtrip() {
1195        let _lock = lean_ctx::core::data_dir::test_env_lock();
1196        let (output, code) = execute_command_in(
1197            "printf '\\xD0\\x9F\\xD1\\x80\\xD0\\xB8\\xD0\\xB2\\xD0\\xB5\\xD1\\x82'",
1198            ".",
1199        );
1200        assert_eq!(code, 0, "printf failed: {output}");
1201        assert_eq!(output, "Привет", "Cyrillic bytes must survive roundtrip");
1202    }
1203
1204    #[test]
1205    #[cfg_attr(windows, ignore)] // ReadToEnd() blocks indefinitely on Windows CI
1206    fn execute_command_closes_stdin() {
1207        let _lock = lean_ctx::core::data_dir::test_env_lock();
1208        let command = "sh -c 'if read -t 1 line; then echo 67890; else echo 12345; fi'";
1209        let (output, code) = execute_command_in(command, ".");
1210        assert_eq!(code, 0, "command failed: {output}");
1211        assert!(
1212            output.contains("12345"),
1213            "child process should receive EOF on stdin, got: {output}"
1214        );
1215    }
1216
1217    /// #1881: a command terminated by a signal reports `128 + signal`, not 1.
1218    /// Exit 1 plus output would even pass as a grep-style success (#1090).
1219    #[test]
1220    #[cfg(unix)]
1221    fn execute_command_reports_signal_termination_as_128_plus_signal() {
1222        let (output, code) = execute_command_in("echo before-kill; kill -TERM $$", ".");
1223        assert_eq!(code, 143, "SIGTERM must map to 143, got {code}: {output}");
1224        assert!(output.contains("before-kill"), "output kept: {output}");
1225
1226        let (_, code) = execute_command_in("kill -KILL $$", ".");
1227        assert_eq!(code, 137, "SIGKILL must map to 137");
1228    }
1229
1230    /// #945: a command that finishes but leaves a process holding the stdout
1231    /// pipe open (here a backgrounded `sleep`) must NOT lose the foreground
1232    /// output. The old `recv_timeout(...).unwrap_or_default()` discarded
1233    /// everything on the reader timeout; now the captured prefix survives and
1234    /// the still-draining reader is flagged instead of returning a bare exit.
1235    #[test]
1236    #[cfg_attr(windows, ignore)] // POSIX backgrounding (`&`) + sleep
1237    fn background_pipe_holder_keeps_foreground_output() {
1238        let _lock = lean_ctx::core::data_dir::test_env_lock();
1239        let (output, code) = execute_command_in("echo REPRO_CANARY_945; sleep 4 &", ".");
1240        assert_eq!(code, 0, "command should succeed: {output:?}");
1241        assert!(
1242            output.contains("REPRO_CANARY_945"),
1243            "foreground stdout must survive a lingering background pipe holder, got: {output:?}"
1244        );
1245        assert!(
1246            output.contains("output reader still draining"),
1247            "an incomplete reader must be flagged, got: {output:?}"
1248        );
1249    }
1250
1251    /// A command runs without a controlling terminal, so an interactive
1252    /// descendant cannot take the terminal's foreground from the agent.
1253    /// (Vacuous where the test runner itself has no terminal, as in CI.)
1254    #[test]
1255    #[cfg(unix)]
1256    fn command_has_no_controlling_terminal() {
1257        let (output, code) = execute_command_in(
1258            "if (exec 3</dev/tty) 2>/dev/null; then echo HAS_TTY; else echo NO_TTY; fi",
1259            ".",
1260        );
1261        assert_eq!(code, 0, "{output:?}");
1262        assert!(output.contains("NO_TTY"), "got: {output:?}");
1263    }
1264
1265    #[test]
1266    #[cfg_attr(windows, ignore)]
1267    fn forwards_captured_agent_runtime_env() {
1268        // #370: the MCP server process lacks CODEX_THREAD_ID; a hook captured it
1269        // from the agent shell. ctx_shell must still forward it to the child.
1270        // The capture lands in `state_dir()`, so all category dirs must be
1271        // isolated — pinning only the data dir let parallel tests race it.
1272        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
1273
1274        // Simulate a hook capturing the var from the native agent environment.
1275        lean_ctx::test_env::remove_var("CODEX_THREAD_ID");
1276        lean_ctx::test_env::set_var("CODEX_THREAD_ID", "thread-from-hook");
1277        lean_ctx_ext::core::agent_runtime_env::capture();
1278        // The MCP server process itself does not carry the var.
1279        lean_ctx::test_env::remove_var("CODEX_THREAD_ID");
1280
1281        let (output, code) = execute_command_in("printf 'TID=%s' \"$CODEX_THREAD_ID\"", ".");
1282
1283        assert_eq!(code, 0, "command failed: {output}");
1284        assert!(
1285            output.contains("TID=thread-from-hook"),
1286            "captured agent runtime var must be forwarded, got: {output}"
1287        );
1288    }
1289
1290    /// Per-call `timeout_ms` must reach the kill loop: a command that sleeps
1291    /// past its 200ms budget is killed with the timeout exit code and message.
1292    #[test]
1293    #[cfg_attr(windows, ignore)] // POSIX sleep
1294    fn per_call_timeout_kills_long_command() {
1295        let _lock = lean_ctx::core::data_dir::test_env_lock();
1296        let (output, code) = super::execute_command_with_env(
1297            "sleep 3",
1298            ".",
1299            &std::collections::HashMap::new(),
1300            Some(200),
1301        );
1302        assert_eq!(code, 124, "timed-out command must exit 124: {output}");
1303        assert!(
1304            output.contains("timed out after 200ms"),
1305            "timeout message must carry the per-call budget, got: {output}"
1306        );
1307    }
1308
1309    /// #995: bytes emitted before a timeout remain visible; a timeout notice is
1310    /// additive rather than a replacement for useful subprocess output.
1311    #[test]
1312    #[cfg_attr(windows, ignore)] // POSIX sleep
1313    fn per_call_timeout_preserves_partial_output() {
1314        let _lock = lean_ctx::core::data_dir::test_env_lock();
1315        let (output, code) = super::execute_command_with_env(
1316            "printf TIMEOUT_PARTIAL_995; sleep 3",
1317            ".",
1318            &std::collections::HashMap::new(),
1319            Some(200),
1320        );
1321        assert_eq!(code, 124, "timed-out command must exit 124: {output}");
1322        assert!(
1323            output.contains("TIMEOUT_PARTIAL_995"),
1324            "stdout emitted before timeout must be preserved: {output:?}"
1325        );
1326        assert!(
1327            output.contains("timed out after 200ms"),
1328            "timeout notice must remain explicit: {output:?}"
1329        );
1330    }
1331
1332    #[test]
1333    fn git_version_returns_when_git_is_available() {
1334        let _lock = lean_ctx::core::data_dir::test_env_lock();
1335        let git_available = std::process::Command::new("git")
1336            .arg("--version")
1337            .stdout(std::process::Stdio::null())
1338            .stderr(std::process::Stdio::null())
1339            .status()
1340            .is_ok();
1341        if !git_available {
1342            return;
1343        }
1344
1345        let (output, code) = execute_command_in("git --version", ".");
1346        assert_eq!(code, 0, "git command failed: {output}");
1347        assert!(
1348            output.to_ascii_lowercase().contains("git version"),
1349            "unexpected git output: {output}"
1350        );
1351    }
1352}