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<'_>) -> Result<Command, crate::errors::AppError> {
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 Ok(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    // GAP-META-005 (v1.0.87, ADR-0045): pre-flight validation gate runs
332    // AFTER argv is fully built. Validates binary existence, argv size,
333    // walk-up of `.mcp.json`, and `CLAUDE_CONFIG_DIR` cleanliness.
334    // Pre-flight failure aborts the spawn with exit 16 — see ADR-0045.
335    let argv_refs: Vec<std::ffi::OsString> = cmd.get_args().map(|s| s.to_os_string()).collect();
336    let preflight_args = crate::spawn::preflight::PreFlightArgs {
337        binary_path: args.binary,
338        argv: &argv_refs,
339        workspace_root: std::path::Path::new("."),
340        mcp_config_inline_json: None, // Codex does not use --mcp-config flag
341        expected_output_bytes: 65_536,
342        spawner_name: "codex_spawn",
343    };
344    if let Err(e) = crate::spawn::preflight::preflight_check(&preflight_args) {
345        // v1.0.88 (BUG-6 fix, ADR-0046): propagate the structured
346        // `PreFlightError` via the `From` impl in `errors.rs` so callers
347        // receive `AppError::PreFlightFailed` (exit 16) instead of a
348        // bare `std::process::exit(16)` that discards the variant name,
349        // tracing context, and PT-BR i18n.
350        return Err(crate::errors::AppError::from(e));
351    }
352
353    Ok(cmd)
354}
355
356/// Parses JSONL output from `codex exec --json`.
357///
358/// Event format (DOTS notation):
359/// - `thread.started` — session init
360/// - `turn.started` — model turn begins
361/// - `item.completed` — message or tool call; last `agent_message` wins
362/// - `turn.completed` — includes usage stats
363/// - `turn.failed` — error with optional rate-limit indicator
364/// - `error` — schema or validation error
365///
366/// G32 (v1.0.69): this function is the single source of truth for JSONL
367/// parsing. Both `enrich` and `ingest --mode codex` consume it.
368pub fn parse_codex_jsonl(stdout: &str) -> Result<CodexResult, AppError> {
369    let mut last_agent_text: Option<String> = None;
370    let mut usage: Option<CodexUsage> = None;
371    let mut rate_limited = false;
372    let mut schema_error = false;
373    let mut turn_failed = false;
374    let mut failed_message = String::new();
375
376    for line in stdout.lines() {
377        let line = line.trim();
378        if line.is_empty() {
379            continue;
380        }
381
382        let event: serde_json::Value = match serde_json::from_str(line) {
383            Ok(v) => v,
384            Err(_) => {
385                tracing::warn!(target: "codex_spawn", line, "skipping malformed JSONL line");
386                continue;
387            }
388        };
389
390        let event_type = match event.get("type").and_then(|t| t.as_str()) {
391            Some(t) => t,
392            None => continue,
393        };
394
395        match event_type {
396            "item.completed" => {
397                if let Some(item) = event.get("item") {
398                    if item.get("type").and_then(|t| t.as_str()) == Some("agent_message") {
399                        if let Some(text) = item.get("text").and_then(|t| t.as_str()) {
400                            last_agent_text = Some(text.to_string());
401                        }
402                    }
403                }
404            }
405            "turn.completed" => {
406                if let Some(u) = event.get("usage") {
407                    // Skip events that lack the recognised token fields
408                    // (e.g. partial broadcasts with `{}`) so the last
409                    // populated usage wins instead of being overwritten
410                    // by an empty one.
411                    let is_populated = u
412                        .get("input_tokens")
413                        .and_then(|v| v.as_u64())
414                        .map(|n| n > 0)
415                        .unwrap_or(false)
416                        || u.get("output_tokens")
417                            .and_then(|v| v.as_u64())
418                            .map(|n| n > 0)
419                            .unwrap_or(false);
420                    if is_populated {
421                        if let Ok(parsed) = serde_json::from_value::<CodexUsage>(u.clone()) {
422                            usage = Some(parsed);
423                        }
424                    }
425                }
426            }
427            "turn.failed" => {
428                turn_failed = true;
429                if let Some(err) = event.get("error") {
430                    let msg = err
431                        .get("message")
432                        .and_then(|m| m.as_str())
433                        .unwrap_or("unknown error");
434                    failed_message = msg.to_string();
435                    if msg.contains("rate_limit")
436                        || msg.contains("429")
437                        || msg.contains("Too Many Requests")
438                    {
439                        rate_limited = true;
440                    }
441                }
442            }
443            "error" => {
444                if let Some(msg) = event.get("message").and_then(|m| m.as_str()) {
445                    if msg.contains("invalid_json_schema") || msg.contains("schema") {
446                        schema_error = true;
447                    }
448                }
449            }
450            _ => {}
451        }
452    }
453
454    let text = last_agent_text.ok_or_else(|| {
455        AppError::Validation(format!(
456            "no agent_message in codex JSONL output (rate_limited={rate_limited}, schema_error={schema_error}, turn_failed={turn_failed})"
457        ))
458    })?;
459
460    if turn_failed {
461        return Err(AppError::Validation(format!(
462            "codex turn failed: {failed_message}"
463        )));
464    }
465    if schema_error {
466        return Err(AppError::Validation(
467            "codex reported invalid_json_schema; check the --output-schema file".to_string(),
468        ));
469    }
470    if rate_limited {
471        return Err(AppError::Validation(format!(
472            "codex rate-limited: {failed_message}"
473        )));
474    }
475
476    let extraction = parse_extraction_text(&text)?;
477    Ok(CodexResult {
478        extraction,
479        last_agent_text: text,
480        usage,
481        rate_limited,
482        schema_error,
483        turn_failed,
484        failed_message,
485    })
486}
487
488/// Parses the agent_message text as an `ExtractionResult` JSON payload.
489///
490/// The schema is shared by both `enrich` and `ingest --mode codex`; the
491/// `text` is the JSON value the assistant returned, not a wrapper object.
492pub fn parse_extraction_text(text: &str) -> Result<ExtractionResult, AppError> {
493    let value: serde_json::Value = serde_json::from_str(text).map_err(|e| {
494        AppError::Validation(format!("failed to parse codex agent_message as JSON: {e}"))
495    })?;
496    let obj = value.as_object().ok_or_else(|| {
497        AppError::Validation("codex agent_message is not a JSON object".to_string())
498    })?;
499
500    let mut entities: Vec<NewEntity> = Vec::new();
501    if let Some(arr) = obj.get("entities").and_then(|v| v.as_array()) {
502        for e in arr {
503            if let Some(name) = e.get("name").and_then(|v| v.as_str()) {
504                // Accept either "type" or "entity_type" from the LLM payload
505                // and fall back to "concept" when the LLM omits it.
506                let entity_type_str = e
507                    .get("type")
508                    .or_else(|| e.get("entity_type"))
509                    .and_then(|v| v.as_str())
510                    .unwrap_or("concept");
511                let entity_type = serde_json::from_value::<crate::entity_type::EntityType>(
512                    serde_json::Value::String(entity_type_str.to_string()),
513                )
514                .unwrap_or(crate::entity_type::EntityType::Concept);
515                entities.push(NewEntity {
516                    name: name.to_string(),
517                    entity_type,
518                    description: None,
519                });
520            }
521        }
522    }
523
524    let mut relationships: Vec<NewRelationship> = Vec::new();
525    if let Some(arr) = obj.get("relationships").and_then(|v| v.as_array()) {
526        for r in arr {
527            let from = r.get("source").or_else(|| r.get("from"));
528            let to = r.get("target").or_else(|| r.get("to"));
529            let rel = r.get("relation").and_then(|v| v.as_str());
530            if let (Some(from_v), Some(to_v), Some(rel_v)) = (
531                from.and_then(|v| v.as_str()),
532                to.and_then(|v| v.as_str()),
533                rel,
534            ) {
535                relationships.push(NewRelationship {
536                    source: from_v.to_string(),
537                    target: to_v.to_string(),
538                    relation: rel_v.to_string(),
539                    strength: r.get("strength").and_then(|v| v.as_f64()).unwrap_or(0.5),
540                    description: None,
541                });
542            }
543        }
544    }
545
546    let urls: Vec<ExtractedUrl> = obj
547        .get("urls")
548        .and_then(|v| v.as_array())
549        .map(|arr| {
550            arr.iter()
551                .filter_map(|u| {
552                    let url = u.get("url")?.as_str()?.to_string();
553                    let start = u.get("start").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
554                    let end = u
555                        .get("end")
556                        .and_then(|v| v.as_u64())
557                        .unwrap_or(start as u64) as usize;
558                    Some(ExtractedUrl { url, start, end })
559                })
560                .collect()
561        })
562        .unwrap_or_default();
563
564    // v1.0.76: ExtractionResult no longer carries relationships or
565    // relationships_truncated fields; those are LLM backend output
566    // (see `ExtractionOutput` in src/extract/mod.rs). The default
567    // build extracts URLs + entities only; relationships are an
568    // LLM-side concern.
569    //
570    // Convert `NewEntity` (storage-side) to `ExtractedEntity`
571    // (extraction-side). The LLM payload doesn't include byte offsets
572    // (the chunker is responsible for that), so start/end are 0.
573    let entities_ext: Vec<crate::extraction::ExtractedEntity> = entities
574        .into_iter()
575        .map(|e| crate::extraction::ExtractedEntity {
576            name: e.name,
577            entity_type: e.entity_type.as_str().to_string(),
578            start: 0,
579            end: 0,
580        })
581        .collect();
582
583    Ok(ExtractionResult {
584        entities: entities_ext,
585        urls,
586        elapsed_ms: 0,
587    })
588}
589
590fn prepare_isolated_codex_home_spawn() -> Option<std::path::PathBuf> {
591    let home = std::env::var("HOME").ok()?;
592    let real_auth = std::path::Path::new(&home).join(".codex/auth.json");
593    if !real_auth.exists() {
594        return None;
595    }
596    let isolated =
597        std::env::temp_dir().join(format!("sqlite-graphrag-codex-home-{}", std::process::id()));
598    let _ = std::fs::create_dir_all(&isolated);
599    let target = isolated.join("auth.json");
600    if !target.exists() {
601        let _ = std::fs::copy(&real_auth, &target);
602    }
603    Some(isolated)
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609
610    const SAMPLE_JSONL: &str = r#"{"type":"thread.started","thread_id":"abc"}
611{"type":"turn.started"}
612{"type":"item.completed","item":{"type":"reasoning","text":"thinking"}}
613{"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\":[]}"}}
614{"type":"turn.completed","usage":{"input_tokens":120,"output_tokens":45}}
615{"type":"turn.completed","usage":{}}
616"#;
617
618    #[test]
619    fn parse_codex_jsonl_extracts_last_agent_message() {
620        // v1.0.76: relationships are no longer carried in the
621        // ExtractionResult struct (they belong to the LLM ExtractionBackend
622        // payload, not the URL-only default build). The default test
623        // validates the entity extraction path only.
624        let result = parse_codex_jsonl(SAMPLE_JSONL).expect("parse must succeed");
625        assert_eq!(result.extraction.entities.len(), 1);
626        assert_eq!(result.extraction.entities[0].name, "alpha");
627    }
628
629    #[test]
630    fn parse_codex_jsonl_collects_usage() {
631        let result = parse_codex_jsonl(SAMPLE_JSONL).expect("parse must succeed");
632        let usage = result.usage.expect("usage must be populated");
633        assert_eq!(usage.input_tokens, 120);
634        assert_eq!(usage.output_tokens, 45);
635    }
636
637    #[test]
638    fn parse_codex_jsonl_detects_rate_limit() {
639        let r = parse_codex_jsonl(
640            "{\"type\":\"turn.failed\",\"error\":{\"message\":\"rate_limit: 429 too many\"}}\n{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"{}\"}}",
641        );
642        assert!(matches!(r, Err(AppError::Validation(_))));
643    }
644
645    #[test]
646    fn parse_codex_jsonl_handles_no_agent_message() {
647        let r = parse_codex_jsonl("{\"type\":\"thread.started\"}");
648        assert!(matches!(r, Err(AppError::Validation(_))));
649    }
650
651    #[test]
652    fn parse_codex_jsonl_skips_malformed_lines() {
653        let r = parse_codex_jsonl(
654            "{not valid json\n{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"{\\\"entities\\\":[],\\\"relationships\\\":[],\\\"extraction_method\\\":\\\"codex\\\"}\"}}",
655        );
656        assert!(r.is_ok(), "malformed lines must be skipped, got {r:?}");
657    }
658
659    #[test]
660    fn validate_codex_model_accepts_known() {
661        assert!(validate_codex_model(Some("gpt-5.5")).is_ok());
662        assert!(validate_codex_model(Some("gpt-5.4")).is_ok());
663        assert!(validate_codex_model(None).is_ok()); // no override
664    }
665
666    #[test]
667    fn validate_codex_model_rejects_unknown() {
668        let err = validate_codex_model(Some("gpt-4")).unwrap_err();
669        let msg = format!("{err}");
670        assert!(msg.contains("not supported"));
671        assert!(msg.contains("gpt-5.5"));
672    }
673
674    #[test]
675    fn list_codex_models_includes_all_static_whitelist() {
676        let models = list_codex_models();
677        for m in CODEX_PRO_OAUTH_MODELS {
678            assert!(models.contains(&m.to_string()), "missing {m} in {models:?}");
679        }
680    }
681
682    #[test]
683    fn suggest_codex_model_substring_match() {
684        let s = suggest_codex_model("gpt-5");
685        assert!(s.is_some(), "must suggest a gpt-5.x model");
686    }
687
688    #[test]
689    fn suggest_codex_model_fuzzy_match() {
690        // 'gpt5.5' has no hyphen; should still suggest 'gpt-5.5'.
691        let s = suggest_codex_model("gpt5.5");
692        assert!(s.is_some(), "fuzzy must suggest gpt-5.5 for 'gpt5.5'");
693        assert_eq!(s.unwrap(), "gpt-5.5");
694    }
695
696    #[test]
697    fn suggest_codex_model_unrelated_returns_none() {
698        let s = suggest_codex_model("totally-unrelated-zzz");
699        assert!(s.is_none());
700    }
701
702    #[test]
703    fn build_codex_command_includes_hardening_flags() {
704        let args = CodexSpawnArgs {
705            binary: Path::new("/bin/true"),
706            prompt: "p",
707            json_schema: "{}",
708            input_text: "i",
709            model: Some("gpt-5.5"),
710            timeout_secs: 60,
711            schema_path: std::env::temp_dir().join("test-schema.json"),
712        };
713        let cmd = build_codex_command(&args).expect("preflight gate accepts valid args");
714        let collected: Vec<String> = cmd
715            .get_args()
716            .filter_map(|a| a.to_str().map(|s| s.to_string()))
717            .collect();
718        for required in &[
719            "exec",
720            "-c",
721            "sandbox_mode='read-only'",
722            "approval_policy='never'",
723            "--json",
724            "--output-schema",
725            "--ephemeral",
726            "--skip-git-repo-check",
727            "--sandbox",
728            "read-only",
729            "--ignore-user-config",
730            "--ignore-rules",
731            "-m",
732            "gpt-5.5",
733            "-",
734        ] {
735            assert!(
736                collected.iter().any(|a| a == required),
737                "missing flag {required} in {collected:?}"
738            );
739        }
740    }
741
742    #[test]
743    fn list_codex_models_dedupes_with_cache_file() {
744        // Ensure the union with the cache file (when present) does not
745        // produce duplicates. We can't actually write a cache file in
746        // a test, so we just verify the static path is dedup'd.
747        let models = list_codex_models();
748        let unique: std::collections::HashSet<_> = models.iter().collect();
749        assert_eq!(unique.len(), models.len(), "list_codex_models must dedupe");
750    }
751    #[test]
752    fn list_codex_models_extracts_from_models_array_v1_0_81_regression() {
753        // v1.0.81 fix: the official codex CLI writes
754        //   {"fetched_at": "...", "etag": "...", "client_version": "...",
755        //    "models": [{"slug": "gpt-5.5", ...}, ...]}
756        // and the old code iterated obj.keys(), polluting the model
757        // list with metadata keys. Here we simulate a cache file by
758        // setting HOME to a tempdir containing a synthetic cache and
759        // verifying the metadata keys are NOT present in the output.
760        let tmp =
761            std::env::temp_dir().join(format!("codex-models-array-test-{}", std::process::id()));
762        std::fs::create_dir_all(tmp.join(".codex")).expect("mkdir");
763        let cache_body = r#"{
764            "fetched_at": "2026-06-14T06:43:56.639903114Z",
765            "etag": "W/\"deadbeef\"",
766            "client_version": "0.139.0",
767            "models": [
768                {"slug": "gpt-5.5", "display_name": "GPT-5.5"},
769                {"slug": "gpt-5.4-mini", "display_name": "GPT-5.4 mini"}
770            ]
771        }"#;
772        std::fs::write(tmp.join(".codex/models_cache.json"), cache_body).expect("write cache");
773        // SAFETY: unit test
774        let prev_home = std::env::var("HOME");
775        unsafe {
776            std::env::set_var("HOME", &tmp);
777        }
778        let models = list_codex_models();
779        unsafe {
780            if let Ok(h) = prev_home {
781                std::env::set_var("HOME", h);
782            } else {
783                std::env::remove_var("HOME");
784            }
785        }
786        let _ = std::fs::remove_dir_all(&tmp);
787
788        for forbidden in &["client_version", "etag", "fetched_at", "models"] {
789            assert!(
790                !models.contains(&forbidden.to_string()),
791                "metadata key {forbidden:?} leaked into model list: {models:?}"
792            );
793        }
794        assert!(
795            models.contains(&"gpt-5.5".to_string()),
796            "gpt-5.5 missing from extracted list: {models:?}"
797        );
798        assert!(
799            models.contains(&"gpt-5.4-mini".to_string()),
800            "gpt-5.4-mini missing from extracted list: {models:?}"
801        );
802    }
803
804    #[test]
805    fn list_codex_models_falls_back_to_keys_when_models_field_absent() {
806        // Legacy cache shape: keys are model ids directly (no models
807        // array). v1.0.81 must still merge those keys into the result.
808        let tmp =
809            std::env::temp_dir().join(format!("codex-models-legacy-test-{}", std::process::id()));
810        std::fs::create_dir_all(tmp.join(".codex")).expect("mkdir");
811        let cache_body = r#"{"legacy-model-x": 1, "legacy-model-y": 2}"#;
812        std::fs::write(tmp.join(".codex/models_cache.json"), cache_body).expect("write cache");
813        let prev_home = std::env::var("HOME");
814        unsafe {
815            std::env::set_var("HOME", &tmp);
816        }
817        let models = list_codex_models();
818        unsafe {
819            if let Ok(h) = prev_home {
820                std::env::set_var("HOME", h);
821            } else {
822                std::env::remove_var("HOME");
823            }
824        }
825        let _ = std::fs::remove_dir_all(&tmp);
826
827        assert!(
828            models.contains(&"legacy-model-x".to_string()),
829            "legacy-model-x missing: {models:?}"
830        );
831        assert!(
832            models.contains(&"legacy-model-y".to_string()),
833            "legacy-model-y missing: {models:?}"
834        );
835    }
836
837    /// OAuth-only conformance test (gaps.md:41-49, v1.0.69 mandate).
838    /// Verifies that `build_codex_command` always emits `-c mcp_servers='{}'`,
839    /// `--ignore-user-config`, `--ask-for-approval never` and does NOT
840    /// whitelist `OPENAI_API_KEY` in the env_clear whitelist.
841    #[test]
842    #[serial_test::serial(env)]
843    fn build_command_oauth_only_mandatory_flags() {
844        // SAFETY: unit test
845        unsafe {
846            std::env::remove_var("OPENAI_API_KEY");
847        }
848        let schema = std::env::temp_dir().join("codex-test-schema.json");
849        let _ = std::fs::remove_file(&schema);
850        let args = CodexSpawnArgs {
851            binary: std::path::Path::new("/usr/bin/false"),
852            prompt: "p",
853            json_schema: "{}",
854            input_text: "i",
855            model: Some("gpt-5.4-mini"),
856            timeout_secs: 60,
857            schema_path: schema.clone(),
858        };
859        let cmd = build_codex_command(&args).expect("preflight gate accepts valid args");
860        let argv: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
861        // Mandatory flags from gaps.md lines 233-238.
862        // -c mcp_servers='{}' was REMOVED in v1.0.76 — codex 0.134+ parses
863        // the value as a string and rejects it ("expected a map"). The
864        // --ignore-user-config flag already covers the MCP isolation
865        // requirement.
866        assert!(
867            argv.contains(&"--ignore-user-config"),
868            "must have --ignore-user-config (gaps.md:266)"
869        );
870        // --ask-for-approval is conditional on codex < 0.134. When the
871        // installed codex is 0.134+ the flag is omitted by the compat
872        // helper. Both outcomes are valid.
873        let ask_for_approval_present = argv.contains(&"--ask-for-approval");
874        if !crate::extract::codex_compat::codex_supports_ask_for_approval() {
875            assert!(
876                !ask_for_approval_present,
877                "codex 0.134+ must NOT include --ask-for-approval"
878            );
879        }
880        assert!(
881            argv.contains(&"--sandbox"),
882            "must have --sandbox read-only (G31)"
883        );
884        assert!(argv.contains(&"--ephemeral"), "must have --ephemeral (G31)");
885        assert!(
886            argv.contains(&"--skip-git-repo-check"),
887            "must have --skip-git-repo-check (G31)"
888        );
889        assert!(
890            argv.contains(&"--ignore-rules"),
891            "must have --ignore-rules (G31)"
892        );
893        // v1.0.77: -c TOML overrides bypass codex exec --sandbox bug (#18113)
894        assert!(
895            argv.contains(&"-c") && argv.contains(&"sandbox_mode='read-only'"),
896            "must have -c sandbox_mode='read-only' (v1.0.77, codex#18113)"
897        );
898        assert!(
899            argv.contains(&"approval_policy='never'"),
900            "must have -c approval_policy='never' (v1.0.77)"
901        );
902    }
903
904    /// OAuth-only guard: when `OPENAI_API_KEY` is in the environment,
905    /// `build_codex_command` MUST abort the spawn (return a `false`
906    /// command), NOT pass the key through to the child.
907    #[test]
908    #[serial_test::serial(env)]
909    fn build_command_aborts_when_openai_api_key_set() {
910        // SAFETY: unit test
911        unsafe {
912            std::env::set_var("OPENAI_API_KEY", "sk-violation-test");
913        }
914        let schema = std::env::temp_dir().join("codex-test-schema-abort.json");
915        let _ = std::fs::remove_file(&schema);
916        let args = CodexSpawnArgs {
917            binary: std::path::Path::new("/usr/bin/codex"),
918            prompt: "p",
919            json_schema: "{}",
920            input_text: "i",
921            model: Some("gpt-5.4-mini"),
922            timeout_secs: 60,
923            schema_path: schema.clone(),
924        };
925        let cmd = build_codex_command(&args).expect("preflight gate accepts valid args");
926        let program = cmd.get_program().to_string_lossy().to_string();
927        let argv: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
928        assert_eq!(
929            program, "false",
930            "when OPENAI_API_KEY is set, build_codex_command must abort"
931        );
932        assert!(
933            argv.contains(&"--oauth-only-violation-openai-api-key-set"),
934            "aborted command must carry violation marker"
935        );
936        unsafe {
937            std::env::remove_var("OPENAI_API_KEY");
938        }
939    }
940}