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