1use crate::errors::AppError;
34use serde::Deserialize;
35use std::process::Stdio;
36use std::sync::Arc;
37use tokio::io::AsyncWriteExt;
38use tokio::process::Command;
39
40const 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
54fn 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
61fn 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 flavour: EmbeddingFlavour,
74 binary: std::path::PathBuf,
76 model: String,
78 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
121pub 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
161fn 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 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 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 pub fn embed_passage(&self, text: &str) -> Result<Vec<f32>, AppError> {
258 self.invoke_with_prefix(crate::constants::PASSAGE_PREFIX, text)
259 }
260
261 pub fn embed_query(&self, text: &str) -> Result<Vec<f32>, AppError> {
264 self.invoke_with_prefix(crate::constants::QUERY_PREFIX, text)
265 }
266
267 pub fn model_label(&self) -> String {
273 format!("{}:{}", self.flavour.as_str(), self.model)
274 }
275
276 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 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 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 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 .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 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
554fn 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 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 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 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 .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
666fn parse_llm_json<T: serde::de::DeserializeOwned>(stdout: &str) -> Result<T, String> {
675 if let Ok(parsed) = serde_json::from_str::<T>(stdout) {
677 return Ok(parsed);
678 }
679 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 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 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 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 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}