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