Skip to main content

sqlite_graphrag/commands/
ingest_codex.rs

1//! Handler for `ingest --mode codex`.
2//!
3//! Orchestrates the locally installed OpenAI Codex CLI binary (`codex exec`)
4//! to extract domain-specific entities and relationships from each file,
5//! then persists them with full embedding pipeline for recall/hybrid-search.
6//!
7//! Architecture: P1 One-Shot per file — each file spawns a separate
8//! `codex exec` process with `--output-schema` for guaranteed structured output.
9//! A SQLite queue DB tracks progress for resume/retry support.
10
11use crate::commands::ingest::IngestArgs;
12use crate::commands::ingest_claude::ExtractionResult;
13use crate::entity_type::EntityType;
14use crate::errors::AppError;
15use crate::paths::AppPaths;
16use crate::storage::connection::{ensure_db_ready, open_rw};
17use crate::storage::entities::{self, NewEntity, NewRelationship};
18use crate::storage::memories::{self, NewMemory};
19
20use rusqlite::Connection;
21use serde::{Deserialize, Serialize};
22use std::io::Write;
23use std::path::{Path, PathBuf};
24use std::process::{Command, Stdio};
25use std::time::Instant;
26
27const MIN_CODEX_VERSION: &str = "0.120.0";
28
29/// OpenAI structured output schema with `additionalProperties: false` at all nested levels.
30const EXTRACTION_SCHEMA_CODEX: &str = r#"{
31  "type": "object",
32  "properties": {
33    "name": { "type": "string" },
34    "description": { "type": "string" },
35    "entities": {
36      "type": "array",
37      "items": {
38        "type": "object",
39        "properties": {
40          "name": { "type": "string" },
41          "entity_type": {
42            "type": "string",
43            "enum": ["project","tool","person","file","concept","incident","decision","organization","location","date"]
44          }
45        },
46        "required": ["name", "entity_type"],
47        "additionalProperties": false
48      }
49    },
50    "relationships": {
51      "type": "array",
52      "items": {
53        "type": "object",
54        "properties": {
55          "source": { "type": "string" },
56          "target": { "type": "string" },
57          "relation": {
58            "type": "string",
59            "enum": ["applies-to","uses","depends-on","causes","fixes","contradicts","supports","follows","related","replaces","tracked-in"]
60          },
61          "strength": { "type": "number", "minimum": 0, "maximum": 1 }
62        },
63        "required": ["source","target","relation","strength"],
64        "additionalProperties": false
65      }
66    }
67  },
68  "required": ["name","description","entities","relationships"],
69  "additionalProperties": false
70}"#;
71
72const EXTRACTION_PROMPT: &str = "You are a knowledge graph entity extractor. Given a document, extract:\n\
731. A short kebab-case name (max 60 chars) capturing the document's main topic\n\
742. A one-sentence description (10-20 words) summarizing the key insight\n\
753. Domain-specific entities (concepts, tools, people, decisions, projects, files)\n\
764. Typed relationships between entities with strength scores\n\n\
77Rules:\n\
78- Entity names: lowercase kebab-case, 2+ chars, domain-specific only\n\
79- NEVER extract generic terms, stop words, numbers, UUIDs, or single characters\n\
80- Relationship types MUST be one of: applies-to, uses, depends-on, causes, fixes, contradicts, supports, follows, related, replaces, tracked-in\n\
81- NEVER use 'mentions' as relationship type\n\
82- Strength: 0.9 for hard dependencies, 0.7 for design relationships, 0.5 for contextual links, 0.3 for weak references\n\
83- Prefer fewer high-quality entities over many low-quality ones\n\
84- Description must answer: What is this about and WHY does it matter?";
85
86/// Token usage reported by Codex CLI on `turn.completed` events.
87#[derive(Debug, Clone, Deserialize, Serialize)]
88struct CodexUsage {
89    input_tokens: u64,
90    #[serde(default)]
91    cached_input_tokens: u64,
92    output_tokens: u64,
93    #[serde(default)]
94    reasoning_output_tokens: u64,
95}
96
97#[derive(Debug, Serialize)]
98struct PhaseEvent<'a> {
99    phase: &'a str,
100    #[serde(skip_serializing_if = "Option::is_none")]
101    codex_path: Option<&'a str>,
102    #[serde(skip_serializing_if = "Option::is_none")]
103    version: Option<&'a str>,
104    #[serde(skip_serializing_if = "Option::is_none")]
105    dir: Option<&'a str>,
106    #[serde(skip_serializing_if = "Option::is_none")]
107    files_total: Option<usize>,
108    #[serde(skip_serializing_if = "Option::is_none")]
109    files_new: Option<usize>,
110    #[serde(skip_serializing_if = "Option::is_none")]
111    files_existing: Option<usize>,
112}
113
114#[derive(Debug, Serialize)]
115struct FileEvent<'a> {
116    file: &'a str,
117    name: &'a str,
118    status: &'a str,
119    #[serde(skip_serializing_if = "Option::is_none")]
120    memory_id: Option<i64>,
121    #[serde(skip_serializing_if = "Option::is_none")]
122    entities: Option<usize>,
123    #[serde(skip_serializing_if = "Option::is_none")]
124    rels: Option<usize>,
125    /// Always None for Codex (no cost_usd in Codex API responses).
126    #[serde(skip_serializing_if = "Option::is_none")]
127    cost_usd: Option<f64>,
128    #[serde(skip_serializing_if = "Option::is_none")]
129    input_tokens: Option<u64>,
130    #[serde(skip_serializing_if = "Option::is_none")]
131    output_tokens: Option<u64>,
132    #[serde(skip_serializing_if = "Option::is_none")]
133    elapsed_ms: Option<u64>,
134    #[serde(skip_serializing_if = "Option::is_none")]
135    error: Option<&'a str>,
136    index: usize,
137    total: usize,
138}
139
140#[derive(Debug, Serialize)]
141struct Summary {
142    summary: bool,
143    files_total: usize,
144    completed: usize,
145    failed: usize,
146    skipped: usize,
147    entities_total: usize,
148    rels_total: usize,
149    input_tokens_total: u64,
150    output_tokens_total: u64,
151    elapsed_ms: u64,
152}
153
154/// Locates the Codex CLI binary on the system.
155///
156/// Search order:
157/// 1. Explicit `--codex-binary` CLI flag.
158/// 2. `SQLITE_GRAPHRAG_CODEX_BINARY` env var.
159/// 3. PATH search for `codex` (or `codex.exe` on Windows).
160pub fn find_codex_binary(explicit: Option<&Path>) -> Result<PathBuf, AppError> {
161    if let Some(p) = explicit {
162        if p.exists() {
163            return Ok(p.to_path_buf());
164        }
165        return Err(AppError::Validation(format!(
166            "Codex CLI binary not found at explicit path: {}",
167            p.display()
168        )));
169    }
170
171    if let Ok(env_path) = std::env::var("SQLITE_GRAPHRAG_CODEX_BINARY") {
172        let p = PathBuf::from(&env_path);
173        if p.exists() {
174            return Ok(p);
175        }
176    }
177
178    let name = if cfg!(windows) { "codex.exe" } else { "codex" };
179    if let Some(path_var) = std::env::var_os("PATH") {
180        for dir in std::env::split_paths(&path_var) {
181            let candidate = dir.join(name);
182            if candidate.exists() {
183                return Ok(candidate);
184            }
185        }
186    }
187
188    Err(AppError::Validation(
189        "Codex CLI binary not found in PATH. Install it from https://github.com/openai/codex or specify --codex-binary".to_string(),
190    ))
191}
192
193/// Validates that the Codex CLI binary meets the minimum version requirement.
194///
195/// # Errors
196///
197/// Returns `AppError::Validation` when the binary cannot be executed or the
198/// version is below `MIN_CODEX_VERSION`.
199fn validate_codex_version(binary: &Path) -> Result<String, AppError> {
200    let output = Command::new(binary)
201        .arg("--version")
202        .stdin(Stdio::null())
203        .stdout(Stdio::piped())
204        .stderr(Stdio::piped())
205        .output()
206        .map_err(AppError::Io)?;
207
208    let raw = String::from_utf8(output.stdout)
209        .map_err(|_| AppError::Validation("codex --version output is not UTF-8".to_string()))?;
210
211    let version_str = raw.trim().to_string();
212
213    // Codex CLI outputs: "codex-cli 0.133.0" or just "0.133.0"
214    let numeric = version_str.split_whitespace().last().unwrap_or("").trim();
215
216    fn parse_semver(s: &str) -> Option<(u64, u64, u64)> {
217        let parts: Vec<&str> = s.splitn(3, '.').collect();
218        if parts.len() < 2 {
219            return None;
220        }
221        let major = parts[0].parse::<u64>().ok()?;
222        let minor = parts[1].parse::<u64>().ok()?;
223        let patch = parts
224            .get(2)
225            .and_then(|p| p.parse::<u64>().ok())
226            .unwrap_or(0);
227        Some((major, minor, patch))
228    }
229
230    if let (Some(actual), Some(min)) = (parse_semver(numeric), parse_semver(MIN_CODEX_VERSION)) {
231        if actual < min {
232            return Err(AppError::Validation(format!(
233                "Codex CLI version {numeric} is below minimum required {MIN_CODEX_VERSION}"
234            )));
235        }
236    }
237
238    Ok(version_str)
239}
240
241/// Writes the extraction schema to a named temp file for `--output-schema`.
242///
243/// # Errors
244///
245/// Returns `AppError::Io` when the temp file cannot be created or written.
246fn write_schema_tempfile() -> Result<tempfile::NamedTempFile, AppError> {
247    let mut f = tempfile::NamedTempFile::new().map_err(AppError::Io)?;
248    std::io::Write::write_all(&mut f, EXTRACTION_SCHEMA_CODEX.as_bytes()).map_err(AppError::Io)?;
249    std::io::Write::flush(&mut f).map_err(AppError::Io)?;
250    Ok(f)
251}
252
253/// Invokes `codex exec` for a single file and returns the extraction result.
254///
255/// Uses `wait-timeout` for cross-platform subprocess timeout, `env_clear()`
256/// for least-privilege environment, and reads prompt + file content from
257/// stdin using the `-` argument (Codex Paperclip pattern).
258///
259/// # Errors
260///
261/// Returns `AppError::Validation` on extraction failure, rate limiting, or
262/// schema errors. Returns `AppError::Io` on process spawn/IO failures.
263fn extract_with_codex(
264    binary: &Path,
265    file_content: &[u8],
266    model: Option<&str>,
267    timeout_secs: u64,
268    schema_file: &Path,
269) -> Result<(ExtractionResult, Option<CodexUsage>), AppError> {
270    use wait_timeout::ChildExt;
271
272    let mut cmd = Command::new(binary);
273
274    cmd.env_clear();
275    for var in &[
276        "PATH",
277        "HOME",
278        "USER",
279        "SHELL",
280        "TERM",
281        "LANG",
282        "XDG_CONFIG_HOME",
283        "XDG_DATA_HOME",
284        "XDG_RUNTIME_DIR",
285        "XDG_CACHE_HOME",
286        "OPENAI_API_KEY",
287        "CODEX_ACCESS_TOKEN",
288        "CODEX_HOME",
289        "TMPDIR",
290        "TMP",
291        "TEMP",
292        "DYLD_FALLBACK_LIBRARY_PATH",
293    ] {
294        if let Ok(val) = std::env::var(var) {
295            cmd.env(var, val);
296        }
297    }
298
299    #[cfg(windows)]
300    for var in &[
301        "LOCALAPPDATA",
302        "APPDATA",
303        "USERPROFILE",
304        "SystemRoot",
305        "COMSPEC",
306        "PATHEXT",
307    ] {
308        if let Ok(val) = std::env::var(var) {
309            cmd.env(var, val);
310        }
311    }
312
313    cmd.arg("exec")
314        .arg("--json")
315        .arg("--output-schema")
316        .arg(schema_file)
317        .arg("--ephemeral")
318        .arg("--skip-git-repo-check")
319        .arg("--sandbox")
320        .arg("read-only")
321        .arg("--ignore-user-config")
322        .arg("--ignore-rules");
323
324    if let Some(m) = model {
325        cmd.arg("-m").arg(m);
326    }
327
328    // `-` means: read the prompt from stdin (Paperclip pattern)
329    cmd.arg("-");
330
331    cmd.stdin(Stdio::piped())
332        .stdout(Stdio::piped())
333        .stderr(Stdio::piped());
334
335    let mut child = cmd.spawn().map_err(|e| {
336        AppError::Io(std::io::Error::new(
337            e.kind(),
338            format!("failed to spawn codex: {e}"),
339        ))
340    })?;
341
342    // Build stdin: prompt + document content
343    let file_utf8 = String::from_utf8_lossy(file_content);
344    let stdin_payload = format!("{EXTRACTION_PROMPT}\n\n---\n\nDocument content:\n\n{file_utf8}");
345    let stdin_bytes = stdin_payload.into_bytes();
346
347    let mut child_stdin = child
348        .stdin
349        .take()
350        .ok_or_else(|| AppError::Validation("failed to open codex stdin".into()))?;
351    let stdin_thread = std::thread::spawn(move || -> Result<(), std::io::Error> {
352        child_stdin.write_all(&stdin_bytes)?;
353        Ok(())
354    });
355
356    let timeout = std::time::Duration::from_secs(timeout_secs);
357    let status = child.wait_timeout(timeout).map_err(AppError::Io)?;
358
359    match status {
360        Some(exit_status) => {
361            stdin_thread
362                .join()
363                .map_err(|_| AppError::Validation("stdin thread panicked".into()))?
364                .map_err(AppError::Io)?;
365
366            let mut stdout_buf = Vec::new();
367            let mut stderr_buf = Vec::new();
368            if let Some(mut out) = child.stdout.take() {
369                std::io::Read::read_to_end(&mut out, &mut stdout_buf).map_err(AppError::Io)?;
370            }
371            if let Some(mut err) = child.stderr.take() {
372                std::io::Read::read_to_end(&mut err, &mut stderr_buf).map_err(AppError::Io)?;
373            }
374
375            if !exit_status.success() {
376                let stderr_str = String::from_utf8_lossy(&stderr_buf);
377                let stdout_str = String::from_utf8_lossy(&stdout_buf);
378                // Check if stdout has JSONL with an error event before falling back
379                if let Ok((result, usage)) = parse_codex_output(&stdout_str) {
380                    return Ok((result, usage));
381                }
382                return Err(AppError::Validation(format!(
383                    "codex exec exited with code {:?}: {}",
384                    exit_status.code(),
385                    stderr_str.trim()
386                )));
387            }
388
389            let stdout = String::from_utf8(stdout_buf)
390                .map_err(|_| AppError::Validation("codex exec stdout is not valid UTF-8".into()))?;
391            parse_codex_output(&stdout)
392        }
393        None => {
394            tracing::warn!(target: "ingest", timeout_secs, "codex exec timed out, killing process");
395            let _ = child.kill();
396            let _ = child.wait();
397            let _ = stdin_thread.join();
398            Err(AppError::Validation(format!(
399                "codex exec timed out after {timeout_secs} seconds"
400            )))
401        }
402    }
403}
404
405/// Parses JSONL output from `codex exec --json`.
406///
407/// Event format (DOTS notation):
408/// - `thread.started` — session init
409/// - `turn.started` — model turn begins
410/// - `item.completed` — message or tool call; last `agent_message` wins
411/// - `turn.completed` — includes usage stats
412/// - `turn.failed` — error with optional rate-limit indicator
413/// - `error` — schema or validation error
414///
415/// # Errors
416///
417/// Returns `AppError::Validation` when no agent_message is found, when the
418/// turn failed, or when the extracted JSON cannot be parsed as `ExtractionResult`.
419fn parse_codex_output(stdout: &str) -> Result<(ExtractionResult, Option<CodexUsage>), AppError> {
420    let mut last_agent_text: Option<String> = None;
421    let mut usage: Option<CodexUsage> = None;
422    let mut rate_limited = false;
423    let mut schema_error = false;
424    let mut turn_failed = false;
425    let mut failed_message = String::new();
426
427    for line in stdout.lines() {
428        let line = line.trim();
429        if line.is_empty() {
430            continue;
431        }
432
433        let event: serde_json::Value = match serde_json::from_str(line) {
434            Ok(v) => v,
435            Err(_) => {
436                tracing::warn!(target: "ingest", line, "codex output: skipping malformed JSONL line");
437                continue;
438            }
439        };
440
441        let event_type = match event.get("type").and_then(|t| t.as_str()) {
442            Some(t) => t,
443            None => continue,
444        };
445
446        match event_type {
447            "item.completed" => {
448                // Last agent_message wins (reasoning / tool calls may appear before)
449                if let Some(item) = event.get("item") {
450                    if item.get("type").and_then(|t| t.as_str()) == Some("agent_message") {
451                        if let Some(text) = item.get("text").and_then(|t| t.as_str()) {
452                            last_agent_text = Some(text.to_string());
453                        }
454                    }
455                }
456            }
457            "turn.completed" => {
458                if let Some(u) = event.get("usage") {
459                    if let Ok(parsed) = serde_json::from_value::<CodexUsage>(u.clone()) {
460                        usage = Some(parsed);
461                    }
462                }
463            }
464            "turn.failed" => {
465                turn_failed = true;
466                if let Some(err) = event.get("error") {
467                    let msg = err
468                        .get("message")
469                        .and_then(|m| m.as_str())
470                        .unwrap_or("unknown error");
471                    failed_message = msg.to_string();
472                    if msg.contains("rate_limit")
473                        || msg.contains("429")
474                        || msg.contains("Too Many Requests")
475                    {
476                        rate_limited = true;
477                    }
478                }
479            }
480            "error" => {
481                if let Some(msg) = event.get("message").and_then(|m| m.as_str()) {
482                    if msg.contains("invalid_json_schema") || msg.contains("schema") {
483                        schema_error = true;
484                    }
485                    tracing::warn!(target: "ingest", error_msg = msg, "codex error event received");
486                }
487            }
488            _ => {
489                // Gracefully skip unknown event types (thread.started, turn.started, etc.)
490            }
491        }
492    }
493
494    if rate_limited {
495        return Err(AppError::Validation(format!(
496            "RATE_LIMITED: {failed_message}"
497        )));
498    }
499
500    if schema_error {
501        return Err(AppError::Validation(
502            "codex rejected the output schema (invalid_json_schema)".to_string(),
503        ));
504    }
505
506    if turn_failed {
507        return Err(AppError::Validation(format!(
508            "codex turn failed: {failed_message}"
509        )));
510    }
511
512    let text = last_agent_text.ok_or_else(|| {
513        AppError::Validation("codex output contained no agent_message item".to_string())
514    })?;
515
516    let extraction: ExtractionResult = serde_json::from_str(&text).map_err(|e| {
517        AppError::Validation(format!(
518            "failed to parse codex agent_message as ExtractionResult: {e}. text={text}"
519        ))
520    })?;
521
522    Ok((extraction, usage))
523}
524
525fn emit_json<T: Serialize>(value: &T) {
526    if let Ok(json) = serde_json::to_string(value) {
527        let stdout = std::io::stdout();
528        let mut lock = stdout.lock();
529        let _ = writeln!(lock, "{json}");
530        let _ = lock.flush();
531    }
532}
533
534/// Collects files matching the pattern (reuses ingest logic).
535fn collect_matching_files(
536    dir: &Path,
537    pattern: &str,
538    recursive: bool,
539    max_files: usize,
540) -> Result<Vec<PathBuf>, AppError> {
541    let mut files = Vec::new();
542    super::ingest::collect_files(dir, pattern, recursive, &mut files)?;
543    files.sort();
544
545    if files.len() > max_files {
546        return Err(AppError::Validation(format!(
547            "found {} files, exceeds --max-files cap of {}",
548            files.len(),
549            max_files
550        )));
551    }
552
553    Ok(files)
554}
555
556/// Opens or creates the queue database for tracking ingest progress.
557fn open_queue_db(path: &str) -> Result<Connection, AppError> {
558    let conn = Connection::open(path)?;
559
560    conn.execute_batch(
561        "PRAGMA journal_mode=WAL;
562        CREATE TABLE IF NOT EXISTS queue (
563            id          INTEGER PRIMARY KEY AUTOINCREMENT,
564            file_path   TEXT NOT NULL UNIQUE,
565            name        TEXT,
566            status      TEXT NOT NULL DEFAULT 'pending',
567            memory_id   INTEGER,
568            entities    INTEGER DEFAULT 0,
569            rels        INTEGER DEFAULT 0,
570            error       TEXT,
571            input_tokens  INTEGER DEFAULT 0,
572            output_tokens INTEGER DEFAULT 0,
573            attempt     INTEGER DEFAULT 0,
574            elapsed_ms  INTEGER,
575            created_at  TEXT DEFAULT (datetime('now')),
576            done_at     TEXT
577        );
578        CREATE INDEX IF NOT EXISTS idx_queue_status ON queue(status);",
579    )?;
580
581    Ok(conn)
582}
583
584/// Main entry point for `ingest --mode codex`.
585///
586/// # Errors
587///
588/// Returns `AppError` on directory/DB access failures or fatal extraction errors.
589pub fn run_codex_ingest(args: &IngestArgs) -> Result<(), AppError> {
590    let started = Instant::now();
591
592    if !args.dir.exists() {
593        return Err(AppError::Validation(format!(
594            "directory not found: {}",
595            args.dir.display()
596        )));
597    }
598
599    // Stage 1: Validate binary
600    let codex_binary = find_codex_binary(args.codex_binary.as_deref())?;
601    let version = validate_codex_version(&codex_binary)?;
602    tracing::info!(
603        target: "ingest",
604        binary = %codex_binary.display(),
605        version = %version,
606        "Codex CLI binary validated"
607    );
608
609    emit_json(&PhaseEvent {
610        phase: "validate",
611        codex_path: codex_binary.to_str(),
612        version: Some(&version),
613        dir: None,
614        files_total: None,
615        files_new: None,
616        files_existing: None,
617    });
618
619    // Stage 2: Scan files
620    let files = collect_matching_files(&args.dir, &args.pattern, args.recursive, args.max_files)?;
621
622    let queue_conn = open_queue_db(&args.queue_db)?;
623
624    if args.resume {
625        let reset = queue_conn
626            .execute(
627                "UPDATE queue SET status='pending' WHERE status='processing'",
628                [],
629            )
630            .map_err(|e| AppError::Validation(format!("queue resume failed: {e}")))?;
631        if reset > 0 {
632            tracing::info!(target: "ingest", count = reset, "reset stuck processing files to pending");
633        }
634    }
635
636    if args.retry_failed {
637        let count = queue_conn
638            .execute(
639                "UPDATE queue SET status='pending', attempt=0 WHERE status='failed'",
640                [],
641            )
642            .map_err(|e| AppError::Validation(format!("queue retry-failed reset failed: {e}")))?;
643        tracing::info!(target: "ingest", count, "retrying failed files");
644    }
645
646    if !args.resume && !args.retry_failed {
647        queue_conn
648            .execute("DELETE FROM queue", [])
649            .map_err(|e| AppError::Validation(format!("queue clear failed: {e}")))?;
650    }
651
652    let mut new_count = 0usize;
653    let mut existing_count = 0usize;
654
655    if !args.retry_failed {
656        for file in &files {
657            let file_str = file.to_string_lossy().to_string();
658            let inserted = queue_conn
659                .execute(
660                    "INSERT OR IGNORE INTO queue (file_path, status) VALUES (?1, 'pending')",
661                    rusqlite::params![file_str],
662                )
663                .map_err(|e| AppError::Validation(format!("queue insert failed: {e}")))?;
664            if inserted > 0 {
665                new_count += 1;
666            } else {
667                existing_count += 1;
668            }
669        }
670    }
671
672    emit_json(&PhaseEvent {
673        phase: "scan",
674        codex_path: None,
675        version: None,
676        dir: args.dir.to_str(),
677        files_total: Some(files.len()),
678        files_new: Some(new_count),
679        files_existing: Some(existing_count),
680    });
681
682    if args.dry_run {
683        for (idx, file) in files.iter().enumerate() {
684            let (name, _truncated, _orig) =
685                super::ingest::derive_kebab_name(file, args.max_name_length);
686            emit_json(&FileEvent {
687                file: &file.to_string_lossy(),
688                name: &name,
689                status: "preview",
690                memory_id: None,
691                entities: None,
692                rels: None,
693                cost_usd: None,
694                input_tokens: None,
695                output_tokens: None,
696                elapsed_ms: None,
697                error: None,
698                index: idx,
699                total: files.len(),
700            });
701        }
702        emit_json(&Summary {
703            summary: true,
704            files_total: files.len(),
705            completed: 0,
706            failed: 0,
707            skipped: 0,
708            entities_total: 0,
709            rels_total: 0,
710            input_tokens_total: 0,
711            output_tokens_total: 0,
712            elapsed_ms: started.elapsed().as_millis() as u64,
713        });
714        if !args.keep_queue {
715            let _ = std::fs::remove_file(&args.queue_db);
716        }
717        return Ok(());
718    }
719
720    // Stage 3: Process files
721    let paths = AppPaths::resolve(args.db.as_deref())?;
722    ensure_db_ready(&paths)?;
723    let conn = open_rw(&paths.db)?;
724    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
725    let memory_type_str = args.r#type.as_str().to_string();
726
727    // Write schema to temp file once (reused across all files)
728    let schema_tempfile = write_schema_tempfile()?;
729    let schema_path = schema_tempfile.path().to_path_buf();
730
731    let mut completed = 0usize;
732    let mut failed = 0usize;
733    let skipped_initial: usize = queue_conn
734        .query_row("SELECT COUNT(*) FROM queue WHERE status='done'", [], |r| {
735            r.get::<_, usize>(0)
736        })
737        .unwrap_or(0);
738    let skipped = skipped_initial;
739    let mut entities_total = 0usize;
740    let mut rels_total = 0usize;
741    let mut input_tokens_total = 0u64;
742    let mut output_tokens_total = 0u64;
743    let total = files.len();
744
745    let mut backoff_secs = args.rate_limit_wait;
746
747    loop {
748        let pending: Option<(i64, String)> = queue_conn
749            .query_row(
750                "UPDATE queue SET status='processing', attempt=attempt+1 \
751                 WHERE id = (SELECT id FROM queue WHERE status='pending' ORDER BY id LIMIT 1) \
752                 RETURNING id, file_path",
753                [],
754                |row| Ok((row.get(0)?, row.get(1)?)),
755            )
756            .ok();
757
758        let (queue_id, file_path) = match pending {
759            Some(p) => p,
760            None => break,
761        };
762
763        let file_started = Instant::now();
764
765        // Reject files that exceed the 10 MB stdin limit
766        const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
767        if let Ok(meta) = std::fs::metadata(&file_path) {
768            if meta.len() > MAX_FILE_SIZE {
769                let err_msg = format!("file exceeds 10MB stdin limit ({} bytes)", meta.len());
770                let _ = queue_conn.execute(
771                    "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
772                    rusqlite::params![err_msg, queue_id],
773                );
774                let current_index = completed + failed + skipped;
775                failed += 1;
776                emit_json(&FileEvent {
777                    file: &file_path,
778                    name: "",
779                    status: "failed",
780                    memory_id: None,
781                    entities: None,
782                    rels: None,
783                    cost_usd: None,
784                    input_tokens: None,
785                    output_tokens: None,
786                    elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
787                    error: Some(&err_msg),
788                    index: current_index,
789                    total,
790                });
791                if args.fail_fast {
792                    break;
793                }
794                continue;
795            }
796        }
797
798        let file_content = match std::fs::read(&file_path) {
799            Ok(c) => c,
800            Err(e) => {
801                let err_msg = format!("IO error: {e}");
802                let _ = queue_conn.execute(
803                    "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
804                    rusqlite::params![err_msg, queue_id],
805                );
806                let current_index = completed + failed + skipped;
807                failed += 1;
808                emit_json(&FileEvent {
809                    file: &file_path,
810                    name: "",
811                    status: "failed",
812                    memory_id: None,
813                    entities: None,
814                    rels: None,
815                    cost_usd: None,
816                    input_tokens: None,
817                    output_tokens: None,
818                    elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
819                    error: Some(&err_msg),
820                    index: current_index,
821                    total,
822                });
823                if args.fail_fast {
824                    break;
825                }
826                continue;
827            }
828        };
829
830        // Retry once on cold-start failure
831        let max_extract_attempts: u32 = 2;
832        let mut extraction_result: Option<(ExtractionResult, Option<CodexUsage>)> = None;
833        let mut last_extract_err: Option<String> = None;
834
835        for attempt in 1..=max_extract_attempts {
836            match extract_with_codex(
837                &codex_binary,
838                &file_content,
839                args.codex_model.as_deref(),
840                args.codex_timeout,
841                &schema_path,
842            ) {
843                Ok(result) => {
844                    extraction_result = Some(result);
845                    break;
846                }
847                Err(ref e) if format!("{e}").contains("RATE_LIMITED") => {
848                    last_extract_err = Some(format!("{e}"));
849                    break;
850                }
851                Err(e) => {
852                    let msg = format!("{e}");
853                    if attempt < max_extract_attempts {
854                        tracing::warn!(
855                            target: "ingest",
856                            attempt,
857                            error = %msg,
858                            "codex extraction failed, retrying"
859                        );
860                        std::thread::sleep(std::time::Duration::from_secs(2));
861                    }
862                    last_extract_err = Some(msg);
863                }
864            }
865        }
866
867        if let Some((extraction, usage)) = extraction_result {
868            backoff_secs = args.rate_limit_wait;
869
870            let in_tok = usage.as_ref().map(|u| u.input_tokens).unwrap_or(0);
871            let out_tok = usage.as_ref().map(|u| u.output_tokens).unwrap_or(0);
872
873            let name = &extraction.name;
874            let ent_count = extraction.entities.len();
875            let rel_count = extraction.relationships.len();
876
877            let new_entities: Vec<NewEntity> = extraction
878                .entities
879                .iter()
880                .filter_map(|e| match e.entity_type.parse::<EntityType>() {
881                    Ok(et) => Some(NewEntity {
882                        name: e.name.clone(),
883                        entity_type: et,
884                        description: None,
885                    }),
886                    Err(_) => {
887                        tracing::warn!(
888                            target: "ingest",
889                            entity = %e.name,
890                            entity_type = %e.entity_type,
891                            "entity type not recognized, skipping"
892                        );
893                        None
894                    }
895                })
896                .collect();
897
898            let new_relationships: Vec<NewRelationship> = extraction
899                .relationships
900                .iter()
901                .map(|r| NewRelationship {
902                    source: r.source.clone(),
903                    target: r.target.clone(),
904                    relation: r.relation.clone(),
905                    strength: r.strength,
906                    description: None,
907                })
908                .collect();
909
910            let body_str = String::from_utf8_lossy(&file_content);
911            let body_hash = blake3::hash(body_str.as_bytes()).to_hex().to_string();
912            let new_memory = NewMemory {
913                name: name.clone(),
914                namespace: namespace.clone(),
915                memory_type: memory_type_str.clone(),
916                description: extraction.description.clone(),
917                body: body_str.to_string(),
918                body_hash,
919                session_id: None,
920                source: "agent".to_string(),
921                metadata: serde_json::Value::Object(serde_json::Map::new()),
922            };
923
924            // Deduplication: update existing memory instead of failing on UNIQUE
925            let memory_id = match memories::find_by_name_any_state(&conn, &namespace, name)? {
926                Some((existing_id, is_deleted)) => {
927                    if is_deleted {
928                        memories::clear_deleted_at(&conn, existing_id)?;
929                    }
930                    let (old_name, old_desc, old_body): (String, String, String) = conn.query_row(
931                        "SELECT name, COALESCE(description,''), COALESCE(body,'') FROM memories WHERE id=?1",
932                        rusqlite::params![existing_id],
933                        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
934                    )?;
935                    memories::update(&conn, existing_id, &new_memory, None)?;
936                    memories::sync_fts_after_update(
937                        &conn,
938                        existing_id,
939                        &old_name,
940                        &old_desc,
941                        &old_body,
942                        &new_memory.name,
943                        &new_memory.description,
944                        &new_memory.body,
945                    )?;
946                    tracing::info!(target: "ingest", name, memory_id = existing_id, "updated existing memory (force-merge)");
947                    existing_id
948                }
949                None => match memories::insert(&conn, &new_memory) {
950                    Ok(id) => id,
951                    Err(e) => {
952                        let err_msg = format!("{e}");
953                        let _ = queue_conn.execute(
954                            "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
955                            rusqlite::params![err_msg, queue_id],
956                        );
957                        let current_index = completed + failed + skipped;
958                        failed += 1;
959                        emit_json(&FileEvent {
960                            file: &file_path,
961                            name,
962                            status: "failed",
963                            memory_id: None,
964                            entities: None,
965                            rels: None,
966                            cost_usd: None,
967                            input_tokens: Some(in_tok),
968                            output_tokens: Some(out_tok),
969                            elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
970                            error: Some(&err_msg),
971                            index: current_index,
972                            total,
973                        });
974                        input_tokens_total += in_tok;
975                        output_tokens_total += out_tok;
976                        if args.fail_fast {
977                            break;
978                        }
979                        continue;
980                    }
981                },
982            };
983
984            for ent in &new_entities {
985                if let Ok(eid) = entities::upsert_entity(&conn, &namespace, ent) {
986                    let _ = entities::link_memory_entity(&conn, memory_id, eid);
987                }
988            }
989            for rel in &new_relationships {
990                crate::parsers::warn_if_non_canonical(&rel.relation);
991                let src_id = entities::find_entity_id(&conn, &namespace, &rel.source);
992                let tgt_id = entities::find_entity_id(&conn, &namespace, &rel.target);
993                if let (Ok(Some(sid)), Ok(Some(tid))) = (src_id, tgt_id) {
994                    let _ = conn.execute(
995                        "INSERT OR IGNORE INTO relationships (namespace, source_id, target_id, relation, weight) VALUES (?1, ?2, ?3, ?4, ?5)",
996                        rusqlite::params![namespace, sid, tid, rel.relation, rel.strength],
997                    );
998                }
999            }
1000
1001            let _ = queue_conn.execute(
1002                "UPDATE queue SET status='done', name=?1, memory_id=?2, entities=?3, rels=?4, \
1003                 input_tokens=?5, output_tokens=?6, elapsed_ms=?7, done_at=datetime('now') WHERE id=?8",
1004                rusqlite::params![
1005                    name,
1006                    memory_id,
1007                    ent_count,
1008                    rel_count,
1009                    in_tok,
1010                    out_tok,
1011                    file_started.elapsed().as_millis() as i64,
1012                    queue_id
1013                ],
1014            );
1015
1016            let current_index = completed + failed + skipped;
1017            completed += 1;
1018            entities_total += ent_count;
1019            rels_total += rel_count;
1020            input_tokens_total += in_tok;
1021            output_tokens_total += out_tok;
1022
1023            emit_json(&FileEvent {
1024                file: &file_path,
1025                name,
1026                status: "done",
1027                memory_id: Some(memory_id),
1028                entities: Some(ent_count),
1029                rels: Some(rel_count),
1030                cost_usd: None,
1031                input_tokens: Some(in_tok),
1032                output_tokens: Some(out_tok),
1033                elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1034                error: None,
1035                index: current_index,
1036                total,
1037            });
1038        } else if let Some(ref err_str) = last_extract_err {
1039            if err_str.contains("RATE_LIMITED") {
1040                tracing::warn!(
1041                    target: "ingest",
1042                    wait_seconds = backoff_secs,
1043                    "rate limited by Codex API, waiting before retry"
1044                );
1045                let _ = queue_conn.execute(
1046                    "UPDATE queue SET status='pending' WHERE id=?1",
1047                    rusqlite::params![queue_id],
1048                );
1049                std::thread::sleep(std::time::Duration::from_secs(backoff_secs));
1050                backoff_secs = (backoff_secs * 2).min(900);
1051                continue;
1052            } else {
1053                let _ = queue_conn.execute(
1054                    "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
1055                    rusqlite::params![err_str, queue_id],
1056                );
1057                let current_index = completed + failed + skipped;
1058                failed += 1;
1059                emit_json(&FileEvent {
1060                    file: &file_path,
1061                    name: "",
1062                    status: "failed",
1063                    memory_id: None,
1064                    entities: None,
1065                    rels: None,
1066                    cost_usd: None,
1067                    input_tokens: None,
1068                    output_tokens: None,
1069                    elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1070                    error: Some(err_str),
1071                    index: current_index,
1072                    total,
1073                });
1074                if args.fail_fast {
1075                    break;
1076                }
1077            }
1078        }
1079    }
1080
1081    // WAL checkpoint before summary
1082    let _ = conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE);");
1083
1084    // Stage 4: Summary
1085    emit_json(&Summary {
1086        summary: true,
1087        files_total: total,
1088        completed,
1089        failed,
1090        skipped,
1091        entities_total,
1092        rels_total,
1093        input_tokens_total,
1094        output_tokens_total,
1095        elapsed_ms: started.elapsed().as_millis() as u64,
1096    });
1097
1098    if !args.keep_queue && failed == 0 {
1099        let _ = std::fs::remove_file(&args.queue_db);
1100    }
1101
1102    Ok(())
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107    use super::*;
1108
1109    fn make_agent_message_event(text: &str) -> String {
1110        format!(
1111            r#"{{"type":"item.completed","item":{{"id":"item_0","type":"agent_message","text":{}}}}}"#,
1112            serde_json::to_string(text).unwrap()
1113        )
1114    }
1115
1116    fn make_usage_event(input: u64, output: u64) -> String {
1117        format!(
1118            r#"{{"type":"turn.completed","usage":{{"input_tokens":{input},"output_tokens":{output}}}}}"#
1119        )
1120    }
1121
1122    fn valid_extraction_json() -> String {
1123        r#"{"name":"test-module","description":"A test module for unit testing purposes","entities":[{"name":"test-entity","entity_type":"concept"}],"relationships":[{"source":"test-entity","target":"test-module","relation":"applies-to","strength":0.8}]}"#.to_string()
1124    }
1125
1126    #[test]
1127    fn test_parse_codex_output_valid() {
1128        let jsonl = format!(
1129            "{}\n{}\n{}",
1130            r#"{"type":"thread.started","thread_id":"t1"}"#,
1131            make_agent_message_event(&valid_extraction_json()),
1132            make_usage_event(100, 50),
1133        );
1134
1135        let (result, usage) = parse_codex_output(&jsonl).expect("parse must succeed");
1136        assert_eq!(result.name, "test-module");
1137        assert_eq!(result.entities.len(), 1);
1138        assert_eq!(result.relationships.len(), 1);
1139        let u = usage.expect("usage must be present");
1140        assert_eq!(u.input_tokens, 100);
1141        assert_eq!(u.output_tokens, 50);
1142    }
1143
1144    #[test]
1145    fn test_parse_codex_output_turn_failed() {
1146        let jsonl = format!(
1147            "{}\n{}",
1148            r#"{"type":"thread.started","thread_id":"t1"}"#,
1149            r#"{"type":"turn.failed","error":{"message":"model error occurred"}}"#,
1150        );
1151
1152        let err = parse_codex_output(&jsonl).unwrap_err();
1153        let msg = format!("{err}");
1154        assert!(
1155            msg.contains("turn failed"),
1156            "expected 'turn failed' in: {msg}"
1157        );
1158        assert!(msg.contains("model error occurred"));
1159    }
1160
1161    #[test]
1162    fn test_parse_codex_output_rate_limit() {
1163        let jsonl = r#"{"type":"turn.failed","error":{"message":"rate_limit exceeded, 429 Too Many Requests"}}"#;
1164
1165        let err = parse_codex_output(jsonl).unwrap_err();
1166        let msg = format!("{err}");
1167        assert!(
1168            msg.contains("RATE_LIMITED"),
1169            "expected 'RATE_LIMITED' in: {msg}"
1170        );
1171    }
1172
1173    #[test]
1174    fn test_parse_codex_output_schema_error() {
1175        let jsonl = r#"{"type":"error","message":"invalid_json_schema: additional properties not allowed"}"#;
1176
1177        let err = parse_codex_output(jsonl).unwrap_err();
1178        let msg = format!("{err}");
1179        assert!(
1180            msg.contains("invalid_json_schema") || msg.contains("schema"),
1181            "expected schema error in: {msg}"
1182        );
1183    }
1184
1185    #[test]
1186    fn test_extraction_schema_codex_valid_json() {
1187        let _: serde_json::Value =
1188            serde_json::from_str(EXTRACTION_SCHEMA_CODEX).expect("schema must be valid JSON");
1189    }
1190
1191    #[test]
1192    fn test_extraction_schema_codex_has_additional_properties_false() {
1193        let schema: serde_json::Value =
1194            serde_json::from_str(EXTRACTION_SCHEMA_CODEX).expect("schema must be valid JSON");
1195
1196        // Root level
1197        assert_eq!(
1198            schema["additionalProperties"].as_bool(),
1199            Some(false),
1200            "root must have additionalProperties: false"
1201        );
1202
1203        // Entity items level
1204        assert_eq!(
1205            schema["properties"]["entities"]["items"]["additionalProperties"].as_bool(),
1206            Some(false),
1207            "entity items must have additionalProperties: false"
1208        );
1209
1210        // Relationship items level
1211        assert_eq!(
1212            schema["properties"]["relationships"]["items"]["additionalProperties"].as_bool(),
1213            Some(false),
1214            "relationship items must have additionalProperties: false"
1215        );
1216    }
1217
1218    #[test]
1219    fn test_parse_codex_output_last_agent_message_wins() {
1220        // Multiple agent_message items — last one should win
1221        let first_text = r#"{"name":"first-result","description":"First result should be ignored","entities":[],"relationships":[]}"#;
1222        let second_text = r#"{"name":"final-result","description":"Final result wins over earlier ones","entities":[{"name":"final-entity","entity_type":"concept"}],"relationships":[]}"#;
1223
1224        let jsonl = format!(
1225            "{}\n{}\n{}\n{}",
1226            r#"{"type":"thread.started","thread_id":"t1"}"#,
1227            make_agent_message_event(first_text),
1228            make_agent_message_event(second_text),
1229            make_usage_event(200, 80),
1230        );
1231
1232        let (result, _) = parse_codex_output(&jsonl).expect("parse must succeed");
1233        assert_eq!(result.name, "final-result", "last agent_message should win");
1234        assert_eq!(result.entities.len(), 1);
1235    }
1236
1237    #[test]
1238    fn test_parse_codex_output_skips_malformed_lines() {
1239        let jsonl = format!(
1240            "not json at all\n{}\n{{broken\n{}",
1241            make_agent_message_event(&valid_extraction_json()),
1242            make_usage_event(10, 5),
1243        );
1244
1245        // Should succeed despite malformed lines
1246        let (result, _) = parse_codex_output(&jsonl).expect("malformed lines must be skipped");
1247        assert_eq!(result.name, "test-module");
1248    }
1249}