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    /// Input tokens.
29    #[serde(default)]
30    pub input_tokens: u64,
31    /// Cached input tokens.
32    #[serde(default)]
33    pub cached_input_tokens: u64,
34    /// Output tokens.
35    #[serde(default)]
36    pub output_tokens: u64,
37    /// Reasoning output tokens.
38    #[serde(default)]
39    pub reasoning_output_tokens: u64,
40}
41
42/// Combined result of one `codex exec` invocation.
43#[derive(Debug)]
44pub struct CodexResult {
45    /// Extraction.
46    pub extraction: ExtractionResult,
47    /// Raw text of the last `item.completed` of type `agent_message` (the
48    /// JSON payload the LLM produced). Callers that need a schema other
49    /// than the extraction shape (e.g. body-enrich's `enriched_body`)
50    /// should parse this directly.
51    pub last_agent_text: String,
52    /// Usage.
53    pub usage: Option<CodexUsage>,
54    /// Rate limited.
55    pub rate_limited: bool,
56    /// Schema error.
57    pub schema_error: bool,
58    /// Turn failed.
59    pub turn_failed: bool,
60    /// Failed message.
61    pub failed_message: String,
62}
63
64/// Configuration for the codex spawner.
65#[allow(rustdoc::broken_intra_doc_links)]
66pub struct CodexSpawnArgs<'a> {
67    /// Binary.
68    pub binary: &'a Path,
69    /// Prompt.
70    pub prompt: &'a str,
71    /// JSON schema.
72    pub json_schema: &'a str,
73    /// Input text.
74    pub input_text: &'a str,
75    /// Model name or identifier.
76    pub model: Option<&'a str>,
77    /// Timeout secs.
78    pub timeout_secs: u64,
79    /// Caller-provided schema path (must be inside a trusted directory
80    /// that codex recognises as sandbox-safe). Use [`trusted_schema_path`]
81    /// to compute one under the cache dir.
82    pub schema_path: PathBuf,
83}
84
85/// Computes a schema path under the cache dir so `codex exec` accepts it
86/// as part of a trusted directory (rejects `/tmp` on hardened installs).
87pub fn trusted_schema_path() -> Result<PathBuf, AppError> {
88    let cache = crate::paths::AppPaths::resolve(None)
89        .map(|p| p.models.parent().map(|m| m.to_path_buf()))
90        .ok()
91        .flatten()
92        .unwrap_or_else(std::env::temp_dir);
93    std::fs::create_dir_all(&cache).map_err(AppError::Io)?;
94    Ok(cache.join(format!("enrich-schema-{}.json", std::process::id())))
95}
96
97/// Models accepted by Codex CLI when using ChatGPT Pro OAuth.
98///
99/// Mirrored from `~/.codex/models_cache.json` (which the official CLI
100/// refreshes on every login). This list is intentionally narrow; passing
101/// a model not in this set with `--mode codex` returns
102/// `AppError::Validation` BEFORE any OAuth turn is spent.
103pub const CODEX_PRO_OAUTH_MODELS: &[&str] = &[
104    "codex-auto-review",
105    "gpt-5.3-codex-spark",
106    "gpt-5.4",
107    "gpt-5.4-mini",
108    "gpt-5.5",
109];
110
111/// Validates the requested model against [`CODEX_PRO_OAUTH_MODELS`].
112///
113/// # Errors
114/// Returns [`AppError::Validation`] listing the accepted models when the
115/// caller supplied a model outside the whitelist.
116pub fn validate_codex_model(model: Option<&str>) -> Result<(), AppError> {
117    let Some(m) = model else {
118        return Ok(()); // no override; codex picks its default
119    };
120    if CODEX_PRO_OAUTH_MODELS.contains(&m) {
121        Ok(())
122    } else {
123        Err(AppError::Validation(crate::i18n::validation::codex_model_not_supported_oauth(
124                m,
125                &CODEX_PRO_OAUTH_MODELS.join(", "),
126            )))
127    }
128}
129
130/// Returns the list of models accepted by Codex with ChatGPT Pro OAuth.
131///
132/// Tries to read `~/.codex/models_cache.json` (which the official CLI
133/// refreshes on every login) and falls back to the static
134/// [`CODEX_PRO_OAUTH_MODELS`] constant when the file is missing or
135/// malformed. The returned `Vec<String>` is the union of both sources,
136/// de-duplicated.
137///
138/// The official cache file is an object with the shape
139/// `{"fetched_at": "...", "etag": "...", "client_version": "...",
140/// "models": [{"slug": "gpt-5.5", ...}, ...]}` (v1.0.81 fix: previously we
141/// iterated `obj.keys()` which produced bogus entries like `client_version`
142/// and `etag` as "models"; now we extract only the `models` array).
143pub fn list_codex_models() -> Vec<String> {
144    use std::collections::BTreeSet;
145    let mut out: BTreeSet<String> = CODEX_PRO_OAUTH_MODELS
146        .iter()
147        .map(|s| s.to_string())
148        .collect();
149
150    if let Some(home) = std::env::var_os("HOME") {
151        let path = std::path::Path::new(&home)
152            .join(".codex")
153            .join("models_cache.json");
154        if let Ok(content) = std::fs::read_to_string(&path) {
155            if let Ok(value) = serde_json::from_str::<serde_json::Value>(&content) {
156                if let Some(obj) = value.as_object() {
157                    // v1.0.81 fix: prefer the well-known `models` array
158                    // (each item has a `slug` field). Fall back to keys
159                    // only when `models` is absent (legacy cache format).
160                    if let Some(models_arr) = obj.get("models").and_then(|m| m.as_array()) {
161                        for v in models_arr {
162                            if let Some(slug) = v.get("slug").and_then(|s| s.as_str()) {
163                                out.insert(slug.to_string());
164                            } else if let Some(s) = v.as_str() {
165                                out.insert(s.to_string());
166                            }
167                        }
168                    } else {
169                        for key in obj.keys() {
170                            out.insert(key.clone());
171                        }
172                    }
173                } else if let Some(arr) = value.as_array() {
174                    for v in arr {
175                        if let Some(s) = v.as_str() {
176                            out.insert(s.to_string());
177                        }
178                    }
179                }
180            }
181        }
182    }
183    out.into_iter().collect()
184}
185
186/// Suggests the closest codex OAuth model to a user-supplied substring
187/// (G33). Returns `None` when no candidate is close enough.
188///
189/// Match strategy: exact substring containment wins; otherwise Levenshtein
190/// distance below `max_distance = max(2, query.len() / 3)`.
191pub fn suggest_codex_model(query: &str) -> Option<String> {
192    let query_lc = query.to_ascii_lowercase();
193    let models = list_codex_model_lc();
194
195    // Exact substring match wins.
196    for m in &models {
197        if m.contains(&query_lc) {
198            return Some(m.clone());
199        }
200    }
201
202    // Levenshtein fallback.
203    let max_distance = (query.len() / 3).max(2);
204    let mut best: Option<(usize, String)> = None;
205    for m in &models {
206        let d = levenshtein(query_lc.as_str(), m.as_str());
207        if d <= max_distance && best.as_ref().is_none_or(|(bd, _)| d < *bd) {
208            best = Some((d, m.clone()));
209        }
210    }
211    best.map(|(_, m)| m)
212}
213
214fn list_codex_model_lc() -> Vec<String> {
215    list_codex_models()
216        .into_iter()
217        .map(|s| s.to_ascii_lowercase())
218        .collect()
219}
220
221fn levenshtein(a: &str, b: &str) -> usize {
222    let a_chars: Vec<char> = a.chars().collect();
223    let b_chars: Vec<char> = b.chars().collect();
224    if a_chars.is_empty() {
225        return b_chars.len();
226    }
227    if b_chars.is_empty() {
228        return a_chars.len();
229    }
230    let mut prev: Vec<usize> = (0..=b_chars.len()).collect();
231    let mut curr = vec![0; b_chars.len() + 1];
232    for (i, &ac) in a_chars.iter().enumerate() {
233        curr[0] = i + 1;
234        for (j, &bc) in b_chars.iter().enumerate() {
235            let cost = if ac == bc { 0 } else { 1 };
236            curr[j + 1] = (curr[j] + 1).min(prev[j + 1] + 1).min(prev[j] + cost);
237        }
238        std::mem::swap(&mut prev, &mut curr);
239    }
240    prev[b_chars.len()]
241}
242
243/// Builds the `codex exec` command with the canonical hardening flags.
244///
245/// G31 + OAuth-only hardening (v1.0.69, mandated by gaps.md lines 41-49):
246/// the command ALWAYS uses the OAuth `auth.json` flow. The flag set is
247/// the canonical one documented in gaps.md Fix A:
248///
249/// ```text
250/// codex exec \
251///   -c mcp_servers='{}' \
252///   --json --output-schema <SCHEMA> \
253///   --ephemeral \
254///   --skip-git-repo-check \
255///   --sandbox read-only \
256///   --ignore-user-config \
257///   --ignore-rules \
258///   --ask-for-approval never \
259///   -m <MODEL> \
260///   -
261/// ```
262///
263/// The combination zeroes MCP servers (via two complementary mechanisms:
264/// the inline `-c mcp_servers='{}'` override AND `--ignore-user-config`),
265/// disables user-defined rules, and never asks for interactive approval.
266///
267/// **`OPENAI_API_KEY` is FORBIDDEN** in the spawned environment (gaps.md:48).
268/// OAuth flows via `~/.codex/auth.json` and `CODEX_ACCESS_TOKEN` only.
269pub fn build_codex_command(args: &CodexSpawnArgs<'_>) -> Result<Command, crate::errors::AppError> {
270    let full_prompt = format!("{}\n\n{}", args.prompt, args.input_text);
271
272    // OAuth-only guard (gaps.md:48, ADR-0011). If `OPENAI_API_KEY` is set
273    // in the environment we MUST abort — that is the API-key path which is
274    // explicitly PROHIBITED. Use the OAuth `auth.json` flow exclusively.
275    if let Ok(_key) = std::env::var("OPENAI_API_KEY") {
276        let mut cmd = crate::spawn::failing_command();
277        cmd.env_clear();
278        cmd.env("PATH", "/nonexistent");
279        cmd.arg("--oauth-only-violation-openai-api-key-set");
280        cmd.arg("--oauth-only-resolution-use-codex-auth-json-or-openai-base-url");
281        return Ok(cmd);
282    }
283
284    // Write the JSON schema to a path the caller controls. Callers should
285    // pass a path under the cache dir (see [`trusted_schema_path`]).
286    std::fs::write(&args.schema_path, args.json_schema).ok();
287
288    let mut cmd = Command::new(args.binary);
289    // v1.0.83 (ADR-0041): env whitelist delegated to the shared helper.
290    // `OPENAI_API_KEY` is INTENTIONALLY ABSENT (defence-in-depth).
291    // `CODEX_ACCESS_TOKEN` and `OPENAI_BASE_URL` ARE whitelisted for
292    // custom providers via the canonical list in src/spawn/env_whitelist.rs.
293    apply_env_whitelist(&mut cmd, crate::spawn::env_whitelist::is_strict_env_clear());
294    crate::spawn::apply_cwd_isolation(&mut cmd)?;
295
296    // v1.0.77: point CODEX_HOME at an isolated dir that only contains
297    // auth.json — this prevents the codex subprocess from loading
298    // ~/.codex/config.toml (which has trust_level=trusted for the project,
299    // causing sandbox escalation per openai/codex#18113).
300    if let Some(isolated) = prepare_isolated_codex_home_spawn() {
301        cmd.env("CODEX_HOME", isolated);
302    }
303
304    // v1.0.77: `-c` TOML overrides bypass the codex exec --sandbox propagation
305    // bug (openai/codex#18113). CLI flags alone are insufficient — the exec
306    // subcommand may not inherit --sandbox from the parent codex command.
307    cmd.arg("exec")
308        .arg("-c")
309        .arg("sandbox_mode='read-only'")
310        .arg("-c")
311        .arg("approval_policy='never'")
312        .arg("--json")
313        .arg("--output-schema")
314        .arg(&args.schema_path)
315        .arg("--ephemeral")
316        .arg("--skip-git-repo-check")
317        .arg("--sandbox")
318        .arg("read-only")
319        .arg("--ignore-user-config")
320        .arg("--ignore-rules");
321
322    // Codex 0.134+ no longer accepts `-c mcp_servers='{}'` — it parses the
323    // value as a string and rejects it ("expected a map"). The
324    // `--ignore-user-config` flag already discards any user-defined MCP
325    // servers, so the override is redundant on all supported versions.
326
327    // Codex 0.134+ removed --ask-for-approval entirely (Issue #26602).
328    // Skip the flag on newer versions; sandbox=read-only already suppresses
329    // approval prompts. See src/extract/codex_compat.rs for the probe.
330    if codex_supports_ask_for_approval() {
331        cmd.arg("--ask-for-approval").arg("never");
332    }
333
334    if let Some(m) = args.model {
335        cmd.arg("-m").arg(m);
336    }
337
338    // `-` means: read the prompt from stdin (Codex Paperclip pattern)
339    cmd.arg("-");
340
341    cmd.stdin(Stdio::piped())
342        .stdout(Stdio::piped())
343        .stderr(Stdio::piped());
344    // Keep the prompt alive for the stdin thread spawned in `spawn_codex`.
345    let _ = full_prompt; // captured by closure below
346
347    // GAP-META-005 (v1.0.87, ADR-0045): pre-flight validation gate runs
348    // AFTER argv is fully built. Validates binary existence, argv size,
349    // walk-up of `.mcp.json`, and `CLAUDE_CONFIG_DIR` cleanliness.
350    // Pre-flight failure aborts the spawn with exit 16 — see ADR-0045.
351    let argv_refs: Vec<std::ffi::OsString> = cmd.get_args().map(|s| s.to_os_string()).collect();
352    let preflight_args = crate::spawn::preflight::PreFlightArgs {
353        binary_path: args.binary,
354        argv: &argv_refs,
355        workspace_root: std::path::Path::new("."),
356        mcp_config_inline_json: None, // Codex does not use --mcp-config flag
357        expected_output_bytes: 65_536,
358        spawner_name: "codex_spawn",
359    };
360    if let Err(e) = crate::spawn::preflight::preflight_check(&preflight_args) {
361        // v1.0.88 (BUG-6 fix, ADR-0046): propagate the structured
362        // `PreFlightError` via the `From` impl in `errors.rs` so callers
363        // receive `AppError::PreFlightFailed` (exit 16) instead of a
364        // bare `std::process::exit(16)` that discards the variant name,
365        // tracing context, and PT-BR i18n.
366        return Err(crate::errors::AppError::from(e));
367    }
368
369    Ok(cmd)
370}
371
372/// Parses JSONL output from `codex exec --json`.
373///
374/// Event format (DOTS notation):
375/// - `thread.started` — session init
376/// - `turn.started` — model turn begins
377/// - `item.completed` — message or tool call; last `agent_message` wins
378/// - `turn.completed` — includes usage stats
379/// - `turn.failed` — error with optional rate-limit indicator
380/// - `error` — schema or validation error
381///
382/// G32 (v1.0.69): this function is the single source of truth for JSONL
383/// parsing. Both `enrich` and `ingest --mode codex` consume it.
384pub fn parse_codex_jsonl(stdout: &str) -> Result<CodexResult, AppError> {
385    let mut last_agent_text: Option<String> = None;
386    let mut usage: Option<CodexUsage> = None;
387    let mut rate_limited = false;
388    let mut schema_error = false;
389    let mut turn_failed = false;
390    let mut failed_message = String::new();
391
392    for line in stdout.lines() {
393        let line = line.trim();
394        if line.is_empty() {
395            continue;
396        }
397
398        let event: serde_json::Value = match serde_json::from_str(line) {
399            Ok(v) => v,
400            Err(_) => {
401                tracing::warn!(target: "codex_spawn", line, "skipping malformed JSONL line");
402                continue;
403            }
404        };
405
406        let event_type = match event.get("type").and_then(|t| t.as_str()) {
407            Some(t) => t,
408            None => continue,
409        };
410
411        match event_type {
412            "item.completed" => {
413                if let Some(item) = event.get("item") {
414                    if item.get("type").and_then(|t| t.as_str()) == Some("agent_message") {
415                        if let Some(text) = item.get("text").and_then(|t| t.as_str()) {
416                            last_agent_text = Some(text.to_string());
417                        }
418                    }
419                }
420            }
421            "turn.completed" => {
422                if let Some(u) = event.get("usage") {
423                    // Skip events that lack the recognised token fields
424                    // (e.g. partial broadcasts with `{}`) so the last
425                    // populated usage wins instead of being overwritten
426                    // by an empty one.
427                    let is_populated = u
428                        .get("input_tokens")
429                        .and_then(|v| v.as_u64())
430                        .map(|n| n > 0)
431                        .unwrap_or(false)
432                        || u.get("output_tokens")
433                            .and_then(|v| v.as_u64())
434                            .map(|n| n > 0)
435                            .unwrap_or(false);
436                    if is_populated {
437                        if let Ok(parsed) = serde_json::from_value::<CodexUsage>(u.clone()) {
438                            usage = Some(parsed);
439                        }
440                    }
441                }
442            }
443            "turn.failed" => {
444                turn_failed = true;
445                if let Some(err) = event.get("error") {
446                    let msg = err
447                        .get("message")
448                        .and_then(|m| m.as_str())
449                        .unwrap_or("unknown error");
450                    failed_message = msg.to_string();
451                    if msg.contains("rate_limit")
452                        || msg.contains("429")
453                        || msg.contains("Too Many Requests")
454                    {
455                        rate_limited = true;
456                    }
457                }
458            }
459            "error" => {
460                if let Some(msg) = event.get("message").and_then(|m| m.as_str()) {
461                    if msg.contains("invalid_json_schema") || msg.contains("schema") {
462                        schema_error = true;
463                    }
464                }
465            }
466            _ => {}
467        }
468    }
469
470    let text = last_agent_text.ok_or_else(|| {
471        AppError::Validation(crate::i18n::validation::no_agent_message_in_codex_jsonl(
472            rate_limited,
473            schema_error,
474            turn_failed,
475        ))
476    })?;
477
478    if turn_failed {
479        return Err(AppError::Validation(crate::i18n::validation::codex_turn_failed(&failed_message)));
480    }
481    if schema_error {
482        return Err(AppError::Validation(
483            "codex reported invalid_json_schema; check the --output-schema file".to_string(),
484        ));
485    }
486    if rate_limited {
487        return Err(AppError::Validation(crate::i18n::validation::codex_rate_limited(&failed_message)));
488    }
489
490    let extraction = parse_extraction_text(&text)?;
491    Ok(CodexResult {
492        extraction,
493        last_agent_text: text,
494        usage,
495        rate_limited,
496        schema_error,
497        turn_failed,
498        failed_message,
499    })
500}
501
502/// Parses the agent_message text as an `ExtractionResult` JSON payload.
503///
504/// The schema is shared by both `enrich` and `ingest --mode codex`; the
505/// `text` is the JSON value the assistant returned, not a wrapper object.
506pub fn parse_extraction_text(text: &str) -> Result<ExtractionResult, AppError> {
507    let value: serde_json::Value = serde_json::from_str(text).map_err(|e| {
508        AppError::Validation(crate::i18n::validation::failed_to_parse_codex_agent_message_json(&e))
509    })?;
510    let obj = value.as_object().ok_or_else(|| {
511        AppError::Validation(crate::i18n::validation::codex_agent_message_not_json_object())
512    })?;
513
514    let mut entities: Vec<NewEntity> = Vec::new();
515    if let Some(arr) = obj.get("entities").and_then(|v| v.as_array()) {
516        for e in arr {
517            if let Some(name) = e.get("name").and_then(|v| v.as_str()) {
518                // Accept either "type" or "entity_type" from the LLM payload
519                // and fall back to "concept" when the LLM omits it.
520                let entity_type_str = e
521                    .get("type")
522                    .or_else(|| e.get("entity_type"))
523                    .and_then(|v| v.as_str())
524                    .unwrap_or("concept");
525                // GAP-SG-47: fold non-canonical labels onto the nearest
526                // canonical kind (preserves aliases/case instead of collapsing
527                // every miss straight to concept).
528                let entity_type = crate::entity_type::EntityType::map_to_canonical(entity_type_str);
529                entities.push(NewEntity {
530                    name: name.to_string(),
531                    entity_type,
532                    description: None,
533                });
534            }
535        }
536    }
537
538    let mut relationships: Vec<NewRelationship> = Vec::new();
539    if let Some(arr) = obj.get("relationships").and_then(|v| v.as_array()) {
540        for r in arr {
541            let from = r.get("source").or_else(|| r.get("from"));
542            let to = r.get("target").or_else(|| r.get("to"));
543            let rel = r.get("relation").and_then(|v| v.as_str());
544            if let (Some(from_v), Some(to_v), Some(rel_v)) = (
545                from.and_then(|v| v.as_str()),
546                to.and_then(|v| v.as_str()),
547                rel,
548            ) {
549                relationships.push(NewRelationship {
550                    source: from_v.to_string(),
551                    target: to_v.to_string(),
552                    // GAP-SG-48: rewrite non-canonical relations to canonical.
553                    relation: crate::parsers::map_to_canonical_relation(rel_v),
554                    strength: r.get("strength").and_then(|v| v.as_f64()).unwrap_or(0.5),
555                    description: None,
556                });
557            }
558        }
559    }
560
561    let urls: Vec<ExtractedUrl> = obj
562        .get("urls")
563        .and_then(|v| v.as_array())
564        .map(|arr| {
565            arr.iter()
566                .filter_map(|u| {
567                    let url = u.get("url")?.as_str()?.to_string();
568                    let start = u.get("start").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
569                    let end = u
570                        .get("end")
571                        .and_then(|v| v.as_u64())
572                        .unwrap_or(start as u64) as usize;
573                    Some(ExtractedUrl { url, start, end })
574                })
575                .collect()
576        })
577        .unwrap_or_default();
578
579    // v1.0.76: ExtractionResult no longer carries relationships or
580    // relationships_truncated fields; those are LLM backend output
581    // (see `ExtractionOutput` in src/extract/mod.rs). The default
582    // build extracts URLs + entities only; relationships are an
583    // LLM-side concern.
584    //
585    // Convert `NewEntity` (storage-side) to `ExtractedEntity`
586    // (extraction-side). The LLM payload doesn't include byte offsets
587    // (the chunker is responsible for that), so start/end are 0.
588    let entities_ext: Vec<crate::extraction::ExtractedEntity> = entities
589        .into_iter()
590        .map(|e| crate::extraction::ExtractedEntity {
591            name: e.name,
592            entity_type: e.entity_type.as_str().to_string(),
593            start: 0,
594            end: 0,
595        })
596        .collect();
597
598    Ok(ExtractionResult {
599        entities: entities_ext,
600        urls,
601        elapsed_ms: 0,
602    })
603}
604
605fn prepare_isolated_codex_home_spawn() -> Option<std::path::PathBuf> {
606    let home = std::env::var("HOME").ok()?;
607    let real_auth = std::path::Path::new(&home).join(".codex/auth.json");
608    if !real_auth.exists() {
609        return None;
610    }
611    let isolated =
612        std::env::temp_dir().join(format!("sqlite-graphrag-codex-home-{}", std::process::id()));
613    let _ = std::fs::create_dir_all(&isolated);
614    let target = isolated.join("auth.json");
615    if !target.exists() {
616        let _ = std::fs::copy(&real_auth, &target);
617    }
618    Some(isolated)
619}
620#[cfg(test)]
621#[path = "codex_spawn_tests.rs"]
622mod tests;