drep-ai 2.3.0

A local commit gate: runs the linters your repo configures, and sends changed code to an LLM for review
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! A fake executable proves the real process receives only the intended surface.

use std::ffi::OsString;
use std::time::Duration;

use serde_json::json;

use crate::config::{BackendKind, LlmConfig, ReasoningEffort};
use crate::llm::codex::CodexClient;
use crate::llm::codex::command::ChildEnvironment;
use crate::llm::codex::process;
use crate::llm::error::{BackendErrorKind, LlmError};
use crate::llm::json_parsing::Extracted;

#[test]
fn client_accessors_and_identity_preserve_the_configured_contract() {
    let (dir, client) = fake_client("#!/bin/sh\nexit 0\n", 5);

    assert_eq!(client.model(), "gpt-5.6-sol");
    assert_eq!(client.cli_version(), "0.148.0");
    assert_eq!(client.reasoning_effort(), Some(&ReasoningEffort::High));
    assert_eq!(client.identity(), "codex:chatgpt:cli=0.148.0:effort=high");
    drop(dir);
}

#[tokio::test]
async fn fake_codex_receives_stdin_empty_cwd_and_allowlisted_environment() {
    let dir = tempfile::tempdir().expect("tempdir");
    let executable = dir.path().join("fake-codex");
    crate::test_support::write_executable(
        &executable,
        r#"#!/bin/sh
set -eu
capture=$(dirname "$0")
printf '%s\n' "$@" > "$capture/args"
pwd > "$capture/cwd"
ls -A > "$capture/cwd_entries"
env | sort > "$capture/env"
sed -n '1,$p' > "$capture/stdin"
printf '%s\n' \
  '{"type":"thread.started","thread_id":"redacted"}' \
  '{"type":"turn.started"}' \
  '{"type":"item.completed","item":{"type":"agent_message","text":"{\"issues\":[],\"summary\":\"clean\"}"}}' \
  '{"type":"turn.completed","usage":{"input_tokens":12,"output_tokens":4}}'
"#,
    );

    let cfg = LlmConfig {
        backend: BackendKind::Codex,
        model: Some("gpt-5.6-sol".to_owned()),
        reasoning_effort: Some(ReasoningEffort::High),
        timeout_secs: 5,
        max_concurrent: 1,
        ..LlmConfig::default()
    };
    let environment = ChildEnvironment::from_iter([
        (OsString::from("PATH"), OsString::from("/usr/bin:/bin")),
        (OsString::from("HOME"), OsString::from("/safe/home")),
        (
            OsString::from("CODEX_HOME"),
            OsString::from("/safe/home/.codex"),
        ),
        (
            OsString::from("OPENAI_API_KEY"),
            OsString::from("must-not-leak"),
        ),
        (
            OsString::from("DREP_AUTH_PATH"),
            OsString::from("/real/auth.toml"),
        ),
    ]);
    let client =
        CodexClient::at(&cfg, executable, environment, "0.148.0").expect("valid test client");

    let result = client
        .complete_json("Review Rust carefully.", "diff --git a/a.rs b/a.rs")
        .await
        .expect("fake Codex succeeds");
    assert_eq!(
        result,
        Extracted::Complete(json!({"issues": [], "summary": "clean"}))
    );
    assert_eq!(
        std::fs::read_to_string(dir.path().join("stdin")).expect("stdin capture"),
        "diff --git a/a.rs b/a.rs"
    );
    let cwd = std::fs::read_to_string(dir.path().join("cwd")).expect("cwd capture");
    assert_ne!(cwd.trim(), env!("CARGO_MANIFEST_DIR"));
    assert_eq!(
        std::fs::read_to_string(dir.path().join("cwd_entries")).expect("cwd entries"),
        ""
    );

    let environment = std::fs::read_to_string(dir.path().join("env")).expect("env capture");
    assert!(environment.contains("HOME=/safe/home\n"));
    assert!(environment.contains("CODEX_HOME=/safe/home/.codex\n"));
    assert!(!environment.contains("OPENAI_API_KEY"));
    assert!(!environment.contains("DREP_AUTH_PATH"));

    let args = std::fs::read_to_string(dir.path().join("args")).expect("args capture");
    assert!(args.contains("forced_login_method=\"chatgpt\"\n"));
    assert!(args.contains("--ignore-user-config\n"));
    assert!(args.contains("--ephemeral\n"));
    assert!(args.ends_with("--json\n-\n"));
}

#[tokio::test]
async fn forbidden_tool_activity_is_a_sticky_contract_failure() {
    let (dir, client) = fake_client(
        concat!(
            "#!/bin/sh\n",
            "sed -n '1,$p' >/dev/null\n",
            "printf '%s\\n' \\\n",
            "  '{\"type\":\"item.completed\",\"item\":{\"type\":\"web_search\"}}' \\\n",
            "  '{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"{\\\"issues\\\":[],\\\"summary\\\":\\\"clean\\\"}\"}}' \\\n",
            "  '{\"type\":\"turn.completed\"}'\n",
        ),
        5,
    );
    let err = client
        .complete_json("review", "payload")
        .await
        .expect_err("tool events fail closed");
    assert!(matches!(
        err,
        LlmError::Backend {
            kind: BackendErrorKind::Contract,
            ..
        }
    ));
    drop(dir);
}

#[tokio::test]
async fn unknown_nonzero_exit_is_not_classified_from_stderr_prose() {
    let (dir, client) = fake_client(
        concat!(
            "#!/bin/sh\n",
            "sed -n '1,$p' >/dev/null\n",
            "printf '%s\\n' '{\"type\":\"error\",\"message\":\"machine-readable terminal detail\"}'\n",
            "printf 'unauthorized timeout quota\\033[31m' >&2\n",
            "exit 19\n",
        ),
        5,
    );
    let err = client
        .complete_json("review", "payload")
        .await
        .expect_err("nonzero exit");
    match err {
        LlmError::Backend {
            kind: BackendErrorKind::UnknownExit,
            message,
        } => {
            assert!(message.contains("status 19"), "{message}");
            assert!(
                message.contains("machine-readable terminal detail"),
                "{message}"
            );
            assert!(!message.chars().any(char::is_control), "{message:?}");
        }
        other => panic!("unexpected classification: {other:?}"),
    }
    drop(dir);
}

#[tokio::test]
async fn a_large_stderr_is_drained_but_only_a_bounded_excerpt_is_reported() {
    let (dir, client) = fake_client(
        "#!/bin/sh\ndd if=/dev/zero bs=1024 count=40 2>/dev/null | tr '\\000' x >&2\nprintf tail-marker >&2\nexit 19\n",
        5,
    );
    let err = client
        .complete_json("review", "payload")
        .await
        .expect_err("nonzero exit");
    match err {
        LlmError::Backend {
            kind: BackendErrorKind::UnknownExit,
            message,
        } => {
            assert!(
                message.len() < 600,
                "stderr was not bounded: {}",
                message.len()
            );
            assert!(!message.contains("tail-marker"), "got {message}");
        }
        other => panic!("unexpected classification: {other:?}"),
    }
    drop(dir);
}

#[tokio::test]
async fn malformed_final_json_stays_an_unparseable_model_response() {
    let (dir, client) = fake_client(
        concat!(
            "#!/bin/sh\n",
            "sed -n '1,$p' >/dev/null\n",
            "printf '%s\\n' \\\n",
            "  '{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"not json\"}}' \\\n",
            "  '{\"type\":\"turn.completed\"}'\n",
        ),
        5,
    );
    let err = client
        .complete_json("review", "payload")
        .await
        .expect_err("final message is malformed");
    assert!(matches!(err, LlmError::Unparseable(_)), "got {err:?}");
    drop(dir);
}

#[tokio::test]
async fn stdout_overflow_is_a_bounded_transport_failure() {
    let (dir, client) = fake_client(
        "#!/bin/sh\ndd if=/dev/zero bs=1048576 count=17 2>/dev/null\n",
        5,
    );
    let err = client
        .complete_json("review", "payload")
        .await
        .expect_err("stdout exceeds its bound");
    assert!(
        matches!(err, LlmError::Transport { status: None, ref message } if message.contains("exceeded")),
        "got {err:?}"
    );
    drop(dir);
}

#[tokio::test]
async fn process_stdout_accepts_exactly_sixteen_mebibytes() {
    const EXPECTED_LIMIT: usize = 16 * 1024 * 1024;
    let dir = tempfile::tempdir().expect("tempdir");
    let executable = dir.path().join("fake-codex");
    let output_path = dir.path().join("stdout");
    std::fs::write(&output_path, vec![b'x'; EXPECTED_LIMIT]).expect("bounded stdout fixture");
    crate::test_support::write_executable(
        &executable,
        "#!/bin/sh\ncapture=$(dirname \"$0\")\nexec /bin/cat \"$capture/stdout\"\n",
    );

    let output = process::run(
        &executable,
        &[],
        &ChildEnvironment::default(),
        dir.path(),
        "",
        Duration::from_secs(5),
    )
    .await
    .expect("the exact stdout ceiling is accepted");

    assert_eq!(output.stdout.len(), EXPECTED_LIMIT);
}

#[tokio::test]
async fn process_stderr_retains_exactly_thirty_two_kibibytes_while_draining() {
    const EXPECTED_LIMIT: usize = 32 * 1024;
    let dir = tempfile::tempdir().expect("tempdir");
    let executable = dir.path().join("fake-codex");
    let stderr_path = dir.path().join("stderr");
    std::fs::write(&stderr_path, vec![b'x'; EXPECTED_LIMIT + 1024]).expect("noisy stderr fixture");
    crate::test_support::write_executable(
        &executable,
        "#!/bin/sh\ncapture=$(dirname \"$0\")\n/bin/cat \"$capture/stderr\" >&2\n",
    );

    let output = process::run(
        &executable,
        &[],
        &ChildEnvironment::default(),
        dir.path(),
        "",
        Duration::from_secs(5),
    )
    .await
    .expect("noisy stderr is drained");

    assert_eq!(output.stderr.len(), EXPECTED_LIMIT);
}

#[tokio::test]
async fn process_missing_binary_is_a_configuration_failure() {
    let dir = tempfile::tempdir().expect("tempdir");
    let result = process::run(
        &dir.path().join("missing-codex"),
        &[],
        &ChildEnvironment::default(),
        dir.path(),
        "",
        Duration::from_secs(5),
    )
    .await;
    let err = match result {
        Err(err) => err,
        Ok(_) => panic!("missing binary unexpectedly ran"),
    };

    assert!(
        matches!(err, LlmError::NotConfigured(ref message) if message.contains("not found")),
        "got {err:?}"
    );
}

#[tokio::test]
async fn a_child_that_closes_stdin_early_is_a_transport_failure() {
    let (dir, client) = fake_client("#!/bin/sh\nexit 0\n", 5);
    let payload = "x".repeat(1024 * 1024);
    let err = client
        .complete_json("review", &payload)
        .await
        .expect_err("the payload was not delivered");
    assert!(
        matches!(err, LlmError::Transport { status: None, ref message } if message.contains("send the review payload")),
        "got {err:?}"
    );
    drop(dir);
}

#[tokio::test]
async fn a_nonzero_exit_keeps_its_diagnostic_when_stdin_closes_early() {
    let (dir, client) = fake_client(
        "#!/bin/sh\nprintf '%s\\n' '{\"type\":\"error\",\"message\":\"terminal detail\"}'\nexit 19\n",
        5,
    );
    let payload = "x".repeat(1024 * 1024);

    let err = client
        .complete_json("review", &payload)
        .await
        .expect_err("the child reported a nonzero exit");

    assert!(
        matches!(err, LlmError::Backend { kind: BackendErrorKind::UnknownExit, ref message }
            if message.contains("terminal detail")),
        "got {err:?}"
    );
    drop(dir);
}

#[cfg(unix)]
#[tokio::test]
async fn a_grandchild_inheriting_output_cannot_hold_a_review_open() {
    let (dir, client) = fake_client(
        concat!(
            "#!/bin/sh\n",
            "sed -n '1,$p' >/dev/null\n",
            "capture=$(dirname \"$0\")\n",
            // Keep the grandchild well beyond the review deadline while
            // leaving enough startup headroom for a heavily parallel suite.
            "sleep 30 &\n",
            "printf '%s' \"$!\" > \"$capture/grandchild.pid\"\n",
            "printf '%s\\n' \\\n",
            "  '{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"{\\\"issues\\\":[],\\\"summary\\\":\\\"clean\\\"}\"}}' \\\n",
            "  '{\"type\":\"turn.completed\"}'\n",
        ),
        10,
    );

    let result = client.complete_json("review", "payload").await;
    let pid = std::fs::read_to_string(dir.path().join("grandchild.pid")).expect("grandchild pid");
    let running = super::probe_and_stop_process(&pid);

    assert!(result.is_ok(), "got {result:?}");
    assert!(
        running,
        "review waited for the unrelated grandchild to exit"
    );
    drop(dir);
}

#[cfg(unix)]
#[tokio::test]
async fn a_signal_terminated_child_is_a_transport_failure() {
    let (dir, client) = fake_client("#!/bin/sh\nkill -TERM $$\n", 5);
    let err = client
        .complete_json("review", "payload")
        .await
        .expect_err("signal termination has no exit code");
    assert!(matches!(err, LlmError::Transport { status: None, .. }));
    drop(dir);
}

#[tokio::test]
async fn timeout_kills_the_child_before_it_can_continue() {
    let (dir, client) = fake_client(
        "#!/bin/sh\ncapture=$(dirname \"$0\")\nsleep 5\nprintf late > \"$capture/late\"\n",
        1,
    );
    let err = client
        .complete_json("review", "payload")
        .await
        .expect_err("child times out");
    assert!(matches!(err, LlmError::Transport { status: None, .. }));
    assert!(
        !dir.path().join("late").exists(),
        "timed-out child continued"
    );
}

fn fake_client(script: &str, timeout_secs: u64) -> (tempfile::TempDir, CodexClient) {
    let dir = tempfile::tempdir().expect("tempdir");
    let executable = dir.path().join("fake-codex");
    crate::test_support::write_executable(&executable, script);
    let cfg = LlmConfig {
        backend: BackendKind::Codex,
        model: Some("gpt-5.6-sol".to_owned()),
        reasoning_effort: Some(ReasoningEffort::High),
        timeout_secs,
        max_concurrent: 1,
        ..LlmConfig::default()
    };
    let client = CodexClient::for_test(
        &cfg,
        executable,
        [
            (OsString::from("PATH"), OsString::from("/usr/bin:/bin")),
            (OsString::from("HOME"), OsString::from("/safe/home")),
        ],
        "0.148.0",
    )
    .expect("test client");
    (dir, client)
}