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