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    // G31 Passo C (v1.0.69): delegate command construction to the shared
280    // `codex_spawn::build_codex_command` helper so `enrich` and `ingest` stay
281    // perfectly aligned on the canonical seven hardening flags. The local
282    // function still owns the stdin pump + JSONL parsing (see below).
283    let _ = timeout_secs; // currently unused; consumed by the helper when it spawns the process
284    let _ = file_content; // pumped into stdin below, see `stdin_pump` thread
285    let _ = schema_file; // helper reuses the temp file at the given path
286    let prompt = String::new(); // empty prompt — helper appends file_content via args.input_text
287    let mut cmd = crate::commands::codex_spawn::build_codex_command(
288        &crate::commands::codex_spawn::CodexSpawnArgs {
289            binary,
290            prompt: &prompt,
291            json_schema: "", // caller writes the schema directly via `schema_file`
292            input_text: "",
293            model,
294            timeout_secs,
295            schema_path: schema_file.to_path_buf(),
296        },
297    );
298
299    // `build_codex_command` writes the JSON schema to `schema_path` and
300    // appends `input_text` to the prompt via Paperclip stdin. For `ingest`
301    // we want the schema content already on disk (the caller pre-wrote
302    // EXTRACTION_SCHEMA_CODEX into the named tempfile), and the document
303    // content goes through stdin via a dedicated thread (see below). Strip
304    // the file the helper just rewrote — our caller pre-wrote it.
305    let _ = std::fs::write(
306        schema_file,
307        crate::commands::ingest_codex::EXTRACTION_SCHEMA_CODEX,
308    );
309
310    cmd.stdin(Stdio::piped())
311        .stdout(Stdio::piped())
312        .stderr(Stdio::piped());
313
314    let mut child = super::claude_runner::spawn_with_memory_limit(&mut cmd).map_err(|e| {
315        AppError::Io(std::io::Error::new(
316            e.kind(),
317            format!("failed to spawn codex: {e}"),
318        ))
319    })?;
320
321    // Build stdin: prompt + document content
322    let file_utf8 = String::from_utf8_lossy(file_content);
323    let stdin_payload = format!("{EXTRACTION_PROMPT}\n\n---\n\nDocument content:\n\n{file_utf8}");
324    let stdin_bytes = stdin_payload.into_bytes();
325
326    let mut child_stdin = child
327        .stdin
328        .take()
329        .ok_or_else(|| AppError::Validation("failed to open codex stdin".into()))?;
330    let stdin_thread = std::thread::spawn(move || -> Result<(), std::io::Error> {
331        child_stdin.write_all(&stdin_bytes)?;
332        drop(child_stdin);
333        Ok(())
334    });
335
336    let start = std::time::Instant::now();
337    let timeout = std::time::Duration::from_secs(timeout_secs);
338    let status = child.wait_timeout(timeout).map_err(AppError::Io)?;
339
340    match status {
341        Some(exit_status) => {
342            stdin_thread
343                .join()
344                .map_err(|_| AppError::Validation("stdin thread panicked".into()))?
345                .map_err(AppError::Io)?;
346
347            tracing::debug!(
348                target: "process",
349                exit_code = ?exit_status.code(),
350                elapsed_ms = start.elapsed().as_millis() as u64,
351                "external process completed"
352            );
353
354            let mut stdout_buf = Vec::new();
355            let mut stderr_buf = Vec::new();
356            if let Some(mut out) = child.stdout.take() {
357                std::io::Read::read_to_end(&mut out, &mut stdout_buf).map_err(AppError::Io)?;
358            }
359            if let Some(mut err) = child.stderr.take() {
360                std::io::Read::read_to_end(&mut err, &mut stderr_buf).map_err(AppError::Io)?;
361            }
362
363            if !exit_status.success() {
364                let stderr_str = String::from_utf8_lossy(&stderr_buf);
365                let stdout_str = String::from_utf8_lossy(&stdout_buf);
366                // Check if stdout has JSONL with an error event before falling back
367                if let Ok((result, usage)) = parse_codex_output(&stdout_str) {
368                    return Ok((result, usage));
369                }
370                if stderr_str.contains("401")
371                    || stderr_str.contains("Unauthorized")
372                    || stderr_str.contains("auth")
373                {
374                    tracing::warn!(
375                        target: "ingest",
376                        "Codex CLI authentication expired. Re-authenticate with: codex auth login"
377                    );
378                }
379                return Err(AppError::Validation(format!(
380                    "codex exec exited with code {:?}: {}",
381                    exit_status.code(),
382                    stderr_str.trim()
383                )));
384            }
385
386            let stdout = String::from_utf8(stdout_buf)
387                .map_err(|_| AppError::Validation("codex exec stdout is not valid UTF-8".into()))?;
388            parse_codex_output(&stdout)
389        }
390        None => {
391            tracing::warn!(target: "ingest", timeout_secs, "codex exec timed out, killing process");
392            let _ = child.kill();
393            let _ = child.wait();
394            let _ = stdin_thread.join();
395            Err(AppError::Validation(format!(
396                "codex exec timed out after {timeout_secs} seconds"
397            )))
398        }
399    }
400}
401
402/// Parses JSONL output from `codex exec --json`.
403///
404/// Event format (DOTS notation):
405/// - `thread.started` — session init
406/// - `turn.started` — model turn begins
407/// - `item.completed` — message or tool call; last `agent_message` wins
408/// - `turn.completed` — includes usage stats
409/// - `turn.failed` — error with optional rate-limit indicator
410/// - `error` — schema or validation error
411///
412/// # Errors
413///
414/// Returns `AppError::Validation` when no agent_message is found, when the
415/// turn failed, or when the extracted JSON cannot be parsed as `ExtractionResult`.
416fn parse_codex_output(stdout: &str) -> Result<(ExtractionResult, Option<CodexUsage>), AppError> {
417    let mut last_agent_text: Option<String> = None;
418    let mut usage: Option<CodexUsage> = None;
419    let mut rate_limited = false;
420    let mut schema_error = false;
421    let mut turn_failed = false;
422    let mut failed_message = String::new();
423
424    for line in stdout.lines() {
425        let line = line.trim();
426        if line.is_empty() {
427            continue;
428        }
429
430        let event: serde_json::Value = match serde_json::from_str(line) {
431            Ok(v) => v,
432            Err(_) => {
433                tracing::warn!(target: "ingest", line, "codex output: skipping malformed JSONL line");
434                continue;
435            }
436        };
437
438        let event_type = match event.get("type").and_then(|t| t.as_str()) {
439            Some(t) => t,
440            None => continue,
441        };
442
443        match event_type {
444            "item.completed" => {
445                // Last agent_message wins (reasoning / tool calls may appear before)
446                if let Some(item) = event.get("item") {
447                    if item.get("type").and_then(|t| t.as_str()) == Some("agent_message") {
448                        if let Some(text) = item.get("text").and_then(|t| t.as_str()) {
449                            last_agent_text = Some(text.to_string());
450                        }
451                    }
452                }
453            }
454            "turn.completed" => {
455                if let Some(u) = event.get("usage") {
456                    if let Ok(parsed) = serde_json::from_value::<CodexUsage>(u.clone()) {
457                        usage = Some(parsed);
458                    }
459                }
460            }
461            "turn.failed" => {
462                turn_failed = true;
463                if let Some(err) = event.get("error") {
464                    let msg = err
465                        .get("message")
466                        .and_then(|m| m.as_str())
467                        .unwrap_or("unknown error");
468                    failed_message = msg.to_string();
469                    if msg.contains("rate_limit")
470                        || msg.contains("429")
471                        || msg.contains("Too Many Requests")
472                    {
473                        rate_limited = true;
474                    }
475                }
476            }
477            "error" => {
478                if let Some(msg) = event.get("message").and_then(|m| m.as_str()) {
479                    if msg.contains("invalid_json_schema") || msg.contains("schema") {
480                        schema_error = true;
481                    }
482                    tracing::warn!(target: "ingest", error_msg = msg, "codex error event received");
483                }
484            }
485            _ => {
486                // Gracefully skip unknown event types (thread.started, turn.started, etc.)
487            }
488        }
489    }
490
491    if rate_limited {
492        return Err(AppError::RateLimited {
493            detail: failed_message,
494        });
495    }
496
497    if schema_error {
498        return Err(AppError::Validation(
499            "codex rejected the output schema (invalid_json_schema)".to_string(),
500        ));
501    }
502
503    if turn_failed {
504        return Err(AppError::Validation(format!(
505            "codex turn failed: {failed_message}"
506        )));
507    }
508
509    let text = last_agent_text.ok_or_else(|| {
510        AppError::Validation("codex output contained no agent_message item".to_string())
511    })?;
512
513    let extraction: ExtractionResult = serde_json::from_str(&text).map_err(|e| {
514        AppError::Validation(format!(
515            "failed to parse codex agent_message as ExtractionResult: {e}. text={text}"
516        ))
517    })?;
518
519    Ok((extraction, usage))
520}
521
522use crate::output::emit_json_line as emit_json;
523
524/// Collects files matching the pattern (reuses ingest logic).
525fn collect_matching_files(
526    dir: &Path,
527    pattern: &str,
528    recursive: bool,
529    max_files: usize,
530) -> Result<Vec<PathBuf>, AppError> {
531    let mut files = Vec::new();
532    super::ingest::collect_files(dir, pattern, recursive, &mut files)?;
533    files.sort_unstable();
534
535    if files.len() > max_files {
536        return Err(AppError::Validation(format!(
537            "found {} files, exceeds --max-files cap of {}",
538            files.len(),
539            max_files
540        )));
541    }
542
543    Ok(files)
544}
545
546/// Opens or creates the queue database for tracking ingest progress.
547fn open_queue_db(path: &str) -> Result<Connection, AppError> {
548    let conn = Connection::open(path)?;
549
550    conn.execute_batch(
551        "PRAGMA journal_mode=WAL;
552        CREATE TABLE IF NOT EXISTS queue (
553            id          INTEGER PRIMARY KEY AUTOINCREMENT,
554            file_path   TEXT NOT NULL UNIQUE,
555            name        TEXT,
556            status      TEXT NOT NULL DEFAULT 'pending',
557            memory_id   INTEGER,
558            entities    INTEGER DEFAULT 0,
559            rels        INTEGER DEFAULT 0,
560            error       TEXT,
561            input_tokens  INTEGER DEFAULT 0,
562            output_tokens INTEGER DEFAULT 0,
563            attempt     INTEGER DEFAULT 0,
564            elapsed_ms  INTEGER,
565            created_at  TEXT DEFAULT (datetime('now')),
566            done_at     TEXT
567        );
568        CREATE INDEX IF NOT EXISTS idx_queue_status ON queue(status);",
569    )?;
570
571    Ok(conn)
572}
573
574/// Main entry point for `ingest --mode codex`.
575///
576/// # Errors
577///
578/// Returns `AppError` on directory/DB access failures or fatal extraction errors.
579pub fn run_codex_ingest(args: &IngestArgs) -> Result<(), AppError> {
580    let started = Instant::now();
581
582    if !args.dir.exists() {
583        return Err(AppError::Validation(format!(
584            "directory not found: {}",
585            args.dir.display()
586        )));
587    }
588
589    // G28-B (v1.0.68) + G30 (v1.0.69): acquire singleton before doing real
590    // work so two parallel `ingest --mode codex` invocations cannot co-exist
591    // on the same database. Scope includes the database hash so concurrent
592    // ingest against different databases is allowed.
593    let early_ns = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
594    let early_paths = AppPaths::resolve(args.db.as_deref())?;
595    let _singleton = crate::lock::acquire_job_singleton(
596        crate::lock::JobType::IngestCodex,
597        &early_ns,
598        &early_paths.db,
599        args.wait_job_singleton,
600        args.force_job_singleton,
601    )?;
602
603    // Stage 1: Validate binary
604    let codex_binary = find_codex_binary(args.codex_binary.as_deref())?;
605    let version = validate_codex_version(&codex_binary)?;
606    tracing::info!(
607        target: "ingest",
608        binary = %codex_binary.display(),
609        version = %version,
610        "Codex CLI binary validated"
611    );
612
613    emit_json(&PhaseEvent {
614        phase: "validate",
615        codex_path: codex_binary.to_str(),
616        version: Some(&version),
617        dir: None,
618        files_total: None,
619        files_new: None,
620        files_existing: None,
621    });
622
623    // Stage 2: Scan files
624    let files = collect_matching_files(&args.dir, &args.pattern, args.recursive, args.max_files)?;
625
626    let queue_conn = open_queue_db(&args.queue_db)?;
627
628    if args.resume {
629        let reset = queue_conn
630            .execute(
631                "UPDATE queue SET status='pending' WHERE status='processing'",
632                [],
633            )
634            .map_err(|e| AppError::Validation(format!("queue resume failed: {e}")))?;
635        if reset > 0 {
636            tracing::info!(target: "ingest", count = reset, "reset stuck processing files to pending");
637        }
638    }
639
640    if args.retry_failed {
641        let count = queue_conn
642            .execute(
643                "UPDATE queue SET status='pending', attempt=0 WHERE status='failed'",
644                [],
645            )
646            .map_err(|e| AppError::Validation(format!("queue retry-failed reset failed: {e}")))?;
647        tracing::info!(target: "ingest", count, "retrying failed files");
648    }
649
650    if !args.resume && !args.retry_failed {
651        queue_conn
652            .execute("DELETE FROM queue", [])
653            .map_err(|e| AppError::Validation(format!("queue clear failed: {e}")))?;
654    }
655
656    let mut new_count = 0usize;
657    let mut existing_count = 0usize;
658
659    if !args.retry_failed {
660        for file in &files {
661            let file_str = file.to_string_lossy().into_owned();
662            let inserted = queue_conn
663                .execute(
664                    "INSERT OR IGNORE INTO queue (file_path, status) VALUES (?1, 'pending')",
665                    rusqlite::params![file_str],
666                )
667                .map_err(|e| AppError::Validation(format!("queue insert failed: {e}")))?;
668            if inserted > 0 {
669                new_count += 1;
670            } else {
671                existing_count += 1;
672            }
673        }
674    }
675
676    emit_json(&PhaseEvent {
677        phase: "scan",
678        codex_path: None,
679        version: None,
680        dir: args.dir.to_str(),
681        files_total: Some(files.len()),
682        files_new: Some(new_count),
683        files_existing: Some(existing_count),
684    });
685
686    if args.dry_run {
687        for (idx, file) in files.iter().enumerate() {
688            let (name, _truncated, _orig) =
689                super::ingest::derive_kebab_name(file, args.max_name_length);
690            emit_json(&FileEvent {
691                file: &file.to_string_lossy(),
692                name: &name,
693                status: "preview",
694                memory_id: None,
695                entities: None,
696                rels: None,
697                cost_usd: None,
698                input_tokens: None,
699                output_tokens: None,
700                elapsed_ms: None,
701                error: None,
702                index: idx,
703                total: files.len(),
704            });
705        }
706        emit_json(&Summary {
707            summary: true,
708            files_total: files.len(),
709            completed: 0,
710            failed: 0,
711            skipped: 0,
712            entities_total: 0,
713            rels_total: 0,
714            input_tokens_total: 0,
715            output_tokens_total: 0,
716            elapsed_ms: started.elapsed().as_millis() as u64,
717        });
718        if !args.keep_queue {
719            let _ = std::fs::remove_file(&args.queue_db);
720        }
721        return Ok(());
722    }
723
724    // Stage 3: Process files
725    let paths = AppPaths::resolve(args.db.as_deref())?;
726    ensure_db_ready(&paths)?;
727    let conn = open_rw(&paths.db)?;
728    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
729    let memory_type_str = args.r#type.as_str().to_string();
730
731    // Write schema to temp file once (reused across all files)
732    let schema_tempfile = write_schema_tempfile()?;
733    let schema_path = schema_tempfile.path().to_path_buf();
734
735    let mut completed = 0usize;
736    let mut failed = 0usize;
737    let skipped_initial: usize = queue_conn
738        .query_row("SELECT COUNT(*) FROM queue WHERE status='done'", [], |r| {
739            r.get::<_, usize>(0)
740        })
741        .unwrap_or(0);
742    let mut skipped = skipped_initial;
743    let mut entities_total = 0usize;
744    let mut rels_total = 0usize;
745    let mut input_tokens_total = 0u64;
746    let mut output_tokens_total = 0u64;
747    let total = files.len();
748
749    let mut backoff_secs = args.rate_limit_wait;
750    let rate_limit_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3600);
751
752    loop {
753        if crate::shutdown_requested() {
754            tracing::info!(target: "ingest", "shutdown requested, stopping before next file");
755            break;
756        }
757
758        let pending: Option<(i64, String)> = queue_conn
759            .query_row(
760                "UPDATE queue SET status='processing', attempt=attempt+1 \
761                 WHERE id = (SELECT id FROM queue WHERE status='pending' ORDER BY id LIMIT 1) \
762                 RETURNING id, file_path",
763                [],
764                |row| Ok((row.get(0)?, row.get(1)?)),
765            )
766            .ok();
767
768        let (queue_id, file_path) = match pending {
769            Some(p) => p,
770            None => break,
771        };
772
773        let file_started = Instant::now();
774
775        // Reject files that exceed the 10 MB stdin limit
776        const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
777        if let Ok(meta) = std::fs::metadata(&file_path) {
778            if meta.len() > MAX_FILE_SIZE {
779                let err_msg = format!("file exceeds 10MB stdin limit ({} bytes)", meta.len());
780                let _ = queue_conn.execute(
781                    "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
782                    rusqlite::params![err_msg, queue_id],
783                );
784                let current_index = completed + failed + skipped;
785                failed += 1;
786                emit_json(&FileEvent {
787                    file: &file_path,
788                    name: "",
789                    status: "failed",
790                    memory_id: None,
791                    entities: None,
792                    rels: None,
793                    cost_usd: None,
794                    input_tokens: None,
795                    output_tokens: None,
796                    elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
797                    error: Some(&err_msg),
798                    index: current_index,
799                    total,
800                });
801                if args.fail_fast {
802                    break;
803                }
804                continue;
805            }
806        }
807
808        let file_content = match std::fs::read(&file_path) {
809            Ok(c) => c,
810            Err(e) => {
811                let err_msg = format!("IO error: {e}");
812                let _ = queue_conn.execute(
813                    "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
814                    rusqlite::params![err_msg, queue_id],
815                );
816                let current_index = completed + failed + skipped;
817                failed += 1;
818                emit_json(&FileEvent {
819                    file: &file_path,
820                    name: "",
821                    status: "failed",
822                    memory_id: None,
823                    entities: None,
824                    rels: None,
825                    cost_usd: None,
826                    input_tokens: None,
827                    output_tokens: None,
828                    elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
829                    error: Some(&err_msg),
830                    index: current_index,
831                    total,
832                });
833                if args.fail_fast {
834                    break;
835                }
836                continue;
837            }
838        };
839
840        // Skip files exceeding body cap BEFORE sending to LLM to avoid wasting tokens
841        if file_content.len() > crate::constants::MAX_MEMORY_BODY_LEN {
842            let err_msg = format!(
843                "file body exceeds {} byte limit ({} bytes) — skipping to avoid wasting LLM tokens",
844                crate::constants::MAX_MEMORY_BODY_LEN,
845                file_content.len()
846            );
847            tracing::warn!(target: "ingest", file = %file_path, size = file_content.len(), "body exceeds limit, skipping LLM extraction");
848            let _ = queue_conn.execute(
849                "UPDATE queue SET status='skipped', error=?1, done_at=datetime('now') WHERE id=?2",
850                rusqlite::params![err_msg, queue_id],
851            );
852            let current_index = completed + failed + skipped;
853            skipped += 1;
854            emit_json(&FileEvent {
855                file: &file_path,
856                name: "",
857                status: "skipped",
858                memory_id: None,
859                entities: None,
860                rels: None,
861                cost_usd: None,
862                input_tokens: None,
863                output_tokens: None,
864                elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
865                error: Some(&err_msg),
866                index: current_index,
867                total,
868            });
869            continue;
870        }
871
872        // Retry once on cold-start failure
873        let max_extract_attempts: u32 = 2;
874        let mut extraction_result: Option<(ExtractionResult, Option<CodexUsage>)> = None;
875        let mut last_extract_err: Option<String> = None;
876        let mut last_was_rate_limited = false;
877
878        for attempt in 1..=max_extract_attempts {
879            match extract_with_codex(
880                &codex_binary,
881                &file_content,
882                args.codex_model.as_deref(),
883                args.codex_timeout,
884                &schema_path,
885            ) {
886                Ok(result) => {
887                    extraction_result = Some(result);
888                    break;
889                }
890                Err(ref e) if matches!(e, AppError::RateLimited { .. }) => {
891                    last_extract_err = Some(format!("{e}"));
892                    last_was_rate_limited = true;
893                    break;
894                }
895                Err(e) => {
896                    let msg = format!("{e}");
897                    if attempt < max_extract_attempts {
898                        let cold_start_delay = 2 * attempt as u64;
899                        tracing::warn!(
900                            target: "ingest",
901                            attempt,
902                            delay_secs = cold_start_delay,
903                            error = %msg,
904                            "codex extraction failed, retrying"
905                        );
906                        std::thread::sleep(std::time::Duration::from_secs(cold_start_delay));
907                    }
908                    last_extract_err = Some(msg);
909                }
910            }
911        }
912
913        if let Some((extraction, usage)) = extraction_result {
914            backoff_secs = args.rate_limit_wait;
915
916            let in_tok = usage.as_ref().map(|u| u.input_tokens).unwrap_or(0);
917            let out_tok = usage.as_ref().map(|u| u.output_tokens).unwrap_or(0);
918
919            let name = &extraction.name;
920            let ent_count = extraction.entities.len();
921            let rel_count = extraction.relationships.len();
922
923            let new_entities: Vec<NewEntity> = extraction
924                .entities
925                .iter()
926                .filter_map(|e| match e.entity_type.parse::<EntityType>() {
927                    Ok(et) => Some(NewEntity {
928                        name: e.name.clone(),
929                        entity_type: et,
930                        description: None,
931                    }),
932                    Err(_) => {
933                        tracing::warn!(
934                            target: "ingest",
935                            entity = %e.name,
936                            entity_type = %e.entity_type,
937                            "entity type not recognized, skipping"
938                        );
939                        None
940                    }
941                })
942                .collect();
943
944            let new_relationships: Vec<NewRelationship> = extraction
945                .relationships
946                .iter()
947                .map(|r| NewRelationship {
948                    source: r.source.clone(),
949                    target: r.target.clone(),
950                    relation: crate::parsers::normalize_relation(&r.relation),
951                    strength: r.strength,
952                    description: None,
953                })
954                .collect();
955
956            let body_str = String::from_utf8_lossy(&file_content);
957            let body_hash = blake3::hash(body_str.as_bytes()).to_hex().to_string();
958            let new_memory = NewMemory {
959                name: name.clone(),
960                namespace: namespace.clone(),
961                memory_type: memory_type_str.clone(),
962                description: extraction.description.clone(),
963                body: body_str.to_string(),
964                body_hash,
965                session_id: None,
966                source: "agent".to_string(),
967                metadata: serde_json::Value::Object(serde_json::Map::new()),
968            };
969
970            // Deduplication: update existing memory instead of failing on UNIQUE
971            let memory_id = match memories::find_by_name_any_state(&conn, &namespace, name)? {
972                Some((existing_id, is_deleted)) => {
973                    if is_deleted {
974                        memories::clear_deleted_at(&conn, existing_id)?;
975                    }
976                    let (old_name, old_desc, old_body): (String, String, String) = conn.query_row(
977                        "SELECT name, COALESCE(description,''), COALESCE(body,'') FROM memories WHERE id=?1",
978                        rusqlite::params![existing_id],
979                        |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
980                    )?;
981                    memories::update(&conn, existing_id, &new_memory, None)?;
982                    memories::sync_fts_after_update(
983                        &conn,
984                        existing_id,
985                        &old_name,
986                        &old_desc,
987                        &old_body,
988                        &new_memory.name,
989                        &new_memory.description,
990                        &new_memory.body,
991                    )?;
992                    tracing::info!(target: "ingest", name, memory_id = existing_id, "updated existing memory (force-merge)");
993                    existing_id
994                }
995                None => match memories::insert(&conn, &new_memory) {
996                    Ok(id) => id,
997                    Err(e) => {
998                        let err_msg = format!("{e}");
999                        let _ = queue_conn.execute(
1000                            "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
1001                            rusqlite::params![err_msg, queue_id],
1002                        );
1003                        let current_index = completed + failed + skipped;
1004                        failed += 1;
1005                        emit_json(&FileEvent {
1006                            file: &file_path,
1007                            name,
1008                            status: "failed",
1009                            memory_id: None,
1010                            entities: None,
1011                            rels: None,
1012                            cost_usd: None,
1013                            input_tokens: Some(in_tok),
1014                            output_tokens: Some(out_tok),
1015                            elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1016                            error: Some(&err_msg),
1017                            index: current_index,
1018                            total,
1019                        });
1020                        input_tokens_total += in_tok;
1021                        output_tokens_total += out_tok;
1022                        if args.fail_fast {
1023                            break;
1024                        }
1025                        continue;
1026                    }
1027                },
1028            };
1029
1030            for ent in &new_entities {
1031                if let Ok(eid) = entities::upsert_entity(&conn, &namespace, ent) {
1032                    let _ = entities::link_memory_entity(&conn, memory_id, eid);
1033                }
1034            }
1035            for rel in &new_relationships {
1036                crate::parsers::warn_if_non_canonical(&rel.relation);
1037                let src_id = entities::find_entity_id(&conn, &namespace, &rel.source);
1038                let tgt_id = entities::find_entity_id(&conn, &namespace, &rel.target);
1039                if let (Ok(Some(sid)), Ok(Some(tid))) = (src_id, tgt_id) {
1040                    let _ = conn.execute(
1041                        "INSERT OR IGNORE INTO relationships (namespace, source_id, target_id, relation, weight) VALUES (?1, ?2, ?3, ?4, ?5)",
1042                        rusqlite::params![namespace, sid, tid, rel.relation, rel.strength],
1043                    );
1044                }
1045            }
1046
1047            let _ = queue_conn.execute(
1048                "UPDATE queue SET status='done', name=?1, memory_id=?2, entities=?3, rels=?4, \
1049                 input_tokens=?5, output_tokens=?6, elapsed_ms=?7, done_at=datetime('now') WHERE id=?8",
1050                rusqlite::params![
1051                    name,
1052                    memory_id,
1053                    ent_count,
1054                    rel_count,
1055                    in_tok,
1056                    out_tok,
1057                    file_started.elapsed().as_millis() as i64,
1058                    queue_id
1059                ],
1060            );
1061
1062            let current_index = completed + failed + skipped;
1063            completed += 1;
1064            entities_total += ent_count;
1065            rels_total += rel_count;
1066            input_tokens_total += in_tok;
1067            output_tokens_total += out_tok;
1068
1069            emit_json(&FileEvent {
1070                file: &file_path,
1071                name,
1072                status: "done",
1073                memory_id: Some(memory_id),
1074                entities: Some(ent_count),
1075                rels: Some(rel_count),
1076                cost_usd: None,
1077                input_tokens: Some(in_tok),
1078                output_tokens: Some(out_tok),
1079                elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1080                error: None,
1081                index: current_index,
1082                total,
1083            });
1084        } else if let Some(ref err_str) = last_extract_err {
1085            if last_was_rate_limited {
1086                if crate::retry::is_kill_switch_active() {
1087                    tracing::warn!(target: "ingest", "SQLITE_GRAPHRAG_DISABLE_RETRY=1, skipping rate-limit retry");
1088                } else if std::time::Instant::now() >= rate_limit_deadline {
1089                    tracing::error!(target: "ingest", "rate-limit retry deadline (1h) exhausted");
1090                } else {
1091                    let half = backoff_secs / 2;
1092                    let jitter = if half == 0 { 0 } else { fastrand::u64(0..half) };
1093                    let actual_wait = half + jitter;
1094                    tracing::warn!(target: "ingest", delay_secs = actual_wait, error_kind = "rate_limited", "Codex rate limited, backing off");
1095                    let _ = queue_conn.execute(
1096                        "UPDATE queue SET status='pending' WHERE id=?1",
1097                        rusqlite::params![queue_id],
1098                    );
1099                    std::thread::sleep(std::time::Duration::from_secs(actual_wait));
1100                    backoff_secs = (backoff_secs * 2).min(900);
1101                    continue;
1102                }
1103            } else {
1104                let _ = queue_conn.execute(
1105                    "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
1106                    rusqlite::params![err_str, queue_id],
1107                );
1108                let current_index = completed + failed + skipped;
1109                failed += 1;
1110                emit_json(&FileEvent {
1111                    file: &file_path,
1112                    name: "",
1113                    status: "failed",
1114                    memory_id: None,
1115                    entities: None,
1116                    rels: None,
1117                    cost_usd: None,
1118                    input_tokens: None,
1119                    output_tokens: None,
1120                    elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1121                    error: Some(err_str),
1122                    index: current_index,
1123                    total,
1124                });
1125                if args.fail_fast {
1126                    break;
1127                }
1128            }
1129        }
1130    }
1131
1132    // WAL checkpoint before summary
1133    let _ = conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE);");
1134
1135    // Stage 4: Summary
1136    emit_json(&Summary {
1137        summary: true,
1138        files_total: total,
1139        completed,
1140        failed,
1141        skipped,
1142        entities_total,
1143        rels_total,
1144        input_tokens_total,
1145        output_tokens_total,
1146        elapsed_ms: started.elapsed().as_millis() as u64,
1147    });
1148
1149    if !args.keep_queue && failed == 0 {
1150        let _ = std::fs::remove_file(&args.queue_db);
1151    }
1152
1153    Ok(())
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use super::*;
1159
1160    fn make_agent_message_event(text: &str) -> String {
1161        format!(
1162            r#"{{"type":"item.completed","item":{{"id":"item_0","type":"agent_message","text":{}}}}}"#,
1163            serde_json::to_string(text).unwrap()
1164        )
1165    }
1166
1167    fn make_usage_event(input: u64, output: u64) -> String {
1168        format!(
1169            r#"{{"type":"turn.completed","usage":{{"input_tokens":{input},"output_tokens":{output}}}}}"#
1170        )
1171    }
1172
1173    fn valid_extraction_json() -> String {
1174        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()
1175    }
1176
1177    #[test]
1178    fn test_parse_codex_output_valid() {
1179        let jsonl = format!(
1180            "{}\n{}\n{}",
1181            r#"{"type":"thread.started","thread_id":"t1"}"#,
1182            make_agent_message_event(&valid_extraction_json()),
1183            make_usage_event(100, 50),
1184        );
1185
1186        let (result, usage) = parse_codex_output(&jsonl).expect("parse must succeed");
1187        assert_eq!(result.name, "test-module");
1188        assert_eq!(result.entities.len(), 1);
1189        assert_eq!(result.relationships.len(), 1);
1190        let u = usage.expect("usage must be present");
1191        assert_eq!(u.input_tokens, 100);
1192        assert_eq!(u.output_tokens, 50);
1193    }
1194
1195    #[test]
1196    fn test_parse_codex_output_turn_failed() {
1197        let jsonl = format!(
1198            "{}\n{}",
1199            r#"{"type":"thread.started","thread_id":"t1"}"#,
1200            r#"{"type":"turn.failed","error":{"message":"model error occurred"}}"#,
1201        );
1202
1203        let err = parse_codex_output(&jsonl).unwrap_err();
1204        let msg = format!("{err}");
1205        assert!(
1206            msg.contains("turn failed"),
1207            "expected 'turn failed' in: {msg}"
1208        );
1209        assert!(msg.contains("model error occurred"));
1210    }
1211
1212    #[test]
1213    fn test_parse_codex_output_rate_limit() {
1214        let jsonl = r#"{"type":"turn.failed","error":{"message":"rate_limit exceeded, 429 Too Many Requests"}}"#;
1215
1216        let err = parse_codex_output(jsonl).unwrap_err();
1217        assert!(
1218            matches!(err, AppError::RateLimited { .. }),
1219            "expected AppError::RateLimited, got: {err}"
1220        );
1221    }
1222
1223    #[test]
1224    fn test_parse_codex_output_schema_error() {
1225        let jsonl = r#"{"type":"error","message":"invalid_json_schema: additional properties not allowed"}"#;
1226
1227        let err = parse_codex_output(jsonl).unwrap_err();
1228        let msg = format!("{err}");
1229        assert!(
1230            msg.contains("invalid_json_schema") || msg.contains("schema"),
1231            "expected schema error in: {msg}"
1232        );
1233    }
1234
1235    #[test]
1236    fn test_extraction_schema_codex_valid_json() {
1237        let _: serde_json::Value =
1238            serde_json::from_str(EXTRACTION_SCHEMA_CODEX).expect("schema must be valid JSON");
1239    }
1240
1241    #[test]
1242    fn test_extraction_schema_codex_has_additional_properties_false() {
1243        let schema: serde_json::Value =
1244            serde_json::from_str(EXTRACTION_SCHEMA_CODEX).expect("schema must be valid JSON");
1245
1246        // Root level
1247        assert_eq!(
1248            schema["additionalProperties"].as_bool(),
1249            Some(false),
1250            "root must have additionalProperties: false"
1251        );
1252
1253        // Entity items level
1254        assert_eq!(
1255            schema["properties"]["entities"]["items"]["additionalProperties"].as_bool(),
1256            Some(false),
1257            "entity items must have additionalProperties: false"
1258        );
1259
1260        // Relationship items level
1261        assert_eq!(
1262            schema["properties"]["relationships"]["items"]["additionalProperties"].as_bool(),
1263            Some(false),
1264            "relationship items must have additionalProperties: false"
1265        );
1266    }
1267
1268    #[test]
1269    fn test_parse_codex_output_last_agent_message_wins() {
1270        // Multiple agent_message items — last one should win
1271        let first_text = r#"{"name":"first-result","description":"First result should be ignored","entities":[],"relationships":[]}"#;
1272        let second_text = r#"{"name":"final-result","description":"Final result wins over earlier ones","entities":[{"name":"final-entity","entity_type":"concept"}],"relationships":[]}"#;
1273
1274        let jsonl = format!(
1275            "{}\n{}\n{}\n{}",
1276            r#"{"type":"thread.started","thread_id":"t1"}"#,
1277            make_agent_message_event(first_text),
1278            make_agent_message_event(second_text),
1279            make_usage_event(200, 80),
1280        );
1281
1282        let (result, _) = parse_codex_output(&jsonl).expect("parse must succeed");
1283        assert_eq!(result.name, "final-result", "last agent_message should win");
1284        assert_eq!(result.entities.len(), 1);
1285    }
1286
1287    #[test]
1288    fn test_parse_codex_output_skips_malformed_lines() {
1289        let jsonl = format!(
1290            "not json at all\n{}\n{{broken\n{}",
1291            make_agent_message_event(&valid_extraction_json()),
1292            make_usage_event(10, 5),
1293        );
1294
1295        // Should succeed despite malformed lines
1296        let (result, _) = parse_codex_output(&jsonl).expect("malformed lines must be skipped");
1297        assert_eq!(result.name, "test-module");
1298    }
1299}