codex-wrapper 0.5.3

A type-safe Codex CLI wrapper for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Helpers for the unix-only process-lifetime tests in [`crate::exec`] and
//! [`crate::streaming`].
//!
//! Those tests assert that a spawned `codex` dies when the future driving it
//! is dropped, which means observing the process from outside the wrapper: the
//! fake codex records its PID to a file, and the test reads that PID back and
//! watches it disappear.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use crate::{Codex, CodexBuilder};

/// A pipe writer deliberately made inheritable for the descriptor probes.
#[cfg(not(target_os = "fuchsia"))]
pub(crate) fn inheritable_pipe_writer() -> std::os::fd::OwnedFd {
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};

    let (_, writer) = std::io::pipe().unwrap();
    // Keep the probe away from Bash's low-numbered temporary descriptors.
    // SAFETY: writer is live and fcntl returns a new descriptor on success.
    let fd = unsafe { libc::fcntl(writer.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 64) };
    assert!(fd >= 64, "dup failed: {}", std::io::Error::last_os_error());
    // SAFETY: the successful duplication gave us an unowned descriptor.
    let writer = unsafe { OwnedFd::from_raw_fd(fd) };
    // SAFETY: writer keeps fd live and F_SETFD accepts an integer flag mask.
    let result = unsafe { libc::fcntl(writer.as_raw_fd(), libc::F_SETFD, 0) };
    assert_eq!(
        result,
        0,
        "fcntl failed: {}",
        std::io::Error::last_os_error()
    );
    writer
}

pub(crate) fn stdin_echo_codex() -> CodexBuilder {
    let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake-codex-echo-stdin.sh");
    Codex::builder()
        .binary("/bin/bash")
        .arg(script.to_str().unwrap())
}

/// A file that the fake codex writes its PID to, cleaned up on drop.
pub(crate) struct PidFile {
    path: PathBuf,
}

/// Environment markers recorded by the fake Codex child, cleaned up on
/// drop. Each caller supplies a unique label because unit tests share a pid.
pub(crate) struct EnvCapture {
    path: PathBuf,
}

impl EnvCapture {
    pub(crate) fn new(label: &str) -> Self {
        let path =
            std::env::temp_dir().join(format!("codex-wrapper-{}-{label}.env", std::process::id()));
        let _ = std::fs::remove_file(&path);
        Self { path }
    }

    pub(crate) fn read(&self) -> std::collections::BTreeMap<String, String> {
        let contents = std::fs::read_to_string(&self.path)
            .unwrap_or_else(|e| panic!("failed to read {}: {e}", self.path.display()));
        contents
            .lines()
            .filter_map(|line| {
                let (key, value) = line.split_once('=')?;
                Some((key.to_string(), value.to_string()))
            })
            .collect()
    }
}

impl Drop for EnvCapture {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

/// A [`Codex`] builder backed by a fake binary that records test-specific
/// environment markers and then emits valid JSONL for streaming callers.
pub(crate) fn env_capturing_codex(capture: &EnvCapture) -> CodexBuilder {
    let script = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fake-codex-capture-env.sh");
    Codex::builder()
        .binary("/bin/bash")
        .arg(script.to_str().expect("fixture path is utf-8"))
        .env_remove("CODEX_WRAPPER_EXPLICIT")
        .env(
            "CODEX_WRAPPER_ENV_CAPTURE",
            capture.path.to_str().expect("capture path is utf-8"),
        )
}

impl PidFile {
    /// Reserve a PID file path. `label` distinguishes concurrent tests, which
    /// share a process ID because cargo runs them as threads.
    pub(crate) fn new(label: &str) -> Self {
        let path =
            std::env::temp_dir().join(format!("codex-wrapper-{}-{label}.pid", std::process::id()));
        let _ = std::fs::remove_file(&path);
        Self { path }
    }

    pub(crate) fn path(&self) -> &Path {
        &self.path
    }

    /// Read back the PID the fake codex recorded, waiting up to a second for
    /// it to appear. Panics rather than returning an error: no PID means the
    /// fake never ran, which makes the calling test meaningless.
    pub(crate) async fn read_pid(&self) -> u32 {
        for _ in 0..100 {
            if let Ok(contents) = std::fs::read_to_string(&self.path)
                && let Ok(pid) = contents.trim().parse()
            {
                return pid;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        panic!("fake codex never recorded a pid at {}", self.path.display());
    }
}

impl Drop for PidFile {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

/// A [`Codex`] client whose binary is a fake codex that blocks until killed,
/// recording its PID to `pid_file` first.
///
/// Returned as a builder so callers can decide whether the run carries a
/// wrapper timeout or is cancelled from outside.
pub(crate) fn blocking_codex(pid_file: &PidFile) -> CodexBuilder {
    let script = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fake-codex-blocks.sh");
    Codex::builder()
        .binary("/bin/bash")
        .arg(script.to_str().expect("fixture path is utf-8"))
        .env(
            "CODEX_WRAPPER_TEST_PIDFILE",
            pid_file.path().to_str().expect("pid file path is utf-8"),
        )
}

/// A process group whose descendant survives SIGTERM, with markers that let
/// tests drop the owning future only after graceful termination has started.
pub(crate) struct GracePeriodFixture {
    pid_file: PidFile,
    cleanup_armed: AtomicBool,
}

impl GracePeriodFixture {
    pub(crate) fn new(label: &str) -> Self {
        let fixture = Self {
            pid_file: PidFile::new(label),
            cleanup_armed: AtomicBool::new(true),
        };
        for suffix in [".ready", ".term"] {
            let _ = std::fs::remove_file(fixture.marker(suffix));
        }
        fixture
    }

    fn marker(&self, suffix: &str) -> PathBuf {
        let mut path = self.pid_file.path().as_os_str().to_owned();
        path.push(suffix);
        PathBuf::from(path)
    }

    pub(crate) fn configure(&self, builder: CodexBuilder) -> CodexBuilder {
        builder
            .env(
                "CODEX_WRAPPER_TEST_PIDFILE",
                self.pid_file.path().to_str().unwrap(),
            )
            .env("CODEX_WRAPPER_TEST_IGNORE_TERM", "1")
            // The marker, rather than a guessed delay, determines when to
            // drop. This leaves ample time even on a loaded CI worker.
            .termination_grace(Duration::from_secs(30))
    }

    pub(crate) fn builder(&self) -> CodexBuilder {
        let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake-codex-spawns-child.sh");
        self.configure(
            Codex::builder()
                .binary("/bin/bash")
                .arg(script.to_str().unwrap()),
        )
    }

    fn pids(&self) -> Option<(u32, u32)> {
        let contents = std::fs::read_to_string(self.pid_file.path()).ok()?;
        let field = |key: &str| {
            contents
                .lines()
                .find_map(|line| line.strip_prefix(key))
                .and_then(|value| value.parse().ok())
        };
        Some((field("parent=")?, field("child=")?))
    }

    pub(crate) async fn ready(&self) {
        tokio::time::timeout(Duration::from_secs(10), async {
            while self.pids().is_none() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("the fixture never recorded its ready process group");
    }

    pub(crate) async fn assert_drop_during_grace(&self, run: impl std::future::Future) {
        let mut run = Box::pin(run);
        let term = self.marker(".term");
        tokio::select! {
            _ = &mut run => panic!("the run finished before its grace period was observed"),
            observed = tokio::time::timeout(Duration::from_secs(10), async {
                while !term.exists() {
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
            }) => observed.expect("the fixture never received SIGTERM"),
        }
        let (parent, child) = self.pids().expect("the fixture recorded its process group");
        assert!(is_running(child), "the descendant must survive SIGTERM");
        drop(run);

        let (parent_gone, child_gone) =
            tokio::join!(wait_until_gone(parent), wait_until_gone(child));
        if parent_gone && child_gone {
            self.cleanup_armed.store(false, Ordering::Relaxed);
        }
        assert!(parent_gone, "the direct child ({parent}) survived the drop");
        assert!(
            child_gone,
            "the SIGTERM-ignoring descendant ({child}) survived dropping during grace"
        );
    }
}

impl Drop for GracePeriodFixture {
    fn drop(&mut self) {
        // Regression failures must not leave the deliberately stubborn
        // process behind. Also clean up when an earlier assertion panics.
        if self.cleanup_armed.load(Ordering::Relaxed)
            && let Some((parent, _)) = self.pids()
        {
            crate::exec::signal_group(parent, libc::SIGKILL);
        }
        for suffix in [".ready", ".term"] {
            let _ = std::fs::remove_file(self.marker(suffix));
        }
    }
}

/// A signal-aware fake CLI with a detached cooperative tool or a stubborn
/// same-group tool. Cleanup on assertion failure covers both topologies.
pub(crate) struct InterruptFixture {
    pid_file: PidFile,
    cleanup_armed: AtomicBool,
}

impl InterruptFixture {
    pub(crate) fn new(label: &str) -> Self {
        let fixture = Self {
            pid_file: PidFile::new(label),
            cleanup_armed: AtomicBool::new(true),
        };
        for suffix in [".ready", ".int", ".term", ".cleaned", ".int-ignored"] {
            let _ = std::fs::remove_file(fixture.marker(suffix));
        }
        fixture
    }

    pub(crate) fn marker(&self, suffix: &str) -> PathBuf {
        let mut path = self.pid_file.path().as_os_str().to_owned();
        path.push(suffix);
        PathBuf::from(path)
    }

    pub(crate) fn builder(&self) -> CodexBuilder {
        let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake-codex-interrupt.sh");
        Codex::builder()
            .binary("/bin/bash")
            .arg(script.to_str().unwrap())
            .env(
                "CODEX_WRAPPER_TEST_PIDFILE",
                self.pid_file.path().to_str().unwrap(),
            )
            .termination_grace(Duration::from_secs(1))
    }

    pub(crate) fn pids(&self) -> Option<(u32, u32)> {
        let contents = std::fs::read_to_string(self.pid_file.path()).ok()?;
        let field = |key: &str| {
            contents
                .lines()
                .find_map(|line| line.strip_prefix(key))
                .and_then(|value| value.parse().ok())
        };
        Some((field("parent=")?, field("child=")?))
    }

    pub(crate) async fn ready(&self) {
        self.wait_for(".ready").await;
        assert!(self.pids().is_some(), "ready requires recorded process IDs");
        // Children inherit an ignored SIGINT from the test process (nohup, a
        // background job), and the fixture's shell then cannot trap it.
        assert!(
            !self.marker(".int-ignored").exists(),
            "SIGINT was ignored when the fixture started, so its trap could not be installed; run the tests with SIGINT at its default disposition"
        );
    }

    pub(crate) async fn wait_for(&self, suffix: &str) {
        tokio::time::timeout(Duration::from_secs(10), async {
            while !self.marker(suffix).exists() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("the fixture never reached its marker");
    }

    pub(crate) async fn detached_ready(&self) {
        self.ready().await;
        let (parent, child) = self.pids().unwrap();
        // SAFETY: getpgid only queries processes owned by this fixture.
        let (parent_group, child_group) =
            unsafe { (libc::getpgid(parent as i32), libc::getpgid(child as i32)) };
        assert!(parent_group > 0 && child_group > 0);
        assert_ne!(
            parent_group, child_group,
            "the tool must escape the CLI group"
        );
    }

    pub(crate) async fn assert_stopped(&self) {
        let (parent, child) = self.pids().unwrap();
        let (parent_gone, child_gone) =
            tokio::join!(wait_until_gone(parent), wait_until_gone(child),);
        assert!(parent_gone, "the direct child survived shutdown");
        assert!(child_gone, "the tool survived shutdown");
        self.cleanup_armed.store(false, Ordering::Relaxed);
    }
}

impl Drop for InterruptFixture {
    fn drop(&mut self) {
        if self.cleanup_armed.load(Ordering::Relaxed)
            && let Some((parent, child)) = self.pids()
        {
            // Only signal the recorded parent's group while it still owns
            // that identity. The opt-out fixture never leads its own group.
            // SAFETY: getpgid only queries the recorded fixture process.
            if unsafe { libc::getpgid(parent as i32) } == parent as i32 {
                crate::exec::signal_group(parent, libc::SIGKILL);
            }
            // The cooperative test's tool is deliberately outside that group.
            // SAFETY: this is a positive PID recorded by the owned fixture.
            unsafe {
                libc::kill(child as i32, libc::SIGKILL);
            }
        }
        for suffix in [".ready", ".int", ".term", ".cleaned", ".int-ignored"] {
            let _ = std::fs::remove_file(self.marker(suffix));
        }
    }
}

/// Wait for `pid` to stop running, up to five seconds.
///
/// Checks the process state rather than `kill -0`: a killed child lingers as a
/// zombie until tokio's orphan reaper collects it, and a zombie still answers
/// `kill -0`, which would read as "still running".
pub(crate) async fn wait_until_gone(pid: u32) -> bool {
    for _ in 0..250 {
        if !is_running(pid) {
            return true;
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    false
}

/// Public-in-crate view of [`is_running`], for a test that asserts a process
/// is still alive rather than waiting for it to go.
pub(crate) fn is_running_for_test(pid: u32) -> bool {
    is_running(pid)
}

/// `true` while `pid` is a live process. Empty `ps` output means the PID is
/// gone; a leading `Z` means it exited and is awaiting reaping.
fn is_running(pid: u32) -> bool {
    let output = std::process::Command::new("ps")
        .args(["-o", "state=", "-p", &pid.to_string()])
        .output()
        .expect("ps must be available");
    let state = String::from_utf8_lossy(&output.stdout);
    let state = state.trim();
    !state.is_empty() && !state.starts_with('Z')
}