Skip to main content

codex_wrapper/
exec.rs

1//! Process execution layer for spawning and communicating with the `codex`
2//! binary, including timeout and retry support.
3
4use std::fmt;
5use std::path::Path;
6use std::process::ExitStatus;
7use std::time::{Duration, Instant};
8
9use tokio::process::Command;
10use tracing::{Instrument, Span, debug, field, info_span};
11
12use crate::Codex;
13use crate::error::{Error, OutputStream, Result, ShutdownAction};
14
15/// Build the span covering one invocation.
16///
17/// The fields carry what identifies a run, never what it contains: no prompt
18/// and no environment. Both routinely hold content a host would not want in
19/// its logs, and a span is recorded whenever any subscriber is installed.
20pub(crate) fn command_span(name: &'static str, codex: &Codex, args: &[String]) -> Span {
21    info_span!(
22        parent: Span::current(),
23        "codex",
24        otel.name = name,
25        subcommand = trace_subcommand(args),
26        arg_count = args.len(),
27        working_dir_set = codex.working_dir.is_some(),
28        outcome = field::Empty,
29        exit_code = field::Empty,
30        duration_ms = field::Empty,
31    )
32}
33
34/// RawCommand permits arbitrary first tokens; only fixed operation labels may
35/// enter diagnostics. Counts retain observability for future/unknown commands.
36fn trace_subcommand(args: &[String]) -> &'static str {
37    match args.first().map(String::as_str) {
38        None => "(none)",
39        Some("exec") => "exec",
40        Some("archive") => "archive",
41        Some("delete") => "delete",
42        Some("unarchive") => "unarchive",
43        Some("--version" | "-V") => "version",
44        Some("review") => "review",
45        Some("login") => "login",
46        Some("logout") => "logout",
47        Some("mcp") => "mcp",
48        Some("mcp-server") => "mcp-server",
49        Some("app-server") => "app-server",
50        Some("completion") => "completion",
51        Some("sandbox") => "sandbox",
52        Some("apply") => "apply",
53        Some("resume") => "resume",
54        Some("fork") => "fork",
55        Some("features") => "features",
56        Some("plugin") => "plugin",
57        Some("doctor") => "doctor",
58        Some("update") => "update",
59        Some(_) => "other",
60    }
61}
62
63/// Records how a run ended on its span, including when it does not end at all.
64///
65/// The dropped-future case is the one worth the machinery. Cancellation kills
66/// the process and runs nothing else, so without this the span would close
67/// with no outcome and an abandoned run would be indistinguishable from one
68/// still in progress. The span is passed in and held rather than read from
69/// [`Span::current`]: current-span tracking is the subscriber's job, and a
70/// subscriber that does not implement it would silently drop every record,
71/// including the drop-time one this exists for.
72pub(crate) struct SpanOutcome {
73    span: Span,
74    started: Instant,
75    settled: bool,
76}
77
78impl SpanOutcome {
79    pub(crate) fn start(span: Span) -> Self {
80        Self {
81            span,
82            started: Instant::now(),
83            settled: false,
84        }
85    }
86
87    pub(crate) fn settle(&mut self, outcome: &'static str, exit_code: Option<i32>) {
88        self.settled = true;
89        self.span.record("outcome", outcome);
90        self.span
91            .record("duration_ms", self.started.elapsed().as_millis() as u64);
92        if let Some(code) = exit_code {
93            self.span.record("exit_code", code);
94        }
95    }
96
97    fn settle_from_ref(&mut self, result: &Result<CommandOutput>) {
98        self.settle_from(result);
99    }
100
101    fn settle_from(&mut self, result: &Result<CommandOutput>) {
102        match result {
103            Ok(output) => self.settle("ok", Some(output.exit_code)),
104            Err(Error::Timeout { .. }) => self.settle("timeout", None),
105            // Its own outcome so the span never reads as a settled timeout or
106            // cancellation when the child may not have been reaped.
107            Err(Error::CleanupFailed { .. }) => self.settle("cleanup_failed", None),
108            // Covers the classified failures too, which are no longer
109            // CommandFailed but did still come from a process exit.
110            Err(e) => match e.exit_code() {
111                Some(code) => self.settle("failed", Some(code)),
112                None => self.settle("error", None),
113            },
114        }
115    }
116}
117
118impl Drop for SpanOutcome {
119    fn drop(&mut self) {
120        if !self.settled {
121            self.settle("cancelled", None);
122        }
123    }
124}
125
126/// Put the child in its own process group so signals also reach descendants
127/// that stay in that group. Tools that detach require cooperative CLI cleanup;
128/// `kill_on_drop` alone only reaches the direct child.
129#[cfg(unix)]
130fn own_process_group(cmd: &mut Command, enabled: bool) {
131    if enabled {
132        cmd.process_group(0);
133    }
134}
135
136#[cfg(not(unix))]
137fn own_process_group(_cmd: &mut Command, _enabled: bool) {}
138
139/// Whether [`CodexBuilder::die_with_parent`](crate::CodexBuilder::die_with_parent)
140/// has a kernel-level effect on this platform.
141///
142/// This is true only on Linux, where `PR_SET_PDEATHSIG` is available. A
143/// supervisor that needs portable containment should use
144/// [`CodexBuilder::on_spawn`](crate::CodexBuilder::on_spawn) to maintain its
145/// own watchdog on other targets.
146#[must_use]
147pub const fn die_with_parent_supported() -> bool {
148    cfg!(target_os = "linux")
149}
150
151/// Ask the kernel to SIGKILL the child when its immediate parent dies.
152///
153/// The parent pid is captured before the fork. After arming the signal in the
154/// child, the hook checks it again and exits if the parent changed in the
155/// fork-to-prctl window. Every call here is async-signal-safe because this hook
156/// runs after `fork` and before `exec`.
157#[cfg(unix)]
158fn pdeathsig_hook() -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static {
159    let parent = std::process::id();
160    move || {
161        #[cfg(target_os = "linux")]
162        {
163            // SAFETY: prctl, getppid, and _exit are async-signal-safe calls.
164            unsafe {
165                if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
166                    return Err(std::io::Error::last_os_error());
167                }
168                if libc::getppid() as u32 != parent {
169                    libc::_exit(1);
170                }
171            }
172        }
173        #[cfg(not(target_os = "linux"))]
174        {
175            let _ = parent;
176        }
177        Ok(())
178    }
179}
180
181/// Apply the parent-death policy to a spawn command.
182fn apply_die_with_parent(cmd: &mut Command, enabled: bool) {
183    #[cfg(unix)]
184    if enabled {
185        // SAFETY: `pdeathsig_hook` uses only async-signal-safe operations.
186        unsafe {
187            cmd.pre_exec(pdeathsig_hook());
188        }
189    }
190    #[cfg(not(unix))]
191    {
192        let _ = (cmd, enabled);
193    }
194}
195
196/// Construct a CLI command with the process policies shared by every spawn path.
197pub(crate) fn child_command(binary: &Path, process_group: bool, die_with_parent: bool) -> Command {
198    let mut cmd = Command::new(binary);
199    // Dropping a future must stop a child even when it shares the parent's group.
200    cmd.kill_on_drop(true);
201    own_process_group(&mut cmd, process_group);
202    apply_die_with_parent(&mut cmd, die_with_parent);
203    #[cfg(any(target_os = "macos", target_os = "ios"))]
204    mark_inherited_fds_close_on_exec(&mut cmd);
205    cmd
206}
207
208/// On macOS and iOS, Rust creates pipes before setting CLOEXEC. A concurrent
209/// fork can inherit the pipes in that window and delay EOF for a sibling.
210#[cfg(any(target_os = "macos", target_os = "ios"))]
211fn mark_inherited_fds_close_on_exec(cmd: &mut Command) {
212    // Bound the number of fcntl calls even if the soft limit is huge or
213    // unlimited. Query the limit in the parent so the hook needs no getrlimit.
214    const FD_SCAN_LIMIT: libc::c_int = 65_536;
215    let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
216    // SAFETY: getrlimit initializes the struct on success.
217    let end = unsafe {
218        if libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) == 0 {
219            limit
220                .assume_init()
221                .rlim_cur
222                .min(FD_SCAN_LIMIT as libc::rlim_t) as libc::c_int
223        } else {
224            FD_SCAN_LIMIT
225        }
226    };
227
228    // SAFETY: fcntl is async-signal-safe. Setting CLOEXEC leaves Rust's
229    // exec-status descriptor open so it can report a failed exec.
230    unsafe {
231        cmd.pre_exec(move || {
232            for fd in 3..end {
233                // Empty slots (EBADF) and other failures are best effort.
234                libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
235            }
236            Ok(())
237        });
238    }
239}
240
241/// Arm group cleanup and notify the observer from one process receipt.
242pub(crate) fn arm_and_notify(
243    process_group: bool,
244    termination_signal: crate::TerminationSignal,
245    pid: Option<u32>,
246    on_spawn: Option<&crate::SpawnObserver>,
247) -> GroupKillGuard {
248    if let (Some(pid), Some(observer)) = (pid, on_spawn) {
249        observer(crate::SpawnInfo {
250            pid,
251            pgid: process_group.then_some(pid),
252        });
253    }
254    GroupKillGuard::new(process_group.then_some(pid).flatten(), termination_signal)
255}
256
257/// Signal a process group, given the group leader's pid.
258///
259/// Unix only: there is no non-unix counterpart, because every caller of this
260/// is itself gated on unix. A stub would only be dead code.
261///
262/// Negating the pid is what makes this reach the group rather than the leader
263/// alone. Returns whether the OS accepted the signal.
264#[cfg(unix)]
265pub(crate) fn signal_group(pid: u32, signal: i32) -> bool {
266    let Ok(pid) = i32::try_from(pid) else {
267        return false;
268    };
269    // SAFETY: `kill` with a negative pid signals a process group. Callers must
270    // retain ownership of the group leader until their final signal is sent.
271    unsafe { libc::kill(-pid, signal) == 0 }
272}
273
274/// Check the group leader without releasing its PID before the final signal.
275#[cfg(any(
276    target_os = "linux",
277    target_os = "android",
278    target_vendor = "apple",
279    target_os = "freebsd",
280    target_os = "dragonfly",
281    target_os = "netbsd",
282    target_os = "openbsd",
283    target_os = "illumos",
284    target_os = "solaris",
285))]
286fn group_leader_running(pid: u32) -> std::io::Result<bool> {
287    loop {
288        let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
289        // SAFETY: P_PID selects our still-owned child. WNOWAIT leaves an
290        // exited child waitable, reserving its PID and process group ID.
291        let result = unsafe {
292            libc::waitid(
293                libc::P_PID,
294                pid as libc::id_t,
295                info.as_mut_ptr(),
296                libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
297            )
298        };
299        if result == 0 {
300            // SAFETY: No pending status leaves si_pid zero. Zeroing also
301            // covers kernels that leave the buffer untouched in that case.
302            return Ok(unsafe { info.assume_init().si_pid() } == 0);
303        }
304        let error = std::io::Error::last_os_error();
305        if error.kind() != std::io::ErrorKind::Interrupted {
306            return Err(error);
307        }
308    }
309}
310
311#[cfg(all(
312    unix,
313    not(any(
314        target_os = "linux",
315        target_os = "android",
316        target_vendor = "apple",
317        target_os = "freebsd",
318        target_os = "dragonfly",
319        target_os = "netbsd",
320        target_os = "openbsd",
321        target_os = "illumos",
322        target_os = "solaris",
323    ))
324))]
325fn group_leader_running(_pid: u32) -> std::io::Result<bool> {
326    // Without a non-reaping check, the final exit status is the only evidence.
327    Ok(true)
328}
329
330#[cfg(test)]
331mod group_leader_probe_tests {
332    // The targets where `group_leader_running` uses `waitid`.
333    #[cfg(any(
334        target_os = "linux",
335        target_os = "android",
336        target_vendor = "apple",
337        target_os = "freebsd",
338        target_os = "dragonfly",
339        target_os = "netbsd",
340        target_os = "openbsd",
341        target_os = "illumos",
342        target_os = "solaris",
343    ))]
344    mod waitid {
345        use super::super::*;
346        use std::os::unix::process::ExitStatusExt;
347
348        #[tokio::test]
349        async fn reports_exit_without_reaping() {
350            let mut child = Command::new("sleep")
351                .arg("60")
352                .kill_on_drop(true)
353                .spawn()
354                .unwrap();
355            let pid = child.id().unwrap();
356            assert!(group_leader_running(pid).unwrap());
357
358            child.start_kill().unwrap();
359            tokio::time::timeout(Duration::from_secs(5), async {
360                while group_leader_running(pid).unwrap() {
361                    tokio::time::sleep(Duration::from_millis(10)).await;
362                }
363            })
364            .await
365            .expect("the probe did not see the child exit");
366            assert!(!group_leader_running(pid).unwrap());
367
368            let status = child
369                .try_wait()
370                .unwrap()
371                .expect("the child is still waitable");
372            assert_eq!(status.signal(), Some(libc::SIGKILL));
373        }
374
375        #[tokio::test]
376        async fn disarms_when_the_leader_is_reaped_during_the_grace_period() {
377            let mut command = Command::new("sleep");
378            command.arg("60").kill_on_drop(true);
379            own_process_group(&mut command, true);
380            let mut child = command.spawn().unwrap();
381            let mut group = GroupKillGuard::new(child.id(), crate::TerminationSignal::Terminate);
382            let mut stop = Box::pin(group.terminate(Duration::from_millis(500)));
383
384            // Poll through SIGTERM, then let a different waiter collect the
385            // status before polling the termination future again.
386            tokio::select! {
387                biased;
388                result = &mut stop => panic!("termination finished before the grace period: {result:?}"),
389                () = std::future::ready(()) => {}
390            }
391            let status = tokio::time::timeout(Duration::from_secs(5), child.wait())
392                .await
393                .expect("the leader did not exit")
394                .unwrap();
395            assert_eq!(status.signal(), Some(libc::SIGTERM));
396
397            let error = stop.await.unwrap_err();
398            assert_eq!(error.raw_os_error(), Some(libc::ECHILD));
399            assert!(group.pid.is_none());
400        }
401    }
402}
403
404/// SIGKILLs the run's process group when dropped.
405///
406/// `kill_on_drop` handles the direct child; this is what reaches the
407/// descendants that remain in the group. Detached tools require CLI cooperation.
408/// Drop cannot await, so this is the abrupt path.
409/// For a graceful one, see
410/// [`ExecCommand::execute_cancellable`](crate::ExecCommand::execute_cancellable).
411pub(crate) struct GroupKillGuard {
412    pid: Option<u32>,
413    signal: crate::TerminationSignal,
414}
415
416impl GroupKillGuard {
417    pub(crate) fn new(pid: Option<u32>, signal: crate::TerminationSignal) -> Self {
418        Self { pid, signal }
419    }
420
421    /// Stop killing on drop, once the run has finished on its own.
422    pub(crate) fn disarm(&mut self) {
423        self.pid = None;
424    }
425
426    #[cfg(unix)]
427    fn leader_running(&mut self, pid: u32) -> std::io::Result<bool> {
428        match group_leader_running(pid) {
429            Ok(running) => Ok(running),
430            Err(error) if error.raw_os_error() == Some(libc::ECHILD) => {
431                // A foreign wait can release the leader's PID. If the group
432                // emptied too, its ID can be reused. Skip further group
433                // signals, including on Drop, even if descendants may survive.
434                self.disarm();
435                Err(error)
436            }
437            // If the probe is unavailable, finish cleanup and use the reaped
438            // status to rule out a hard stop that did not end the leader.
439            Err(_) => Ok(true),
440        }
441    }
442
443    /// Give the group a grace period, then kill any remaining members while
444    /// the leader still reserves the group ID. Report which signals could
445    /// have reached the leader before it exited.
446    async fn terminate(
447        &mut self,
448        grace: Duration,
449    ) -> std::io::Result<(Option<ShutdownAction>, bool)> {
450        #[cfg(unix)]
451        if let Some(pid) = self.pid {
452            let running = self.leader_running(pid)?;
453            let soft = (signal_group(pid, self.signal.as_raw()) && running)
454                .then_some(ShutdownAction::Signal(self.signal));
455            // Keep drop cleanup armed while this await can be cancelled.
456            tokio::time::sleep(grace).await;
457            let running = self.leader_running(pid)?;
458            let hard = signal_group(pid, libc::SIGKILL) && running;
459            self.disarm();
460            return Ok((soft, hard));
461        }
462        #[cfg(not(unix))]
463        let _ = (self.pid.take(), self.signal, grace);
464        Ok((None, false))
465    }
466}
467
468impl Drop for GroupKillGuard {
469    fn drop(&mut self) {
470        // Taken unconditionally so the field is read on every platform, not
471        // just the one that can act on it.
472        if let Some(pid) = self.pid.take() {
473            #[cfg(unix)]
474            signal_group(pid, libc::SIGKILL);
475            #[cfg(not(unix))]
476            let _ = pid;
477        }
478    }
479}
480
481/// Raw output from a Codex CLI invocation.
482///
483/// Contains captured stdout/stderr, the process exit code, and a convenience
484/// `success` flag.
485#[derive(Clone)]
486pub struct CommandOutput {
487    /// Standard output as a UTF-8 string.
488    pub stdout: String,
489    /// Standard error as a UTF-8 string.
490    pub stderr: String,
491    /// Process exit code (`-1` if the process was killed by a signal).
492    pub exit_code: i32,
493    /// `true` when the process exited with code 0.
494    pub success: bool,
495}
496
497const DEBUG_TRUNCATE_LEN: usize = 200;
498
499fn truncate_for_debug(s: &str) -> String {
500    if s.len() > DEBUG_TRUNCATE_LEN {
501        format!("{}... ({} bytes total)", &s[..DEBUG_TRUNCATE_LEN], s.len())
502    } else {
503        s.to_string()
504    }
505}
506
507impl fmt::Debug for CommandOutput {
508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509        f.debug_struct("CommandOutput")
510            .field("stdout", &truncate_for_debug(&self.stdout))
511            .field("stderr", &truncate_for_debug(&self.stderr))
512            .field("exit_code", &self.exit_code)
513            .field("success", &self.success)
514            .finish()
515    }
516}
517
518/// Run a codex command with the given arguments.
519///
520/// If the [`Codex`] client has a retry policy set, transient errors will be
521/// retried according to that policy. A per-command retry policy can be passed
522/// to override the client default.
523pub async fn run_codex(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
524    run_codex_with_retry(codex, args, None).await
525}
526
527/// Run a codex command with an optional per-command retry policy override.
528pub async fn run_codex_with_retry(
529    codex: &Codex,
530    args: Vec<String>,
531    retry_override: Option<&crate::retry::RetryPolicy>,
532) -> Result<CommandOutput> {
533    let policy = retry_override.or(codex.retry_policy.as_ref());
534
535    match policy {
536        Some(policy) => {
537            // A parent span so the retry events and each attempt's own span
538            // nest under one run rather than arriving as unrelated lines.
539            let span = info_span!(
540                "codex.retry",
541                subcommand = trace_subcommand(&args),
542                max_attempts = policy.max_attempts,
543            );
544            crate::retry::with_retry(policy, || run_codex_once(codex, args.clone()))
545                .instrument(span)
546                .await
547        }
548        None => run_codex_once(codex, args).await,
549    }
550}
551
552/// Assemble the full argument list for an invocation: the client's global
553/// args first, since they precede the subcommand, then the command's own.
554///
555/// Both spawn paths and [`CodexCommand::to_command_string`] go through here,
556/// so a previewed command cannot drift from the one that actually runs.
557///
558/// [`CodexCommand::to_command_string`]: crate::command::CodexCommand::to_command_string
559pub(crate) fn assemble_args(codex: &Codex, args: Vec<String>) -> Vec<String> {
560    let mut command_args = Vec::with_capacity(codex.global_args.len() + args.len());
561    let protects_rollout_budget = args
562        .windows(2)
563        .any(|pair| pair[0] == "-c" && crate::RolloutBudgetConfig::is_config_override(&pair[1]));
564    let mut global_args = codex.global_args.iter().peekable();
565    while let Some(arg) = global_args.next() {
566        if protects_rollout_budget
567            && matches!(arg.as_str(), "--enable" | "--disable")
568            && global_args
569                .peek()
570                .is_some_and(|feature| feature.as_str() == "rollout_budget")
571        {
572            global_args.next();
573            continue;
574        }
575        if protects_rollout_budget
576            && matches!(
577                arg.as_str(),
578                "--enable=rollout_budget" | "--disable=rollout_budget"
579            )
580        {
581            continue;
582        }
583        command_args.push(arg.clone());
584    }
585    command_args.extend(args);
586    command_args
587}
588
589/// Render an invocation as a copy-pasteable shell command.
590pub(crate) fn command_string(codex: &Codex, args: Vec<String>) -> String {
591    let mut out = shell_quote(&codex.binary.display().to_string());
592    for arg in assemble_args(codex, args) {
593        out.push(' ');
594        out.push_str(&shell_quote(&arg));
595    }
596    out
597}
598
599/// Quote a single argument for a POSIX shell, if it needs it.
600///
601/// The empty string is quoted: unquoted it would vanish from the rendered
602/// command, turning a preview into something that runs differently from what
603/// it describes.
604pub(crate) fn shell_quote(arg: &str) -> String {
605    if arg.is_empty() {
606        return "''".to_string();
607    }
608    if arg.contains(|c: char| c.is_whitespace() || "\"'$\\`|;<>&()[]{}*?!~#".contains(c)) {
609        return format!("'{}'", arg.replace('\'', r"'\''"));
610    }
611    arg.to_string()
612}
613
614async fn run_codex_once(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
615    let span = command_span("codex.exec", codex, &args);
616    let outcome_span = span.clone();
617    let command_args = assemble_args(codex, args);
618
619    async move {
620        debug!(arg_count = command_args.len(), "executing codex command");
621
622        let mut outcome = SpanOutcome::start(outcome_span);
623        let result = match codex.timeout {
624            Some(timeout) => {
625                run_internal_inner(
626                    SpawnSpec {
627                        binary: &codex.binary,
628                        args: &command_args,
629                        env: &codex.env,
630                        clear_env: codex.clear_env,
631                        working_dir: codex.working_dir.as_deref(),
632                        stdin_prompt: None,
633                        process_group: codex.process_group,
634                        termination_signal: codex.termination_signal,
635                        output_limit: codex.output_limit,
636                        die_with_parent: codex.die_with_parent,
637                        on_spawn: codex.on_spawn.as_ref(),
638                    },
639                    Some(timeout_stop(timeout)),
640                    codex.termination_grace,
641                )
642                .await
643            }
644            None => {
645                run_internal_inner(
646                    SpawnSpec {
647                        binary: &codex.binary,
648                        args: &command_args,
649                        env: &codex.env,
650                        clear_env: codex.clear_env,
651                        working_dir: codex.working_dir.as_deref(),
652                        stdin_prompt: None,
653                        process_group: codex.process_group,
654                        termination_signal: codex.termination_signal,
655                        output_limit: codex.output_limit,
656                        die_with_parent: codex.die_with_parent,
657                        on_spawn: codex.on_spawn.as_ref(),
658                    },
659                    None,
660                    Duration::ZERO,
661                )
662                .await
663            }
664        };
665        outcome.settle_from(&result);
666        result
667    }
668    .instrument(span)
669    .await
670}
671
672/// Run a codex command, stopping it gracefully if `cancel` resolves first.
673///
674/// On cancellation the run's process group is sent the configured signal,
675/// given the client's [`termination_grace`](crate::CodexBuilder::termination_grace),
676/// then killed.
677/// This reaches descendants in the owned group. Detached tools require the
678/// CLI's cooperation; [`TerminationSignal::Interrupt`](crate::TerminationSignal::Interrupt)
679/// lets its interrupt handler run before the hard fallback. Output during
680/// shutdown is drained and discarded, and the cancellation reason stays latched
681/// even if the CLI exits successfully. If stopping or reaping the child fails,
682/// the stop reason is returned inside [`Error::CleanupFailed`] rather than as a
683/// bare [`Error::Cancelled`] or [`Error::Timeout`].
684///
685/// Dropping the future instead kills the owned group abruptly: `Drop` cannot
686/// wait out a grace period or allow cooperative cleanup of detached tools.
687///
688/// Retry does not apply. A cancelled run is a decision, not a transient
689/// failure.
690///
691/// On platforms without process groups this degrades to killing the child.
692pub async fn run_codex_cancellable<C>(
693    codex: &Codex,
694    args: Vec<String>,
695    cancel: C,
696) -> Result<CommandOutput>
697where
698    C: std::future::Future<Output = ()> + Send,
699{
700    let span = command_span("codex.exec", codex, &args);
701    let outcome_span = span.clone();
702    let command_args = assemble_args(codex, args);
703
704    async move {
705        debug!(
706            arg_count = command_args.len(),
707            "executing cancellable codex command"
708        );
709
710        let mut outcome = SpanOutcome::start(outcome_span);
711        let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
712        let result = run_internal_inner(
713            SpawnSpec {
714                binary: &codex.binary,
715                args: &command_args,
716                env: &codex.env,
717                clear_env: codex.clear_env,
718                working_dir: codex.working_dir.as_deref(),
719                stdin_prompt: None,
720                process_group: codex.process_group,
721                termination_signal: codex.termination_signal,
722                output_limit: codex.output_limit,
723                die_with_parent: codex.die_with_parent,
724                on_spawn: codex.on_spawn.as_ref(),
725            },
726            Some(stop),
727            codex.termination_grace,
728        )
729        .await;
730
731        match &result {
732            Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
733            other => outcome.settle_from_ref(other),
734        }
735        result
736    }
737    .instrument(span)
738    .await
739}
740
741/// Run a codex command and allow specific non-zero exit codes.
742pub async fn run_codex_allow_exit_codes(
743    codex: &Codex,
744    args: Vec<String>,
745    allowed_codes: &[i32],
746) -> Result<CommandOutput> {
747    let output = run_codex(codex, args).await;
748
749    match output {
750        // Matched on the exit code rather than the variant: classification
751        // moves some failures off CommandFailed, and an allowed code is
752        // allowed whatever the wrapper made of the message.
753        Err(e)
754            if e.exit_code()
755                .is_some_and(|code| allowed_codes.contains(&code)) =>
756        {
757            let exit_code = e.exit_code().unwrap_or(-1);
758            let (stdout, stderr) = match &e {
759                Error::CommandFailed { stdout, stderr, .. } => (stdout.clone(), stderr.clone()),
760                Error::Auth { message, .. }
761                | Error::Config { message, .. }
762                | Error::NotTrustedDirectory { message, .. }
763                | Error::SessionNotFound { message, .. } => (String::new(), message.clone()),
764                _ => (String::new(), String::new()),
765            };
766            Ok(CommandOutput {
767                stdout,
768                stderr,
769                exit_code,
770                success: false,
771            })
772        }
773        other => other,
774    }
775}
776
777/// Run a codex command, writing `prompt` to the child's stdin.
778///
779/// For `codex exec -`, where the prompt is delivered on stdin rather than as
780/// an argument. The prompt is written and the handle dropped, so the CLI sees
781/// EOF and stops waiting for more.
782///
783/// Retry does not apply. The policy is deliberately ignored rather than
784/// honored: a retry would have to write the prompt again, and the first
785/// attempt has already moved the caller's data into a pipe that cannot be
786/// rewound. Silently retrying with an empty stdin would be worse than not
787/// retrying at all.
788pub async fn run_codex_with_stdin_prompt(
789    codex: &Codex,
790    args: Vec<String>,
791    prompt: &str,
792) -> Result<CommandOutput> {
793    let span = command_span("codex.exec", codex, &args);
794    let outcome_span = span.clone();
795    let command_args = assemble_args(codex, args);
796
797    async move {
798        debug!(
799            arg_count = command_args.len(),
800            prompt_bytes = prompt.len(),
801            "executing codex command with a stdin prompt"
802        );
803
804        let mut outcome = SpanOutcome::start(outcome_span);
805        let stop = codex.timeout.map(timeout_stop);
806        let result = run_internal_inner(
807            SpawnSpec {
808                binary: &codex.binary,
809                args: &command_args,
810                env: &codex.env,
811                clear_env: codex.clear_env,
812                working_dir: codex.working_dir.as_deref(),
813                stdin_prompt: Some(prompt),
814                process_group: codex.process_group,
815                termination_signal: codex.termination_signal,
816                output_limit: codex.output_limit,
817                die_with_parent: codex.die_with_parent,
818                on_spawn: codex.on_spawn.as_ref(),
819            },
820            stop,
821            codex.termination_grace,
822        )
823        .await;
824        outcome.settle_from(&result);
825        result
826    }
827    .instrument(span)
828    .await
829}
830
831/// Run a codex command with a stdin prompt and an explicit cancellation signal.
832///
833/// Cancellation and the client's timeout both terminate the owned process
834/// group and await the direct child before returning. Retry does not apply.
835pub async fn run_codex_with_stdin_prompt_cancellable<C>(
836    codex: &Codex,
837    args: Vec<String>,
838    prompt: &str,
839    cancel: C,
840) -> Result<CommandOutput>
841where
842    C: std::future::Future<Output = ()> + Send,
843{
844    let span = command_span("codex.exec", codex, &args);
845    let outcome_span = span.clone();
846    let command_args = assemble_args(codex, args);
847
848    async move {
849        debug!(
850            arg_count = command_args.len(),
851            prompt_bytes = prompt.len(),
852            "executing cancellable codex command with a stdin prompt"
853        );
854
855        let mut outcome = SpanOutcome::start(outcome_span);
856        let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
857        let result = run_internal_inner(
858            SpawnSpec {
859                binary: &codex.binary,
860                args: &command_args,
861                env: &codex.env,
862                clear_env: codex.clear_env,
863                working_dir: codex.working_dir.as_deref(),
864                stdin_prompt: Some(prompt),
865                process_group: codex.process_group,
866                termination_signal: codex.termination_signal,
867                output_limit: codex.output_limit,
868                die_with_parent: codex.die_with_parent,
869                on_spawn: codex.on_spawn.as_ref(),
870            },
871            Some(stop),
872            codex.termination_grace,
873        )
874        .await;
875
876        match &result {
877            Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
878            other => outcome.settle_from_ref(other),
879        }
880        result
881    }
882    .instrument(span)
883    .await
884}
885
886#[derive(Clone, Copy, Debug)]
887enum StopReason {
888    Cancelled { grace_seconds: u64 },
889    Timeout { timeout_seconds: u64 },
890}
891
892impl StopReason {
893    fn into_error(self) -> Error {
894        match self {
895            Self::Cancelled { grace_seconds } => Error::Cancelled { grace_seconds },
896            Self::Timeout { timeout_seconds } => Error::Timeout { timeout_seconds },
897        }
898    }
899}
900
901type StopFuture<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = StopReason> + Send + 'a>>;
902
903fn timeout_stop(timeout: Duration) -> StopFuture<'static> {
904    Box::pin(async move {
905        tokio::time::sleep(timeout).await;
906        StopReason::Timeout {
907            timeout_seconds: timeout.as_secs(),
908        }
909    })
910}
911
912fn cancellation_or_timeout<'a, C>(
913    cancel: C,
914    timeout: Option<Duration>,
915    grace: Duration,
916) -> StopFuture<'a>
917where
918    C: std::future::Future<Output = ()> + Send + 'a,
919{
920    Box::pin(async move {
921        match timeout {
922            Some(timeout) => tokio::select! {
923                () = cancel => StopReason::Cancelled {
924                    grace_seconds: grace.as_secs(),
925                },
926                () = tokio::time::sleep(timeout) => StopReason::Timeout {
927                    timeout_seconds: timeout.as_secs(),
928                },
929            },
930            None => {
931                cancel.await;
932                StopReason::Cancelled {
933                    grace_seconds: grace.as_secs(),
934                }
935            }
936        }
937    })
938}
939
940/// Everything one spawn needs, gathered so the signature stays readable.
941struct SpawnSpec<'a> {
942    binary: &'a std::path::Path,
943    args: &'a [String],
944    env: &'a crate::EnvironmentOverrides,
945    /// Whether the child starts without the wrapper's ambient environment.
946    clear_env: bool,
947    working_dir: Option<&'a std::path::Path>,
948    /// A prompt to deliver on stdin, for `codex exec -`.
949    stdin_prompt: Option<&'a str>,
950    /// Whether the run leads its own process group.
951    process_group: bool,
952    termination_signal: crate::TerminationSignal,
953    /// Stop capturing a stream once it passes this many bytes.
954    output_limit: Option<usize>,
955    /// Whether the child should die with its immediate parent on Linux.
956    die_with_parent: bool,
957    /// Who to notify immediately after a successful spawn.
958    on_spawn: Option<&'a crate::SpawnObserver>,
959}
960
961/// Read one captured stream to EOF, or stop once it passes `limit`.
962///
963/// With no limit this is `read_to_end`, unchanged. With one, the buffer never
964/// exceeds the ceiling, so a run holds at most twice it across the two
965/// streams no matter what the child prints.
966///
967/// Exceeding it is an error rather than a truncated success. A prefix
968/// returned as though it were the whole result would be indistinguishable
969/// from a short answer, which is the failure worth preventing. Enough of the
970/// prefix to identify the runaway is logged instead.
971async fn capture<R>(
972    reader: &mut R,
973    limit: Option<usize>,
974    stream: OutputStream,
975    working_dir: Option<&std::path::Path>,
976) -> Result<Vec<u8>>
977where
978    R: tokio::io::AsyncRead + Unpin,
979{
980    use tokio::io::AsyncReadExt;
981
982    let io_error = |e: std::io::Error| Error::Io {
983        message: format!("failed to read codex {stream}: {e}"),
984        source: e,
985        working_dir: working_dir.map(std::path::Path::to_path_buf),
986    };
987
988    let Some(limit) = limit else {
989        let mut bytes = Vec::new();
990        reader.read_to_end(&mut bytes).await.map_err(io_error)?;
991        return Ok(bytes);
992    };
993
994    let mut bytes = Vec::new();
995    let mut chunk = [0u8; CAPTURE_CHUNK];
996    loop {
997        let read = reader.read(&mut chunk).await.map_err(io_error)?;
998        if read == 0 {
999            return Ok(bytes);
1000        }
1001        if bytes.len() + read > limit {
1002            tracing::warn!(
1003                %stream,
1004                limit_bytes = limit,
1005                captured_bytes = bytes.len(),
1006                "codex output exceeded its capture limit; stopping the run"
1007            );
1008            return Err(Error::OutputLimitExceeded {
1009                stream,
1010                limit_bytes: limit,
1011            });
1012        }
1013        bytes.extend_from_slice(&chunk[..read]);
1014    }
1015}
1016
1017/// Read size for a bounded capture. Large enough not to syscall per line,
1018/// small enough that the overshoot before noticing stays trivial.
1019const CAPTURE_CHUNK: usize = 8 * 1024;
1020
1021async fn run_internal_inner(
1022    spec: SpawnSpec<'_>,
1023    stop: Option<StopFuture<'_>>,
1024    grace: Duration,
1025) -> Result<CommandOutput> {
1026    let SpawnSpec {
1027        binary,
1028        args,
1029        env,
1030        clear_env,
1031        working_dir,
1032        stdin_prompt,
1033        process_group,
1034        termination_signal,
1035        output_limit,
1036        die_with_parent,
1037        on_spawn,
1038    } = spec;
1039    let mut cmd = child_command(binary, process_group, die_with_parent);
1040    cmd.args(args);
1041
1042    // Pipe stdin only when there is a prompt to write. Otherwise close it, so
1043    // the child neither inherits nor blocks on the parent's.
1044    if stdin_prompt.is_some() {
1045        cmd.stdin(std::process::Stdio::piped());
1046    } else {
1047        cmd.stdin(std::process::Stdio::null());
1048    }
1049
1050    if let Some(dir) = working_dir {
1051        cmd.current_dir(dir);
1052    }
1053
1054    apply_child_environment(&mut cmd, clear_env, env);
1055
1056    // Always spawn rather than using `Command::output`: the pid is needed to
1057    // signal the process group, and `output` does not surrender it. It also
1058    // forces stdin to null, which the stdin-prompt path cannot use.
1059    cmd.stdout(std::process::Stdio::piped());
1060    cmd.stderr(std::process::Stdio::piped());
1061
1062    let mut child = cmd.spawn().map_err(|e| Error::Io {
1063        message: format!("failed to spawn codex: {e}"),
1064        source: e,
1065        working_dir: working_dir.map(|p| p.to_path_buf()),
1066    })?;
1067
1068    // Armed for the whole run. If this future is dropped, its Drop signals the
1069    // group, which also reaches descendants still in that group.
1070    // Only meaningful when the run leads its own group. Sharing the parent's
1071    // means signalling it would hit the parent too.
1072    let mut group = arm_and_notify(process_group, termination_signal, child.id(), on_spawn);
1073    let child_stdin = child.stdin.take();
1074    let mut child_stdout = child.stdout.take().expect("stdout was configured as piped");
1075    let mut child_stderr = child.stderr.take().expect("stderr was configured as piped");
1076
1077    let write = async move {
1078        let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
1079            return Ok(());
1080        };
1081        use tokio::io::AsyncWriteExt;
1082        stdin
1083            .write_all(prompt.as_bytes())
1084            .await
1085            .map_err(|e| Error::Io {
1086                message: format!("failed to write the prompt to codex stdin: {e}"),
1087                source: e,
1088                working_dir: working_dir.map(|p| p.to_path_buf()),
1089            })?;
1090        // Closing the write half is what tells the CLI the prompt is
1091        // complete. Without it the child waits for more input.
1092        stdin.shutdown().await.map_err(|e| Error::Io {
1093            message: format!("failed to close codex stdin: {e}"),
1094            source: e,
1095            working_dir: working_dir.map(|p| p.to_path_buf()),
1096        })
1097    };
1098
1099    // Concurrently, not sequentially: a prompt larger than the pipe buffer
1100    // blocks until the child reads it, and a child that writes to stdout
1101    // meanwhile blocks until we read that. Waiting for the write to finish
1102    // before draining stdout would deadlock both.
1103    let read_stdout = async {
1104        capture(
1105            &mut child_stdout,
1106            output_limit,
1107            OutputStream::Stdout,
1108            working_dir,
1109        )
1110        .await
1111    };
1112    let read_stderr = async {
1113        capture(
1114            &mut child_stderr,
1115            output_limit,
1116            OutputStream::Stderr,
1117            working_dir,
1118        )
1119        .await
1120    };
1121    let run = async {
1122        let ((), stdout, stderr) = tokio::try_join!(write, read_stdout, read_stderr)?;
1123        // Do not reap while pipes are still open: if cancellation wins then,
1124        // delayed group signaling must not target a recycled group-leader PID.
1125        let status = child.wait().await.map_err(|e| wait_error(e, working_dir))?;
1126        Ok::<_, Error>((stdout, stderr, status))
1127    };
1128
1129    let finished = match stop {
1130        None => Ok(run.await),
1131        // Racing the run against the caller's signal. Cancellation here is
1132        // graceful, which is the whole reason it cannot live in `Drop`:
1133        // asking a process to stop and then waiting requires awaiting.
1134        Some(stop) => tokio::select! {
1135            outcome = run => Ok(outcome),
1136            reason = stop => Err(reason),
1137        },
1138    };
1139
1140    let (stdout, stderr, status) = match finished {
1141        Ok(Ok(finished)) => finished,
1142        Ok(Err(error)) => {
1143            // A stdin or pipe failure can happen while the child continues
1144            // running. Treat it as a stop request and settle ownership before
1145            // exposing the I/O error.
1146            let cleanup = terminate_and_reap_draining(
1147                &mut child,
1148                &mut group,
1149                grace,
1150                working_dir,
1151                &mut child_stdout,
1152                &mut child_stderr,
1153            )
1154            .await;
1155            return Err(Error::after_cleanup(error, cleanup));
1156        }
1157        Err(reason) => {
1158            // The run future is gone before this branch executes, returning
1159            // ownership of `child` so cleanup can explicitly reap it.
1160            // `GroupKillGuard::terminate` reaches same-group descendants. The
1161            // direct-child kill below is the portable fallback and makes the
1162            // wait authoritative on every platform.
1163            let cleanup = terminate_and_reap_draining(
1164                &mut child,
1165                &mut group,
1166                grace,
1167                working_dir,
1168                &mut child_stdout,
1169                &mut child_stderr,
1170            )
1171            .await;
1172            return Err(Error::after_cleanup(reason.into_error(), cleanup));
1173        }
1174    };
1175
1176    // Finished on its own, so there is no group left to kill.
1177    group.disarm();
1178
1179    let stdout = String::from_utf8_lossy(&stdout).to_string();
1180    let stderr = String::from_utf8_lossy(&stderr).to_string();
1181    let exit_code = status.code().unwrap_or(-1);
1182
1183    if !status.success() {
1184        return Err(Error::from_command_failure(
1185            format!("{} {}", binary.display(), args.join(" ")),
1186            exit_code,
1187            stdout,
1188            stderr,
1189            working_dir.map(|p| p.to_path_buf()),
1190        ));
1191    }
1192
1193    Ok(CommandOutput {
1194        stdout,
1195        stderr,
1196        exit_code,
1197        success: true,
1198    })
1199}
1200
1201/// Keep both pipes open and flowing while shutdown runs. Shutdown output is
1202/// discarded in fixed-size chunks, never parsed or sent to event handlers.
1203/// The drain is dropped when cleanup finishes even if an escaped descendant
1204/// still holds a pipe open. No child wait is polled before group signaling ends.
1205pub(crate) async fn terminate_and_reap_draining<O, E>(
1206    child: &mut tokio::process::Child,
1207    group: &mut GroupKillGuard,
1208    grace: Duration,
1209    working_dir: Option<&std::path::Path>,
1210    stdout: &mut O,
1211    stderr: &mut E,
1212) -> Result<()>
1213where
1214    O: tokio::io::AsyncRead + Unpin,
1215    E: tokio::io::AsyncRead + Unpin,
1216{
1217    let drain = async {
1218        let mut stdout_sink = tokio::io::sink();
1219        let mut stderr_sink = tokio::io::sink();
1220        let _ = tokio::join!(
1221            tokio::io::copy(stdout, &mut stdout_sink),
1222            tokio::io::copy(stderr, &mut stderr_sink),
1223        );
1224        std::future::pending::<()>().await;
1225    };
1226    let result = tokio::select! {
1227        result = terminate_and_reap(child, group, grace) => {
1228            result.map(|_| ()).map_err(|e| wait_error(e, working_dir))
1229        },
1230        () = drain => unreachable!("the drain waits until shutdown finishes"),
1231    };
1232    #[cfg(test)]
1233    let result = result.and_then(|()| injected_cleanup_failure(working_dir));
1234    if result.is_err() {
1235        tracing::warn!("codex cleanup failed; the child may not have been reaped");
1236    }
1237    result
1238}
1239
1240#[cfg(test)]
1241thread_local! {
1242    static INJECT_CLEANUP_FAILURE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1243}
1244
1245/// Test-only fault injection for [`terminate_and_reap_draining`].
1246///
1247/// While armed, a cleanup on this thread that actually succeeded reports a
1248/// synthetic I/O error instead. The real termination and wait still run first,
1249/// so the fixture child is reaped either way. This exercises how callers
1250/// report a failed cleanup; it does not show that any syscall can fail.
1251/// Thread-local because `#[tokio::test]` runs each test on its own
1252/// current-thread runtime, which keeps concurrent tests isolated. Every caller
1253/// is a unix-only test, hence the `dead_code` allowance elsewhere.
1254#[cfg(test)]
1255#[cfg_attr(not(unix), allow(dead_code))]
1256pub(crate) struct CleanupFailureInjection(std::marker::PhantomData<std::rc::Rc<()>>);
1257
1258#[cfg(test)]
1259#[cfg_attr(not(unix), allow(dead_code))]
1260impl CleanupFailureInjection {
1261    pub(crate) fn arm() -> Self {
1262        INJECT_CLEANUP_FAILURE.with(|armed| armed.set(true));
1263        // The thread-local guard must stay on its originating test thread.
1264        Self(std::marker::PhantomData)
1265    }
1266}
1267
1268#[cfg(test)]
1269impl Drop for CleanupFailureInjection {
1270    fn drop(&mut self) {
1271        INJECT_CLEANUP_FAILURE.with(|armed| armed.set(false));
1272    }
1273}
1274
1275#[cfg(test)]
1276fn injected_cleanup_failure(working_dir: Option<&std::path::Path>) -> Result<()> {
1277    if INJECT_CLEANUP_FAILURE.with(std::cell::Cell::get) {
1278        return Err(wait_error(
1279            std::io::Error::other("injected cleanup failure"),
1280            working_dir,
1281        ));
1282    }
1283    Ok(())
1284}
1285
1286pub(crate) async fn terminate_and_reap(
1287    child: &mut tokio::process::Child,
1288    group: &mut GroupKillGuard,
1289    grace: Duration,
1290) -> std::io::Result<(ExitStatus, Option<ShutdownAction>)> {
1291    let (soft, mut hard) = group.terminate(grace).await?;
1292    let status = if let Some(status) = child.try_wait()? {
1293        status
1294    } else {
1295        match child.start_kill() {
1296            Ok(()) => hard = true,
1297            Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {}
1298            Err(error) => return Err(error),
1299        }
1300        child.wait().await?
1301    };
1302    // A natural exit can race a successful kill syscall. The native status
1303    // tells us whether the hard stop could have been what ended the child.
1304    let action = if hard && hard_kill_matches(status) {
1305        Some(ShutdownAction::Kill)
1306    } else {
1307        soft
1308    };
1309    Ok((status, action))
1310}
1311
1312pub(crate) fn hard_kill_matches(status: ExitStatus) -> bool {
1313    #[cfg(unix)]
1314    {
1315        use std::os::unix::process::ExitStatusExt;
1316        status.signal() == Some(libc::SIGKILL)
1317    }
1318    #[cfg(windows)]
1319    {
1320        // Both std::process::Child::kill and the app-server kill switch use 1.
1321        status.code() == Some(1)
1322    }
1323    #[cfg(not(any(unix, windows)))]
1324    {
1325        let _ = status;
1326        true
1327    }
1328}
1329
1330fn wait_error(error: std::io::Error, working_dir: Option<&std::path::Path>) -> Error {
1331    Error::Io {
1332        message: format!("failed to wait on codex: {error}"),
1333        source: error,
1334        working_dir: working_dir.map(|p| p.to_path_buf()),
1335    }
1336}
1337
1338/// Apply the client environment policy to a direct child process.
1339///
1340/// Kept in one helper because buffered and streaming execution construct
1341/// separate commands. Clearing must happen before explicit values are added.
1342pub(crate) fn apply_child_environment(
1343    cmd: &mut Command,
1344    clear_env: bool,
1345    env: &crate::EnvironmentOverrides,
1346) {
1347    if clear_env {
1348        cmd.env_clear();
1349    }
1350    for (key, value) in env {
1351        match value {
1352            Some(value) => cmd.env(key, value),
1353            None => cmd.env_remove(key),
1354        };
1355    }
1356}
1357
1358#[cfg(test)]
1359mod tests {
1360    use super::*;
1361    use crate::CodexCommand;
1362
1363    #[test]
1364    fn production_commands_use_child_command() {
1365        fn check_directory(dir: &Path) {
1366            for entry in std::fs::read_dir(dir).unwrap() {
1367                let entry = entry.unwrap();
1368                let path = entry.path();
1369                if entry.file_type().unwrap().is_dir() {
1370                    check_directory(&path);
1371                    continue;
1372                }
1373                if path.extension().and_then(|ext| ext.to_str()) != Some("rs")
1374                    || entry.file_name() == "test_support.rs"
1375                {
1376                    continue;
1377                }
1378                let source = std::fs::read_to_string(&path).unwrap();
1379                let mut test_item = false;
1380                let mut skip_body = false;
1381                for (index, line) in source.lines().enumerate() {
1382                    if skip_body {
1383                        // Rustfmt puts a top-level item's closing brace at column zero.
1384                        skip_body = line != "}";
1385                        continue;
1386                    }
1387                    test_item |= line == "#[cfg(test)]" || line.starts_with("#[cfg(all(test,");
1388                    if line.is_empty()
1389                        || line.starts_with("#[")
1390                        || line.trim_start().starts_with("//")
1391                    {
1392                        continue;
1393                    }
1394                    let shared_constructor = entry.file_name() == "exec.rs"
1395                        && line.starts_with("pub(crate) fn child_command(");
1396                    skip_body = (std::mem::take(&mut test_item) || shared_constructor)
1397                        && line.ends_with('{');
1398                    if skip_body {
1399                        continue;
1400                    }
1401                    // If this fails, use child_command for the new launch so
1402                    // it gets the same process policies as the existing paths.
1403                    assert!(
1404                        line.match_indices("Command::new(").all(|(offset, _)| {
1405                            line[..offset].ends_with(|ch: char| ch.is_alphanumeric() || ch == '_')
1406                        }),
1407                        "{}:{}: use crate::exec::child_command for production spawns",
1408                        path.display(),
1409                        index + 1
1410                    );
1411                }
1412            }
1413        }
1414
1415        check_directory(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"));
1416    }
1417
1418    #[cfg(all(unix, not(target_os = "fuchsia")))]
1419    async fn buffered_descriptor_probe(expected: &str) {
1420        use crate::test_support::{inheritable_pipe_writer, stdin_echo_codex};
1421        use std::os::fd::AsRawFd;
1422
1423        let writer = inheritable_pipe_writer();
1424        let codex = stdin_echo_codex()
1425            .env("CODEX_WRAPPER_TEST_FD", writer.as_raw_fd().to_string())
1426            .build()
1427            .unwrap();
1428        let output = crate::ExecCommand::new("probe")
1429            .execute(&codex)
1430            .await
1431            .unwrap();
1432        assert!(
1433            output.stdout.contains(&format!(r#""text":"{expected}""#)),
1434            "{output:?}"
1435        );
1436    }
1437
1438    #[cfg(any(target_os = "macos", target_os = "ios"))]
1439    #[tokio::test]
1440    async fn buffered_exec_marks_inherited_descriptors_close_on_exec() {
1441        buffered_descriptor_probe("fd-closed").await;
1442    }
1443
1444    // Fuchsia's native launcher only transfers the configured stdio.
1445    #[cfg(all(
1446        unix,
1447        not(any(target_os = "macos", target_os = "ios", target_os = "fuchsia"))
1448    ))]
1449    #[tokio::test]
1450    async fn buffered_exec_preserves_inheritable_descriptors() {
1451        buffered_descriptor_probe("fd-open").await;
1452    }
1453
1454    #[cfg(unix)]
1455    #[tokio::test]
1456    async fn spawn_reports_missing_and_non_executable_binaries() {
1457        use std::os::unix::fs::OpenOptionsExt;
1458
1459        let binary = crate::test_support::PidFile::new("unlaunchable-binary");
1460        let codex = Codex::builder().binary(binary.path()).build().unwrap();
1461        for errno in [libc::ENOENT, libc::EACCES] {
1462            if errno == libc::EACCES {
1463                std::fs::OpenOptions::new()
1464                    .write(true)
1465                    .create_new(true)
1466                    .mode(0o600)
1467                    .open(binary.path())
1468                    .unwrap();
1469            }
1470            let error = crate::VersionCommand::new()
1471                .execute(&codex)
1472                .await
1473                .unwrap_err();
1474            assert!(
1475                matches!(&error, Error::Io { message, source, working_dir: None }
1476                    if message == &format!("failed to spawn codex: {source}")
1477                    && source.raw_os_error() == Some(errno)),
1478                "expected spawn errno {errno}, got {error:?}"
1479            );
1480        }
1481    }
1482
1483    #[test]
1484    fn typed_rollout_budget_suppresses_conflicting_client_global_toggles() {
1485        let codex = Codex::builder()
1486            .binary("/bin/echo")
1487            .config("features.rollout_budget=false")
1488            .enable("rollout_budget")
1489            .disable("rollout_budget")
1490            .arg("--enable=rollout_budget")
1491            .arg("--disable=rollout_budget")
1492            .arg("--disable")
1493            .arg("rollout_budget")
1494            .enable("keep-enabled")
1495            .disable("keep-disabled")
1496            .build()
1497            .expect("echo must exist");
1498        let budget = crate::RolloutBudgetConfig::builder(10_000)
1499            .build()
1500            .expect("valid budget");
1501        let expected = budget.config_override();
1502        let opening = crate::ExecCommand::new("hi")
1503            .rollout_budget(budget.clone())
1504            .args();
1505        let resumed = crate::ExecResumeCommand::new()
1506            .session_id("thread")
1507            .rollout_budget(budget)
1508            .args();
1509
1510        for args in [opening, resumed] {
1511            let assembled = assemble_args(&codex, args);
1512            assert!(assembled.iter().any(|arg| arg == &expected));
1513            assert!(
1514                !assembled.windows(2).any(|pair| {
1515                    matches!(pair[0].as_str(), "--enable" | "--disable")
1516                        && pair[1] == "rollout_budget"
1517                }),
1518                "typed budget must suppress paired client toggles: {assembled:?}"
1519            );
1520            assert!(
1521                !assembled.iter().any(|arg| {
1522                    matches!(
1523                        arg.as_str(),
1524                        "--enable=rollout_budget" | "--disable=rollout_budget"
1525                    )
1526                }),
1527                "typed budget must suppress equals-form client toggles: {assembled:?}"
1528            );
1529            assert!(
1530                assembled
1531                    .windows(2)
1532                    .any(|pair| pair == ["--enable", "keep-enabled"])
1533            );
1534            assert!(
1535                assembled
1536                    .windows(2)
1537                    .any(|pair| pair == ["--disable", "keep-disabled"])
1538            );
1539        }
1540    }
1541
1542    fn make_output(stdout: &str, stderr: &str) -> CommandOutput {
1543        CommandOutput {
1544            stdout: stdout.to_string(),
1545            stderr: stderr.to_string(),
1546            exit_code: 0,
1547            success: true,
1548        }
1549    }
1550
1551    #[test]
1552    fn shell_quote_leaves_plain_words_alone() {
1553        assert_eq!(shell_quote("exec"), "exec");
1554        assert_eq!(shell_quote("--ephemeral"), "--ephemeral");
1555        assert_eq!(shell_quote("model=gpt-5"), "model=gpt-5");
1556    }
1557
1558    #[test]
1559    fn shell_quote_wraps_anything_a_shell_would_read() {
1560        assert_eq!(shell_quote("fix the tests"), "'fix the tests'");
1561        assert_eq!(shell_quote("$HOME"), "'$HOME'");
1562        assert_eq!(shell_quote("a;b"), "'a;b'");
1563        assert_eq!(shell_quote("*.rs"), "'*.rs'");
1564        assert_eq!(shell_quote("it's"), r"'it'\''s'");
1565    }
1566
1567    /// An unquoted empty string would disappear from the rendered command,
1568    /// making the preview describe a different invocation than it previews.
1569    #[test]
1570    fn shell_quote_keeps_the_empty_argument_visible() {
1571        assert_eq!(shell_quote(""), "''");
1572    }
1573
1574    #[test]
1575    fn debug_short_output_not_truncated() {
1576        let output = make_output("hello", "world");
1577        let debug = format!("{output:?}");
1578        assert!(debug.contains("hello"));
1579        assert!(debug.contains("world"));
1580        assert!(!debug.contains("bytes total"));
1581    }
1582
1583    #[test]
1584    fn debug_long_output_truncated() {
1585        let long = "x".repeat(300);
1586        let output = make_output(&long, &long);
1587        let debug = format!("{output:?}");
1588        assert!(debug.contains("... (300 bytes total)"));
1589        assert!(!debug.contains(&long));
1590    }
1591
1592    /// Compatibility is explicit: callers that do not opt in keep the
1593    /// ambient environment they relied on before `clear_env` existed.
1594    #[cfg(unix)]
1595    #[tokio::test]
1596    async fn child_environment_is_inherited_by_default() {
1597        let capture = crate::test_support::EnvCapture::new("env-default");
1598        let codex = crate::test_support::env_capturing_codex(&capture)
1599            .build()
1600            .expect("bash must exist");
1601
1602        crate::ExecCommand::new("probe")
1603            .execute(&codex)
1604            .await
1605            .unwrap();
1606
1607        let environment = capture.read();
1608        assert!(environment.contains_key("PATH"));
1609    }
1610
1611    #[cfg(unix)]
1612    #[tokio::test]
1613    async fn selective_environment_removal() {
1614        use std::ffi::OsStr;
1615        use std::os::unix::ffi::OsStrExt;
1616
1617        // Re-enter this test with known inherited values without touching the
1618        // shared environment of the other test threads.
1619        const MARKER: &str = "CODEX_WRAPPER_ENV_REMOVE_TEST";
1620        if std::env::var_os(MARKER).is_none() {
1621            let output = std::process::Command::new(std::env::current_exe().unwrap())
1622                .args(["--exact", "exec::tests::selective_environment_removal"])
1623                .env_clear()
1624                .env(MARKER, "1")
1625                .env("CODEX_API_KEY", "fixture")
1626                .env("KEEP", "inherited")
1627                .env("RAW", OsStr::from_bytes(b"\xff"))
1628                .output()
1629                .unwrap();
1630            let report = String::from_utf8_lossy(&output.stdout);
1631            assert!(
1632                output.status.success() && report.contains("1 passed"),
1633                "{report}"
1634            );
1635            return;
1636        }
1637
1638        for clear in [false, true] {
1639            let mut builder = Codex::builder()
1640                .binary("/bin/bash")
1641                .env("CODEX_HOME", "/dev/null")
1642                .env("REMOVED", "explicit")
1643                .env_remove("RESTORED")
1644                .env("RESTORED", "set")
1645                .envs([("REMOVED", "updated"), ("BULK", "initial")])
1646                .env_remove("BULK")
1647                .envs([("BULK", "restored")]);
1648            if clear {
1649                builder = builder.clear_env();
1650            }
1651            let client = builder
1652                .env_remove("REMOVED")
1653                .env_remove("CODEX_API_KEY")
1654                .build()
1655                .unwrap();
1656
1657            #[cfg(feature = "json")]
1658            assert!(!client.auth_status().is_configured());
1659            #[cfg(any(feature = "json", feature = "config"))]
1660            assert_eq!(client.environment_value("CODEX_API_KEY"), None);
1661
1662            let inherited_check = if clear {
1663                r#"[[ -z ${KEEP+x} && -z ${RAW+x} ]]"#
1664            } else {
1665                r#"[[ $KEEP == inherited && $RAW == $'\xff' ]]"#
1666            };
1667            let script = format!(
1668                r#"[[ -z ${{REMOVED+x}} && -z ${{CODEX_API_KEY+x}} &&
1669                      $RESTORED == set && $BULK == restored ]] && {inherited_check}"#
1670            );
1671            run_codex(&client, vec!["-c".into(), script]).await.unwrap();
1672        }
1673    }
1674
1675    /// The timeout and ordinary buffered paths use different wrapper entry
1676    /// points. Opening and resume both have to reach the same environment
1677    /// policy, and explicit values on either side of `clear_env` must survive.
1678    #[cfg(unix)]
1679    #[tokio::test]
1680    async fn cleared_environment_reaches_buffered_open_and_resume() {
1681        let capture = crate::test_support::EnvCapture::new("env-buffered");
1682        let opening_client = crate::test_support::env_capturing_codex(&capture)
1683            .clear_env()
1684            .env("CODEX_WRAPPER_EXPLICIT", "opening")
1685            .timeout(Duration::from_secs(2))
1686            .build()
1687            .expect("bash must exist");
1688
1689        crate::ExecCommand::new("probe")
1690            .execute(&opening_client)
1691            .await
1692            .unwrap();
1693        let opening_environment = capture.read();
1694        assert!(!opening_environment.contains_key("PATH"));
1695        assert_eq!(
1696            opening_environment
1697                .get("CODEX_WRAPPER_EXPLICIT")
1698                .map(String::as_str),
1699            Some("opening")
1700        );
1701        assert!(opening_environment.contains_key("CODEX_WRAPPER_ENV_CAPTURE"));
1702
1703        let resume_client = crate::test_support::env_capturing_codex(&capture)
1704            .clear_env()
1705            .env("CODEX_WRAPPER_EXPLICIT", "resume")
1706            .build()
1707            .expect("bash must exist");
1708        crate::ExecResumeCommand::new()
1709            .last()
1710            .execute(&resume_client)
1711            .await
1712            .unwrap();
1713        let resume_environment = capture.read();
1714        assert!(!resume_environment.contains_key("PATH"));
1715        assert_eq!(
1716            resume_environment
1717                .get("CODEX_WRAPPER_EXPLICIT")
1718                .map(String::as_str),
1719            Some("resume")
1720        );
1721    }
1722
1723    /// Stdin delivery and graceful cancellation each construct their own
1724    /// spawn specification, so cover both instead of treating the buffered
1725    /// test as proof for them.
1726    #[cfg(unix)]
1727    #[tokio::test]
1728    async fn cleared_environment_reaches_stdin_and_cancellable_runs() {
1729        let capture = crate::test_support::EnvCapture::new("env-specialized");
1730        let codex = crate::test_support::env_capturing_codex(&capture)
1731            .env("CODEX_WRAPPER_EXPLICIT", "specialized")
1732            .clear_env()
1733            .build()
1734            .expect("bash must exist");
1735
1736        crate::ExecCommand::new("stdin prompt")
1737            .prompt_via_stdin()
1738            .execute(&codex)
1739            .await
1740            .unwrap();
1741        let stdin_environment = capture.read();
1742        assert!(!stdin_environment.contains_key("PATH"));
1743        assert_eq!(
1744            stdin_environment
1745                .get("CODEX_WRAPPER_EXPLICIT")
1746                .map(String::as_str),
1747            Some("specialized")
1748        );
1749
1750        let never = std::future::pending::<()>();
1751        run_codex_cancellable(&codex, crate::ExecCommand::new("cancellable").args(), never)
1752            .await
1753            .unwrap();
1754        let cancellable_environment = capture.read();
1755        assert!(!cancellable_environment.contains_key("PATH"));
1756        assert_eq!(
1757            cancellable_environment
1758                .get("CODEX_WRAPPER_EXPLICIT")
1759                .map(String::as_str),
1760            Some("specialized")
1761        );
1762    }
1763
1764    #[cfg(unix)]
1765    #[tokio::test]
1766    async fn environment_values_do_not_leak_into_spawn_errors() {
1767        let secret = "spawn-error-must-not-leak-this";
1768        let codex = Codex::builder()
1769            .binary("/codex-wrapper/this-binary-does-not-exist")
1770            .clear_env()
1771            .env("CODEX_WRAPPER_SECRET", secret)
1772            .build()
1773            .unwrap();
1774
1775        let error = run_codex(&codex, vec!["exec".into()])
1776            .await
1777            .expect_err("the fake path must not spawn");
1778        assert!(!error.to_string().contains(secret));
1779        assert!(!format!("{error:?}").contains(secret));
1780    }
1781
1782    /// A wrapper timeout is not terminal until the direct child is reaped.
1783    #[cfg(unix)]
1784    #[tokio::test]
1785    async fn timeout_kills_the_spawned_process() {
1786        use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1787
1788        let pid_file = PidFile::new("exec-timeout");
1789        let codex = blocking_codex(&pid_file)
1790            .timeout(Duration::from_millis(500))
1791            .build()
1792            .expect("bash must exist");
1793
1794        let result = run_codex(&codex, vec!["exec".into(), "probe".into()]).await;
1795        assert!(
1796            matches!(result, Err(Error::Timeout { .. })),
1797            "expected timeout error, got: {result:?}"
1798        );
1799
1800        let pid = pid_file.read_pid().await;
1801        assert!(
1802            !is_running_for_test(pid),
1803            "codex ({pid}) survived the timeout"
1804        );
1805    }
1806
1807    /// The caller dropping the future is the case an operator kill or a
1808    /// graceful shutdown produces, with no wrapper timeout involved.
1809    #[cfg(unix)]
1810    #[tokio::test]
1811    async fn cancellation_kills_the_spawned_process() {
1812        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
1813
1814        let pid_file = PidFile::new("exec-cancel");
1815        let codex = blocking_codex(&pid_file).build().expect("bash must exist");
1816
1817        let cancelled = tokio::time::timeout(
1818            Duration::from_millis(500),
1819            run_codex(&codex, vec!["exec".into(), "probe".into()]),
1820        )
1821        .await;
1822        assert!(
1823            cancelled.is_err(),
1824            "fake codex should still have been running, got: {cancelled:?}"
1825        );
1826
1827        let pid = pid_file.read_pid().await;
1828        assert!(
1829            wait_until_gone(pid).await,
1830            "codex ({pid}) survived the dropped future"
1831        );
1832    }
1833
1834    /// Minimal recording subscriber, written by hand because #63 rules out a
1835    /// new dependency and `tracing-subscriber` would be one.
1836    ///
1837    /// Installed once as the **global** default, fanning out to a per-thread
1838    /// sink. A thread-local `set_default` is not enough: tracing caches
1839    /// callsite interest globally, so a test running concurrently against no
1840    /// subscriber caches this crate's span callsites as `never` and the
1841    /// recording test then sees nothing. That produced a real flake, about one
1842    /// run in three. A single always-enabled global subscriber keeps interest
1843    /// stable, and the per-thread sink keeps tests isolated.
1844    #[cfg(unix)]
1845    mod recorder {
1846        use std::cell::RefCell;
1847        use std::sync::{Arc, Mutex, Once};
1848
1849        use tracing::field::{Field, Visit};
1850        use tracing::span::{Attributes, Id, Record};
1851        use tracing::{Event, Metadata, Subscriber};
1852
1853        type Sink = Arc<Mutex<Vec<(String, String)>>>;
1854
1855        thread_local! {
1856            static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
1857        }
1858
1859        struct Global;
1860
1861        impl Global {
1862            fn collect(f: impl FnOnce(&mut Vec<(String, String)>)) {
1863                SINK.with(|sink| {
1864                    if let Some(sink) = sink.borrow().as_ref() {
1865                        f(&mut sink.lock().unwrap());
1866                    }
1867                });
1868            }
1869        }
1870
1871        impl Subscriber for Global {
1872            /// Always true, so callsite interest is never cached as `never`.
1873            fn enabled(&self, _: &Metadata<'_>) -> bool {
1874                true
1875            }
1876            fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1877                Self::collect(|fields| attrs.record(&mut Collect(fields)));
1878                Id::from_u64(1)
1879            }
1880            fn record(&self, _: &Id, values: &Record<'_>) {
1881                Self::collect(|fields| values.record(&mut Collect(fields)));
1882            }
1883            fn record_follows_from(&self, _: &Id, _: &Id) {}
1884            fn event(&self, event: &Event<'_>) {
1885                Self::collect(|fields| event.record(&mut Collect(fields)));
1886            }
1887            fn enter(&self, _: &Id) {}
1888            fn exit(&self, _: &Id) {}
1889        }
1890
1891        struct Collect<'a>(&'a mut Vec<(String, String)>);
1892
1893        impl Visit for Collect<'_> {
1894            fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
1895                self.0.push((field.name().into(), format!("{value:?}")));
1896            }
1897            fn record_str(&mut self, field: &Field, value: &str) {
1898                self.0.push((field.name().into(), value.into()));
1899            }
1900            fn record_i64(&mut self, field: &Field, value: i64) {
1901                self.0.push((field.name().into(), value.to_string()));
1902            }
1903            fn record_u64(&mut self, field: &Field, value: u64) {
1904                self.0.push((field.name().into(), value.to_string()));
1905            }
1906        }
1907
1908        pub(super) struct Recorder(Sink);
1909
1910        impl Recorder {
1911            /// Start recording spans raised on this thread.
1912            pub(super) fn install() -> Self {
1913                static INIT: Once = Once::new();
1914                INIT.call_once(|| {
1915                    let _ = tracing::subscriber::set_global_default(Global);
1916                });
1917                let sink: Sink = Arc::new(Mutex::new(Vec::new()));
1918                SINK.with(|slot| *slot.borrow_mut() = Some(Arc::clone(&sink)));
1919                Self(sink)
1920            }
1921
1922            pub(super) fn dump(&self) -> String {
1923                format!("{:?}", self.0.lock().unwrap())
1924            }
1925
1926            pub(super) fn value(&self, field: &str) -> Option<String> {
1927                self.0
1928                    .lock()
1929                    .unwrap()
1930                    .iter()
1931                    .rev()
1932                    .find(|(name, _)| name == field)
1933                    .map(|(_, value)| value.clone())
1934            }
1935        }
1936
1937        impl Drop for Recorder {
1938            fn drop(&mut self) {
1939                SINK.with(|slot| *slot.borrow_mut() = None);
1940            }
1941        }
1942    }
1943
1944    #[cfg(unix)]
1945    #[tokio::test]
1946    async fn span_records_the_subcommand_and_a_clean_outcome() {
1947        let recorder = recorder::Recorder::install();
1948
1949        let codex = Codex::builder()
1950            .binary("/bin/echo")
1951            .build()
1952            .expect("echo must exist");
1953        run_codex(&codex, vec!["exec".into()]).await.unwrap();
1954
1955        assert_eq!(recorder.value("subcommand").as_deref(), Some("exec"));
1956        assert_eq!(recorder.value("outcome").as_deref(), Some("ok"));
1957        assert_eq!(recorder.value("exit_code").as_deref(), Some("0"));
1958        assert!(recorder.value("duration_ms").is_some());
1959    }
1960
1961    /// The prompt must never reach the span. It is in argv, so recording the
1962    /// arguments would leak it into any host's logs.
1963    #[cfg(unix)]
1964    #[tokio::test]
1965    async fn span_does_not_carry_the_prompt() {
1966        let recorder = recorder::Recorder::install();
1967
1968        let codex = Codex::builder()
1969            .binary("/bin/echo")
1970            .build()
1971            .expect("echo must exist");
1972        run_codex(&codex, vec!["exec".into(), "a very secret prompt".into()])
1973            .await
1974            .unwrap();
1975
1976        assert!(!recorder.dump().contains("secret"), "{}", recorder.dump());
1977        assert!(recorder.value("binary").is_none());
1978        assert!(recorder.value("working_dir").is_none());
1979    }
1980
1981    /// A dropped future records an outcome rather than leaving the span open,
1982    /// so an abandoned run is distinguishable from one still in progress.
1983    #[cfg(unix)]
1984    #[tokio::test]
1985    async fn a_cancelled_run_is_recorded_as_cancelled() {
1986        let recorder = recorder::Recorder::install();
1987
1988        let pid_file = crate::test_support::PidFile::new("span-cancel");
1989        let codex = crate::test_support::blocking_codex(&pid_file)
1990            .build()
1991            .expect("bash must exist");
1992
1993        let cancelled = tokio::time::timeout(
1994            Duration::from_millis(300),
1995            run_codex(&codex, vec!["exec".into()]),
1996        )
1997        .await;
1998        assert!(cancelled.is_err(), "the run should still have been going");
1999
2000        assert_eq!(
2001            recorder.value("outcome").as_deref(),
2002            Some("cancelled"),
2003            "recorded: {}",
2004            recorder.dump()
2005        );
2006    }
2007
2008    /// A wrapper timeout is its own outcome, distinct from a caller
2009    /// cancelling: the run reached its deadline rather than being abandoned.
2010    #[cfg(unix)]
2011    #[tokio::test]
2012    async fn a_timed_out_run_is_recorded_as_timeout() {
2013        let recorder = recorder::Recorder::install();
2014
2015        let pid_file = crate::test_support::PidFile::new("span-timeout");
2016        let codex = crate::test_support::blocking_codex(&pid_file)
2017            .timeout(Duration::from_millis(300))
2018            .build()
2019            .expect("bash must exist");
2020
2021        let result = run_codex(&codex, vec!["exec".into()]).await;
2022        assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
2023
2024        assert_eq!(recorder.value("outcome").as_deref(), Some("timeout"));
2025    }
2026
2027    // -----------------------------------------------------------------
2028    // Bounded capture (#132)
2029    // -----------------------------------------------------------------
2030
2031    #[cfg(unix)]
2032    fn flooding_codex(stream: &str, limit: Option<usize>) -> Codex {
2033        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2034            .join("tests")
2035            .join("fake-codex-floods.sh");
2036        let mut builder = Codex::builder()
2037            .binary("/bin/bash")
2038            .arg(script.to_str().unwrap())
2039            .env("CODEX_WRAPPER_TEST_FLOOD_STREAM", stream);
2040        if let Some(max_bytes) = limit {
2041            builder = builder.output_limit(max_bytes);
2042        }
2043        builder.build().expect("bash must exist")
2044    }
2045
2046    /// The ceiling has to hold on a single unbroken line, or it is really
2047    /// just a line-length check that a runaway one-line writer defeats.
2048    #[cfg(unix)]
2049    #[tokio::test]
2050    async fn a_stream_past_the_ceiling_fails_without_carrying_its_bytes() {
2051        for stream in ["stdout", "stderr"] {
2052            let codex = flooding_codex(stream, Some(64 * 1024));
2053            let error = crate::ExecCommand::new("hello")
2054                .execute(&codex)
2055                .await
2056                .expect_err("the flood exceeds the ceiling");
2057
2058            let Error::OutputLimitExceeded {
2059                stream: reported,
2060                limit_bytes,
2061            } = error
2062            else {
2063                panic!("expected OutputLimitExceeded for {stream}, got {error:?}");
2064            };
2065            assert_eq!(reported.to_string(), stream);
2066            assert_eq!(limit_bytes, 64 * 1024);
2067
2068            // The captured bytes must not ride along in the error, or the
2069            // ceiling has bounded nothing.
2070            let error = Error::OutputLimitExceeded {
2071                stream: reported,
2072                limit_bytes,
2073            };
2074            let rendered = format!("{error} {error:?}");
2075            assert!(!rendered.contains("xxxxxxxx"), "{rendered}");
2076            assert!(rendered.len() < 512, "error text grew with the output");
2077        }
2078    }
2079
2080    /// Off by default, so adding the control changes nothing until a host
2081    /// asks for it. This is also the measurement of what the ceiling buys:
2082    /// the same child hands back a megabyte when nothing bounds it.
2083    #[cfg(unix)]
2084    #[tokio::test]
2085    async fn without_a_ceiling_the_whole_flood_is_captured() {
2086        let codex = flooding_codex("stdout", None);
2087        let result = crate::ExecCommand::new("hello")
2088            .execute(&codex)
2089            .await
2090            .expect("an unbounded capture succeeds, however large");
2091        assert_eq!(result.stdout.len(), 128 * 8192);
2092    }
2093
2094    /// A run that stays under its ceiling is untouched.
2095    #[cfg(unix)]
2096    #[tokio::test]
2097    async fn output_within_the_ceiling_is_returned_whole() {
2098        let codex = crate::test_support::stdin_echo_codex()
2099            .output_limit(64 * 1024)
2100            .build()
2101            .expect("bash must exist");
2102        let result = crate::ExecCommand::new("a short prompt")
2103            .execute(&codex)
2104            .await
2105            .expect("well under the ceiling");
2106        // Whole means whole: the last line of the stream has to survive, not
2107        // just the first, or the ceiling is silently truncating.
2108        assert!(
2109            result.stdout.contains("thread.started"),
2110            "{}",
2111            result.stdout
2112        );
2113        assert!(
2114            result.stdout.contains("turn.completed"),
2115            "{}",
2116            result.stdout
2117        );
2118    }
2119
2120    // -----------------------------------------------------------------
2121    // Classification end to end (#85)
2122    // -----------------------------------------------------------------
2123
2124    #[cfg(unix)]
2125    fn failing_codex(case: &str) -> Codex {
2126        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2127            .join("tests")
2128            .join("fake-codex-failure.sh");
2129        Codex::builder()
2130            .binary("/bin/bash")
2131            .arg(script.to_str().unwrap())
2132            .env("CODEX_WRAPPER_TEST_FAILURE", case)
2133            .build()
2134            .expect("bash must exist")
2135    }
2136
2137    /// Classification has to happen on the spawn path, not only in the
2138    /// constructor, or a caller still gets a bare CommandFailed.
2139    #[cfg(unix)]
2140    #[tokio::test]
2141    async fn a_real_spawn_returns_a_classified_error() {
2142        use crate::error::FailureKind;
2143
2144        for (case, expected) in [
2145            ("auth", FailureKind::Auth),
2146            ("not-trusted", FailureKind::NotTrustedDirectory),
2147            ("config", FailureKind::Config),
2148            ("session", FailureKind::SessionNotFound),
2149            ("mystery", FailureKind::Unclassified),
2150        ] {
2151            let codex = failing_codex(case);
2152            let err = run_codex(&codex, vec!["exec".into()]).await.unwrap_err();
2153            assert_eq!(err.failure_kind(), Some(expected), "case {case}: {err}");
2154        }
2155    }
2156
2157    /// A deterministic failure must not be retried even when its exit code is
2158    /// on the retry list. Re-running gets the same rejection, and the auth
2159    /// case has already been retried inside the CLI before it reaches here.
2160    #[cfg(unix)]
2161    #[tokio::test]
2162    async fn a_classified_failure_is_not_retried() {
2163        let policy = crate::retry::RetryPolicy::new()
2164            .max_attempts(3)
2165            .initial_backoff(Duration::from_millis(1))
2166            .retry_on_exit_codes([1]);
2167
2168        let started = Instant::now();
2169        let codex = failing_codex("auth");
2170        let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
2171            .await
2172            .unwrap_err();
2173
2174        assert!(matches!(err, Error::Auth { .. }), "{err}");
2175        // Three attempts with backoff would be visibly slower; this asserts
2176        // the shape rather than the timing, but the timing corroborates it.
2177        assert!(
2178            started.elapsed() < Duration::from_secs(2),
2179            "looks like it retried: {:?}",
2180            started.elapsed()
2181        );
2182    }
2183
2184    /// An unclassified failure keeps the old retry behaviour.
2185    #[cfg(unix)]
2186    #[tokio::test]
2187    async fn an_unclassified_failure_still_retries() {
2188        let policy = crate::retry::RetryPolicy::new()
2189            .max_attempts(2)
2190            .initial_backoff(Duration::from_millis(1))
2191            .retry_on_exit_codes([1]);
2192
2193        let codex = failing_codex("mystery");
2194        let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
2195            .await
2196            .unwrap_err();
2197
2198        assert!(matches!(err, Error::CommandFailed { .. }), "{err}");
2199    }
2200
2201    /// The allow-list works on the exit code, so it still applies to a
2202    /// failure that classification moved off CommandFailed.
2203    #[cfg(unix)]
2204    #[tokio::test]
2205    async fn allowed_exit_codes_still_apply_to_a_classified_failure() {
2206        let codex = failing_codex("auth");
2207        let output = run_codex_allow_exit_codes(&codex, vec!["exec".into()], &[1])
2208            .await
2209            .expect("exit code 1 was allowed");
2210
2211        assert_eq!(output.exit_code, 1);
2212        assert!(!output.success);
2213        assert!(
2214            output.stderr.contains("401 Unauthorized"),
2215            "{}",
2216            output.stderr
2217        );
2218    }
2219
2220    // -----------------------------------------------------------------
2221    // Process groups and cancellation (#78)
2222    // -----------------------------------------------------------------
2223
2224    /// A fake codex that spawns a child of its own, the way the real CLI does
2225    /// for tool use, and the pids of both.
2226    #[cfg(unix)]
2227    fn spawning_codex(label: &str) -> (Codex, crate::test_support::PidFile) {
2228        let pid_file = crate::test_support::PidFile::new(label);
2229        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2230            .join("tests")
2231            .join("fake-codex-spawns-child.sh");
2232        let codex = Codex::builder()
2233            .binary("/bin/bash")
2234            .arg(script.to_str().unwrap())
2235            .env(
2236                "CODEX_WRAPPER_TEST_PIDFILE",
2237                pid_file.path().to_str().unwrap(),
2238            )
2239            .build()
2240            .expect("bash must exist");
2241        (codex, pid_file)
2242    }
2243
2244    #[cfg(unix)]
2245    async fn read_pids(pid_file: &crate::test_support::PidFile) -> (u32, u32) {
2246        for _ in 0..200 {
2247            if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
2248                let parse = |prefix: &str| -> Option<u32> {
2249                    contents
2250                        .lines()
2251                        .find_map(|l| l.strip_prefix(prefix))
2252                        .and_then(|v| v.trim().parse().ok())
2253                };
2254                if let (Some(parent), Some(child)) = (parse("parent="), parse("child=")) {
2255                    return (parent, child);
2256                }
2257            }
2258            tokio::time::sleep(Duration::from_millis(10)).await;
2259        }
2260        panic!("the fake codex never recorded both pids");
2261    }
2262
2263    /// The point of #78. `kill_on_drop` reaps the direct child only, so before
2264    /// process groups the grandchild outlived a cancelled run.
2265    #[cfg(unix)]
2266    #[tokio::test]
2267    async fn cancelling_kills_the_whole_process_group() {
2268        use crate::test_support::wait_until_gone;
2269
2270        let (codex, pid_file) = spawning_codex("group-drop");
2271
2272        let cancelled = tokio::time::timeout(
2273            Duration::from_millis(400),
2274            run_codex(&codex, vec!["exec".into()]),
2275        )
2276        .await;
2277        assert!(cancelled.is_err(), "the run should still have been going");
2278
2279        let (parent, child) = read_pids(&pid_file).await;
2280        assert!(wait_until_gone(parent).await, "codex ({parent}) survived");
2281        assert!(
2282            wait_until_gone(child).await,
2283            "the subprocess ({child}) survived the cancelled run"
2284        );
2285    }
2286
2287    /// The graceful path: SIGTERM, a grace period, then SIGKILL. It cannot
2288    /// live in `Drop`, which is why there is an explicit entry point.
2289    #[cfg(unix)]
2290    #[tokio::test]
2291    async fn run_codex_cancellable_stops_the_group_gracefully() {
2292        use crate::test_support::is_running_for_test;
2293
2294        let (codex, pid_file) = spawning_codex("group-cancel");
2295        let codex = Codex::builder()
2296            .binary(codex.binary())
2297            .arg(
2298                std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2299                    .join("tests")
2300                    .join("fake-codex-spawns-child.sh")
2301                    .to_str()
2302                    .unwrap(),
2303            )
2304            .env(
2305                "CODEX_WRAPPER_TEST_PIDFILE",
2306                pid_file.path().to_str().unwrap(),
2307            )
2308            .termination_grace(Duration::from_millis(50))
2309            .build()
2310            .unwrap();
2311
2312        let cancel = async {
2313            tokio::time::sleep(Duration::from_millis(300)).await;
2314        };
2315        let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel).await;
2316
2317        assert!(
2318            matches!(result, Err(Error::Cancelled { .. })),
2319            "expected a cancellation, got: {result:?}"
2320        );
2321
2322        let (parent, child) = read_pids(&pid_file).await;
2323        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2324        assert!(
2325            !is_running_for_test(child),
2326            "the subprocess ({child}) survived cancellation"
2327        );
2328    }
2329
2330    #[cfg(unix)]
2331    #[tokio::test]
2332    async fn dropping_during_cancellation_grace_kills_the_group() {
2333        let fixture = crate::test_support::GracePeriodFixture::new("buffered-cancel-grace-drop");
2334        let codex = fixture.builder().build().unwrap();
2335        fixture
2336            .assert_drop_during_grace(run_codex_cancellable(
2337                &codex,
2338                vec!["exec".into()],
2339                fixture.ready(),
2340            ))
2341            .await;
2342    }
2343
2344    #[cfg(unix)]
2345    #[tokio::test]
2346    async fn dropping_during_timeout_grace_kills_the_group() {
2347        let fixture = crate::test_support::GracePeriodFixture::new("buffered-timeout-grace-drop");
2348        let codex = fixture
2349            .builder()
2350            .timeout(Duration::from_secs(2))
2351            .build()
2352            .unwrap();
2353        fixture
2354            .assert_drop_during_grace(run_codex(&codex, vec!["exec".into()]))
2355            .await;
2356    }
2357
2358    #[cfg(unix)]
2359    #[tokio::test]
2360    async fn default_shutdown_still_sends_term_and_drains_both_pipes() {
2361        let fixture = crate::test_support::InterruptFixture::new("default-term-drain");
2362        let codex = fixture.builder().build().unwrap();
2363        let result =
2364            run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()).await;
2365        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2366        assert!(fixture.marker(".term").exists());
2367        assert!(!fixture.marker(".int").exists());
2368        assert!(
2369            fixture.marker(".cleaned").exists(),
2370            "shutdown output blocked cleanup"
2371        );
2372        fixture.assert_stopped().await;
2373    }
2374
2375    #[cfg(unix)]
2376    #[tokio::test]
2377    async fn interrupt_cancellation_drains_large_shutdown_output_and_cleans_detached_tool() {
2378        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drain");
2379        let codex = fixture
2380            .builder()
2381            .termination_signal(crate::TerminationSignal::Interrupt)
2382            // The shutdown output must not be captured against this limit.
2383            .output_limit(64)
2384            .build()
2385            .unwrap();
2386        let result = run_codex_with_stdin_prompt_cancellable(
2387            &codex,
2388            vec!["exec".into(), "-".into()],
2389            "prompt",
2390            fixture.detached_ready(),
2391        )
2392        .await;
2393        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2394        assert!(fixture.marker(".int").exists());
2395        assert!(!fixture.marker(".term").exists());
2396        assert!(
2397            fixture.marker(".cleaned").exists(),
2398            "shutdown output blocked cleanup"
2399        );
2400        fixture.assert_stopped().await;
2401    }
2402
2403    #[cfg(unix)]
2404    #[tokio::test]
2405    async fn interrupt_timeout_keeps_timeout_error_after_cooperative_exit() {
2406        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-timeout");
2407        let codex = fixture
2408            .builder()
2409            .termination_signal(crate::TerminationSignal::Interrupt)
2410            .timeout(Duration::from_secs(1))
2411            .build()
2412            .unwrap();
2413        let run = run_codex(&codex, vec!["exec".into()]);
2414        tokio::pin!(run);
2415        tokio::select! {
2416            result = &mut run => panic!("run ended before readiness: {result:?}"),
2417            () = fixture.detached_ready() => {}
2418        }
2419        let result = run.await;
2420        assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
2421        assert!(fixture.marker(".int").exists());
2422        assert!(fixture.marker(".cleaned").exists());
2423        fixture.assert_stopped().await;
2424    }
2425
2426    #[cfg(unix)]
2427    #[tokio::test]
2428    async fn interrupt_ignored_uses_bounded_hard_fallback() {
2429        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-ignored");
2430        let codex = fixture
2431            .builder()
2432            .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
2433            .termination_signal(crate::TerminationSignal::Interrupt)
2434            .termination_grace(Duration::from_millis(100))
2435            .build()
2436            .unwrap();
2437        let result = tokio::time::timeout(
2438            Duration::from_secs(3),
2439            run_codex_cancellable(&codex, vec!["exec".into()], fixture.ready()),
2440        )
2441        .await
2442        .expect("hard fallback exceeded the grace budget");
2443        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2444        assert!(fixture.marker(".int").exists());
2445        assert!(!fixture.marker(".cleaned").exists());
2446        fixture.assert_stopped().await;
2447    }
2448
2449    #[cfg(unix)]
2450    #[tokio::test]
2451    async fn dropping_during_interrupt_grace_kills_immediately() {
2452        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drop");
2453        let codex = fixture
2454            .builder()
2455            .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
2456            .termination_signal(crate::TerminationSignal::Interrupt)
2457            .termination_grace(Duration::from_secs(30))
2458            .build()
2459            .unwrap();
2460        let mut run = Box::pin(run_codex_cancellable(
2461            &codex,
2462            vec!["exec".into()],
2463            fixture.ready(),
2464        ));
2465        tokio::select! {
2466            result = &mut run => panic!("run ended before its grace period: {result:?}"),
2467            () = fixture.wait_for(".int") => {}
2468        }
2469        drop(run);
2470        fixture.assert_stopped().await;
2471    }
2472
2473    #[cfg(unix)]
2474    #[tokio::test]
2475    async fn process_group_optout_skips_interrupt_and_grace() {
2476        let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-optout");
2477        let codex = fixture
2478            .builder()
2479            .process_group(false)
2480            .termination_signal(crate::TerminationSignal::Interrupt)
2481            .termination_grace(Duration::from_secs(30))
2482            .build()
2483            .unwrap();
2484        let result = tokio::time::timeout(
2485            Duration::from_secs(3),
2486            run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()),
2487        )
2488        .await
2489        .expect("optout must not wait through the grace period");
2490        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2491        assert!(!fixture.marker(".int").exists());
2492        assert!(!fixture.marker(".term").exists());
2493        let (parent, child) = fixture.pids().unwrap();
2494        assert!(crate::test_support::wait_until_gone(parent).await);
2495        assert!(crate::test_support::is_running_for_test(child));
2496        // Fixture Drop cleans the deliberately surviving detached child.
2497    }
2498
2499    /// Buffered timeout uses the same settled process-group cleanup as an
2500    /// explicit cancellation signal.
2501    #[cfg(unix)]
2502    #[tokio::test]
2503    async fn timeout_stops_the_group_before_returning() {
2504        use crate::test_support::is_running_for_test;
2505
2506        let pid_file = crate::test_support::PidFile::new("group-timeout-settled");
2507        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2508            .join("tests")
2509            .join("fake-codex-spawns-child.sh");
2510        let codex = Codex::builder()
2511            .binary("/bin/bash")
2512            .arg(script.to_str().unwrap())
2513            .env(
2514                "CODEX_WRAPPER_TEST_PIDFILE",
2515                pid_file.path().to_str().unwrap(),
2516            )
2517            .timeout(Duration::from_millis(300))
2518            .termination_grace(Duration::from_millis(10))
2519            .build()
2520            .unwrap();
2521
2522        let result = run_codex(&codex, vec!["exec".into()]).await;
2523        assert!(
2524            matches!(result, Err(Error::Timeout { .. })),
2525            "expected a timeout, got: {result:?}"
2526        );
2527
2528        let (parent, child) = read_pids(&pid_file).await;
2529        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2530        assert!(
2531            !is_running_for_test(child),
2532            "the subprocess ({child}) survived the timeout"
2533        );
2534    }
2535
2536    /// A broken stdin pipe is terminal only after the owned process group has been
2537    /// stopped. Returning the write error first would release the caller while
2538    /// the provider could still mutate the workspace.
2539    #[cfg(unix)]
2540    #[tokio::test]
2541    async fn stdin_write_failure_stops_and_reaps_before_returning() {
2542        use crate::test_support::is_running_for_test;
2543
2544        let pid_file = crate::test_support::PidFile::new("stdin-write-failure");
2545        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2546            .join("tests")
2547            .join("fake-codex-closes-stdin-spawns-child.sh");
2548        let codex = Codex::builder()
2549            .binary("/bin/bash")
2550            .arg(script.to_str().unwrap())
2551            .env(
2552                "CODEX_WRAPPER_TEST_PIDFILE",
2553                pid_file.path().to_str().unwrap(),
2554            )
2555            .termination_grace(Duration::from_millis(10))
2556            .build()
2557            .unwrap();
2558
2559        let prompt = "x".repeat(4 * 1024 * 1024);
2560        let result = run_codex_with_stdin_prompt(
2561            &codex,
2562            crate::ExecCommand::from_stdin(&prompt).args(),
2563            &prompt,
2564        )
2565        .await;
2566        assert!(
2567            matches!(result, Err(Error::Io { ref message, .. }) if message.contains("stdin")),
2568            "expected a stdin error, got: {result:?}"
2569        );
2570
2571        let (parent, child) = read_pids(&pid_file).await;
2572        assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2573        assert!(
2574            !is_running_for_test(child),
2575            "the subprocess ({child}) survived the stdin failure"
2576        );
2577    }
2578
2579    // -----------------------------------------------------------------
2580    // Failed cleanup is not reported as a settled stop
2581    //
2582    // These inject the cleanup result after the real termination and wait
2583    // have run, so they cover how a failure is reported, not that one occurs.
2584    // The real-child tests above remain the evidence for normal reaping.
2585    // -----------------------------------------------------------------
2586
2587    /// The stop reason inside a [`Error::CleanupFailed`] whose cleanup half
2588    /// is the injected failure, not some other error.
2589    #[cfg(unix)]
2590    fn injected_cleanup_reason(result: Result<CommandOutput>) -> Error {
2591        match result {
2592            Err(Error::CleanupFailed { reason, cleanup }) => {
2593                assert!(
2594                    cleanup.to_string().contains("injected cleanup failure"),
2595                    "{cleanup:?}"
2596                );
2597                *reason
2598            }
2599            other => panic!("expected CleanupFailed, got {other:?}"),
2600        }
2601    }
2602
2603    #[cfg(unix)]
2604    #[tokio::test]
2605    async fn failed_cleanup_after_cancellation_is_not_a_bare_cancel() {
2606        let pid_file = crate::test_support::PidFile::new("cleanup-failed-cancel");
2607        let codex = crate::test_support::blocking_codex(&pid_file)
2608            .termination_grace(Duration::from_millis(10))
2609            .build()
2610            .unwrap();
2611        let cancel_soon = || tokio::time::sleep(Duration::from_millis(100));
2612
2613        let injection = CleanupFailureInjection::arm();
2614        let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
2615        let reason = injected_cleanup_reason(result);
2616        assert!(matches!(reason, Error::Cancelled { .. }), "{reason:?}");
2617
2618        // The same run with cleanup succeeding keeps the bare typed reason.
2619        drop(injection);
2620        let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
2621        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2622    }
2623
2624    /// The timeout stays readable as the reason, the span does not record a
2625    /// settled timeout, and a policy that retries timeouts does not start a
2626    /// second process while the first is not known to be gone.
2627    #[cfg(unix)]
2628    #[tokio::test]
2629    async fn failed_cleanup_after_timeout_is_recorded_and_not_retried() {
2630        use std::sync::Arc;
2631        use std::sync::atomic::{AtomicUsize, Ordering};
2632
2633        let recorder = recorder::Recorder::install();
2634        let spawns = Arc::new(AtomicUsize::new(0));
2635        let counted = Arc::clone(&spawns);
2636        let pid_file = crate::test_support::PidFile::new("cleanup-failed-timeout");
2637        let codex = crate::test_support::blocking_codex(&pid_file)
2638            .timeout(Duration::from_millis(200))
2639            .termination_grace(Duration::from_millis(10))
2640            .on_spawn(Arc::new(move |_| {
2641                counted.fetch_add(1, Ordering::SeqCst);
2642            }))
2643            .build()
2644            .unwrap();
2645        let policy = crate::retry::RetryPolicy::new()
2646            .max_attempts(3)
2647            .initial_backoff(Duration::from_millis(1))
2648            .retry_on_timeout(true);
2649
2650        let _injection = CleanupFailureInjection::arm();
2651        let result = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy)).await;
2652        let reason = injected_cleanup_reason(result);
2653        assert!(matches!(reason, Error::Timeout { .. }), "{reason:?}");
2654        assert_eq!(spawns.load(Ordering::SeqCst), 1, "a timeout was retried");
2655        assert_eq!(
2656            recorder.value("outcome").as_deref(),
2657            Some("cleanup_failed"),
2658            "recorded: {}",
2659            recorder.dump()
2660        );
2661    }
2662
2663    /// The run's own error branch, as opposed to a stop signal, goes through
2664    /// the same construction.
2665    #[cfg(unix)]
2666    #[tokio::test]
2667    async fn failed_cleanup_after_an_output_limit_keeps_the_limit_as_reason() {
2668        let codex = flooding_codex("stdout", Some(64 * 1024));
2669
2670        let injection = CleanupFailureInjection::arm();
2671        let result = run_codex(&codex, vec!["exec".into()]).await;
2672        let reason = injected_cleanup_reason(result);
2673        assert!(
2674            matches!(
2675                reason,
2676                Error::OutputLimitExceeded {
2677                    stream: OutputStream::Stdout,
2678                    limit_bytes: 65_536,
2679                }
2680            ),
2681            "{reason:?}"
2682        );
2683
2684        drop(injection);
2685        let result = run_codex(&codex, vec!["exec".into()]).await;
2686        assert!(
2687            matches!(result, Err(Error::OutputLimitExceeded { .. })),
2688            "{result:?}"
2689        );
2690    }
2691
2692    /// A run that finishes before the signal must not be reported as
2693    /// cancelled, and must not be killed on the way out.
2694    #[cfg(unix)]
2695    #[tokio::test]
2696    async fn a_run_that_finishes_first_is_not_cancelled() {
2697        let codex = Codex::builder()
2698            .binary("/bin/echo")
2699            .build()
2700            .expect("echo must exist");
2701
2702        let never = std::future::pending::<()>();
2703        let output = run_codex_cancellable(&codex, vec!["exec".into()], never)
2704            .await
2705            .unwrap();
2706        assert!(output.success);
2707    }
2708
2709    #[cfg(unix)]
2710    #[tokio::test]
2711    async fn spawn_observer_reports_each_buffered_child_before_returning() {
2712        use std::sync::{Arc, Mutex};
2713
2714        let seen = Arc::new(Mutex::new(Vec::new()));
2715        let sink = Arc::clone(&seen);
2716        let codex = Codex::builder()
2717            .binary("/bin/echo")
2718            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2719            .build()
2720            .expect("echo must exist");
2721
2722        let output = run_codex(&codex, vec!["probe".into()]).await.unwrap();
2723        let seen = seen.lock().unwrap();
2724        assert_eq!(seen.len(), 1);
2725        assert!(seen[0].pid > 0);
2726        assert_eq!(seen[0].pgid, Some(seen[0].pid));
2727        assert!(output.stdout.contains("probe"));
2728    }
2729
2730    #[cfg(unix)]
2731    #[tokio::test]
2732    async fn spawn_receipt_never_claims_a_shared_group() {
2733        use std::sync::{Arc, Mutex};
2734
2735        let seen = Arc::new(Mutex::new(Vec::new()));
2736        let sink = Arc::clone(&seen);
2737        let codex = Codex::builder()
2738            .binary("/bin/echo")
2739            .process_group(false)
2740            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2741            .build()
2742            .expect("echo must exist");
2743
2744        run_codex(&codex, vec!["probe".into()]).await.unwrap();
2745        assert_eq!(seen.lock().unwrap()[0].pgid, None);
2746    }
2747
2748    #[test]
2749    fn parent_death_support_matches_the_target() {
2750        assert_eq!(die_with_parent_supported(), cfg!(target_os = "linux"));
2751    }
2752
2753    #[cfg(unix)]
2754    #[tokio::test]
2755    async fn parent_death_policy_composes_with_spawn_observation() {
2756        use std::sync::{Arc, Mutex};
2757
2758        let seen = Arc::new(Mutex::new(Vec::new()));
2759        let sink = Arc::clone(&seen);
2760        let codex = Codex::builder()
2761            .binary("/bin/echo")
2762            .die_with_parent(true)
2763            .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2764            .build()
2765            .expect("echo must exist");
2766
2767        run_codex(&codex, vec!["probe".into()]).await.unwrap();
2768        assert_eq!(seen.lock().unwrap().len(), 1);
2769    }
2770
2771    const PDEATHSIG_HELPER_ENV: &str = "CODEX_WRAPPER_PDEATHSIG_HELPER";
2772
2773    #[test]
2774    fn pdeathsig_helper_process() {
2775        if std::env::var(PDEATHSIG_HELPER_ENV).is_err() {
2776            return;
2777        }
2778        use std::io::Write;
2779        use std::sync::Arc;
2780
2781        let codex = Codex::builder()
2782            .binary("/bin/sleep")
2783            .die_with_parent(true)
2784            .on_spawn(Arc::new(|info| {
2785                println!("PID {}", info.pid);
2786                let _ = std::io::stdout().flush();
2787            }))
2788            .build()
2789            .unwrap();
2790        let runtime = tokio::runtime::Builder::new_current_thread()
2791            .enable_all()
2792            .build()
2793            .unwrap();
2794        let _ = runtime.block_on(run_codex(&codex, vec!["300".into()]));
2795    }
2796
2797    #[cfg(target_os = "linux")]
2798    #[test]
2799    fn child_dies_when_its_parent_is_sigkilled() {
2800        use std::io::{BufRead, BufReader};
2801        use std::process::{Command, Stdio};
2802
2803        let executable = std::env::current_exe().expect("test binary path");
2804        let mut helper = Command::new(executable)
2805            .args([
2806                "--exact",
2807                "exec::tests::pdeathsig_helper_process",
2808                "--nocapture",
2809            ])
2810            .env(PDEATHSIG_HELPER_ENV, "1")
2811            .stdout(Stdio::piped())
2812            .spawn()
2813            .expect("spawn helper");
2814        let stdout = helper.stdout.take().expect("piped stdout");
2815        let pid = BufReader::new(stdout)
2816            .lines()
2817            .map_while(std::result::Result::ok)
2818            .find_map(|line| line.strip_prefix("PID ").and_then(|pid| pid.parse().ok()))
2819            .expect("helper reported child pid");
2820
2821        // SAFETY: this deliberately simulates an uncatchable supervisor crash.
2822        unsafe { libc::kill(helper.id() as i32, libc::SIGKILL) };
2823        let _ = helper.wait();
2824
2825        for _ in 0..50 {
2826            if !crate::test_support::is_running_for_test(pid) {
2827                return;
2828            }
2829            std::thread::sleep(Duration::from_millis(100));
2830        }
2831        panic!("child {pid} survived its SIGKILLed parent");
2832    }
2833
2834    /// Opting out is not cosmetic: without a group of its own, cancelling
2835    /// reaches the direct child only and its subprocesses survive. That is the
2836    /// terminal-attached contract, where the terminal is the supervisor and
2837    /// Ctrl-C reaches the whole run directly instead.
2838    #[cfg(unix)]
2839    #[tokio::test]
2840    async fn opting_out_of_process_groups_leaves_the_subprocess() {
2841        use crate::test_support::wait_until_gone;
2842
2843        let pid_file = crate::test_support::PidFile::new("group-optout");
2844        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2845            .join("tests")
2846            .join("fake-codex-spawns-child.sh");
2847        let codex = Codex::builder()
2848            .binary("/bin/bash")
2849            .arg(script.to_str().unwrap())
2850            .env(
2851                "CODEX_WRAPPER_TEST_PIDFILE",
2852                pid_file.path().to_str().unwrap(),
2853            )
2854            .process_group(false)
2855            .build()
2856            .expect("bash must exist");
2857
2858        let cancelled = tokio::time::timeout(
2859            Duration::from_millis(400),
2860            run_codex(&codex, vec!["exec".into()]),
2861        )
2862        .await;
2863        assert!(cancelled.is_err(), "the run should still have been going");
2864
2865        let (parent, child) = read_pids(&pid_file).await;
2866        assert!(
2867            wait_until_gone(parent).await,
2868            "kill_on_drop still reaps the direct child ({parent})"
2869        );
2870        // The point of the contrast with
2871        // `cancelling_kills_the_whole_process_group`.
2872        assert!(
2873            crate::test_support::is_running_for_test(child),
2874            "with groups off, the subprocess ({child}) is expected to survive"
2875        );
2876        // Do not leave it behind.
2877        signal_group(child, libc::SIGKILL);
2878        unsafe { libc::kill(i32::try_from(child).unwrap_or(0), libc::SIGKILL) };
2879    }
2880    #[cfg(unix)]
2881    struct PrivateTraceDir(std::path::PathBuf);
2882
2883    #[cfg(unix)]
2884    impl Drop for PrivateTraceDir {
2885        fn drop(&mut self) {
2886            let _ = std::fs::remove_dir_all(&self.0);
2887        }
2888    }
2889
2890    #[cfg(unix)]
2891    fn private_trace_client(body: &str) -> (PrivateTraceDir, Codex) {
2892        use std::os::unix::fs::symlink;
2893        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2894        let name = format!(
2895            "TRACE_PRIVATE_path-{}-{}-{}",
2896            std::process::id(),
2897            std::time::SystemTime::now()
2898                .duration_since(std::time::UNIX_EPOCH)
2899                .unwrap()
2900                .as_nanos(),
2901            NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2902        );
2903        let dir = PrivateTraceDir(std::env::temp_dir().join(name));
2904        std::fs::create_dir(&dir.0).unwrap();
2905        let binary = dir.0.join("TRACE_PRIVATE_binary");
2906        symlink("/bin/bash", &binary).unwrap();
2907        let script = dir.0.join("TRACE_PRIVATE_script");
2908        std::fs::write(&script, body).unwrap();
2909        let codex = Codex::builder()
2910            .binary(binary)
2911            .arg(script.to_string_lossy())
2912            .arg("TRACE_PRIVATE_config")
2913            .working_dir(&dir.0)
2914            .termination_grace(Duration::ZERO)
2915            .build()
2916            .unwrap();
2917        (dir, codex)
2918    }
2919
2920    #[cfg(unix)]
2921    #[tokio::test]
2922    async fn invocation_traces_exclude_private_content_at_every_level() {
2923        let recorder = recorder::Recorder::install();
2924        let body = concat!(
2925            "cat >/dev/null\n",
2926            "printf 'TRACE_PRIVATE_output'\n",
2927            "printf 'TRACE_PRIVATE_stderr' >&2\n"
2928        );
2929        let (_dir, codex) = private_trace_client(body);
2930        let args = vec![
2931            "exec".into(),
2932            "TRACE_PRIVATE_prompt".into(),
2933            "--resume".into(),
2934            "TRACE_PRIVATE_resume".into(),
2935        ];
2936        assert!(
2937            run_codex(&codex, args.clone())
2938                .await
2939                .unwrap()
2940                .stdout
2941                .contains("TRACE_PRIVATE")
2942        );
2943        run_codex_cancellable(&codex, args.clone(), std::future::pending())
2944            .await
2945            .unwrap();
2946        run_codex_with_stdin_prompt(&codex, args.clone(), "TRACE_PRIVATE_stdin")
2947            .await
2948            .unwrap();
2949        run_codex_with_stdin_prompt_cancellable(
2950            &codex,
2951            args,
2952            "TRACE_PRIVATE_stdin",
2953            std::future::pending(),
2954        )
2955        .await
2956        .unwrap();
2957        run_codex(&codex, vec!["TRACE_PRIVATE_unknown_command".into()])
2958            .await
2959            .unwrap();
2960        assert!(
2961            recorder.value("outcome").is_some(),
2962            "subscriber must observe outcomes"
2963        );
2964        assert!(
2965            !recorder.dump().contains("TRACE_PRIVATE"),
2966            "{}",
2967            recorder.dump()
2968        );
2969        assert!(
2970            recorder.value("arg_count").is_some(),
2971            "useful argument count remains available"
2972        );
2973    }
2974
2975    #[cfg(all(unix, feature = "json"))]
2976    #[tokio::test]
2977    async fn stream_and_resume_traces_exclude_private_content() {
2978        use crate::{CodexCommand, ExecCommand, ExecResumeCommand};
2979        let recorder = recorder::Recorder::install();
2980        // Existing verified wire shapes, with synthetic content and identifiers.
2981        let body = format!(
2982            "cat >/dev/null\n{}",
2983            include_str!("../tests/fake-codex.sh")
2984                .replace("thread_test", "TRACE_PRIVATE_thread")
2985                .replace("hello", "TRACE_PRIVATE_output")
2986        );
2987        let (_dir, codex) = private_trace_client(&body);
2988        let cmd = ExecCommand::new("TRACE_PRIVATE_prompt");
2989        let mut observed = 0;
2990        crate::streaming::stream_exec(&codex, &cmd, |_| observed += 1)
2991            .await
2992            .unwrap();
2993        crate::streaming::stream_exec_cancellable(&codex, &cmd, std::future::pending(), |_| {})
2994            .await
2995            .unwrap();
2996        let stdin_cmd = ExecCommand::new("TRACE_PRIVATE_stdin").prompt_via_stdin();
2997        crate::streaming::stream_exec(&codex, &stdin_cmd, |_| {})
2998            .await
2999            .unwrap();
3000        let resume = ExecResumeCommand::new()
3001            .session_id("TRACE_PRIVATE_resume")
3002            .prompt("TRACE_PRIVATE_prompt");
3003        crate::streaming::stream_exec_resume(&codex, &resume, |_| {})
3004            .await
3005            .unwrap();
3006        crate::streaming::stream_exec_resume_cancellable(
3007            &codex,
3008            &resume,
3009            std::future::pending(),
3010            |_| {},
3011        )
3012        .await
3013        .unwrap();
3014        assert!(observed > 0, "protocol delivery remains intact");
3015        assert!(
3016            cmd.to_command_string(&codex).contains("TRACE_PRIVATE"),
3017            "explicit preview stays caller-controlled"
3018        );
3019        assert!(
3020            !recorder.dump().contains("TRACE_PRIVATE"),
3021            "{}",
3022            recorder.dump()
3023        );
3024    }
3025
3026    #[cfg(unix)]
3027    #[tokio::test]
3028    async fn failure_and_retry_traces_exclude_rendered_errors_and_output() {
3029        let recorder = recorder::Recorder::install();
3030        let (_dir, mut codex) = private_trace_client(
3031            "printf 'TRACE_PRIVATE_output'; printf 'TRACE_PRIVATE_stderr' >&2; exit 7",
3032        );
3033        codex.retry_policy = Some(
3034            crate::RetryPolicy::new()
3035                .max_attempts(2)
3036                .initial_backoff(Duration::ZERO)
3037                .retry_on_exit_codes([7]),
3038        );
3039        let error = run_codex(&codex, vec!["exec".into(), "TRACE_PRIVATE_prompt".into()])
3040            .await
3041            .unwrap_err();
3042        assert!(
3043            error.to_string().contains("TRACE_PRIVATE"),
3044            "explicit error retains diagnostics"
3045        );
3046        codex.retry_policy = None;
3047        codex.output_limit = Some(8);
3048        assert!(matches!(
3049            run_codex(&codex, vec!["exec".into()]).await,
3050            Err(Error::OutputLimitExceeded { .. })
3051        ));
3052        assert!(
3053            !recorder.dump().contains("TRACE_PRIVATE"),
3054            "{}",
3055            recorder.dump()
3056        );
3057        assert!(
3058            recorder.value("attempt").is_some(),
3059            "retry event must be captured"
3060        );
3061    }
3062
3063    #[cfg(all(unix, feature = "app-server"))]
3064    #[tokio::test]
3065    async fn app_server_startup_trace_excludes_private_arguments() {
3066        let recorder = recorder::Recorder::install();
3067        let codex = Codex::builder()
3068            .binary("/bin/false")
3069            .arg("TRACE_PRIVATE_configuration")
3070            .build()
3071            .unwrap();
3072        assert!(
3073            crate::app_server::AppServer::builder(&codex)
3074                .start()
3075                .await
3076                .is_err()
3077        );
3078        assert!(
3079            !recorder.dump().contains("TRACE_PRIVATE"),
3080            "{}",
3081            recorder.dump()
3082        );
3083        assert!(
3084            recorder.value("arg_count").is_some(),
3085            "startup event must be captured"
3086        );
3087    }
3088    #[cfg(unix)]
3089    #[tokio::test]
3090    async fn output_limit_trace_omits_captured_prefix() {
3091        let recorder = recorder::Recorder::install();
3092        // Separate writes let the reader retain a prefix before the breach.
3093        let (_dir, mut codex) = private_trace_client(
3094            "printf 'TRACE_PRIVATE_output'; sleep 0.05; head -c 4096 /dev/zero",
3095        );
3096        codex.output_limit = Some(64);
3097        assert!(matches!(
3098            run_codex(&codex, vec!["exec".into()]).await,
3099            Err(Error::OutputLimitExceeded { .. })
3100        ));
3101        assert!(
3102            recorder.value("captured_bytes").is_some(),
3103            "capture warning was observed"
3104        );
3105        assert!(
3106            !recorder.dump().contains("TRACE_PRIVATE"),
3107            "{}",
3108            recorder.dump()
3109        );
3110    }
3111}