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 cmd.arg("-p")
306 .arg(EXTRACTION_PROMPT)
307 .arg("--strict-mcp-config")
308 .arg("--mcp-config")
309 .arg("{}")
310 .arg("--dangerously-skip-permissions")
311 .arg("--settings")
312 .arg(r#"{"hooks":{}}"#)
313 .arg("--output-format")
314 .arg("json")
315 .arg("--json-schema")
316 .arg(EXTRACTION_SCHEMA)
317 .arg("--max-turns")
318 .arg("7")
319 .arg("--no-session-persistence");
320
321 if let Some(m) = model {
322 cmd.arg("--model").arg(m);
323 }
324
325 cmd.stdin(Stdio::piped())
326 .stdout(Stdio::piped())
327 .stderr(Stdio::piped());
328
329 let mut child = super::claude_runner::spawn_with_memory_limit(&mut cmd).map_err(|e| {
330 AppError::Io(std::io::Error::new(
331 e.kind(),
332 format!("failed to spawn claude: {e}"),
333 ))
334 })?;
335
336 let stdin_data = file_content.to_vec();
337 let mut child_stdin = child
338 .stdin
339 .take()
340 .ok_or_else(|| AppError::Validation("failed to open claude stdin".into()))?;
341 let stdin_thread = std::thread::spawn(move || -> Result<(), std::io::Error> {
342 child_stdin.write_all(&stdin_data)?;
343 drop(child_stdin);
344 Ok(())
345 });
346
347 let start = std::time::Instant::now();
348 let timeout = std::time::Duration::from_secs(timeout_secs);
349 let status = child.wait_timeout(timeout).map_err(AppError::Io)?;
350
351 match status {
352 Some(exit_status) => {
353 stdin_thread
354 .join()
355 .map_err(|_| AppError::Validation("stdin thread panicked".into()))?
356 .map_err(AppError::Io)?;
357
358 tracing::debug!(
359 target: "process",
360 exit_code = ?exit_status.code(),
361 elapsed_ms = start.elapsed().as_millis() as u64,
362 "external process completed"
363 );
364
365 let mut stdout_buf = Vec::new();
366 let mut stderr_buf = Vec::new();
367 if let Some(mut out) = child.stdout.take() {
368 std::io::Read::read_to_end(&mut out, &mut stdout_buf).map_err(AppError::Io)?;
369 }
370 if let Some(mut err) = child.stderr.take() {
371 std::io::Read::read_to_end(&mut err, &mut stderr_buf).map_err(AppError::Io)?;
372 }
373
374 if !exit_status.success() {
375 let stdout_str = String::from_utf8_lossy(&stdout_buf);
376 if let Ok(elements) = serde_json::from_str::<Vec<ClaudeOutputElement>>(&stdout_str)
377 {
378 if let Some(re) = elements
379 .iter()
380 .find(|e| e.r#type.as_deref() == Some("result"))
381 {
382 if re.terminal_reason.as_deref() == Some("max_turns") {
383 tracing::warn!(
384 target: "ingest",
385 "extraction hit max_turns limit — hooks may have consumed turns"
386 );
387 return Err(AppError::Validation(
388 "claude -p hit max_turns: hooks may be consuming turns".into(),
389 ));
390 }
391 if re.is_error {
392 let err_msg = re
393 .error
394 .as_deref()
395 .or(re.result.as_deref())
396 .unwrap_or("unknown error");
397 if err_msg.contains("rate_limit") || err_msg.contains("overloaded") {
398 return Err(AppError::RateLimited {
399 detail: err_msg.to_string(),
400 });
401 }
402 if err_msg.contains("Not logged in")
403 || err_msg.contains("authentication")
404 {
405 tracing::warn!(
406 target: "ingest",
407 "Claude Code authentication failed. Re-authenticate interactively with: claude"
408 );
409 }
410 return Err(AppError::Validation(format!(
411 "claude -p failed: {err_msg}"
412 )));
413 }
414 }
415 }
416 let stderr_str = String::from_utf8_lossy(&stderr_buf);
417 if stderr_str.contains("auth") || stderr_str.contains("login") {
418 tracing::warn!(
419 target: "ingest",
420 "Claude Code authentication may have failed. Re-authenticate with: claude"
421 );
422 }
423 return Err(AppError::Validation(format!(
424 "claude -p exited with code {:?}: {}",
425 exit_status.code(),
426 stderr_str.trim()
427 )));
428 }
429
430 let stdout = String::from_utf8(stdout_buf)
431 .map_err(|_| AppError::Validation("claude -p stdout is not valid UTF-8".into()))?;
432 parse_claude_output(&stdout)
433 }
434 None => {
435 tracing::warn!(target: "ingest", timeout_secs, "claude -p timed out, killing process");
436 let _ = child.kill();
437 let _ = child.wait();
438 let _ = stdin_thread.join();
439 Err(AppError::Validation(format!(
440 "claude -p timed out after {timeout_secs} seconds"
441 )))
442 }
443 }
444}
445
446fn parse_claude_output(stdout: &str) -> Result<(ExtractionResult, f64, bool), AppError> {
451 let elements: Vec<ClaudeOutputElement> = serde_json::from_str(stdout).map_err(|e| {
452 AppError::Validation(format!("failed to parse claude output as JSON array: {e}"))
453 })?;
454
455 let is_oauth = elements
456 .iter()
457 .find(|e| e.r#type.as_deref() == Some("system") && e.subtype.as_deref() == Some("init"))
458 .and_then(|e| e.api_key_source.as_deref())
459 .map(|s| s == "none")
460 .unwrap_or(false);
461
462 let result_elem = elements
463 .iter()
464 .find(|e| e.r#type.as_deref() == Some("result"))
465 .ok_or_else(|| {
466 AppError::Validation("claude output missing 'result' element".to_string())
467 })?;
468
469 if result_elem.is_error {
470 let err_msg = result_elem
471 .error
472 .as_deref()
473 .or(result_elem.result.as_deref())
474 .unwrap_or("unknown error");
475 if err_msg.contains("rate_limit") || err_msg.contains("overloaded") {
476 return Err(AppError::RateLimited {
477 detail: err_msg.to_string(),
478 });
479 }
480 return Err(AppError::Validation(format!(
481 "claude extraction failed: {err_msg}"
482 )));
483 }
484
485 let extraction = result_elem
486 .structured_output
487 .clone()
488 .or_else(|| {
489 result_elem
490 .result
491 .as_ref()
492 .and_then(|text| serde_json::from_str::<ExtractionResult>(text).ok())
493 })
494 .ok_or_else(|| {
495 AppError::Validation("claude result missing structured_output and result field".into())
496 })?;
497
498 let cost = result_elem.total_cost_usd.unwrap_or(0.0);
499
500 Ok((extraction, cost, is_oauth))
501}
502
503use crate::output::emit_json_line as emit_json;
504
505fn collect_matching_files(
507 dir: &Path,
508 pattern: &str,
509 recursive: bool,
510 max_files: usize,
511) -> Result<Vec<PathBuf>, AppError> {
512 let mut files = Vec::new();
513 super::ingest::collect_files(dir, pattern, recursive, &mut files)?;
514 files.sort_unstable();
515
516 if files.len() > max_files {
517 return Err(AppError::Validation(format!(
518 "found {} files, exceeds --max-files cap of {}",
519 files.len(),
520 max_files
521 )));
522 }
523
524 Ok(files)
525}
526
527fn open_queue_db(path: &str) -> Result<Connection, AppError> {
529 let conn = Connection::open(path)?;
530
531 conn.pragma_update(None, "journal_mode", "wal")?;
532
533 conn.execute_batch(
534 "CREATE TABLE IF NOT EXISTS queue (
535 id INTEGER PRIMARY KEY AUTOINCREMENT,
536 file_path TEXT NOT NULL UNIQUE,
537 name TEXT,
538 status TEXT NOT NULL DEFAULT 'pending',
539 memory_id INTEGER,
540 entities INTEGER DEFAULT 0,
541 rels INTEGER DEFAULT 0,
542 error TEXT,
543 cost_usd REAL DEFAULT 0.0,
544 attempt INTEGER DEFAULT 0,
545 elapsed_ms INTEGER,
546 created_at TEXT DEFAULT (datetime('now')),
547 done_at TEXT
548 );
549 CREATE INDEX IF NOT EXISTS idx_queue_status ON queue(status);",
550 )?;
551
552 Ok(conn)
553}
554
555pub fn run_claude_ingest(args: &IngestArgs) -> Result<(), AppError> {
557 let started = Instant::now();
558
559 if !args.dir.exists() {
560 return Err(AppError::Validation(format!(
561 "directory not found: {}",
562 args.dir.display()
563 )));
564 }
565
566 let early_ns = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
571 let early_paths = AppPaths::resolve(args.db.as_deref())?;
572 let _singleton = crate::lock::acquire_job_singleton(
573 crate::lock::JobType::IngestClaudeCode,
574 &early_ns,
575 &early_paths.db,
576 args.wait_job_singleton,
577 args.force_job_singleton,
578 )?;
579
580 let claude_binary = find_claude_binary(args.claude_binary.as_deref())?;
582 let version = validate_claude_version(&claude_binary)?;
583 tracing::info!(
584 target: "ingest",
585 binary = %claude_binary.display(),
586 version = %version,
587 "Claude Code binary validated"
588 );
589
590 emit_json(&PhaseEvent {
591 phase: "validate",
592 claude_path: claude_binary.to_str(),
593 version: Some(&version),
594 dir: None,
595 files_total: None,
596 files_new: None,
597 files_existing: None,
598 });
599
600 let files = collect_matching_files(&args.dir, &args.pattern, args.recursive, args.max_files)?;
602
603 let queue_conn = open_queue_db(&args.queue_db)?;
604
605 if args.resume {
606 let reset = queue_conn
607 .execute(
608 "UPDATE queue SET status='pending' WHERE status='processing'",
609 [],
610 )
611 .map_err(|e| AppError::Validation(format!("queue resume failed: {e}")))?;
612 if reset > 0 {
613 tracing::info!(target: "ingest", count = reset, "reset stuck processing files to pending");
614 }
615 }
616
617 if args.retry_failed {
618 let count = queue_conn
619 .execute(
620 "UPDATE queue SET status='pending', attempt=0 WHERE status='failed'",
621 [],
622 )
623 .map_err(|e| AppError::Validation(format!("queue retry-failed reset failed: {e}")))?;
624 tracing::info!(target: "ingest", count, "retrying failed files");
625 }
626
627 if !args.resume && !args.retry_failed {
628 queue_conn
629 .execute("DELETE FROM queue", [])
630 .map_err(|e| AppError::Validation(format!("queue clear failed: {e}")))?;
631 }
632
633 let mut new_count = 0usize;
634 let mut existing_count = 0usize;
635
636 if !args.retry_failed {
637 for file in &files {
638 let file_str = file.to_string_lossy().into_owned();
639 let inserted = queue_conn
640 .execute(
641 "INSERT OR IGNORE INTO queue (file_path, status) VALUES (?1, 'pending')",
642 rusqlite::params![file_str],
643 )
644 .map_err(|e| AppError::Validation(format!("queue insert failed: {e}")))?;
645 if inserted > 0 {
646 new_count += 1;
647 } else {
648 existing_count += 1;
649 }
650 }
651 }
652
653 emit_json(&PhaseEvent {
654 phase: "scan",
655 claude_path: None,
656 version: None,
657 dir: args.dir.to_str(),
658 files_total: Some(files.len()),
659 files_new: Some(new_count),
660 files_existing: Some(existing_count),
661 });
662
663 if args.dry_run {
664 for (idx, file) in files.iter().enumerate() {
665 let (name, _truncated, _orig) =
666 super::ingest::derive_kebab_name(file, args.max_name_length);
667 emit_json(&FileEvent {
668 file: &file.to_string_lossy(),
669 name: &name,
670 status: "preview",
671 memory_id: None,
672 entities: None,
673 rels: None,
674 cost_usd: None,
675 elapsed_ms: None,
676 error: None,
677 index: idx,
678 total: files.len(),
679 });
680 }
681 emit_json(&Summary {
682 summary: true,
683 files_total: files.len(),
684 completed: 0,
685 failed: 0,
686 skipped: 0,
687 entities_total: 0,
688 rels_total: 0,
689 cost_usd: 0.0,
690 elapsed_ms: started.elapsed().as_millis() as u64,
691 });
692 if !args.keep_queue {
693 let _ = std::fs::remove_file(&args.queue_db);
694 }
695 return Ok(());
696 }
697
698 let paths = AppPaths::resolve(args.db.as_deref())?;
700 ensure_db_ready(&paths)?;
701 let conn = open_rw(&paths.db)?;
702
703 let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
704 let memory_type_str = args.r#type.as_str().to_string();
705
706 let mut completed = 0usize;
707 let mut failed = 0usize;
708 let skipped_initial: usize = queue_conn
709 .query_row("SELECT COUNT(*) FROM queue WHERE status='done'", [], |r| {
710 r.get::<_, usize>(0)
711 })
712 .unwrap_or(0);
713 let mut skipped = skipped_initial;
714 let mut entities_total = 0usize;
715 let mut rels_total = 0usize;
716 let mut cost_total = 0.0f64;
717 let mut oauth_detected = false;
718 let total = files.len();
719
720 let mut backoff_secs = args.rate_limit_wait;
721 let rate_limit_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3600);
722
723 loop {
724 if crate::shutdown_requested() {
725 tracing::info!(target: "ingest", "shutdown requested, stopping before next file");
726 break;
727 }
728
729 let pending: Option<(i64, String)> = queue_conn
730 .query_row(
731 "UPDATE queue SET status='processing', attempt=attempt+1 \
732 WHERE id = (SELECT id FROM queue WHERE status='pending' ORDER BY id LIMIT 1) \
733 RETURNING id, file_path",
734 [],
735 |row| Ok((row.get(0)?, row.get(1)?)),
736 )
737 .ok();
738
739 let (queue_id, file_path) = match pending {
740 Some(p) => p,
741 None => break,
742 };
743
744 let file_started = Instant::now();
745
746 const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
748 if let Ok(meta) = std::fs::metadata(&file_path) {
749 if meta.len() > MAX_FILE_SIZE {
750 let err_msg = format!("file exceeds 10MB stdin limit ({} bytes)", meta.len());
751 let _ = queue_conn.execute(
752 "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
753 rusqlite::params![err_msg, queue_id],
754 );
755 let current_index = completed + failed + skipped;
756 failed += 1;
757 emit_json(&FileEvent {
758 file: &file_path,
759 name: "",
760 status: "failed",
761 memory_id: None,
762 entities: None,
763 rels: None,
764 cost_usd: None,
765 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
766 error: Some(&err_msg),
767 index: current_index,
768 total,
769 });
770 if args.fail_fast {
771 break;
772 }
773 continue;
774 }
775 }
776
777 let file_content = match std::fs::read(&file_path) {
778 Ok(c) => c,
779 Err(e) => {
780 let err_msg = format!("IO error: {e}");
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 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
796 error: Some(&err_msg),
797 index: current_index,
798 total,
799 });
800 if args.fail_fast {
801 break;
802 }
803 continue;
804 }
805 };
806
807 if file_content.len() > crate::constants::MAX_MEMORY_BODY_LEN {
809 let err_msg = format!(
810 "file body exceeds {} byte limit ({} bytes) — skipping to avoid wasting LLM tokens",
811 crate::constants::MAX_MEMORY_BODY_LEN,
812 file_content.len()
813 );
814 tracing::warn!(target: "ingest", file = %file_path, size = file_content.len(), "body exceeds limit, skipping LLM extraction");
815 let _ = queue_conn.execute(
816 "UPDATE queue SET status='skipped', error=?1, done_at=datetime('now') WHERE id=?2",
817 rusqlite::params![err_msg, queue_id],
818 );
819 let current_index = completed + failed + skipped;
820 skipped += 1;
821 emit_json(&FileEvent {
822 file: &file_path,
823 name: "",
824 status: "skipped",
825 memory_id: None,
826 entities: None,
827 rels: None,
828 cost_usd: 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 continue;
835 }
836
837 let max_extract_attempts: u32 = 2;
839 let mut extraction_result: Option<(ExtractionResult, f64, bool)> = None;
840 let mut last_extract_err: Option<String> = None;
841 let mut last_was_rate_limited = false;
842
843 for attempt in 1..=max_extract_attempts {
844 match extract_with_claude(
845 &claude_binary,
846 &file_content,
847 args.claude_model.as_deref(),
848 args.claude_timeout,
849 ) {
850 Ok(result) => {
851 extraction_result = Some(result);
852 break;
853 }
854 Err(ref e) if matches!(e, AppError::RateLimited { .. }) => {
855 last_extract_err = Some(format!("{e}"));
856 last_was_rate_limited = true;
857 break;
858 }
859 Err(e) => {
860 let msg = format!("{e}");
861 if attempt < max_extract_attempts {
862 let cold_start_delay = 2 * attempt as u64;
863 tracing::warn!(target: "ingest", attempt, delay_secs = cold_start_delay, error = %msg, "extraction failed, retrying (cold-start workaround)");
864 std::thread::sleep(std::time::Duration::from_secs(cold_start_delay));
865 }
866 last_extract_err = Some(msg);
867 }
868 }
869 }
870
871 if let Some((extraction, cost, is_oauth)) = extraction_result {
872 if is_oauth && !oauth_detected {
873 oauth_detected = true;
874 tracing::info!(target: "ingest", "OAuth subscription detected — cost_usd omitted from output");
875 }
876 backoff_secs = args.rate_limit_wait;
877
878 let (normalized_name, _truncated, _orig) = crate::commands::ingest::derive_kebab_name(
879 std::path::Path::new(&extraction.name),
880 args.max_name_length,
881 );
882 let name = &normalized_name;
883 let ent_count = extraction.entities.len();
884 let rel_count = 0;
885
886 let new_entities: Vec<NewEntity> = extraction
887 .entities
888 .iter()
889 .filter_map(|e| match e.entity_type.parse::<EntityType>() {
890 Ok(et) => Some(NewEntity {
891 name: e.name.clone(),
892 entity_type: et,
893 description: None,
894 }),
895 Err(_) => {
896 tracing::warn!(
897 target: "ingest",
898 entity = %e.name,
899 entity_type = %e.entity_type,
900 "entity type not recognized, skipping"
901 );
902 None
903 }
904 })
905 .collect();
906
907 let new_relationships: Vec<NewRelationship> = extraction
908 .relationships
909 .iter()
910 .map(|r| NewRelationship {
911 source: r.source.clone(),
912 target: r.target.clone(),
913 relation: crate::parsers::normalize_relation(&r.relation),
914 strength: r.strength,
915 description: None,
916 })
917 .collect();
918
919 let body_str = String::from_utf8(file_content.clone())
920 .map_err(|e| AppError::Validation(format!("file is not valid UTF-8: {e}")))?;
921 let body_hash = blake3::hash(body_str.as_bytes()).to_hex().to_string();
922 let new_memory = NewMemory {
923 name: name.clone(),
924 namespace: namespace.clone(),
925 memory_type: memory_type_str.clone(),
926 description: extraction.description.clone(),
927 body: body_str.to_string(),
928 body_hash,
929 session_id: None,
930 source: "agent".to_string(),
931 metadata: serde_json::Value::Object(serde_json::Map::new()),
932 };
933
934 let memory_id = match memories::find_by_name_any_state(&conn, &namespace, name)? {
936 Some((existing_id, is_deleted)) => {
937 if is_deleted {
938 memories::clear_deleted_at(&conn, existing_id)?;
939 }
940 let (old_name, old_desc, old_body): (String, String, String) = conn.query_row(
941 "SELECT name, COALESCE(description,''), COALESCE(body,'') FROM memories WHERE id=?1",
942 rusqlite::params![existing_id],
943 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
944 )?;
945 memories::update(&conn, existing_id, &new_memory, None)?;
946 memories::sync_fts_after_update(
947 &conn,
948 existing_id,
949 &old_name,
950 &old_desc,
951 &old_body,
952 &new_memory.name,
953 &new_memory.description,
954 &new_memory.body,
955 )?;
956 tracing::info!(target: "ingest", name, memory_id = existing_id, "updated existing memory (force-merge)");
957 existing_id
958 }
959 None => match memories::insert(&conn, &new_memory) {
960 Ok(id) => id,
961 Err(e) => {
962 let err_msg = format!("{e}");
963 let _ = queue_conn.execute(
964 "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
965 rusqlite::params![err_msg, queue_id],
966 );
967 let current_index = completed + failed + skipped;
968 failed += 1;
969 emit_json(&FileEvent {
970 file: &file_path,
971 name,
972 status: "failed",
973 memory_id: None,
974 entities: None,
975 rels: None,
976 cost_usd: if is_oauth { None } else { Some(cost) },
977 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
978 error: Some(&err_msg),
979 index: current_index,
980 total,
981 });
982 if !is_oauth {
983 cost_total += cost;
984 }
985 if args.fail_fast {
986 break;
987 }
988 continue;
989 }
990 },
991 };
992
993 for ent in &new_entities {
994 match entities::upsert_entity(&conn, &namespace, ent) {
995 Ok(eid) => {
996 let _ = entities::link_memory_entity(&conn, memory_id, eid);
997 }
998 Err(e) => {
999 tracing::warn!(
1000 target: "ingest",
1001 entity = %ent.name,
1002 error = %e,
1003 "entity skipped due to validation error"
1004 );
1005 }
1006 }
1007 }
1008 for rel in &new_relationships {
1009 crate::parsers::warn_if_non_canonical(&rel.relation);
1010 let src_id = entities::find_entity_id(&conn, &namespace, &rel.source);
1011 let tgt_id = entities::find_entity_id(&conn, &namespace, &rel.target);
1012 if let (Ok(Some(sid)), Ok(Some(tid))) = (src_id, tgt_id) {
1013 let _ = conn.execute(
1014 "INSERT OR IGNORE INTO relationships (namespace, source_id, target_id, relation, weight) VALUES (?1, ?2, ?3, ?4, ?5)",
1015 rusqlite::params![namespace, sid, tid, rel.relation, rel.strength],
1016 );
1017 }
1018 }
1019
1020 let body_text = String::from_utf8(file_content.clone())
1022 .map_err(|e| AppError::Validation(format!("file is not valid UTF-8: {e}")))?;
1023 let snippet: String = body_text.chars().take(200).collect();
1024 let chunks_info = crate::chunking::split_into_chunks_hierarchical(&body_text);
1025
1026 let embedding_result = if chunks_info.len() <= 1 {
1027 crate::embedder::embed_passage_local(&paths.models, &body_text)
1028 } else {
1029 let mut chunk_embeddings: Vec<Vec<f32>> = Vec::with_capacity(chunks_info.len());
1030 let mut multi_ok = true;
1031 for chunk in &chunks_info {
1032 let chunk_text = crate::chunking::chunk_text(&body_text, chunk);
1033 match crate::embedder::embed_passage_local(&paths.models, chunk_text) {
1034 Ok(emb) => chunk_embeddings.push(emb),
1035 Err(e) => {
1036 tracing::warn!(
1037 target: "ingest",
1038 file = %file_path,
1039 error = %e,
1040 "chunk embedding failed, skipping vector index for this file"
1041 );
1042 multi_ok = false;
1043 break;
1044 }
1045 }
1046 }
1047 if multi_ok {
1048 let aggregated = crate::chunking::aggregate_embeddings(&chunk_embeddings);
1049 if let Err(e) = crate::storage::chunks::insert_chunk_slices(
1051 &conn,
1052 memory_id,
1053 &body_text,
1054 &chunks_info,
1055 ) {
1056 tracing::warn!(
1057 target: "ingest",
1058 file = %file_path,
1059 error = %e,
1060 "chunk slice insert failed"
1061 );
1062 } else {
1063 for (i, emb) in chunk_embeddings.iter().enumerate() {
1064 if let Err(e) = crate::storage::chunks::upsert_chunk_vec(
1065 &conn, i as i64, memory_id, i as i32, emb,
1066 ) {
1067 tracing::warn!(
1068 target: "ingest",
1069 file = %file_path,
1070 chunk = i,
1071 error = %e,
1072 "chunk vec upsert failed"
1073 );
1074 }
1075 }
1076 }
1077 Ok(aggregated)
1078 } else {
1079 crate::embedder::embed_passage_local(&paths.models, &body_text)
1081 }
1082 };
1083
1084 match embedding_result {
1085 Ok(embedding) => {
1086 if let Err(e) = memories::upsert_vec(
1087 &conn,
1088 memory_id,
1089 &namespace,
1090 &memory_type_str,
1091 &embedding,
1092 name,
1093 &snippet,
1094 ) {
1095 tracing::warn!(
1096 target: "ingest",
1097 file = %file_path,
1098 error = %e,
1099 "memory vec upsert failed; recall may not find this memory"
1100 );
1101 }
1102 for ent in &new_entities {
1104 if let Ok(Some(eid)) =
1105 entities::find_entity_id(&conn, &namespace, &ent.name)
1106 {
1107 let entity_text = ent.name.clone();
1108 match crate::embedder::embed_passage_local(&paths.models, &entity_text)
1109 {
1110 Ok(emb) => {
1111 if let Err(e) = entities::upsert_entity_vec(
1112 &conn,
1113 eid,
1114 &namespace,
1115 ent.entity_type,
1116 &emb,
1117 &ent.name,
1118 ) {
1119 tracing::warn!(
1120 target: "ingest",
1121 entity = %ent.name,
1122 error = %e,
1123 "entity vec upsert failed"
1124 );
1125 }
1126 }
1127 Err(e) => {
1128 tracing::warn!(
1129 target: "ingest",
1130 entity = %ent.name,
1131 error = %e,
1132 "entity embedding failed"
1133 );
1134 }
1135 }
1136 }
1137 }
1138 }
1139 Err(e) => {
1140 tracing::warn!(
1141 target: "ingest",
1142 file = %file_path,
1143 error = %e,
1144 "memory embedding failed; recall will not find this memory"
1145 );
1146 }
1147 }
1148
1149 let _ = queue_conn.execute(
1150 "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",
1151 rusqlite::params![
1152 name,
1153 memory_id,
1154 ent_count,
1155 rel_count,
1156 cost,
1157 file_started.elapsed().as_millis() as i64,
1158 queue_id
1159 ],
1160 );
1161
1162 let current_index = completed + failed + skipped;
1163 completed += 1;
1164 entities_total += ent_count;
1165 rels_total += rel_count;
1166 if !is_oauth {
1167 cost_total += cost;
1168 }
1169
1170 emit_json(&FileEvent {
1171 file: &file_path,
1172 name,
1173 status: "done",
1174 memory_id: Some(memory_id),
1175 entities: Some(ent_count),
1176 rels: Some(rel_count),
1177 cost_usd: if is_oauth { None } else { Some(cost) },
1178 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1179 error: None,
1180 index: current_index,
1181 total,
1182 });
1183 } else if let Some(ref err_str) = last_extract_err {
1184 if last_was_rate_limited {
1185 if crate::retry::is_kill_switch_active() {
1186 tracing::warn!(target: "ingest", "SQLITE_GRAPHRAG_DISABLE_RETRY=1, skipping rate-limit retry");
1187 } else if std::time::Instant::now() >= rate_limit_deadline {
1188 tracing::error!(target: "ingest", "rate-limit retry deadline (1h) exhausted");
1189 } else {
1190 let half = backoff_secs / 2;
1191 let jitter = if half == 0 { 0 } else { fastrand::u64(0..half) };
1192 let actual_wait = half + jitter;
1193 tracing::warn!(target: "ingest", delay_secs = actual_wait, error_kind = "rate_limited", "rate limited, backing off");
1194 let _ = queue_conn.execute(
1195 "UPDATE queue SET status='pending' WHERE id=?1",
1196 rusqlite::params![queue_id],
1197 );
1198 std::thread::sleep(std::time::Duration::from_secs(actual_wait));
1199 backoff_secs = (backoff_secs * 2).min(900);
1200 continue;
1201 }
1202 } else {
1203 let _ = queue_conn.execute(
1204 "UPDATE queue SET status='failed', error=?1, done_at=datetime('now') WHERE id=?2",
1205 rusqlite::params![err_str, queue_id],
1206 );
1207 let current_index = completed + failed + skipped;
1208 failed += 1;
1209 emit_json(&FileEvent {
1210 file: &file_path,
1211 name: "",
1212 status: "failed",
1213 memory_id: None,
1214 entities: None,
1215 rels: None,
1216 cost_usd: None,
1217 elapsed_ms: Some(file_started.elapsed().as_millis() as u64),
1218 error: Some(err_str),
1219 index: current_index,
1220 total,
1221 });
1222 if args.fail_fast {
1223 break;
1224 }
1225 }
1226 }
1227
1228 if let Some(budget) = args.max_cost_usd {
1229 if oauth_detected {
1230 tracing::debug!(target: "ingest", "--max-cost-usd ignored: OAuth subscription detected");
1231 } else if cost_total >= budget {
1232 tracing::warn!(
1233 target: "ingest",
1234 spent = cost_total,
1235 budget = budget,
1236 "budget exceeded, stopping"
1237 );
1238 break;
1239 }
1240 }
1241 }
1242
1243 let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1245 let _ = queue_conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1246
1247 emit_json(&Summary {
1248 summary: true,
1249 files_total: total,
1250 completed,
1251 failed,
1252 skipped,
1253 entities_total,
1254 rels_total,
1255 cost_usd: cost_total,
1256 elapsed_ms: started.elapsed().as_millis() as u64,
1257 });
1258
1259 if !args.keep_queue && failed == 0 {
1260 let _ = std::fs::remove_file(&args.queue_db);
1261 }
1262
1263 Ok(())
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268 use super::*;
1269
1270 #[test]
1271 fn test_extraction_schema_valid_json() {
1272 let _: serde_json::Value =
1273 serde_json::from_str(EXTRACTION_SCHEMA).expect("schema must be valid JSON");
1274 }
1275
1276 #[test]
1277 fn test_parse_claude_output_valid() {
1278 let output = r#"[
1279 {"type":"system","subtype":"init"},
1280 {"type":"assistant"},
1281 {"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}]}}
1282 ]"#;
1283 let (result, cost, _is_oauth) = parse_claude_output(output).expect("parse must succeed");
1284 assert_eq!(result.name, "test-doc");
1285 assert_eq!(result.entities.len(), 1);
1286 assert_eq!(result.relationships.len(), 1);
1287 assert!((cost - 0.02).abs() < f64::EPSILON);
1288 }
1289
1290 #[test]
1291 fn test_parse_claude_output_error() {
1292 let output = r#"[
1293 {"type":"system","subtype":"init"},
1294 {"type":"result","is_error":true,"error":"authentication failed"}
1295 ]"#;
1296 let err = parse_claude_output(output).unwrap_err();
1297 assert!(format!("{err}").contains("authentication failed"));
1298 }
1299
1300 #[test]
1301 fn test_parse_claude_output_rate_limit() {
1302 let output = r#"[
1303 {"type":"system","subtype":"init"},
1304 {"type":"result","is_error":true,"error":"rate_limit exceeded"}
1305 ]"#;
1306 let err = parse_claude_output(output).unwrap_err();
1307 assert!(matches!(err, AppError::RateLimited { .. }));
1308 }
1309
1310 #[test]
1311 fn test_parse_claude_output_malformed() {
1312 let output = "not json at all";
1313 assert!(parse_claude_output(output).is_err());
1314 }
1315
1316 #[test]
1317 fn test_find_claude_binary_not_found() {
1318 let original_path = std::env::var_os("PATH");
1319 std::env::set_var("PATH", "/nonexistent");
1320 std::env::remove_var("SQLITE_GRAPHRAG_CLAUDE_BINARY");
1321 let result = find_claude_binary(None);
1322 if let Some(p) = original_path {
1323 std::env::set_var("PATH", p);
1324 }
1325 assert!(result.is_err());
1326 }
1327
1328 #[test]
1329 fn test_parse_claude_output_result_fallback() {
1330 let output = r#"[
1331 {"type":"system","subtype":"init"},
1332 {"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\":[]}"}
1333 ]"#;
1334 let (result, cost, _is_oauth) =
1335 parse_claude_output(output).expect("result fallback must work");
1336 assert_eq!(result.name, "test-fallback");
1337 assert_eq!(result.entities.len(), 1);
1338 assert!(result.relationships.is_empty());
1339 assert!((cost - 0.01).abs() < f64::EPSILON);
1340 }
1341
1342 #[test]
1343 fn test_parse_claude_output_error_with_result_field() {
1344 let output = r#"[
1345 {"type":"system","subtype":"init"},
1346 {"type":"result","is_error":true,"result":"Not logged in · Please run /login"}
1347 ]"#;
1348 let err = parse_claude_output(output).unwrap_err();
1349 let msg = format!("{err}");
1350 assert!(
1351 msg.contains("Not logged in"),
1352 "expected 'Not logged in' in: {msg}"
1353 );
1354 }
1355
1356 #[test]
1357 fn test_terminal_reason_max_turns_detected() {
1358 let output = r#"[
1359 {"type":"system","subtype":"init"},
1360 {"type":"result","is_error":false,"terminal_reason":"max_turns","structured_output":{"name":"t","description":"d","entities":[],"relationships":[]}}
1361 ]"#;
1362 let err_or_ok = parse_claude_output(output);
1363 assert!(
1364 err_or_ok.is_ok(),
1365 "max_turns in result without is_error should still parse"
1366 );
1367 }
1368
1369 #[test]
1370 fn test_detect_oauth_from_init_json() {
1371 let output = r#"[
1372 {"type":"system","subtype":"init","apiKeySource":"none"},
1373 {"type":"result","is_error":false,"total_cost_usd":0.50,"structured_output":{"name":"test-oauth","description":"oauth test","entities":[],"relationships":[]}}
1374 ]"#;
1375 let (_result, cost, is_oauth) = parse_claude_output(output).expect("parse must succeed");
1376 assert!(is_oauth, "apiKeySource=none must be detected as OAuth");
1377 assert!((cost - 0.50).abs() < f64::EPSILON);
1378 }
1379
1380 #[test]
1381 fn test_api_key_source_not_oauth() {
1382 let output = r#"[
1383 {"type":"system","subtype":"init","apiKeySource":"env"},
1384 {"type":"result","is_error":false,"total_cost_usd":0.10,"structured_output":{"name":"test-api","description":"api test","entities":[],"relationships":[]}}
1385 ]"#;
1386 let (_result, _cost, is_oauth) = parse_claude_output(output).expect("parse must succeed");
1387 assert!(!is_oauth, "apiKeySource=env must NOT be detected as OAuth");
1388 }
1389
1390 #[test]
1391 fn test_missing_api_key_source_defaults_not_oauth() {
1392 let output = r#"[
1393 {"type":"system","subtype":"init"},
1394 {"type":"result","is_error":false,"total_cost_usd":0.05,"structured_output":{"name":"test-missing","description":"missing test","entities":[],"relationships":[]}}
1395 ]"#;
1396 let (_result, _cost, is_oauth) = parse_claude_output(output).expect("parse must succeed");
1397 assert!(!is_oauth, "missing apiKeySource must default to not OAuth");
1398 }
1399
1400 #[test]
1401 fn test_extraction_schema_entity_types_match_enum() {
1402 let schema: serde_json::Value = serde_json::from_str(EXTRACTION_SCHEMA).unwrap();
1403 let types = schema["properties"]["entities"]["items"]["properties"]["entity_type"]["enum"]
1404 .as_array()
1405 .expect("schema must have entity_type enum");
1406 for t in types {
1407 let s = t.as_str().unwrap();
1408 assert!(
1409 s.parse::<EntityType>().is_ok(),
1410 "schema entity_type '{s}' not in EntityType enum"
1411 );
1412 }
1413 }
1414}