1use crate::commands::ingest::IngestArgs;
13use crate::entity_type::EntityType;
14use crate::errors::AppError;
15use crate::paths::AppPaths;
16use crate::spawn::env_whitelist::apply_env_whitelist;
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_CLAUDE_VERSION: &str = "2.1.0";
29
30const EXTRACTION_SCHEMA: &str = r#"{
31 "type": "object",
32 "properties": {
33 "name": { "type": "string" },
34 "description": { "type": "string" },
35 "entities": {
36 "type": "array",
37 "items": {
38 "type": "object",
39 "properties": {
40 "name": { "type": "string" },
41 "entity_type": {
42 "type": "string",
43 "enum": ["project","tool","person","file","concept","incident","decision","organization","location","date"]
44 }
45 },
46 "required": ["name", "entity_type"],
47 "additionalProperties": false
48 }
49 },
50 "relationships": {
51 "type": "array",
52 "items": {
53 "type": "object",
54 "properties": {
55 "source": { "type": "string" },
56 "target": { "type": "string" },
57 "relation": {
58 "type": "string",
59 "enum": ["applies-to","uses","depends-on","causes","fixes","contradicts","supports","follows","related","replaces","tracked-in"]
60 },
61 "strength": { "type": "number", "minimum": 0, "maximum": 1 }
62 },
63 "required": ["source","target","relation","strength"],
64 "additionalProperties": false
65 }
66 }
67 },
68 "required": ["name","description","entities","relationships"],
69 "additionalProperties": false
70}"#;
71
72const EXTRACTION_PROMPT: &str = "You are a knowledge graph entity extractor. Given a document, extract:\n\
731. A short kebab-case name (max 60 chars) capturing the document's main topic\n\
742. A one-sentence description (10-20 words) summarizing the key insight\n\
753. Domain-specific entities (concepts, tools, people, decisions, projects, files)\n\
764. Typed relationships between entities with strength scores\n\n\
77Rules:\n\
78- Entity names: lowercase kebab-case, 2+ chars, domain-specific only\n\
79- NEVER extract generic terms, stop words, numbers, UUIDs, or single characters\n\
80- Relationship types MUST be one of: applies-to, uses, depends-on, causes, fixes, contradicts, supports, follows, related, replaces, tracked-in\n\
81- NEVER use 'mentions' as relationship type\n\
82- Strength: 0.9 for hard dependencies, 0.7 for design relationships, 0.5 for contextual links, 0.3 for weak references\n\
83- Prefer fewer high-quality entities over many low-quality ones\n\
84- Description must answer: What is this about and WHY does it matter?";
85
86#[derive(Debug, Deserialize)]
87struct ClaudeOutputElement {
88 r#type: Option<String>,
89 subtype: Option<String>,
90 #[serde(default)]
91 is_error: bool,
92 structured_output: Option<ExtractionResult>,
93 result: Option<String>,
94 total_cost_usd: Option<f64>,
95 error: Option<String>,
96 terminal_reason: Option<String>,
97 #[serde(rename = "apiKeySource")]
98 api_key_source: Option<String>,
99}
100
101#[derive(Debug, Clone, Deserialize, Serialize)]
102pub struct ExtractionResult {
103 pub name: String,
104 pub description: String,
105 pub entities: Vec<ExtractedEntity>,
106 pub relationships: Vec<ExtractedRelationship>,
107}
108
109#[derive(Debug, Clone, Deserialize, Serialize)]
110pub struct ExtractedEntity {
111 pub name: String,
112 pub entity_type: String,
113}
114
115#[derive(Debug, Clone, Deserialize, Serialize)]
116pub struct ExtractedRelationship {
117 pub source: String,
118 pub target: String,
119 pub relation: String,
120 pub strength: f64,
121}
122
123#[derive(Debug, Serialize)]
124struct PhaseEvent<'a> {
125 phase: &'a str,
126 #[serde(skip_serializing_if = "Option::is_none")]
127 claude_path: Option<&'a str>,
128 #[serde(skip_serializing_if = "Option::is_none")]
129 version: Option<&'a str>,
130 #[serde(skip_serializing_if = "Option::is_none")]
131 dir: Option<&'a str>,
132 #[serde(skip_serializing_if = "Option::is_none")]
133 files_total: Option<usize>,
134 #[serde(skip_serializing_if = "Option::is_none")]
135 files_new: Option<usize>,
136 #[serde(skip_serializing_if = "Option::is_none")]
137 files_existing: Option<usize>,
138}
139
140#[derive(Debug, Serialize)]
141struct FileEvent<'a> {
142 file: &'a str,
143 name: &'a str,
144 status: &'a str,
145 #[serde(skip_serializing_if = "Option::is_none")]
146 memory_id: Option<i64>,
147 #[serde(skip_serializing_if = "Option::is_none")]
148 entities: Option<usize>,
149 #[serde(skip_serializing_if = "Option::is_none")]
150 rels: Option<usize>,
151 #[serde(skip_serializing_if = "Option::is_none")]
152 cost_usd: Option<f64>,
153 #[serde(skip_serializing_if = "Option::is_none")]
154 elapsed_ms: Option<u64>,
155 #[serde(skip_serializing_if = "Option::is_none")]
156 error: Option<&'a str>,
157 index: usize,
158 total: usize,
159}
160
161#[derive(Debug, Serialize)]
162struct Summary {
163 summary: bool,
164 files_total: usize,
165 completed: usize,
166 failed: usize,
167 skipped: usize,
168 entities_total: usize,
169 rels_total: usize,
170 cost_usd: f64,
171 elapsed_ms: u64,
172}
173
174pub fn find_claude_binary(explicit: Option<&Path>) -> Result<PathBuf, AppError> {
176 if let Some(p) = explicit {
177 if p.exists() {
178 return Ok(p.to_path_buf());
179 }
180 return Err(AppError::Validation(format!(
181 "Claude Code binary not found at explicit path: {}",
182 p.display()
183 )));
184 }
185
186 if let Ok(env_path) = std::env::var("SQLITE_GRAPHRAG_CLAUDE_BINARY") {
187 let p = PathBuf::from(&env_path);
188 if p.exists() {
189 return Ok(p);
190 }
191 }
192
193 let name = if cfg!(windows) {
194 "claude.exe"
195 } else {
196 "claude"
197 };
198 if let Some(path_var) = std::env::var_os("PATH") {
199 for dir in std::env::split_paths(&path_var) {
200 let candidate = dir.join(name);
201 if candidate.exists() {
202 return Ok(candidate);
203 }
204 }
205 }
206
207 Err(AppError::Validation(
208 "Claude Code binary not found in PATH. Install it from https://docs.anthropic.com/claude-code or specify --claude-binary".to_string(),
209 ))
210}
211
212fn validate_claude_version(binary: &Path) -> Result<String, AppError> {
214 let output = Command::new(binary)
215 .arg("--version")
216 .stdin(Stdio::null())
217 .stdout(Stdio::piped())
218 .stderr(Stdio::piped())
219 .output()
220 .map_err(AppError::Io)?;
221
222 if !output.status.success() {
223 return Err(AppError::Validation(
224 "failed to run 'claude --version'".to_string(),
225 ));
226 }
227
228 let version_str = String::from_utf8(output.stdout)
229 .map_err(|_| AppError::Validation("claude --version output is not UTF-8".to_string()))?;
230 let version = version_str.trim().to_string();
231
232 let numeric = version.split([' ', '(']).next().unwrap_or("").trim();
234
235 fn parse_semver(s: &str) -> Option<(u64, u64, u64)> {
236 let parts: Vec<&str> = s.splitn(3, '.').collect();
237 if parts.len() < 2 {
238 return None;
239 }
240 let major = parts[0].parse::<u64>().ok()?;
241 let minor = parts[1].parse::<u64>().ok()?;
242 let patch = parts
243 .get(2)
244 .and_then(|p| p.parse::<u64>().ok())
245 .unwrap_or(0);
246 Some((major, minor, patch))
247 }
248
249 if let (Some(actual), Some(min)) = (parse_semver(numeric), parse_semver(MIN_CLAUDE_VERSION)) {
250 if actual < min {
251 return Err(AppError::Validation(format!(
252 "Claude Code version {numeric} is below minimum required {MIN_CLAUDE_VERSION}"
253 )));
254 }
255 }
256
257 Ok(version)
258}
259
260fn extract_with_claude(
273 binary: &Path,
274 file_content: &[u8],
275 model: Option<&str>,
276 timeout_secs: u64,
277) -> Result<(ExtractionResult, f64, bool), AppError> {
278 use wait_timeout::ChildExt;
279
280 if let Ok(_key) = std::env::var("ANTHROPIC_API_KEY") {
284 let mut cmd = Command::new("false");
285 cmd.env_clear();
286 cmd.env("PATH", "/nonexistent");
287 cmd.arg("--oauth-only-violation-anthropic-api-key-set");
288 return Err(AppError::Validation(
289 "ANTHROPIC_API_KEY is set in the environment; \
290 sqlite-graphrag operates exclusively with OAuth (Pro/Max) and \
291 the API-key path is PROHIBITED (gaps.md:47). Unset the variable \
292 and re-run with `claude login` already completed in this session."
293 .to_string(),
294 ));
295 }
296
297 let mut cmd = Command::new(binary);
298
299 apply_env_whitelist(&mut cmd, crate::spawn::env_whitelist::is_strict_env_clear());
302
303 let mcp_config_path = crate::spawn::preflight::write_empty_mcp_config_tempfile()?;
310
311 cmd.arg("-p")
312 .arg(EXTRACTION_PROMPT)
313 .arg("--strict-mcp-config")
314 .arg("--mcp-config")
315 .arg(mcp_config_path.as_os_str())
316 .arg("--dangerously-skip-permissions")
317 .arg("--settings")
318 .arg(r#"{"hooks":{}}"#)
319 .arg("--output-format")
320 .arg("json")
321 .arg("--json-schema")
322 .arg(EXTRACTION_SCHEMA)
323 .arg("--max-turns")
324 .arg("7")
325 .arg("--no-session-persistence");
326
327 if let Some(m) = model {
328 cmd.arg("--model").arg(m);
329 }
330
331 cmd.stdin(Stdio::piped())
332 .stdout(Stdio::piped())
333 .stderr(Stdio::piped());
334
335 let argv_refs: Vec<std::ffi::OsString> = cmd.get_args().map(|s| s.to_os_string()).collect();
339 let preflight_args = crate::spawn::preflight::PreFlightArgs {
340 binary_path: binary,
341 argv: &argv_refs,
342 workspace_root: std::path::Path::new("."),
343 mcp_config_inline_json: None,
344 expected_output_bytes: 65_536,
345 spawner_name: "ingest_claude",
346 };
347 if let Err(e) = crate::spawn::preflight::preflight_check(&preflight_args) {
348 return Err(crate::errors::AppError::from(e));
354 }
355
356 let mut child = super::claude_runner::spawn_with_memory_limit(&mut cmd).map_err(|e| {
357 AppError::Io(std::io::Error::new(
358 e.kind(),
359 format!("failed to spawn claude: {e}"),
360 ))
361 })?;
362
363 let stdin_data = file_content.to_vec();
364 let mut child_stdin = child
365 .stdin
366 .take()
367 .ok_or_else(|| AppError::Validation("failed to open claude stdin".into()))?;
368 let stdin_thread = std::thread::spawn(move || -> Result<(), std::io::Error> {
369 child_stdin.write_all(&stdin_data)?;
370 drop(child_stdin);
371 Ok(())
372 });
373
374 let start = std::time::Instant::now();
375 let timeout = std::time::Duration::from_secs(timeout_secs);
376 let status = child.wait_timeout(timeout).map_err(AppError::Io)?;
377
378 match status {
379 Some(exit_status) => {
380 stdin_thread
381 .join()
382 .map_err(|_| AppError::Validation("stdin thread panicked".into()))?
383 .map_err(AppError::Io)?;
384
385 tracing::debug!(
386 target: "process",
387 exit_code = ?exit_status.code(),
388 elapsed_ms = start.elapsed().as_millis() as u64,
389 "external process completed"
390 );
391
392 let mut stdout_buf = Vec::new();
393 let mut stderr_buf = Vec::new();
394 if let Some(mut out) = child.stdout.take() {
395 std::io::Read::read_to_end(&mut out, &mut stdout_buf).map_err(AppError::Io)?;
396 }
397 if let Some(mut err) = child.stderr.take() {
398 std::io::Read::read_to_end(&mut err, &mut stderr_buf).map_err(AppError::Io)?;
399 }
400
401 if !exit_status.success() {
402 let stdout_str = String::from_utf8_lossy(&stdout_buf);
403 if let Ok(elements) = serde_json::from_str::<Vec<ClaudeOutputElement>>(&stdout_str)
404 {
405 if let Some(re) = elements
406 .iter()
407 .find(|e| e.r#type.as_deref() == Some("result"))
408 {
409 if re.terminal_reason.as_deref() == Some("max_turns") {
410 tracing::warn!(
411 target: "ingest",
412 "extraction hit max_turns limit — hooks may have consumed turns"
413 );
414 return Err(AppError::Validation(
415 "claude -p hit max_turns: hooks may be consuming turns".into(),
416 ));
417 }
418 if re.is_error {
419 let err_msg = re
420 .error
421 .as_deref()
422 .or(re.result.as_deref())
423 .unwrap_or("unknown error");
424 if err_msg.contains("rate_limit") || err_msg.contains("overloaded") {
425 return Err(AppError::RateLimited {
426 detail: err_msg.to_string(),
427 });
428 }
429 if err_msg.contains("Not logged in")
430 || err_msg.contains("authentication")
431 {
432 tracing::warn!(
433 target: "ingest",
434 "Claude Code authentication failed. Re-authenticate interactively with: claude"
435 );
436 }
437 return Err(AppError::Validation(format!(
438 "claude -p failed: {err_msg}"
439 )));
440 }
441 }
442 }
443 let stderr_str = String::from_utf8_lossy(&stderr_buf);
444 if stderr_str.contains("auth") || stderr_str.contains("login") {
445 tracing::warn!(
446 target: "ingest",
447 "Claude Code authentication may have failed. Re-authenticate with: claude"
448 );
449 }
450 return Err(AppError::Validation(format!(
451 "claude -p exited with code {:?}: {}",
452 exit_status.code(),
453 stderr_str.trim()
454 )));
455 }
456
457 let stdout = String::from_utf8(stdout_buf)
458 .map_err(|_| AppError::Validation("claude -p stdout is not valid UTF-8".into()))?;
459 parse_claude_output(&stdout)
460 }
461 None => {
462 tracing::warn!(target: "ingest", timeout_secs, "claude -p timed out, killing process");
463 let _ = child.kill();
464 let _ = child.wait();
465 let _ = stdin_thread.join();
466 Err(AppError::Validation(format!(
467 "claude -p timed out after {timeout_secs} seconds"
468 )))
469 }
470 }
471}
472
473fn parse_claude_output(stdout: &str) -> Result<(ExtractionResult, f64, bool), AppError> {
478 let elements: Vec<ClaudeOutputElement> = serde_json::from_str(stdout).map_err(|e| {
479 AppError::Validation(format!("failed to parse claude output as JSON array: {e}"))
480 })?;
481
482 let is_oauth = elements
483 .iter()
484 .find(|e| e.r#type.as_deref() == Some("system") && e.subtype.as_deref() == Some("init"))
485 .and_then(|e| e.api_key_source.as_deref())
486 .map(|s| s == "none")
487 .unwrap_or(false);
488
489 let result_elem = elements
490 .iter()
491 .find(|e| e.r#type.as_deref() == Some("result"))
492 .ok_or_else(|| {
493 AppError::Validation("claude output missing 'result' element".to_string())
494 })?;
495
496 if result_elem.is_error {
497 let err_msg = result_elem
498 .error
499 .as_deref()
500 .or(result_elem.result.as_deref())
501 .unwrap_or("unknown error");
502 if err_msg.contains("rate_limit") || err_msg.contains("overloaded") {
503 return Err(AppError::RateLimited {
504 detail: err_msg.to_string(),
505 });
506 }
507 return Err(AppError::Validation(format!(
508 "claude extraction failed: {err_msg}"
509 )));
510 }
511
512 let extraction = result_elem
513 .structured_output
514 .clone()
515 .or_else(|| {
516 result_elem
517 .result
518 .as_ref()
519 .and_then(|text| serde_json::from_str::<ExtractionResult>(text).ok())
520 })
521 .ok_or_else(|| {
522 AppError::Validation("claude result missing structured_output and result field".into())
523 })?;
524
525 let cost = result_elem.total_cost_usd.unwrap_or(0.0);
526
527 Ok((extraction, cost, is_oauth))
528}
529
530use crate::output::emit_json_line as emit_json;
531
532fn collect_matching_files(
534 dir: &Path,
535 pattern: &str,
536 recursive: bool,
537 max_files: usize,
538) -> Result<Vec<PathBuf>, AppError> {
539 let mut files = Vec::new();
540 super::ingest::collect_files(dir, pattern, recursive, &mut files)?;
541 files.sort_unstable();
542
543 if files.len() > max_files {
544 return Err(AppError::Validation(format!(
545 "found {} files, exceeds --max-files cap of {}",
546 files.len(),
547 max_files
548 )));
549 }
550
551 Ok(files)
552}
553
554fn open_queue_db(path: &str) -> Result<Connection, AppError> {
556 let conn = Connection::open(path)?;
557
558 conn.pragma_update(None, "journal_mode", "wal")?;
559
560 conn.execute_batch(
561 "CREATE TABLE IF NOT EXISTS queue (
562 id INTEGER PRIMARY KEY AUTOINCREMENT,
563 file_path TEXT NOT NULL UNIQUE,
564 name TEXT,
565 status TEXT NOT NULL DEFAULT 'pending',
566 memory_id INTEGER,
567 entities INTEGER DEFAULT 0,
568 rels INTEGER DEFAULT 0,
569 error TEXT,
570 cost_usd REAL DEFAULT 0.0,
571 attempt INTEGER DEFAULT 0,
572 elapsed_ms INTEGER,
573 created_at TEXT DEFAULT (datetime('now')),
574 done_at TEXT
575 );
576 CREATE INDEX IF NOT EXISTS idx_queue_status ON queue(status);",
577 )?;
578
579 Ok(conn)
580}
581
582pub fn run_claude_ingest(args: &IngestArgs) -> Result<(), AppError> {
584 let started = Instant::now();
585
586 if !args.dir.exists() {
587 return Err(AppError::Validation(format!(
588 "directory not found: {}",
589 args.dir.display()
590 )));
591 }
592
593 let early_ns = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
598 let early_paths = AppPaths::resolve(args.db.as_deref())?;
599 let _singleton = crate::lock::acquire_job_singleton(
600 crate::lock::JobType::IngestClaudeCode,
601 &early_ns,
602 &early_paths.db,
603 args.wait_job_singleton,
604 args.force_job_singleton,
605 )?;
606
607 let claude_binary = find_claude_binary(args.claude_binary.as_deref())?;
609 let version = validate_claude_version(&claude_binary)?;
610 tracing::info!(
611 target: "ingest",
612 binary = %claude_binary.display(),
613 version = %version,
614 "Claude Code binary validated"
615 );
616
617 emit_json(&PhaseEvent {
618 phase: "validate",
619 claude_path: claude_binary.to_str(),
620 version: Some(&version),
621 dir: None,
622 files_total: None,
623 files_new: None,
624 files_existing: None,
625 });
626
627 let files = collect_matching_files(&args.dir, &args.pattern, args.recursive, args.max_files)?;
629
630 let queue_conn = open_queue_db(&args.queue_db)?;
631
632 if args.resume {
633 let reset = queue_conn
634 .execute(
635 "UPDATE queue SET status='pending' WHERE status='processing'",
636 [],
637 )
638 .map_err(|e| AppError::Validation(format!("queue resume failed: {e}")))?;
639 if reset > 0 {
640 tracing::info!(target: "ingest", count = reset, "reset stuck processing files to pending");
641 }
642 }
643
644 if args.retry_failed {
645 let count = queue_conn
646 .execute(
647 "UPDATE queue SET status='pending', attempt=0 WHERE status='failed'",
648 [],
649 )
650 .map_err(|e| AppError::Validation(format!("queue retry-failed reset failed: {e}")))?;
651 tracing::info!(target: "ingest", count, "retrying failed files");
652 }
653
654 if !args.resume && !args.retry_failed {
655 queue_conn
656 .execute("DELETE FROM queue", [])
657 .map_err(|e| AppError::Validation(format!("queue clear failed: {e}")))?;
658 }
659
660 let mut new_count = 0usize;
661 let mut existing_count = 0usize;
662
663 if !args.retry_failed {
664 for file in &files {
665 let file_str = file.to_string_lossy().into_owned();
666 let inserted = queue_conn
667 .execute(
668 "INSERT OR IGNORE INTO queue (file_path, status) VALUES (?1, 'pending')",
669 rusqlite::params![file_str],
670 )
671 .map_err(|e| AppError::Validation(format!("queue insert failed: {e}")))?;
672 if inserted > 0 {
673 new_count += 1;
674 } else {
675 existing_count += 1;
676 }
677 }
678 }
679
680 emit_json(&PhaseEvent {
681 phase: "scan",
682 claude_path: None,
683 version: None,
684 dir: args.dir.to_str(),
685 files_total: Some(files.len()),
686 files_new: Some(new_count),
687 files_existing: Some(existing_count),
688 });
689
690 if args.dry_run {
691 for (idx, file) in files.iter().enumerate() {
692 let (name, _truncated, _orig) =
693 super::ingest::derive_kebab_name(file, args.max_name_length);
694 emit_json(&FileEvent {
695 file: &file.to_string_lossy(),
696 name: &name,
697 status: "preview",
698 memory_id: None,
699 entities: None,
700 rels: None,
701 cost_usd: None,
702 elapsed_ms: None,
703 error: None,
704 index: idx,
705 total: files.len(),
706 });
707 }
708 emit_json(&Summary {
709 summary: true,
710 files_total: files.len(),
711 completed: 0,
712 failed: 0,
713 skipped: 0,
714 entities_total: 0,
715 rels_total: 0,
716 cost_usd: 0.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
730 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
731 let memory_type_str = args.r#type.as_str().to_string();
732
733 let mut completed = 0usize;
734 let mut failed = 0usize;
735 let skipped_initial: usize = queue_conn
736 .query_row("SELECT COUNT(*) FROM queue WHERE status='done'", [], |r| {
737 r.get::<_, usize>(0)
738 })
739 .unwrap_or(0);
740 let mut skipped = skipped_initial;
741 let mut entities_total = 0usize;
742 let mut rels_total = 0usize;
743 let mut cost_total = 0.0f64;
744 let mut oauth_detected = false;
745 let total = files.len();
746
747 let mut backoff_secs = args.rate_limit_wait;
748 let rate_limit_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3600);
749
750 loop {
751 if crate::shutdown_requested() {
752 tracing::info!(target: "ingest", "shutdown requested, stopping before next file");
753 break;
754 }
755
756 let pending: Option<(i64, String)> = queue_conn
757 .query_row(
758 "UPDATE queue SET status='processing', attempt=attempt+1 \
759 WHERE id = (SELECT id FROM queue WHERE status='pending' ORDER BY id LIMIT 1) \
760 RETURNING id, file_path",
761 [],
762 |row| Ok((row.get(0)?, row.get(1)?)),
763 )
764 .ok();
765
766 let (queue_id, file_path) = match pending {
767 Some(p) => p,
768 None => break,
769 };
770
771 let file_started = Instant::now();
772
773 const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
775 if let Ok(meta) = std::fs::metadata(&file_path) {
776 if meta.len() > MAX_FILE_SIZE {
777 let err_msg = format!("file exceeds 10MB stdin limit ({} bytes)", meta.len());
778 let _ = queue_conn.execute(
779 "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
780 rusqlite::params![err_msg, queue_id],
781 );
782 let current_index = completed + failed + skipped;
783 failed += 1;
784 emit_json(&FileEvent {
785 file: &file_path,
786 name: "",
787 status: "failed",
788 memory_id: None,
789 entities: None,
790 rels: None,
791 cost_usd: None,
792 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
793 error: Some(&err_msg),
794 index: current_index,
795 total,
796 });
797 if args.fail_fast {
798 break;
799 }
800 continue;
801 }
802 }
803
804 let file_content = match std::fs::read(&file_path) {
805 Ok(c) => c,
806 Err(e) => {
807 let err_msg = format!("IO error: {e}");
808 let _ = queue_conn.execute(
809 "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
810 rusqlite::params![err_msg, queue_id],
811 );
812 let current_index = completed + failed + skipped;
813 failed += 1;
814 emit_json(&FileEvent {
815 file: &file_path,
816 name: "",
817 status: "failed",
818 memory_id: None,
819 entities: None,
820 rels: None,
821 cost_usd: None,
822 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
823 error: Some(&err_msg),
824 index: current_index,
825 total,
826 });
827 if args.fail_fast {
828 break;
829 }
830 continue;
831 }
832 };
833
834 if file_content.len() > crate::constants::MAX_MEMORY_BODY_LEN {
836 let err_msg = format!(
837 "file body exceeds {} byte limit ({} bytes) — skipping to avoid wasting LLM tokens",
838 crate::constants::MAX_MEMORY_BODY_LEN,
839 file_content.len()
840 );
841 tracing::warn!(target: "ingest", file = %file_path, size = file_content.len(), "body exceeds limit, skipping LLM extraction");
842 let _ = queue_conn.execute(
843 "UPDATE queue SET status='skipped', error=?1, done_at=datetime('now') WHERE id=?2",
844 rusqlite::params![err_msg, queue_id],
845 );
846 let current_index = completed + failed + skipped;
847 skipped += 1;
848 emit_json(&FileEvent {
849 file: &file_path,
850 name: "",
851 status: "skipped",
852 memory_id: None,
853 entities: None,
854 rels: None,
855 cost_usd: None,
856 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
857 error: Some(&err_msg),
858 index: current_index,
859 total,
860 });
861 continue;
862 }
863
864 let max_extract_attempts: u32 = 2;
866 let mut extraction_result: Option<(ExtractionResult, f64, bool)> = None;
867 let mut last_extract_err: Option<String> = None;
868 let mut last_was_rate_limited = false;
869
870 for attempt in 1..=max_extract_attempts {
871 match extract_with_claude(
872 &claude_binary,
873 &file_content,
874 args.claude_model.as_deref(),
875 args.claude_timeout,
876 ) {
877 Ok(result) => {
878 extraction_result = Some(result);
879 break;
880 }
881 Err(ref e) if matches!(e, AppError::RateLimited { .. }) => {
882 last_extract_err = Some(format!("{e}"));
883 last_was_rate_limited = true;
884 break;
885 }
886 Err(e) => {
887 let msg = format!("{e}");
888 if attempt < max_extract_attempts {
889 let cold_start_delay = 2 * attempt as u64;
890 tracing::warn!(target: "ingest", attempt, delay_secs = cold_start_delay, error = %msg, "extraction failed, retrying (cold-start workaround)");
891 std::thread::sleep(std::time::Duration::from_secs(cold_start_delay));
892 }
893 last_extract_err = Some(msg);
894 }
895 }
896 }
897
898 if let Some((extraction, cost, is_oauth)) = extraction_result {
899 if is_oauth && !oauth_detected {
900 oauth_detected = true;
901 tracing::info!(target: "ingest", "OAuth subscription detected — cost_usd omitted from output");
902 }
903 backoff_secs = args.rate_limit_wait;
904
905 let (normalized_name, _truncated, _orig) = crate::commands::ingest::derive_kebab_name(
906 std::path::Path::new(&extraction.name),
907 args.max_name_length,
908 );
909 let name = &normalized_name;
910 let ent_count = extraction.entities.len();
911 let rel_count = 0;
912
913 let new_entities: Vec<NewEntity> = extraction
914 .entities
915 .iter()
916 .filter_map(|e| match e.entity_type.parse::<EntityType>() {
917 Ok(et) => Some(NewEntity {
918 name: e.name.clone(),
919 entity_type: et,
920 description: None,
921 }),
922 Err(_) => {
923 tracing::warn!(
924 target: "ingest",
925 entity = %e.name,
926 entity_type = %e.entity_type,
927 "entity type not recognized, skipping"
928 );
929 None
930 }
931 })
932 .collect();
933
934 let new_relationships: Vec<NewRelationship> = extraction
935 .relationships
936 .iter()
937 .map(|r| NewRelationship {
938 source: r.source.clone(),
939 target: r.target.clone(),
940 relation: crate::parsers::normalize_relation(&r.relation),
941 strength: r.strength,
942 description: None,
943 })
944 .collect();
945
946 let body_str = String::from_utf8(file_content.clone())
947 .map_err(|e| AppError::Validation(format!("file is not valid UTF-8: {e}")))?;
948 let body_hash = blake3::hash(body_str.as_bytes()).to_hex().to_string();
949 let new_memory = NewMemory {
950 name: name.clone(),
951 namespace: namespace.clone(),
952 memory_type: memory_type_str.clone(),
953 description: extraction.description.clone(),
954 body: body_str.to_string(),
955 body_hash,
956 session_id: None,
957 source: "agent".to_string(),
958 metadata: serde_json::Value::Object(serde_json::Map::new()),
959 };
960
961 let memory_id = match memories::find_by_name_any_state(&conn, &namespace, name)? {
963 Some((existing_id, is_deleted)) => {
964 if is_deleted {
965 memories::clear_deleted_at(&conn, existing_id)?;
966 }
967 let (old_name, old_desc, old_body): (String, String, String) = conn.query_row(
968 "SELECT name, COALESCE(description,''), COALESCE(body,'') FROM memories WHERE id=?1",
969 rusqlite::params![existing_id],
970 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
971 )?;
972 memories::update(&conn, existing_id, &new_memory, None)?;
973 memories::sync_fts_after_update(
974 &conn,
975 existing_id,
976 &old_name,
977 &old_desc,
978 &old_body,
979 &new_memory.name,
980 &new_memory.description,
981 &new_memory.body,
982 )?;
983 tracing::info!(target: "ingest", name, memory_id = existing_id, "updated existing memory (force-merge)");
984 existing_id
985 }
986 None => match memories::insert(&conn, &new_memory) {
987 Ok(id) => id,
988 Err(e) => {
989 let err_msg = format!("{e}");
990 let _ = queue_conn.execute(
991 "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
992 rusqlite::params![err_msg, queue_id],
993 );
994 let current_index = completed + failed + skipped;
995 failed += 1;
996 emit_json(&FileEvent {
997 file: &file_path,
998 name,
999 status: "failed",
1000 memory_id: None,
1001 entities: None,
1002 rels: None,
1003 cost_usd: if is_oauth { None } else { Some(cost) },
1004 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1005 error: Some(&err_msg),
1006 index: current_index,
1007 total,
1008 });
1009 if !is_oauth {
1010 cost_total += cost;
1011 }
1012 if args.fail_fast {
1013 break;
1014 }
1015 continue;
1016 }
1017 },
1018 };
1019
1020 for ent in &new_entities {
1021 match entities::upsert_entity(&conn, &namespace, ent) {
1022 Ok(eid) => {
1023 let _ = entities::link_memory_entity(&conn, memory_id, eid);
1024 }
1025 Err(e) => {
1026 tracing::warn!(
1027 target: "ingest",
1028 entity = %ent.name,
1029 error = %e,
1030 "entity skipped due to validation error"
1031 );
1032 }
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 body_text = String::from_utf8(file_content.clone())
1049 .map_err(|e| AppError::Validation(format!("file is not valid UTF-8: {e}")))?;
1050 let snippet: String = body_text.chars().take(200).collect();
1051 let chunks_info = crate::chunking::split_into_chunks_hierarchical(&body_text);
1052
1053 let embedding_result = if chunks_info.len() <= 1 {
1055 crate::embedder::embed_passage_with_choice(&paths.models, &body_text, None)
1056 .map(|(v, _)| v)
1057 } else {
1058 let mut chunk_embeddings: Vec<Vec<f32>> = Vec::with_capacity(chunks_info.len());
1059 let mut multi_ok = true;
1060 for chunk in &chunks_info {
1061 let chunk_text = crate::chunking::chunk_text(&body_text, chunk);
1062 match crate::embedder::embed_passage_with_choice(
1063 &paths.models,
1064 chunk_text,
1065 None,
1066 )
1067 .map(|(v, _)| v)
1068 {
1069 Ok(emb) => chunk_embeddings.push(emb),
1070 Err(e) => {
1071 tracing::warn!(
1072 target: "ingest",
1073 file = %file_path,
1074 error = %e,
1075 "chunk embedding failed, skipping vector index for this file"
1076 );
1077 multi_ok = false;
1078 break;
1079 }
1080 }
1081 }
1082 if multi_ok {
1083 let aggregated = crate::chunking::aggregate_embeddings(&chunk_embeddings);
1084 if let Err(e) = crate::storage::chunks::insert_chunk_slices(
1086 &conn,
1087 memory_id,
1088 &body_text,
1089 &chunks_info,
1090 ) {
1091 tracing::warn!(
1092 target: "ingest",
1093 file = %file_path,
1094 error = %e,
1095 "chunk slice insert failed"
1096 );
1097 } else {
1098 for (i, emb) in chunk_embeddings.iter().enumerate() {
1099 if let Err(e) = crate::storage::chunks::upsert_chunk_vec(
1100 &conn, i as i64, memory_id, i as i32, emb,
1101 ) {
1102 tracing::warn!(
1103 target: "ingest",
1104 file = %file_path,
1105 chunk = i,
1106 error = %e,
1107 "chunk vec upsert failed"
1108 );
1109 }
1110 }
1111 }
1112 Ok(aggregated)
1113 } else {
1114 crate::embedder::embed_passage_with_choice(&paths.models, &body_text, None)
1116 .map(|(v, _)| v)
1117 }
1118 };
1119
1120 match embedding_result {
1121 Ok(embedding) => {
1122 if let Err(e) = memories::upsert_vec(
1123 &conn,
1124 memory_id,
1125 &namespace,
1126 &memory_type_str,
1127 &embedding,
1128 name,
1129 &snippet,
1130 ) {
1131 tracing::warn!(
1132 target: "ingest",
1133 file = %file_path,
1134 error = %e,
1135 "memory vec upsert failed; recall may not find this memory"
1136 );
1137 }
1138 for ent in &new_entities {
1140 if let Ok(Some(eid)) =
1141 entities::find_entity_id(&conn, &namespace, &ent.name)
1142 {
1143 let entity_text = ent.name.clone();
1144 match crate::embedder::embed_passage_with_choice(
1145 &paths.models,
1146 &entity_text,
1147 None,
1148 )
1149 .map(|(v, _)| v)
1150 {
1151 Ok(emb) => {
1152 if let Err(e) = entities::upsert_entity_vec(
1153 &conn,
1154 eid,
1155 &namespace,
1156 ent.entity_type,
1157 &emb,
1158 &ent.name,
1159 ) {
1160 tracing::warn!(
1161 target: "ingest",
1162 entity = %ent.name,
1163 error = %e,
1164 "entity vec upsert failed"
1165 );
1166 }
1167 }
1168 Err(e) => {
1169 tracing::warn!(
1170 target: "ingest",
1171 entity = %ent.name,
1172 error = %e,
1173 "entity embedding failed"
1174 );
1175 }
1176 }
1177 }
1178 }
1179 }
1180 Err(e) => {
1181 tracing::warn!(
1182 target: "ingest",
1183 file = %file_path,
1184 error = %e,
1185 "memory embedding failed; recall will not find this memory"
1186 );
1187 }
1188 }
1189
1190 let _ = queue_conn.execute(
1191 "UPDATE queue SET status='done', name=?1, memory_id=?2, entities=?3, rels=?4, cost_usd=?5, elapsed_ms=?6, done_at=datetime('now') WHERE id=?7",
1192 rusqlite::params![
1193 name,
1194 memory_id,
1195 ent_count,
1196 rel_count,
1197 cost,
1198 file_started.elapsed().as_millis() as i64,
1199 queue_id
1200 ],
1201 );
1202
1203 let current_index = completed + failed + skipped;
1204 completed += 1;
1205 entities_total += ent_count;
1206 rels_total += rel_count;
1207 if !is_oauth {
1208 cost_total += cost;
1209 }
1210
1211 emit_json(&FileEvent {
1212 file: &file_path,
1213 name,
1214 status: "done",
1215 memory_id: Some(memory_id),
1216 entities: Some(ent_count),
1217 rels: Some(rel_count),
1218 cost_usd: if is_oauth { None } else { Some(cost) },
1219 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1220 error: None,
1221 index: current_index,
1222 total,
1223 });
1224 } else if let Some(ref err_str) = last_extract_err {
1225 if last_was_rate_limited {
1226 if crate::retry::is_kill_switch_active() {
1227 tracing::warn!(target: "ingest", "SQLITE_GRAPHRAG_DISABLE_RETRY=1, skipping rate-limit retry");
1228 } else if std::time::Instant::now() >= rate_limit_deadline {
1229 tracing::error!(target: "ingest", "rate-limit retry deadline (1h) exhausted");
1230 } else {
1231 let half = backoff_secs / 2;
1232 let jitter = if half == 0 { 0 } else { fastrand::u64(0..half) };
1233 let actual_wait = half + jitter;
1234 tracing::warn!(target: "ingest", delay_secs = actual_wait, error_kind = "rate_limited", "rate limited, backing off");
1235 let _ = queue_conn.execute(
1236 "UPDATE queue SET status='pending' WHERE id=?1",
1237 rusqlite::params![queue_id],
1238 );
1239 std::thread::sleep(std::time::Duration::from_secs(actual_wait));
1240 backoff_secs = (backoff_secs * 2).min(900);
1241 continue;
1242 }
1243 } else {
1244 let _ = queue_conn.execute(
1245 "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
1246 rusqlite::params![err_str, queue_id],
1247 );
1248 let current_index = completed + failed + skipped;
1249 failed += 1;
1250 emit_json(&FileEvent {
1251 file: &file_path,
1252 name: "",
1253 status: "failed",
1254 memory_id: None,
1255 entities: None,
1256 rels: None,
1257 cost_usd: None,
1258 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1259 error: Some(err_str),
1260 index: current_index,
1261 total,
1262 });
1263 if args.fail_fast {
1264 break;
1265 }
1266 }
1267 }
1268
1269 if let Some(budget) = args.max_cost_usd {
1270 if oauth_detected {
1271 tracing::debug!(target: "ingest", "--max-cost-usd ignored: OAuth subscription detected");
1272 } else if cost_total >= budget {
1273 tracing::warn!(
1274 target: "ingest",
1275 spent = cost_total,
1276 budget = budget,
1277 "budget exceeded, stopping"
1278 );
1279 break;
1280 }
1281 }
1282 }
1283
1284 let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1286 let _ = queue_conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1287
1288 emit_json(&Summary {
1289 summary: true,
1290 files_total: total,
1291 completed,
1292 failed,
1293 skipped,
1294 entities_total,
1295 rels_total,
1296 cost_usd: cost_total,
1297 elapsed_ms: started.elapsed().as_millis() as u64,
1298 });
1299
1300 if !args.keep_queue && failed == 0 {
1301 let _ = std::fs::remove_file(&args.queue_db);
1302 }
1303
1304 Ok(())
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309 use super::*;
1310
1311 #[test]
1312 fn test_extraction_schema_valid_json() {
1313 let _: serde_json::Value =
1314 serde_json::from_str(EXTRACTION_SCHEMA).expect("schema must be valid JSON");
1315 }
1316
1317 #[test]
1318 fn test_parse_claude_output_valid() {
1319 let output = r#"[
1320 {"type":"system","subtype":"init"},
1321 {"type":"assistant"},
1322 {"type":"result","is_error":false,"total_cost_usd":0.02,"structured_output":{"name":"test-doc","description":"A test document","entities":[{"name":"test-entity","entity_type":"concept"}],"relationships":[{"source":"test-entity","target":"test-doc","relation":"applies-to","strength":0.8}]}}
1323 ]"#;
1324 let (result, cost, _is_oauth) = parse_claude_output(output).expect("parse must succeed");
1325 assert_eq!(result.name, "test-doc");
1326 assert_eq!(result.entities.len(), 1);
1327 assert_eq!(result.relationships.len(), 1);
1328 assert!((cost - 0.02).abs() < f64::EPSILON);
1329 }
1330
1331 #[test]
1332 fn test_parse_claude_output_error() {
1333 let output = r#"[
1334 {"type":"system","subtype":"init"},
1335 {"type":"result","is_error":true,"error":"authentication failed"}
1336 ]"#;
1337 let err = parse_claude_output(output).unwrap_err();
1338 assert!(format!("{err}").contains("authentication failed"));
1339 }
1340
1341 #[test]
1342 fn test_parse_claude_output_rate_limit() {
1343 let output = r#"[
1344 {"type":"system","subtype":"init"},
1345 {"type":"result","is_error":true,"error":"rate_limit exceeded"}
1346 ]"#;
1347 let err = parse_claude_output(output).unwrap_err();
1348 assert!(matches!(err, AppError::RateLimited { .. }));
1349 }
1350
1351 #[test]
1352 fn test_parse_claude_output_malformed() {
1353 let output = "not json at all";
1354 assert!(parse_claude_output(output).is_err());
1355 }
1356
1357 #[test]
1358 fn test_find_claude_binary_not_found() {
1359 let original_path = std::env::var_os("PATH");
1360 std::env::set_var("PATH", "/nonexistent");
1361 std::env::remove_var("SQLITE_GRAPHRAG_CLAUDE_BINARY");
1362 let result = find_claude_binary(None);
1363 if let Some(p) = original_path {
1364 std::env::set_var("PATH", p);
1365 }
1366 assert!(result.is_err());
1367 }
1368
1369 #[test]
1370 fn test_parse_claude_output_result_fallback() {
1371 let output = r#"[
1372 {"type":"system","subtype":"init"},
1373 {"type":"result","is_error":false,"total_cost_usd":0.01,"structured_output":null,"result":"{\"name\":\"test-fallback\",\"description\":\"A fallback test\",\"entities\":[{\"name\":\"fb-entity\",\"entity_type\":\"concept\"}],\"relationships\":[]}"}
1374 ]"#;
1375 let (result, cost, _is_oauth) =
1376 parse_claude_output(output).expect("result fallback must work");
1377 assert_eq!(result.name, "test-fallback");
1378 assert_eq!(result.entities.len(), 1);
1379 assert!(result.relationships.is_empty());
1380 assert!((cost - 0.01).abs() < f64::EPSILON);
1381 }
1382
1383 #[test]
1384 fn test_parse_claude_output_error_with_result_field() {
1385 let output = r#"[
1386 {"type":"system","subtype":"init"},
1387 {"type":"result","is_error":true,"result":"Not logged in · Please run /login"}
1388 ]"#;
1389 let err = parse_claude_output(output).unwrap_err();
1390 let msg = format!("{err}");
1391 assert!(
1392 msg.contains("Not logged in"),
1393 "expected 'Not logged in' in: {msg}"
1394 );
1395 }
1396
1397 #[test]
1398 fn test_terminal_reason_max_turns_detected() {
1399 let output = r#"[
1400 {"type":"system","subtype":"init"},
1401 {"type":"result","is_error":false,"terminal_reason":"max_turns","structured_output":{"name":"t","description":"d","entities":[],"relationships":[]}}
1402 ]"#;
1403 let err_or_ok = parse_claude_output(output);
1404 assert!(
1405 err_or_ok.is_ok(),
1406 "max_turns in result without is_error should still parse"
1407 );
1408 }
1409
1410 #[test]
1411 fn test_detect_oauth_from_init_json() {
1412 let output = r#"[
1413 {"type":"system","subtype":"init","apiKeySource":"none"},
1414 {"type":"result","is_error":false,"total_cost_usd":0.50,"structured_output":{"name":"test-oauth","description":"oauth test","entities":[],"relationships":[]}}
1415 ]"#;
1416 let (_result, cost, is_oauth) = parse_claude_output(output).expect("parse must succeed");
1417 assert!(is_oauth, "apiKeySource=none must be detected as OAuth");
1418 assert!((cost - 0.50).abs() < f64::EPSILON);
1419 }
1420
1421 #[test]
1422 fn test_api_key_source_not_oauth() {
1423 let output = r#"[
1424 {"type":"system","subtype":"init","apiKeySource":"env"},
1425 {"type":"result","is_error":false,"total_cost_usd":0.10,"structured_output":{"name":"test-api","description":"api test","entities":[],"relationships":[]}}
1426 ]"#;
1427 let (_result, _cost, is_oauth) = parse_claude_output(output).expect("parse must succeed");
1428 assert!(!is_oauth, "apiKeySource=env must NOT be detected as OAuth");
1429 }
1430
1431 #[test]
1432 fn test_missing_api_key_source_defaults_not_oauth() {
1433 let output = r#"[
1434 {"type":"system","subtype":"init"},
1435 {"type":"result","is_error":false,"total_cost_usd":0.05,"structured_output":{"name":"test-missing","description":"missing test","entities":[],"relationships":[]}}
1436 ]"#;
1437 let (_result, _cost, is_oauth) = parse_claude_output(output).expect("parse must succeed");
1438 assert!(!is_oauth, "missing apiKeySource must default to not OAuth");
1439 }
1440
1441 #[test]
1442 fn test_extraction_schema_entity_types_match_enum() {
1443 let schema: serde_json::Value = serde_json::from_str(EXTRACTION_SCHEMA).unwrap();
1444 let types = schema["properties"]["entities"]["items"]["properties"]["entity_type"]["enum"]
1445 .as_array()
1446 .expect("schema must have entity_type enum");
1447 for t in types {
1448 let s = t.as_str().unwrap();
1449 assert!(
1450 s.parse::<EntityType>().is_ok(),
1451 "schema entity_type '{s}' not in EntityType enum"
1452 );
1453 }
1454 }
1455}