Skip to main content

sqlite_graphrag/extract/
llm_embedding.rs

1//! LLM-based embedding backend (v1.0.76 default; reworked in v1.0.79 G42).
2//!
3//! `LlmEmbedding` is the production embedding client. It wraps headless
4//! invocations of `claude code` or `codex` and returns f32 vectors of the
5//! active dimensionality (`crate::constants::embedding_dim()`, default 64).
6//!
7//! v1.0.79 (G42) changes:
8//! - S1: the dimensionality is no longer hardcoded here — the single
9//!   source of truth lives in `crate::constants` and the JSON schemas
10//!   are generated dynamically.
11//! - S2: `embed_batch` embeds N numbered texts per LLM call with the
12//!   `{items:[{i,v}]}` schema, collapsing 39 subprocess spawns into 4-5.
13//! - S4: the codex `--output-schema` file is a `tempfile::NamedTempFile`
14//!   with a randomised name created once per client and shared across
15//!   clones via `Arc` — no per-call write+delete, no PID-path races.
16//! - S5: the claude model honours `SQLITE_GRAPHRAG_CLAUDE_EMBED_MODEL`
17//!   (symmetric to the codex env var). ZERO hardcoded models without
18//!   an env override.
19//! - S6: `CLAUDE_CONFIG_DIR` points at an empty managed directory BY
20//!   DEFAULT, because `--strict-mcp-config`/`--mcp-config '{}'` are
21//!   silently ignored upstream (anthropics/claude-code#10787) and a
22//!   full `~/.claude` costs ~223k cache-creation tokens per call.
23//! - S7: the codex `request_user_input` failure mode maps to an
24//!   actionable error instead of an opaque exit 11.
25//! - BLOCO 4: every subprocess uses `kill_on_drop(true)` plus an
26//!   explicit `tokio::time::timeout`, so cancellation never leaks a
27//!   child and a hung LLM cannot stall the pipeline forever.
28//!
29//! OAuth is the only supported credential path. The constructor rejects
30//! `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` in the environment — see
31//! `v1.0.69 (G31) OAuth-Only Enforcement`.
32
33use crate::errors::AppError;
34use serde::Deserialize;
35use std::process::Stdio;
36use std::sync::Arc;
37use tokio::io::AsyncWriteExt;
38use tokio::process::Command;
39
40/// Default per-LLM-call timeout in seconds. Consistent with the
41/// `--claude-timeout` / `--codex-timeout` defaults used by ingest.
42/// Override via `SQLITE_GRAPHRAG_EMBED_TIMEOUT_SECS`.
43const DEFAULT_EMBED_TIMEOUT_SECS: u64 = 300;
44
45fn embed_timeout() -> std::time::Duration {
46    let secs = std::env::var("SQLITE_GRAPHRAG_EMBED_TIMEOUT_SECS")
47        .ok()
48        .and_then(|v| v.parse::<u64>().ok())
49        .filter(|&n| (10..=3_600).contains(&n))
50        .unwrap_or(DEFAULT_EMBED_TIMEOUT_SECS);
51    std::time::Duration::from_secs(secs)
52}
53
54/// G42/S1: single-vector JSON schema generated from the active dim.
55fn build_single_schema(dim: usize) -> String {
56    format!(
57        r#"{{"type":"object","properties":{{"embedding":{{"type":"array","items":{{"type":"number"}},"minItems":{dim},"maxItems":{dim}}}}},"required":["embedding"],"additionalProperties":false}}"#
58    )
59}
60
61/// G42/S2: batch JSON schema `{items:[{i,v}]}`. The `items` array length
62/// is deliberately unconstrained so ONE schema file serves every batch
63/// size (index coverage is validated in Rust after parsing).
64fn build_batch_schema(dim: usize) -> String {
65    format!(
66        r#"{{"type":"object","properties":{{"items":{{"type":"array","items":{{"type":"object","properties":{{"i":{{"type":"integer"}},"v":{{"type":"array","items":{{"type":"number"}},"minItems":{dim},"maxItems":{dim}}}}},"required":["i","v"],"additionalProperties":false}}}}}},"required":["items"],"additionalProperties":false}}"#
67    )
68}
69
70#[derive(Clone, Debug)]
71pub struct LlmEmbedding {
72    /// Which LLM headless binary to spawn. `claude` or `codex`.
73    flavour: EmbeddingFlavour,
74    /// Cached path to the binary to avoid PATH lookups on every call.
75    binary: std::path::PathBuf,
76    /// Model name. Resolved from env overrides at construction time.
77    model: String,
78    /// G42/S4: lazily-created codex `--output-schema` tempfiles, shared
79    /// across clones. Keyed by dim so an env change between tests cannot
80    /// serve a stale schema.
81    codex_schemas: Arc<parking_lot::Mutex<CodexSchemaFiles>>,
82}
83
84#[derive(Debug, Default)]
85struct CodexSchemaFiles {
86    single: Option<(usize, Arc<tempfile::NamedTempFile>)>,
87    batch: Option<(usize, Arc<tempfile::NamedTempFile>)>,
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
91pub enum EmbeddingFlavour {
92    Claude,
93    Codex,
94}
95
96impl EmbeddingFlavour {
97    pub fn as_str(self) -> &'static str {
98        match self {
99            Self::Claude => "claude",
100            Self::Codex => "codex",
101        }
102    }
103}
104
105#[derive(Debug, Deserialize)]
106struct EmbeddingResponse {
107    embedding: Vec<f32>,
108}
109
110#[derive(Debug, Deserialize)]
111struct BatchEmbeddingResponse {
112    items: Vec<BatchEmbeddingItem>,
113}
114
115#[derive(Debug, Deserialize)]
116struct BatchEmbeddingItem {
117    i: usize,
118    v: Vec<f32>,
119}
120
121/// Follows symlinks and shell-script shim `exec` targets to find
122/// the real ELF binary. Shim wrappers (like `~/.graphrag-shim/codex`)
123/// can strip hardening flags; bypassing them is a security requirement.
124pub fn resolve_real_binary(path: &std::path::Path) -> std::path::PathBuf {
125    if let Ok(canonical) = std::fs::canonicalize(path) {
126        if is_elf_binary(&canonical) {
127            return canonical;
128        }
129        if let Some(exec_target) = extract_exec_target_from_shim(&canonical) {
130            if exec_target.exists() && is_elf_binary(&exec_target) {
131                return exec_target;
132            }
133        }
134        return canonical;
135    }
136    path.to_path_buf()
137}
138
139fn is_elf_binary(path: &std::path::Path) -> bool {
140    std::fs::read(path)
141        .map(|bytes| bytes.len() >= 4 && bytes[..4] == [0x7f, b'E', b'L', b'F'])
142        .unwrap_or(false)
143}
144
145fn extract_exec_target_from_shim(path: &std::path::Path) -> Option<std::path::PathBuf> {
146    let content = std::fs::read_to_string(path).ok()?;
147    if !content.starts_with("#!") {
148        return None;
149    }
150    for line in content.lines().rev() {
151        let trimmed = line.trim();
152        if trimmed.starts_with("exec ") {
153            let after_exec = trimmed.strip_prefix("exec ")?;
154            let binary = after_exec.split_whitespace().next()?;
155            return Some(std::path::PathBuf::from(binary));
156        }
157    }
158    None
159}
160
161/// G42/S5: claude embedding model with env override, symmetric to the
162/// codex `SQLITE_GRAPHRAG_CODEX_EMBED_MODEL` introduced in v1.0.78.
163fn claude_embed_model() -> String {
164    std::env::var("SQLITE_GRAPHRAG_CLAUDE_EMBED_MODEL")
165        .unwrap_or_else(|_| "claude-sonnet-4-6".to_string())
166}
167
168fn codex_embed_model() -> String {
169    std::env::var("SQLITE_GRAPHRAG_CODEX_EMBED_MODEL").unwrap_or_else(|_| "gpt-5.5".to_string())
170}
171
172impl LlmEmbedding {
173    /// Detects which LLM CLI is available on PATH and returns the
174    /// matching embedding client.
175    ///
176    /// v1.0.76: PREFERS `codex` over `claude` because:
177    /// - Claude Code 2.1+ ships a 180k+ token system context (plugins,
178    ///   skills, agents, MCP) that overflows the 200k context window
179    ///   for even trivial embedding prompts and returns "Prompt is too
180    ///   long". (v1.0.79/S6 mitigates this with an empty
181    ///   `CLAUDE_CONFIG_DIR`, but codex stays the lighter default.)
182    /// - Codex 0.134+ is lightweight (~5k system context) and the
183    ///   `StructuredOutput` tool reliably returns the requested vectors.
184    pub fn detect_available() -> Result<Self, AppError> {
185        Self::oauth_only_enforce()?;
186
187        if let Ok(path) = which::which("codex") {
188            return Ok(Self {
189                flavour: EmbeddingFlavour::Codex,
190                binary: resolve_real_binary(&path),
191                model: codex_embed_model(),
192                codex_schemas: Arc::new(parking_lot::Mutex::new(CodexSchemaFiles::default())),
193            });
194        }
195        if let Ok(path) = which::which("claude") {
196            return Ok(Self {
197                flavour: EmbeddingFlavour::Claude,
198                binary: resolve_real_binary(&path),
199                model: claude_embed_model(),
200                codex_schemas: Arc::new(parking_lot::Mutex::new(CodexSchemaFiles::default())),
201            });
202        }
203        Err(AppError::Embedding(
204            "no LLM CLI found on PATH: install `codex` (0.130+) or `claude` (Claude Code 2.1+)"
205                .to_string(),
206        ))
207    }
208
209    pub fn with_codex() -> Result<Self, AppError> {
210        Self::oauth_only_enforce()?;
211        let path = which::which("codex")
212            .map_err(|_| AppError::Embedding("`codex` not found on PATH".to_string()))?;
213        Ok(Self {
214            flavour: EmbeddingFlavour::Codex,
215            binary: resolve_real_binary(&path),
216            model: codex_embed_model(),
217            codex_schemas: Arc::new(parking_lot::Mutex::new(CodexSchemaFiles::default())),
218        })
219    }
220
221    pub fn with_claude() -> Result<Self, AppError> {
222        Self::oauth_only_enforce()?;
223        let path = which::which("claude")
224            .map_err(|_| AppError::Embedding("`claude` not found on PATH".to_string()))?;
225        Ok(Self {
226            flavour: EmbeddingFlavour::Claude,
227            binary: resolve_real_binary(&path),
228            model: claude_embed_model(),
229            codex_schemas: Arc::new(parking_lot::Mutex::new(CodexSchemaFiles::default())),
230        })
231    }
232
233    /// v1.0.69 (G31): refuse to spawn if an API key is set. The CLI
234    /// must use OAuth. The two API-key env vars are NOT in the
235    /// env-clear whitelist, so a parent process that exports them
236    /// will see this error.
237    fn oauth_only_enforce() -> Result<(), AppError> {
238        if std::env::var("ANTHROPIC_API_KEY").is_ok() {
239            return Err(AppError::Validation(
240                "ANTHROPIC_API_KEY is set; v1.0.76 requires OAuth. \
241                 unset it and use `claude login` instead."
242                    .into(),
243            ));
244        }
245        if std::env::var("OPENAI_API_KEY").is_ok() {
246            return Err(AppError::Validation(
247                "OPENAI_API_KEY is set; v1.0.76 requires OAuth. \
248                 unset it and use `codex login` instead."
249                    .into(),
250            ));
251        }
252        Ok(())
253    }
254
255    /// Embeds a single passage (chunk of a memory body). Returns an
256    /// f32 vector of the active dimensionality.
257    pub fn embed_passage(&self, text: &str) -> Result<Vec<f32>, AppError> {
258        self.invoke_with_prefix(crate::constants::PASSAGE_PREFIX, text)
259    }
260
261    /// Embeds a single query. The LLM uses a different prompt prefix
262    /// to disambiguate query from passage.
263    pub fn embed_query(&self, text: &str) -> Result<Vec<f32>, AppError> {
264        self.invoke_with_prefix(crate::constants::QUERY_PREFIX, text)
265    }
266
267    /// G56: returns a stable label for the active embedding model so the
268    /// in-process entity-embedding cache can key by `(model, text)`.
269    /// Embeddings produced by different models are not interchangeable,
270    /// so a cache entry from one model must never satisfy a request
271    /// served by another.
272    pub fn model_label(&self) -> String {
273        format!("{}:{}", self.flavour.as_str(), self.model)
274    }
275
276    /// G42/S2: embeds a batch of `(global_index, text)` pairs in ONE
277    /// LLM call. Returns `(global_index, vector)` pairs. Async — this
278    /// is the unit of work scheduled by the bounded fan-out in
279    /// `crate::embedder`.
280    ///
281    /// Cancel safety: the future owns its subprocess via
282    /// `kill_on_drop(true)`, so dropping it (e.g. losing a
283    /// `tokio::select!` race against a cancellation token) kills the
284    /// child and leaks nothing.
285    pub async fn embed_batch_async(
286        &self,
287        prefix: &str,
288        batch: &[(usize, String)],
289    ) -> Result<Vec<(usize, Vec<f32>)>, AppError> {
290        let dim = crate::constants::embedding_dim();
291        if batch.is_empty() {
292            return Ok(Vec::new());
293        }
294        if batch.len() == 1 {
295            let (idx, text) = (&batch[0].0, &batch[0].1);
296            let v = self.invoke_single_async(prefix, text, dim).await?;
297            return Ok(vec![(*idx, v)]);
298        }
299
300        let mut prompt = format!(
301            "Generate {dim}-dimensional semantic embedding vectors for each numbered text below.\n\
302             Return a JSON object with an \"items\" array containing EXACTLY {n} items.\n\
303             Each item has \"i\" (the 1-based index) and \"v\" (the {dim}-float vector, values between -1 and 1).\n\n",
304            n = batch.len()
305        );
306        for (pos, (_, text)) in batch.iter().enumerate() {
307            prompt.push_str(&format!("{}: {prefix}{text}\n", pos + 1));
308        }
309
310        let stdout = match self.flavour {
311            EmbeddingFlavour::Claude => {
312                self.invoke_claude(&prompt, &build_batch_schema(dim))
313                    .await?
314            }
315            EmbeddingFlavour::Codex => {
316                let schema = self.codex_schema_file(dim, true)?;
317                self.invoke_codex(&prompt, schema.path()).await?
318            }
319        };
320
321        let parsed: BatchEmbeddingResponse = parse_llm_json(&stdout).map_err(|e| {
322            AppError::Embedding(format!(
323                "LLM batch embedding response parse failed: {e}; raw={stdout}"
324            ))
325        })?;
326        if parsed.items.len() != batch.len() {
327            return Err(AppError::Embedding(format!(
328                "LLM batch returned {} items, expected {} (G42/S2 coverage check)",
329                parsed.items.len(),
330                batch.len()
331            )));
332        }
333        let mut out: Vec<Option<Vec<f32>>> = vec![None; batch.len()];
334        for item in parsed.items {
335            if item.i == 0 || item.i > batch.len() {
336                return Err(AppError::Embedding(format!(
337                    "LLM batch item index {} out of range 1..={}",
338                    item.i,
339                    batch.len()
340                )));
341            }
342            if item.v.len() != dim {
343                return Err(AppError::Embedding(format!(
344                    "LLM batch item {} returned {} dims, expected {dim}; \
345                     refusing to truncate or pad silently (G42/C5)",
346                    item.i,
347                    item.v.len()
348                )));
349            }
350            out[item.i - 1] = Some(item.v);
351        }
352        let mut result = Vec::with_capacity(batch.len());
353        for (pos, slot) in out.into_iter().enumerate() {
354            let v = slot.ok_or_else(|| {
355                AppError::Embedding(format!(
356                    "LLM batch response is missing item index {} (G42/S2 coverage check)",
357                    pos + 1
358                ))
359            })?;
360            result.push((batch[pos].0, v));
361        }
362        Ok(result)
363    }
364
365    fn invoke_with_prefix(&self, prefix: &str, text: &str) -> Result<Vec<f32>, AppError> {
366        let dim = crate::constants::embedding_dim();
367        let inner = self.invoke_single_async(prefix, text, dim);
368        // v1.0.79 (G42/A2): reuse the process-wide multi-thread runtime
369        // instead of building a current-thread runtime PER CALL. Inside
370        // an existing runtime (tests, async commands) block_in_place
371        // keeps the worker pool healthy.
372        match tokio::runtime::Handle::try_current() {
373            Ok(handle) => tokio::task::block_in_place(|| handle.block_on(inner)),
374            Err(_) => crate::embedder::shared_runtime()?.block_on(inner),
375        }
376    }
377
378    async fn invoke_single_async(
379        &self,
380        prefix: &str,
381        text: &str,
382        dim: usize,
383    ) -> Result<Vec<f32>, AppError> {
384        let prompt = format!("{prefix}{text}");
385        let stdout = match self.flavour {
386            EmbeddingFlavour::Claude => {
387                self.invoke_claude(&prompt, &build_single_schema(dim))
388                    .await?
389            }
390            EmbeddingFlavour::Codex => {
391                let schema = self.codex_schema_file(dim, false)?;
392                self.invoke_codex(&prompt, schema.path()).await?
393            }
394        };
395        let parsed: EmbeddingResponse = parse_llm_json(&stdout).map_err(|e| {
396            AppError::Embedding(format!(
397                "LLM embedding response parse failed: {e}; raw={stdout}"
398            ))
399        })?;
400        if parsed.embedding.len() != dim {
401            return Err(AppError::Embedding(format!(
402                "LLM returned {} dims, expected {dim}; \
403                 refusing to truncate or pad silently (G42/C5)",
404                parsed.embedding.len()
405            )));
406        }
407        Ok(parsed.embedding)
408    }
409
410    /// G42/S4: returns the lazily-created, process-shared codex schema
411    /// tempfile for the requested mode. `NamedTempFile` randomises the
412    /// filename (no PID-based collisions) and removes the file on drop
413    /// of the last `Arc` clone.
414    fn codex_schema_file(
415        &self,
416        dim: usize,
417        batch: bool,
418    ) -> Result<Arc<tempfile::NamedTempFile>, AppError> {
419        let mut guard = self.codex_schemas.lock();
420        let slot = if batch {
421            &mut guard.batch
422        } else {
423            &mut guard.single
424        };
425        if let Some((cached_dim, file)) = slot {
426            if *cached_dim == dim {
427                return Ok(Arc::clone(file));
428            }
429        }
430        let content = if batch {
431            build_batch_schema(dim)
432        } else {
433            build_single_schema(dim)
434        };
435        let file = tempfile::Builder::new()
436            .prefix("sqlite-graphrag-embed-schema-")
437            .suffix(".json")
438            .tempfile()
439            .map_err(|e| AppError::Embedding(format!("schema tempfile create failed: {e}")))?;
440        std::fs::write(file.path(), content)
441            .map_err(|e| AppError::Embedding(format!("schema tempfile write failed: {e}")))?;
442        let file = Arc::new(file);
443        *slot = Some((dim, Arc::clone(&file)));
444        Ok(file)
445    }
446
447    async fn invoke_claude(&self, prompt: &str, schema: &str) -> Result<String, AppError> {
448        // v1.0.69 hardening: --strict-mcp-config --mcp-config '{}' --settings
449        // '{"hooks":{}}' --dangerously-skip-permissions.
450        //
451        // v1.0.76 hardening: Claude Code 2.1+ renamed --output-schema to
452        // --json-schema and accepts the schema as an inline JSON string
453        // (NOT a file path). Also pass --output-format json so the
454        // response is a single JSON object on stdout.
455        //
456        // v1.0.79 (G42/S6): CLAUDE_CONFIG_DIR points at an empty managed
457        // directory BY DEFAULT — the MCP-isolation flags above are
458        // silently ignored upstream (anthropics/claude-code#10787) and a
459        // populated ~/.claude costs ~223k cache-creation tokens per call.
460        let mut cmd = Command::new(&self.binary);
461        cmd.arg("-p")
462            .arg(prompt)
463            .arg("--model")
464            .arg(&self.model)
465            .arg("--json-schema")
466            .arg(schema)
467            .arg("--output-format")
468            .arg("json")
469            .arg("--strict-mcp-config")
470            .arg("--mcp-config")
471            .arg(r#"{"mcpServers":{}}"#)
472            .arg("--settings")
473            .arg(r#"{"hooks":{}}"#)
474            .arg("--dangerously-skip-permissions")
475            .env_clear()
476            .env("PATH", std::env::var("PATH").unwrap_or_default())
477            .env("HOME", std::env::var("HOME").unwrap_or_default())
478            .stdin(Stdio::null())
479            .stdout(Stdio::piped())
480            .stderr(Stdio::piped())
481            // BLOCO 4: cancellation (dropped future) must kill the child.
482            .kill_on_drop(true);
483        if let Some(config_dir) = claude_embedding_config_dir() {
484            cmd.env("CLAUDE_CONFIG_DIR", &config_dir);
485        }
486        let output = tokio::time::timeout(embed_timeout(), cmd.output())
487            .await
488            .map_err(|_| {
489                AppError::Embedding(format!(
490                    "claude embedding call timed out after {}s \
491                     (override via SQLITE_GRAPHRAG_EMBED_TIMEOUT_SECS)",
492                    embed_timeout().as_secs()
493                ))
494            })?
495            .map_err(|e| AppError::Embedding(format!("claude spawn failed: {e}")))?;
496        if !output.status.success() {
497            return Err(AppError::Embedding(format!(
498                "claude exited with {}: stderr={}",
499                output.status,
500                String::from_utf8_lossy(&output.stderr)
501            )));
502        }
503        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
504    }
505
506    async fn invoke_codex(
507        &self,
508        prompt: &str,
509        schema_path: &std::path::Path,
510    ) -> Result<String, AppError> {
511        let mut child = build_codex_embedding_command(&self.binary, &self.model, schema_path)
512            .spawn()
513            .map_err(|e| AppError::Embedding(format!("codex spawn failed: {e}")))?;
514        if let Some(mut stdin) = child.stdin.take() {
515            stdin
516                .write_all(prompt.as_bytes())
517                .await
518                .map_err(|e| AppError::Embedding(format!("codex stdin write failed: {e}")))?;
519        }
520        let output = tokio::time::timeout(embed_timeout(), child.wait_with_output())
521            .await
522            .map_err(|_| {
523                AppError::Embedding(format!(
524                    "codex embedding call timed out after {}s \
525                     (override via SQLITE_GRAPHRAG_EMBED_TIMEOUT_SECS)",
526                    embed_timeout().as_secs()
527                ))
528            })?
529            .map_err(|e| AppError::Embedding(format!("codex wait failed: {e}")))?;
530        if !output.status.success() {
531            let stderr = String::from_utf8_lossy(&output.stderr);
532            // G42/S7: the headless spawn can still hit interactive
533            // prompts on some codex builds; map the failure to an
534            // actionable message instead of an opaque exit.
535            if stderr.contains("request_user_input") {
536                return Err(AppError::Embedding(format!(
537                    "codex requested interactive input in a headless embedding call \
538                     (exit {}). This codex build ignores the non-interactive flags; \
539                     upgrade codex (>= 0.134) or switch the embedding backend to \
540                     claude by removing `codex` from PATH or installing `claude`. \
541                     stderr={stderr}",
542                    output.status
543                )));
544            }
545            return Err(AppError::Embedding(format!(
546                "codex exited with {}: stderr={stderr}",
547                output.status
548            )));
549        }
550        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
551    }
552}
553
554/// G42/S6: resolves the empty `CLAUDE_CONFIG_DIR` used for embedding
555/// subprocesses.
556///
557/// - `SQLITE_GRAPHRAG_CLAUDE_EMPTY_CONFIG_DIR` is honoured when set and
558///   pointing at a directory (same contract as G28-A in claude_runner);
559/// - otherwise a managed directory is created at
560///   `~/.local/state/sqlite-graphrag/claude-empty-config` (mode 0700).
561///   If `~/.claude/.credentials.json` exists (Linux OAuth storage) it is
562///   copied in so authentication still works; on macOS credentials live
563///   in the Keychain and the empty dir is sufficient.
564///
565/// Returns `None` only when HOME is unset AND no override is given —
566/// in that case the subprocess falls back to claude's own default.
567fn claude_embedding_config_dir() -> Option<std::path::PathBuf> {
568    if let Ok(dir) = std::env::var("SQLITE_GRAPHRAG_CLAUDE_EMPTY_CONFIG_DIR") {
569        let path = std::path::PathBuf::from(dir);
570        if path.is_dir() {
571            return Some(path);
572        }
573        tracing::warn!(
574            target: "embedding",
575            path = %path.display(),
576            "SQLITE_GRAPHRAG_CLAUDE_EMPTY_CONFIG_DIR is set but not a directory; \
577             falling back to the managed empty config dir"
578        );
579    }
580    let home = std::env::var("HOME").ok()?;
581    let dir = std::path::Path::new(&home)
582        .join(".local/state/sqlite-graphrag")
583        .join("claude-empty-config");
584    if std::fs::create_dir_all(&dir).is_err() {
585        return None;
586    }
587    #[cfg(unix)]
588    {
589        use std::os::unix::fs::PermissionsExt;
590        let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
591    }
592    // Linux stores OAuth credentials on disk; copy them so the isolated
593    // config dir still authenticates. Best-effort: macOS uses Keychain.
594    let creds = std::path::Path::new(&home).join(".claude/.credentials.json");
595    if creds.exists() {
596        let target = dir.join(".credentials.json");
597        if !target.exists() {
598            let _ = std::fs::copy(&creds, &target);
599        }
600    }
601    Some(dir)
602}
603
604fn build_codex_embedding_command(
605    binary: &std::path::Path,
606    model: &str,
607    schema_path: &std::path::Path,
608) -> Command {
609    let mut cmd = Command::new(binary);
610    // v1.0.77: `-c` TOML overrides bypass the codex exec --sandbox propagation
611    // bug (openai/codex#18113). CLI flags alone are insufficient — the exec
612    // subcommand may not inherit --sandbox from the parent codex command.
613    cmd.arg("exec")
614        .arg("-c")
615        .arg("sandbox_mode='read-only'")
616        .arg("-c")
617        .arg("approval_policy='never'")
618        .arg("--json")
619        .arg("--output-schema")
620        .arg(schema_path)
621        .arg("--ephemeral")
622        .arg("--skip-git-repo-check")
623        .arg("--sandbox")
624        .arg("read-only")
625        .arg("--ignore-user-config")
626        .arg("--ignore-rules");
627    if crate::extract::codex_compat::codex_supports_ask_for_approval() {
628        cmd.arg("--ask-for-approval").arg("never");
629    }
630    // v1.0.77: isolate codex from user config by pointing CODEX_HOME at a
631    // minimal directory containing only auth.json (OAuth credentials).
632    let codex_home = prepare_isolated_codex_home();
633    cmd.arg("--model")
634        .arg(model)
635        .arg("-")
636        .env_clear()
637        .env("PATH", std::env::var("PATH").unwrap_or_default())
638        .env("HOME", std::env::var("HOME").unwrap_or_default());
639    if let Some(ref ch) = codex_home {
640        cmd.env("CODEX_HOME", ch);
641    }
642    cmd.stdin(Stdio::piped())
643        .stdout(Stdio::piped())
644        .stderr(Stdio::piped())
645        // BLOCO 4: cancellation (dropped future) must kill the child.
646        .kill_on_drop(true);
647    cmd
648}
649
650fn prepare_isolated_codex_home() -> Option<std::path::PathBuf> {
651    let home = std::env::var("HOME").ok()?;
652    let real_auth = std::path::Path::new(&home).join(".codex/auth.json");
653    if !real_auth.exists() {
654        return None;
655    }
656    let base = std::path::Path::new(&home).join(".local/share/sqlite-graphrag");
657    let isolated = base.join(format!("codex-home-{}", std::process::id()));
658    let _ = std::fs::create_dir_all(&isolated);
659    let target = isolated.join("auth.json");
660    if !target.exists() {
661        let _ = std::fs::copy(&real_auth, &target);
662    }
663    Some(isolated)
664}
665
666/// Parse an LLM JSON response of type `T`. The two backends emit
667/// different shapes:
668/// - Claude (with `--output-format json`): single JSON object on stdout.
669/// - Codex (with `--json`): JSONL stream with one event per line; the
670///   `agent_message` event's `text` field is the JSON payload.
671///
672/// This helper accepts both shapes and returns the parsed value (or an
673/// error describing the first mismatch).
674fn parse_llm_json<T: serde::de::DeserializeOwned>(stdout: &str) -> Result<T, String> {
675    // Strategy 1: try the whole stdout as JSON (Claude path).
676    if let Ok(parsed) = serde_json::from_str::<T>(stdout) {
677        return Ok(parsed);
678    }
679    // Strategy 2: walk the JSONL line by line and pick the last
680    // `item.completed` of type `agent_message` (Codex path).
681    let mut last_agent_text: Option<String> = None;
682    for line in stdout.lines() {
683        let line = line.trim();
684        if line.is_empty() {
685            continue;
686        }
687        let Ok(event) = serde_json::from_str::<serde_json::Value>(line) else {
688            continue;
689        };
690        if event.get("type").and_then(|t| t.as_str()) != Some("item.completed") {
691            continue;
692        }
693        let item = match event.get("item") {
694            Some(i) => i,
695            None => continue,
696        };
697        if item.get("type").and_then(|t| t.as_str()) != Some("agent_message") {
698            continue;
699        }
700        if let Some(text) = item.get("text").and_then(|t| t.as_str()) {
701            last_agent_text = Some(text.to_string());
702        }
703    }
704    let text = last_agent_text
705        .ok_or_else(|| "no agent_message found in codex JSONL output".to_string())?;
706    serde_json::from_str::<T>(&text)
707        .map_err(|e| format!("codex agent_message text does not match schema: {e}; raw={text}"))
708}
709
710#[cfg(test)]
711mod tests {
712    use super::*;
713
714    fn test_client(flavour: EmbeddingFlavour, binary: std::path::PathBuf) -> LlmEmbedding {
715        LlmEmbedding {
716            flavour,
717            binary,
718            model: "gpt-5.4".to_string(),
719            codex_schemas: Arc::new(parking_lot::Mutex::new(CodexSchemaFiles::default())),
720        }
721    }
722
723    #[test]
724    #[serial_test::serial(env)]
725    fn oauth_only_enforce_blocks_api_keys() {
726        // SAFETY: this test only sets and unsets env vars; the
727        // `serial(env)` group prevents cross-test interference.
728        unsafe {
729            std::env::set_var("ANTHROPIC_API_KEY", "test");
730            assert!(LlmEmbedding::oauth_only_enforce().is_err());
731            std::env::remove_var("ANTHROPIC_API_KEY");
732
733            std::env::set_var("OPENAI_API_KEY", "test");
734            assert!(LlmEmbedding::oauth_only_enforce().is_err());
735            std::env::remove_var("OPENAI_API_KEY");
736        }
737        assert!(LlmEmbedding::oauth_only_enforce().is_ok());
738    }
739
740    #[test]
741    fn flavour_as_str_is_stable() {
742        assert_eq!(EmbeddingFlavour::Claude.as_str(), "claude");
743        assert_eq!(EmbeddingFlavour::Codex.as_str(), "codex");
744    }
745
746    #[test]
747    fn single_schema_embeds_active_dim() {
748        let schema = build_single_schema(64);
749        assert!(schema.contains(r#""minItems":64"#));
750        assert!(schema.contains(r#""maxItems":64"#));
751        let parsed: serde_json::Value =
752            serde_json::from_str(&schema).expect("single schema must be valid JSON");
753        assert_eq!(parsed["properties"]["embedding"]["minItems"], 64);
754    }
755
756    #[test]
757    fn batch_schema_is_valid_json_and_unbounded_items() {
758        let schema = build_batch_schema(64);
759        let parsed: serde_json::Value =
760            serde_json::from_str(&schema).expect("batch schema must be valid JSON");
761        // The items array must NOT constrain its length so one schema
762        // file serves every batch size (G42/S4).
763        assert!(parsed["properties"]["items"].get("minItems").is_none());
764        assert_eq!(
765            parsed["properties"]["items"]["items"]["properties"]["v"]["minItems"],
766            64
767        );
768    }
769
770    #[test]
771    fn parse_llm_json_accepts_claude_json() {
772        let stdout = r#"{"embedding":[0.0,1.0,2.0]}"#;
773
774        let parsed: EmbeddingResponse = parse_llm_json(stdout).expect("claude JSON must parse");
775
776        assert_eq!(parsed.embedding, vec![0.0, 1.0, 2.0]);
777    }
778
779    #[test]
780    fn parse_llm_json_accepts_codex_jsonl() {
781        let stdout = r#"{"type":"thread.started","thread_id":"mock-thread-0"}
782{"type":"item.completed","item":{"type":"agent_message","text":"{\"embedding\":[0.0,1.0,2.0]}"}}
783{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}"#;
784
785        let parsed: EmbeddingResponse = parse_llm_json(stdout).expect("codex JSONL must parse");
786
787        assert_eq!(parsed.embedding, vec![0.0, 1.0, 2.0]);
788    }
789
790    #[test]
791    fn parse_llm_json_rejects_jsonl_without_agent_message() {
792        let stdout = r#"{"type":"thread.started","thread_id":"mock-thread-0"}"#;
793
794        let err = parse_llm_json::<EmbeddingResponse>(stdout)
795            .expect_err("missing agent_message must fail");
796
797        assert!(err.contains("no agent_message"));
798    }
799
800    #[test]
801    fn parse_llm_json_accepts_batch_response() {
802        let stdout = r#"{"items":[{"i":1,"v":[0.0,1.0]},{"i":2,"v":[2.0,3.0]}]}"#;
803
804        let parsed: BatchEmbeddingResponse = parse_llm_json(stdout).expect("batch JSON must parse");
805
806        assert_eq!(parsed.items.len(), 2);
807        assert_eq!(parsed.items[0].i, 1);
808        assert_eq!(parsed.items[1].v, vec![2.0, 3.0]);
809    }
810
811    #[test]
812    fn codex_schema_file_is_created_once_and_reused() {
813        let client = test_client(
814            EmbeddingFlavour::Codex,
815            std::path::PathBuf::from("/bin/true"),
816        );
817        let first = client
818            .codex_schema_file(64, false)
819            .expect("schema file must be created");
820        let second = client
821            .codex_schema_file(64, false)
822            .expect("schema file must be reused");
823        assert_eq!(first.path(), second.path(), "same dim must reuse the file");
824
825        let batch = client
826            .codex_schema_file(64, true)
827            .expect("batch schema file must be created");
828        assert_ne!(
829            first.path(),
830            batch.path(),
831            "single and batch schemas are distinct files"
832        );
833
834        let content = std::fs::read_to_string(first.path()).expect("schema file must be readable");
835        assert!(content.contains(r#""minItems":64"#));
836    }
837
838    #[test]
839    fn codex_embedding_command_reads_prompt_from_stdin() {
840        let schema_path = std::env::temp_dir().join("sqlite-graphrag-embed-schema-test.json");
841        let cmd = build_codex_embedding_command(
842            std::path::Path::new("/bin/true"),
843            "gpt-5.4",
844            &schema_path,
845        );
846        let argv: Vec<String> = cmd
847            .as_std()
848            .get_args()
849            .filter_map(|arg| arg.to_str().map(|s| s.to_string()))
850            .collect();
851
852        assert!(
853            argv.iter().any(|arg| arg == "-"),
854            "codex embedding command must read prompt from stdin: {argv:?}"
855        );
856        assert!(
857            !argv.iter().any(|arg| arg.starts_with("passage: ")),
858            "prompt text must not be passed as argv: {argv:?}"
859        );
860        for required in &[
861            "exec",
862            "-c",
863            "sandbox_mode='read-only'",
864            "approval_policy='never'",
865            "--json",
866            "--output-schema",
867            "--ephemeral",
868            "--skip-git-repo-check",
869            "--sandbox",
870            "read-only",
871            "--ignore-user-config",
872            "--ignore-rules",
873            "--model",
874            "gpt-5.4",
875        ] {
876            assert!(
877                argv.iter().any(|arg| arg == required),
878                "missing flag {required} in {argv:?}"
879            );
880        }
881    }
882
883    #[cfg(unix)]
884    #[test]
885    #[serial_test::serial(env)]
886    fn embed_passage_sends_prompt_to_codex_stdin() {
887        use std::os::unix::fs::PermissionsExt;
888
889        // Pin the dimensionality so the mock script and the validation
890        // agree regardless of test execution order.
891        // SAFETY: guarded by serial(env).
892        unsafe {
893            std::env::set_var("SQLITE_GRAPHRAG_EMBEDDING_DIM", "64");
894        }
895
896        let temp = tempfile::tempdir().expect("tempdir must exist");
897        let binary = temp.path().join("codex-stdin-check");
898        let script = r#"#!/usr/bin/env bash
899set -euo pipefail
900
901prompt="$(cat)"
902if [[ "$prompt" != "passage: codex-cli" ]]; then
903  echo "unexpected stdin: $prompt" >&2
904  exit 41
905fi
906
907vals="0.0"
908for _ in $(seq 2 64); do
909  vals="$vals,0.0"
910done
911payload="{\"embedding\":[$vals]}"
912escaped="${payload//\"/\\\"}"
913echo "{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"$escaped\"}}"
914"#;
915        std::fs::write(&binary, script).expect("mock codex script must be written");
916        let mut perms = std::fs::metadata(&binary)
917            .expect("mock codex metadata must exist")
918            .permissions();
919        perms.set_mode(0o755);
920        std::fs::set_permissions(&binary, perms).expect("mock codex must be executable");
921
922        let embedding = test_client(EmbeddingFlavour::Codex, binary);
923
924        let vector = embedding
925            .embed_passage("codex-cli")
926            .expect("stdin-backed codex embedding must succeed");
927
928        // SAFETY: guarded by serial(env).
929        unsafe {
930            std::env::remove_var("SQLITE_GRAPHRAG_EMBEDDING_DIM");
931        }
932
933        assert_eq!(vector.len(), 64);
934        assert!(vector.iter().all(|value| *value == 0.0));
935    }
936}