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