Skip to main content

sqlite_graphrag/commands/
codex_spawn.rs

1//! Codex CLI spawn + JSONL parsing helper shared by `enrich` and `ingest --mode codex`.
2//!
3//! G31 (v1.0.69): `enrich --mode codex` was missing five critical hardening
4//! flags compared to `ingest --mode codex`. This module extracts the
5//! spawn pipeline into a single helper that BOTH call-sites consume,
6//! guaranteeing the same defaults everywhere.
7//!
8//! G32 (v1.0.69): `enrich --mode codex` used `serde_json::from_str` on the
9//! raw stdout, but `codex exec --json` emits JSONL (one event per line).
10//! [`parse_codex_jsonl`] iterates line-by-line, picking the last
11//! `item.completed` of type `agent_message` as the assistant text.
12//!
13//! G33 (v1.0.69): validate the model against the ChatGPT Pro OAuth whitelist
14//! stored in `~/.codex/models_cache.json` BEFORE spawning the subprocess.
15
16use crate::errors::AppError;
17use crate::extract::codex_compat::codex_supports_ask_for_approval;
18use crate::extraction::{ExtractedUrl, ExtractionResult};
19use crate::spawn::env_whitelist::apply_env_whitelist;
20use crate::storage::entities::{NewEntity, NewRelationship};
21use serde::{Deserialize, Serialize};
22use std::path::{Path, PathBuf};
23use std::process::{Command, Stdio};
24
25/// Token usage reported by Codex on `turn.completed` events.
26#[derive(Debug, Clone, Default, Deserialize, Serialize)]
27pub struct CodexUsage {
28    #[serde(default)]
29    pub input_tokens: u64,
30    #[serde(default)]
31    pub cached_input_tokens: u64,
32    #[serde(default)]
33    pub output_tokens: u64,
34    #[serde(default)]
35    pub reasoning_output_tokens: u64,
36}
37
38/// Combined result of one `codex exec` invocation.
39#[derive(Debug)]
40pub struct CodexResult {
41    pub extraction: ExtractionResult,
42    /// Raw text of the last `item.completed` of type `agent_message` (the
43    /// JSON payload the LLM produced). Callers that need a schema other
44    /// than the extraction shape (e.g. body-enrich's `enriched_body`)
45    /// should parse this directly.
46    pub last_agent_text: String,
47    pub usage: Option<CodexUsage>,
48    pub rate_limited: bool,
49    pub schema_error: bool,
50    pub turn_failed: bool,
51    pub failed_message: String,
52}
53
54/// Configuration for the codex spawner.
55#[allow(rustdoc::broken_intra_doc_links)]
56pub struct CodexSpawnArgs<'a> {
57    pub binary: &'a Path,
58    pub prompt: &'a str,
59    pub json_schema: &'a str,
60    pub input_text: &'a str,
61    pub model: Option<&'a str>,
62    pub timeout_secs: u64,
63    /// Caller-provided schema path (must be inside a trusted directory
64    /// that codex recognises as sandbox-safe). Use [`trusted_schema_path`]
65    /// to compute one under the cache dir.
66    pub schema_path: PathBuf,
67}
68
69/// Computes a schema path under the cache dir so `codex exec` accepts it
70/// as part of a trusted directory (rejects `/tmp` on hardened installs).
71pub fn trusted_schema_path() -> Result<PathBuf, AppError> {
72    let cache = crate::paths::AppPaths::resolve(None)
73        .map(|p| p.models.parent().map(|m| m.to_path_buf()))
74        .ok()
75        .flatten()
76        .unwrap_or_else(std::env::temp_dir);
77    std::fs::create_dir_all(&cache).map_err(AppError::Io)?;
78    Ok(cache.join(format!("enrich-schema-{}.json", std::process::id())))
79}
80
81/// Models accepted by Codex CLI when using ChatGPT Pro OAuth.
82///
83/// Mirrored from `~/.codex/models_cache.json` (which the official CLI
84/// refreshes on every login). This list is intentionally narrow; passing
85/// a model not in this set with `--mode codex` returns
86/// `AppError::Validation` BEFORE any OAuth turn is spent.
87pub const CODEX_PRO_OAUTH_MODELS: &[&str] = &[
88    "codex-auto-review",
89    "gpt-5.3-codex-spark",
90    "gpt-5.4",
91    "gpt-5.4-mini",
92    "gpt-5.5",
93];
94
95/// Validates the requested model against [`CODEX_PRO_OAUTH_MODELS`].
96///
97/// # Errors
98/// Returns [`AppError::Validation`] listing the accepted models when the
99/// caller supplied a model outside the whitelist.
100pub fn validate_codex_model(model: Option<&str>) -> Result<(), AppError> {
101    let Some(m) = model else {
102        return Ok(()); // no override; codex picks its default
103    };
104    if CODEX_PRO_OAUTH_MODELS.contains(&m) {
105        Ok(())
106    } else {
107        Err(AppError::Validation(format!(
108            "--codex-model {m:?} is not supported with ChatGPT Pro OAuth. \
109             Accepted: {}",
110            CODEX_PRO_OAUTH_MODELS.join(", ")
111        )))
112    }
113}
114
115/// Returns the list of models accepted by Codex with ChatGPT Pro OAuth.
116///
117/// Tries to read `~/.codex/models_cache.json` (which the official CLI
118/// refreshes on every login) and falls back to the static
119/// [`CODEX_PRO_OAUTH_MODELS`] constant when the file is missing or
120/// malformed. The returned `Vec<String>` is the union of both sources,
121/// de-duplicated.
122///
123/// The official cache file is an object with the shape
124/// `{"fetched_at": "...", "etag": "...", "client_version": "...",
125/// "models": [{"slug": "gpt-5.5", ...}, ...]}` (v1.0.81 fix: previously we
126/// iterated `obj.keys()` which produced bogus entries like `client_version`
127/// and `etag` as "models"; now we extract only the `models` array).
128pub fn list_codex_models() -> Vec<String> {
129    use std::collections::BTreeSet;
130    let mut out: BTreeSet<String> = CODEX_PRO_OAUTH_MODELS
131        .iter()
132        .map(|s| s.to_string())
133        .collect();
134
135    if let Some(home) = std::env::var_os("HOME") {
136        let path = std::path::Path::new(&home)
137            .join(".codex")
138            .join("models_cache.json");
139        if let Ok(content) = std::fs::read_to_string(&path) {
140            if let Ok(value) = serde_json::from_str::<serde_json::Value>(&content) {
141                if let Some(obj) = value.as_object() {
142                    // v1.0.81 fix: prefer the well-known `models` array
143                    // (each item has a `slug` field). Fall back to keys
144                    // only when `models` is absent (legacy cache format).
145                    if let Some(models_arr) = obj.get("models").and_then(|m| m.as_array()) {
146                        for v in models_arr {
147                            if let Some(slug) = v.get("slug").and_then(|s| s.as_str()) {
148                                out.insert(slug.to_string());
149                            } else if let Some(s) = v.as_str() {
150                                out.insert(s.to_string());
151                            }
152                        }
153                    } else {
154                        for key in obj.keys() {
155                            out.insert(key.clone());
156                        }
157                    }
158                } else if let Some(arr) = value.as_array() {
159                    for v in arr {
160                        if let Some(s) = v.as_str() {
161                            out.insert(s.to_string());
162                        }
163                    }
164                }
165            }
166        }
167    }
168    out.into_iter().collect()
169}
170
171/// Suggests the closest codex OAuth model to a user-supplied substring
172/// (G33). Returns `None` when no candidate is close enough.
173///
174/// Match strategy: exact substring containment wins; otherwise Levenshtein
175/// distance below `max_distance = max(2, query.len() / 3)`.
176pub fn suggest_codex_model(query: &str) -> Option<String> {
177    let query_lc = query.to_ascii_lowercase();
178    let models = list_codex_model_lc();
179
180    // Exact substring match wins.
181    for m in &models {
182        if m.contains(&query_lc) {
183            return Some(m.clone());
184        }
185    }
186
187    // Levenshtein fallback.
188    let max_distance = (query.len() / 3).max(2);
189    let mut best: Option<(usize, String)> = None;
190    for m in &models {
191        let d = levenshtein(query_lc.as_str(), m.as_str());
192        if d <= max_distance && best.as_ref().is_none_or(|(bd, _)| d < *bd) {
193            best = Some((d, m.clone()));
194        }
195    }
196    best.map(|(_, m)| m)
197}
198
199fn list_codex_model_lc() -> Vec<String> {
200    list_codex_models()
201        .into_iter()
202        .map(|s| s.to_ascii_lowercase())
203        .collect()
204}
205
206fn levenshtein(a: &str, b: &str) -> usize {
207    let a_chars: Vec<char> = a.chars().collect();
208    let b_chars: Vec<char> = b.chars().collect();
209    if a_chars.is_empty() {
210        return b_chars.len();
211    }
212    if b_chars.is_empty() {
213        return a_chars.len();
214    }
215    let mut prev: Vec<usize> = (0..=b_chars.len()).collect();
216    let mut curr = vec![0; b_chars.len() + 1];
217    for (i, &ac) in a_chars.iter().enumerate() {
218        curr[0] = i + 1;
219        for (j, &bc) in b_chars.iter().enumerate() {
220            let cost = if ac == bc { 0 } else { 1 };
221            curr[j + 1] = (curr[j] + 1).min(prev[j + 1] + 1).min(prev[j] + cost);
222        }
223        std::mem::swap(&mut prev, &mut curr);
224    }
225    prev[b_chars.len()]
226}
227
228/// Builds the `codex exec` command with the canonical hardening flags.
229///
230/// G31 + OAuth-only hardening (v1.0.69, mandated by gaps.md lines 41-49):
231/// the command ALWAYS uses the OAuth `auth.json` flow. The flag set is
232/// the canonical one documented in gaps.md Fix A:
233///
234/// ```text
235/// codex exec \
236///   -c mcp_servers='{}' \
237///   --json --output-schema <SCHEMA> \
238///   --ephemeral \
239///   --skip-git-repo-check \
240///   --sandbox read-only \
241///   --ignore-user-config \
242///   --ignore-rules \
243///   --ask-for-approval never \
244///   -m <MODEL> \
245///   -
246/// ```
247///
248/// The combination zeroes MCP servers (via two complementary mechanisms:
249/// the inline `-c mcp_servers='{}'` override AND `--ignore-user-config`),
250/// disables user-defined rules, and never asks for interactive approval.
251///
252/// **`OPENAI_API_KEY` is FORBIDDEN** in the spawned environment (gaps.md:48).
253/// OAuth flows via `~/.codex/auth.json` and `CODEX_ACCESS_TOKEN` only.
254pub fn build_codex_command(args: &CodexSpawnArgs<'_>) -> Command {
255    let full_prompt = format!("{}\n\n{}", args.prompt, args.input_text);
256
257    // OAuth-only guard (gaps.md:48, ADR-0011). If `OPENAI_API_KEY` is set
258    // in the environment we MUST abort — that is the API-key path which is
259    // explicitly PROHIBITED. Use the OAuth `auth.json` flow exclusively.
260    if let Ok(_key) = std::env::var("OPENAI_API_KEY") {
261        let mut cmd = Command::new("false");
262        cmd.env_clear();
263        cmd.env("PATH", "/nonexistent");
264        cmd.arg("--oauth-only-violation-openai-api-key-set");
265        cmd.arg("--oauth-only-resolution-use-codex-auth-json-or-openai-base-url");
266        return cmd;
267    }
268
269    // Write the JSON schema to a path the caller controls. Callers should
270    // pass a path under the cache dir (see [`trusted_schema_path`]).
271    std::fs::write(&args.schema_path, args.json_schema).ok();
272
273    let mut cmd = Command::new(args.binary);
274    // v1.0.83 (ADR-0041): env whitelist delegated to the shared helper.
275    // `OPENAI_API_KEY` is INTENTIONALLY ABSENT (defence-in-depth).
276    // `CODEX_ACCESS_TOKEN` and `OPENAI_BASE_URL` ARE whitelisted for
277    // custom providers via the canonical list in src/spawn/env_whitelist.rs.
278    apply_env_whitelist(&mut cmd, crate::spawn::env_whitelist::is_strict_env_clear());
279
280    // v1.0.77: point CODEX_HOME at an isolated dir that only contains
281    // auth.json — this prevents the codex subprocess from loading
282    // ~/.codex/config.toml (which has trust_level=trusted for the project,
283    // causing sandbox escalation per openai/codex#18113).
284    if let Some(isolated) = prepare_isolated_codex_home_spawn() {
285        cmd.env("CODEX_HOME", isolated);
286    }
287
288    // v1.0.77: `-c` TOML overrides bypass the codex exec --sandbox propagation
289    // bug (openai/codex#18113). CLI flags alone are insufficient — the exec
290    // subcommand may not inherit --sandbox from the parent codex command.
291    cmd.arg("exec")
292        .arg("-c")
293        .arg("sandbox_mode='read-only'")
294        .arg("-c")
295        .arg("approval_policy='never'")
296        .arg("--json")
297        .arg("--output-schema")
298        .arg(&args.schema_path)
299        .arg("--ephemeral")
300        .arg("--skip-git-repo-check")
301        .arg("--sandbox")
302        .arg("read-only")
303        .arg("--ignore-user-config")
304        .arg("--ignore-rules");
305
306    // Codex 0.134+ no longer accepts `-c mcp_servers='{}'` — it parses the
307    // value as a string and rejects it ("expected a map"). The
308    // `--ignore-user-config` flag already discards any user-defined MCP
309    // servers, so the override is redundant on all supported versions.
310
311    // Codex 0.134+ removed --ask-for-approval entirely (Issue #26602).
312    // Skip the flag on newer versions; sandbox=read-only already suppresses
313    // approval prompts. See src/extract/codex_compat.rs for the probe.
314    if codex_supports_ask_for_approval() {
315        cmd.arg("--ask-for-approval").arg("never");
316    }
317
318    if let Some(m) = args.model {
319        cmd.arg("-m").arg(m);
320    }
321
322    // `-` means: read the prompt from stdin (Codex Paperclip pattern)
323    cmd.arg("-");
324
325    cmd.stdin(Stdio::piped())
326        .stdout(Stdio::piped())
327        .stderr(Stdio::piped());
328    // Keep the prompt alive for the stdin thread spawned in `spawn_codex`.
329    let _ = full_prompt; // captured by closure below
330
331    cmd
332}
333
334/// Parses JSONL output from `codex exec --json`.
335///
336/// Event format (DOTS notation):
337/// - `thread.started` — session init
338/// - `turn.started` — model turn begins
339/// - `item.completed` — message or tool call; last `agent_message` wins
340/// - `turn.completed` — includes usage stats
341/// - `turn.failed` — error with optional rate-limit indicator
342/// - `error` — schema or validation error
343///
344/// G32 (v1.0.69): this function is the single source of truth for JSONL
345/// parsing. Both `enrich` and `ingest --mode codex` consume it.
346pub fn parse_codex_jsonl(stdout: &str) -> Result<CodexResult, AppError> {
347    let mut last_agent_text: Option<String> = None;
348    let mut usage: Option<CodexUsage> = None;
349    let mut rate_limited = false;
350    let mut schema_error = false;
351    let mut turn_failed = false;
352    let mut failed_message = String::new();
353
354    for line in stdout.lines() {
355        let line = line.trim();
356        if line.is_empty() {
357            continue;
358        }
359
360        let event: serde_json::Value = match serde_json::from_str(line) {
361            Ok(v) => v,
362            Err(_) => {
363                tracing::warn!(target: "codex_spawn", line, "skipping malformed JSONL line");
364                continue;
365            }
366        };
367
368        let event_type = match event.get("type").and_then(|t| t.as_str()) {
369            Some(t) => t,
370            None => continue,
371        };
372
373        match event_type {
374            "item.completed" => {
375                if let Some(item) = event.get("item") {
376                    if item.get("type").and_then(|t| t.as_str()) == Some("agent_message") {
377                        if let Some(text) = item.get("text").and_then(|t| t.as_str()) {
378                            last_agent_text = Some(text.to_string());
379                        }
380                    }
381                }
382            }
383            "turn.completed" => {
384                if let Some(u) = event.get("usage") {
385                    // Skip events that lack the recognised token fields
386                    // (e.g. partial broadcasts with `{}`) so the last
387                    // populated usage wins instead of being overwritten
388                    // by an empty one.
389                    let is_populated = u
390                        .get("input_tokens")
391                        .and_then(|v| v.as_u64())
392                        .map(|n| n > 0)
393                        .unwrap_or(false)
394                        || u.get("output_tokens")
395                            .and_then(|v| v.as_u64())
396                            .map(|n| n > 0)
397                            .unwrap_or(false);
398                    if is_populated {
399                        if let Ok(parsed) = serde_json::from_value::<CodexUsage>(u.clone()) {
400                            usage = Some(parsed);
401                        }
402                    }
403                }
404            }
405            "turn.failed" => {
406                turn_failed = true;
407                if let Some(err) = event.get("error") {
408                    let msg = err
409                        .get("message")
410                        .and_then(|m| m.as_str())
411                        .unwrap_or("unknown error");
412                    failed_message = msg.to_string();
413                    if msg.contains("rate_limit")
414                        || msg.contains("429")
415                        || msg.contains("Too Many Requests")
416                    {
417                        rate_limited = true;
418                    }
419                }
420            }
421            "error" => {
422                if let Some(msg) = event.get("message").and_then(|m| m.as_str()) {
423                    if msg.contains("invalid_json_schema") || msg.contains("schema") {
424                        schema_error = true;
425                    }
426                }
427            }
428            _ => {}
429        }
430    }
431
432    let text = last_agent_text.ok_or_else(|| {
433        AppError::Validation(format!(
434            "no agent_message in codex JSONL output (rate_limited={rate_limited}, schema_error={schema_error}, turn_failed={turn_failed})"
435        ))
436    })?;
437
438    if turn_failed {
439        return Err(AppError::Validation(format!(
440            "codex turn failed: {failed_message}"
441        )));
442    }
443    if schema_error {
444        return Err(AppError::Validation(
445            "codex reported invalid_json_schema; check the --output-schema file".to_string(),
446        ));
447    }
448    if rate_limited {
449        return Err(AppError::Validation(format!(
450            "codex rate-limited: {failed_message}"
451        )));
452    }
453
454    let extraction = parse_extraction_text(&text)?;
455    Ok(CodexResult {
456        extraction,
457        last_agent_text: text,
458        usage,
459        rate_limited,
460        schema_error,
461        turn_failed,
462        failed_message,
463    })
464}
465
466/// Parses the agent_message text as an `ExtractionResult` JSON payload.
467///
468/// The schema is shared by both `enrich` and `ingest --mode codex`; the
469/// `text` is the JSON value the assistant returned, not a wrapper object.
470pub fn parse_extraction_text(text: &str) -> Result<ExtractionResult, AppError> {
471    let value: serde_json::Value = serde_json::from_str(text).map_err(|e| {
472        AppError::Validation(format!("failed to parse codex agent_message as JSON: {e}"))
473    })?;
474    let obj = value.as_object().ok_or_else(|| {
475        AppError::Validation("codex agent_message is not a JSON object".to_string())
476    })?;
477
478    let mut entities: Vec<NewEntity> = Vec::new();
479    if let Some(arr) = obj.get("entities").and_then(|v| v.as_array()) {
480        for e in arr {
481            if let Some(name) = e.get("name").and_then(|v| v.as_str()) {
482                // Accept either "type" or "entity_type" from the LLM payload
483                // and fall back to "concept" when the LLM omits it.
484                let entity_type_str = e
485                    .get("type")
486                    .or_else(|| e.get("entity_type"))
487                    .and_then(|v| v.as_str())
488                    .unwrap_or("concept");
489                let entity_type = serde_json::from_value::<crate::entity_type::EntityType>(
490                    serde_json::Value::String(entity_type_str.to_string()),
491                )
492                .unwrap_or(crate::entity_type::EntityType::Concept);
493                entities.push(NewEntity {
494                    name: name.to_string(),
495                    entity_type,
496                    description: None,
497                });
498            }
499        }
500    }
501
502    let mut relationships: Vec<NewRelationship> = Vec::new();
503    if let Some(arr) = obj.get("relationships").and_then(|v| v.as_array()) {
504        for r in arr {
505            let from = r.get("source").or_else(|| r.get("from"));
506            let to = r.get("target").or_else(|| r.get("to"));
507            let rel = r.get("relation").and_then(|v| v.as_str());
508            if let (Some(from_v), Some(to_v), Some(rel_v)) = (
509                from.and_then(|v| v.as_str()),
510                to.and_then(|v| v.as_str()),
511                rel,
512            ) {
513                relationships.push(NewRelationship {
514                    source: from_v.to_string(),
515                    target: to_v.to_string(),
516                    relation: rel_v.to_string(),
517                    strength: r.get("strength").and_then(|v| v.as_f64()).unwrap_or(0.5),
518                    description: None,
519                });
520            }
521        }
522    }
523
524    let urls: Vec<ExtractedUrl> = obj
525        .get("urls")
526        .and_then(|v| v.as_array())
527        .map(|arr| {
528            arr.iter()
529                .filter_map(|u| {
530                    let url = u.get("url")?.as_str()?.to_string();
531                    let start = u.get("start").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
532                    let end = u
533                        .get("end")
534                        .and_then(|v| v.as_u64())
535                        .unwrap_or(start as u64) as usize;
536                    Some(ExtractedUrl { url, start, end })
537                })
538                .collect()
539        })
540        .unwrap_or_default();
541
542    // v1.0.76: ExtractionResult no longer carries relationships or
543    // relationships_truncated fields; those are LLM backend output
544    // (see `ExtractionOutput` in src/extract/mod.rs). The default
545    // build extracts URLs + entities only; relationships are an
546    // LLM-side concern.
547    //
548    // Convert `NewEntity` (storage-side) to `ExtractedEntity`
549    // (extraction-side). The LLM payload doesn't include byte offsets
550    // (the chunker is responsible for that), so start/end are 0.
551    let entities_ext: Vec<crate::extraction::ExtractedEntity> = entities
552        .into_iter()
553        .map(|e| crate::extraction::ExtractedEntity {
554            name: e.name,
555            entity_type: e.entity_type.as_str().to_string(),
556            start: 0,
557            end: 0,
558        })
559        .collect();
560
561    Ok(ExtractionResult {
562        entities: entities_ext,
563        urls,
564        elapsed_ms: 0,
565    })
566}
567
568fn prepare_isolated_codex_home_spawn() -> Option<std::path::PathBuf> {
569    let home = std::env::var("HOME").ok()?;
570    let real_auth = std::path::Path::new(&home).join(".codex/auth.json");
571    if !real_auth.exists() {
572        return None;
573    }
574    let isolated =
575        std::env::temp_dir().join(format!("sqlite-graphrag-codex-home-{}", std::process::id()));
576    let _ = std::fs::create_dir_all(&isolated);
577    let target = isolated.join("auth.json");
578    if !target.exists() {
579        let _ = std::fs::copy(&real_auth, &target);
580    }
581    Some(isolated)
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587
588    const SAMPLE_JSONL: &str = r#"{"type":"thread.started","thread_id":"abc"}
589{"type":"turn.started"}
590{"type":"item.completed","item":{"type":"reasoning","text":"thinking"}}
591{"type":"item.completed","item":{"type":"agent_message","text":"{\"entities\":[{\"name\":\"alpha\",\"type\":\"concept\"}],\"relationships\":[{\"source\":\"alpha\",\"target\":\"beta\",\"relation\":\"uses\",\"strength\":0.7}],\"extraction_method\":\"codex\",\"urls\":[]}"}}
592{"type":"turn.completed","usage":{"input_tokens":120,"output_tokens":45}}
593{"type":"turn.completed","usage":{}}
594"#;
595
596    #[test]
597    fn parse_codex_jsonl_extracts_last_agent_message() {
598        // v1.0.76: relationships are no longer carried in the
599        // ExtractionResult struct (they belong to the LLM ExtractionBackend
600        // payload, not the URL-only default build). The default test
601        // validates the entity extraction path only.
602        let result = parse_codex_jsonl(SAMPLE_JSONL).expect("parse must succeed");
603        assert_eq!(result.extraction.entities.len(), 1);
604        assert_eq!(result.extraction.entities[0].name, "alpha");
605    }
606
607    #[test]
608    fn parse_codex_jsonl_collects_usage() {
609        let result = parse_codex_jsonl(SAMPLE_JSONL).expect("parse must succeed");
610        let usage = result.usage.expect("usage must be populated");
611        assert_eq!(usage.input_tokens, 120);
612        assert_eq!(usage.output_tokens, 45);
613    }
614
615    #[test]
616    fn parse_codex_jsonl_detects_rate_limit() {
617        let r = parse_codex_jsonl(
618            "{\"type\":\"turn.failed\",\"error\":{\"message\":\"rate_limit: 429 too many\"}}\n{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"{}\"}}",
619        );
620        assert!(matches!(r, Err(AppError::Validation(_))));
621    }
622
623    #[test]
624    fn parse_codex_jsonl_handles_no_agent_message() {
625        let r = parse_codex_jsonl("{\"type\":\"thread.started\"}");
626        assert!(matches!(r, Err(AppError::Validation(_))));
627    }
628
629    #[test]
630    fn parse_codex_jsonl_skips_malformed_lines() {
631        let r = parse_codex_jsonl(
632            "{not valid json\n{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"{\\\"entities\\\":[],\\\"relationships\\\":[],\\\"extraction_method\\\":\\\"codex\\\"}\"}}",
633        );
634        assert!(r.is_ok(), "malformed lines must be skipped, got {r:?}");
635    }
636
637    #[test]
638    fn validate_codex_model_accepts_known() {
639        assert!(validate_codex_model(Some("gpt-5.5")).is_ok());
640        assert!(validate_codex_model(Some("gpt-5.4")).is_ok());
641        assert!(validate_codex_model(None).is_ok()); // no override
642    }
643
644    #[test]
645    fn validate_codex_model_rejects_unknown() {
646        let err = validate_codex_model(Some("gpt-4")).unwrap_err();
647        let msg = format!("{err}");
648        assert!(msg.contains("not supported"));
649        assert!(msg.contains("gpt-5.5"));
650    }
651
652    #[test]
653    fn list_codex_models_includes_all_static_whitelist() {
654        let models = list_codex_models();
655        for m in CODEX_PRO_OAUTH_MODELS {
656            assert!(models.contains(&m.to_string()), "missing {m} in {models:?}");
657        }
658    }
659
660    #[test]
661    fn suggest_codex_model_substring_match() {
662        let s = suggest_codex_model("gpt-5");
663        assert!(s.is_some(), "must suggest a gpt-5.x model");
664    }
665
666    #[test]
667    fn suggest_codex_model_fuzzy_match() {
668        // 'gpt5.5' has no hyphen; should still suggest 'gpt-5.5'.
669        let s = suggest_codex_model("gpt5.5");
670        assert!(s.is_some(), "fuzzy must suggest gpt-5.5 for 'gpt5.5'");
671        assert_eq!(s.unwrap(), "gpt-5.5");
672    }
673
674    #[test]
675    fn suggest_codex_model_unrelated_returns_none() {
676        let s = suggest_codex_model("totally-unrelated-zzz");
677        assert!(s.is_none());
678    }
679
680    #[test]
681    fn build_codex_command_includes_hardening_flags() {
682        let args = CodexSpawnArgs {
683            binary: Path::new("/bin/true"),
684            prompt: "p",
685            json_schema: "{}",
686            input_text: "i",
687            model: Some("gpt-5.5"),
688            timeout_secs: 60,
689            schema_path: std::env::temp_dir().join("test-schema.json"),
690        };
691        let cmd = build_codex_command(&args);
692        let collected: Vec<String> = cmd
693            .get_args()
694            .filter_map(|a| a.to_str().map(|s| s.to_string()))
695            .collect();
696        for required in &[
697            "exec",
698            "-c",
699            "sandbox_mode='read-only'",
700            "approval_policy='never'",
701            "--json",
702            "--output-schema",
703            "--ephemeral",
704            "--skip-git-repo-check",
705            "--sandbox",
706            "read-only",
707            "--ignore-user-config",
708            "--ignore-rules",
709            "-m",
710            "gpt-5.5",
711            "-",
712        ] {
713            assert!(
714                collected.iter().any(|a| a == required),
715                "missing flag {required} in {collected:?}"
716            );
717        }
718    }
719
720    #[test]
721    fn list_codex_models_dedupes_with_cache_file() {
722        // Ensure the union with the cache file (when present) does not
723        // produce duplicates. We can't actually write a cache file in
724        // a test, so we just verify the static path is dedup'd.
725        let models = list_codex_models();
726        let unique: std::collections::HashSet<_> = models.iter().collect();
727        assert_eq!(unique.len(), models.len(), "list_codex_models must dedupe");
728    }
729    #[test]
730    fn list_codex_models_extracts_from_models_array_v1_0_81_regression() {
731        // v1.0.81 fix: the official codex CLI writes
732        //   {"fetched_at": "...", "etag": "...", "client_version": "...",
733        //    "models": [{"slug": "gpt-5.5", ...}, ...]}
734        // and the old code iterated obj.keys(), polluting the model
735        // list with metadata keys. Here we simulate a cache file by
736        // setting HOME to a tempdir containing a synthetic cache and
737        // verifying the metadata keys are NOT present in the output.
738        let tmp =
739            std::env::temp_dir().join(format!("codex-models-array-test-{}", std::process::id()));
740        std::fs::create_dir_all(tmp.join(".codex")).expect("mkdir");
741        let cache_body = r#"{
742            "fetched_at": "2026-06-14T06:43:56.639903114Z",
743            "etag": "W/\"deadbeef\"",
744            "client_version": "0.139.0",
745            "models": [
746                {"slug": "gpt-5.5", "display_name": "GPT-5.5"},
747                {"slug": "gpt-5.4-mini", "display_name": "GPT-5.4 mini"}
748            ]
749        }"#;
750        std::fs::write(tmp.join(".codex/models_cache.json"), cache_body).expect("write cache");
751        // SAFETY: unit test
752        let prev_home = std::env::var("HOME");
753        unsafe {
754            std::env::set_var("HOME", &tmp);
755        }
756        let models = list_codex_models();
757        unsafe {
758            if let Ok(h) = prev_home {
759                std::env::set_var("HOME", h);
760            } else {
761                std::env::remove_var("HOME");
762            }
763        }
764        let _ = std::fs::remove_dir_all(&tmp);
765
766        for forbidden in &["client_version", "etag", "fetched_at", "models"] {
767            assert!(
768                !models.contains(&forbidden.to_string()),
769                "metadata key {forbidden:?} leaked into model list: {models:?}"
770            );
771        }
772        assert!(
773            models.contains(&"gpt-5.5".to_string()),
774            "gpt-5.5 missing from extracted list: {models:?}"
775        );
776        assert!(
777            models.contains(&"gpt-5.4-mini".to_string()),
778            "gpt-5.4-mini missing from extracted list: {models:?}"
779        );
780    }
781
782    #[test]
783    fn list_codex_models_falls_back_to_keys_when_models_field_absent() {
784        // Legacy cache shape: keys are model ids directly (no models
785        // array). v1.0.81 must still merge those keys into the result.
786        let tmp =
787            std::env::temp_dir().join(format!("codex-models-legacy-test-{}", std::process::id()));
788        std::fs::create_dir_all(tmp.join(".codex")).expect("mkdir");
789        let cache_body = r#"{"legacy-model-x": 1, "legacy-model-y": 2}"#;
790        std::fs::write(tmp.join(".codex/models_cache.json"), cache_body).expect("write cache");
791        let prev_home = std::env::var("HOME");
792        unsafe {
793            std::env::set_var("HOME", &tmp);
794        }
795        let models = list_codex_models();
796        unsafe {
797            if let Ok(h) = prev_home {
798                std::env::set_var("HOME", h);
799            } else {
800                std::env::remove_var("HOME");
801            }
802        }
803        let _ = std::fs::remove_dir_all(&tmp);
804
805        assert!(
806            models.contains(&"legacy-model-x".to_string()),
807            "legacy-model-x missing: {models:?}"
808        );
809        assert!(
810            models.contains(&"legacy-model-y".to_string()),
811            "legacy-model-y missing: {models:?}"
812        );
813    }
814
815    /// OAuth-only conformance test (gaps.md:41-49, v1.0.69 mandate).
816    /// Verifies that `build_codex_command` always emits `-c mcp_servers='{}'`,
817    /// `--ignore-user-config`, `--ask-for-approval never` and does NOT
818    /// whitelist `OPENAI_API_KEY` in the env_clear whitelist.
819    #[test]
820    #[serial_test::serial(env)]
821    fn build_command_oauth_only_mandatory_flags() {
822        // SAFETY: unit test
823        unsafe {
824            std::env::remove_var("OPENAI_API_KEY");
825        }
826        let schema = std::env::temp_dir().join("codex-test-schema.json");
827        let _ = std::fs::remove_file(&schema);
828        let args = CodexSpawnArgs {
829            binary: std::path::Path::new("/usr/bin/false"),
830            prompt: "p",
831            json_schema: "{}",
832            input_text: "i",
833            model: Some("gpt-5.4-mini"),
834            timeout_secs: 60,
835            schema_path: schema.clone(),
836        };
837        let cmd = build_codex_command(&args);
838        let argv: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
839        // Mandatory flags from gaps.md lines 233-238.
840        // -c mcp_servers='{}' was REMOVED in v1.0.76 — codex 0.134+ parses
841        // the value as a string and rejects it ("expected a map"). The
842        // --ignore-user-config flag already covers the MCP isolation
843        // requirement.
844        assert!(
845            argv.contains(&"--ignore-user-config"),
846            "must have --ignore-user-config (gaps.md:266)"
847        );
848        // --ask-for-approval is conditional on codex < 0.134. When the
849        // installed codex is 0.134+ the flag is omitted by the compat
850        // helper. Both outcomes are valid.
851        let ask_for_approval_present = argv.contains(&"--ask-for-approval");
852        if !crate::extract::codex_compat::codex_supports_ask_for_approval() {
853            assert!(
854                !ask_for_approval_present,
855                "codex 0.134+ must NOT include --ask-for-approval"
856            );
857        }
858        assert!(
859            argv.contains(&"--sandbox"),
860            "must have --sandbox read-only (G31)"
861        );
862        assert!(argv.contains(&"--ephemeral"), "must have --ephemeral (G31)");
863        assert!(
864            argv.contains(&"--skip-git-repo-check"),
865            "must have --skip-git-repo-check (G31)"
866        );
867        assert!(
868            argv.contains(&"--ignore-rules"),
869            "must have --ignore-rules (G31)"
870        );
871        // v1.0.77: -c TOML overrides bypass codex exec --sandbox bug (#18113)
872        assert!(
873            argv.contains(&"-c") && argv.contains(&"sandbox_mode='read-only'"),
874            "must have -c sandbox_mode='read-only' (v1.0.77, codex#18113)"
875        );
876        assert!(
877            argv.contains(&"approval_policy='never'"),
878            "must have -c approval_policy='never' (v1.0.77)"
879        );
880    }
881
882    /// OAuth-only guard: when `OPENAI_API_KEY` is in the environment,
883    /// `build_codex_command` MUST abort the spawn (return a `false`
884    /// command), NOT pass the key through to the child.
885    #[test]
886    #[serial_test::serial(env)]
887    fn build_command_aborts_when_openai_api_key_set() {
888        // SAFETY: unit test
889        unsafe {
890            std::env::set_var("OPENAI_API_KEY", "sk-violation-test");
891        }
892        let schema = std::env::temp_dir().join("codex-test-schema-abort.json");
893        let _ = std::fs::remove_file(&schema);
894        let args = CodexSpawnArgs {
895            binary: std::path::Path::new("/usr/bin/codex"),
896            prompt: "p",
897            json_schema: "{}",
898            input_text: "i",
899            model: Some("gpt-5.4-mini"),
900            timeout_secs: 60,
901            schema_path: schema.clone(),
902        };
903        let cmd = build_codex_command(&args);
904        let program = cmd.get_program().to_string_lossy().to_string();
905        let argv: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
906        assert_eq!(
907            program, "false",
908            "when OPENAI_API_KEY is set, build_codex_command must abort"
909        );
910        assert!(
911            argv.contains(&"--oauth-only-violation-openai-api-key-set"),
912            "aborted command must carry violation marker"
913        );
914        unsafe {
915            std::env::remove_var("OPENAI_API_KEY");
916        }
917    }
918}