sqlite_graphrag/commands/
claude_runner.rs1use crate::errors::AppError;
12use crate::spawn::env_whitelist::apply_env_whitelist;
13use std::path::Path;
14use std::process::{Command, Stdio};
15
16const MIN_CLAUDE_VERSION: &str = "2.1.0";
18
19#[cfg(target_os = "linux")]
21const DEFAULT_SUBPROCESS_MEMORY_LIMIT_MB: u64 = 4096;
22
23#[cfg(target_os = "linux")]
48pub fn spawn_with_memory_limit(cmd: &mut Command) -> std::io::Result<std::process::Child> {
49 use std::os::unix::process::CommandExt;
50 let max_mb: u64 = std::env::var("SQLITE_GRAPHRAG_SUBPROCESS_MEMORY_LIMIT_MB")
51 .ok()
52 .and_then(|v| v.parse().ok())
53 .unwrap_or(DEFAULT_SUBPROCESS_MEMORY_LIMIT_MB);
54 let max_bytes = max_mb * 1024 * 1024;
55 unsafe {
62 cmd.pre_exec(move || {
63 let sid = libc::setsid();
64 if sid == -1 {
65 let err = std::io::Error::last_os_error();
66 if err.raw_os_error() != Some(libc::EPERM) {
67 return Err(err);
68 }
69 }
70 let limit = libc::rlimit {
71 rlim_cur: max_bytes,
72 rlim_max: max_bytes,
73 };
74 if libc::setrlimit(libc::RLIMIT_AS, &limit) != 0 {
75 return Err(std::io::Error::last_os_error());
76 }
77 Ok(())
78 });
79 }
80 tracing::debug!(
81 target: "process",
82 program = ?cmd.get_program(),
83 args = ?cmd.get_args().collect::<Vec<_>>(),
84 "spawning external process"
85 );
86 cmd.spawn()
87}
88
89#[cfg(not(target_os = "linux"))]
92pub fn spawn_with_memory_limit(cmd: &mut Command) -> std::io::Result<std::process::Child> {
93 #[cfg(unix)]
94 {
95 use std::os::unix::process::CommandExt;
96 unsafe {
99 cmd.pre_exec(|| {
100 let sid = libc::setsid();
101 if sid == -1 {
102 let err = std::io::Error::last_os_error();
103 if err.raw_os_error() != Some(libc::EPERM) {
104 return Err(err);
105 }
106 }
107 Ok(())
108 });
109 }
110 }
111 tracing::debug!(
112 target: "process",
113 program = ?cmd.get_program(),
114 args = ?cmd.get_args().collect::<Vec<_>>(),
115 "spawning external process"
116 );
117 cmd.spawn()
118}
119
120#[derive(Debug, serde::Deserialize)]
122pub struct ClaudeOutputElement {
123 pub r#type: Option<String>,
124 pub subtype: Option<String>,
125 #[serde(default)]
126 pub is_error: bool,
127 pub structured_output: Option<serde_json::Value>,
128 pub result: Option<String>,
129 pub total_cost_usd: Option<f64>,
130 pub error: Option<String>,
131 pub terminal_reason: Option<String>,
132 #[serde(rename = "apiKeySource")]
133 pub api_key_source: Option<String>,
134}
135
136#[derive(Debug)]
138pub struct ClaudeResult {
139 pub value: serde_json::Value,
140 pub cost_usd: f64,
141 pub is_oauth: bool,
142}
143
144pub fn validate_claude_version(binary: &Path) -> Result<String, AppError> {
146 let resolved = which::which(binary).map_err(|_| {
147 AppError::Validation(format!(
148 "executable '{}' not found in PATH; ensure it is installed and accessible",
149 binary.display()
150 ))
151 })?;
152 let output = Command::new(&resolved)
153 .arg("--version")
154 .stdin(Stdio::null())
155 .stdout(Stdio::piped())
156 .stderr(Stdio::piped())
157 .output()
158 .map_err(AppError::Io)?;
159
160 if !output.status.success() {
161 return Err(AppError::Validation(
162 "failed to run 'claude --version'".to_string(),
163 ));
164 }
165
166 let version_str = String::from_utf8(output.stdout)
167 .map_err(|_| AppError::Validation("claude --version output is not UTF-8".to_string()))?;
168 let version = version_str.trim().to_string();
169 let numeric = version.split([' ', '(']).next().unwrap_or("").trim();
170
171 fn parse_semver(s: &str) -> Option<(u64, u64, u64)> {
172 let parts: Vec<&str> = s.splitn(3, '.').collect();
173 if parts.len() < 2 {
174 return None;
175 }
176 let major = parts[0].parse::<u64>().ok()?;
177 let minor = parts[1].parse::<u64>().ok()?;
178 let patch = parts
179 .get(2)
180 .and_then(|p| p.parse::<u64>().ok())
181 .unwrap_or(0);
182 Some((major, minor, patch))
183 }
184
185 if let (Some(actual), Some(min)) = (parse_semver(numeric), parse_semver(MIN_CLAUDE_VERSION)) {
186 if actual < min {
187 return Err(AppError::Validation(format!(
188 "Claude Code version {numeric} is below minimum required {MIN_CLAUDE_VERSION}"
189 )));
190 }
191 }
192
193 Ok(version)
194}
195
196pub fn build_claude_command(
233 binary: &Path,
234 prompt: &str,
235 json_schema: &str,
236 model: Option<&str>,
237 max_turns: u32,
238) -> Result<Command, crate::errors::AppError> {
239 if let Ok(_key) = std::env::var("ANTHROPIC_API_KEY") {
243 let mut cmd = Command::new("false");
248 cmd.env_clear();
249 cmd.env("PATH", "/nonexistent");
250 cmd.arg("--oauth-only-violation-anthropic-api-key-set");
251 cmd.arg("--oauth-only-resolution-use-anthropic-auth-token");
252 return Ok(cmd);
253 }
254
255 let mut cmd = Command::new(binary);
256
257 apply_env_whitelist(&mut cmd, crate::spawn::env_whitelist::is_strict_env_clear());
262 crate::spawn::apply_cwd_isolation(&mut cmd)?;
263
264 let mcp_config_path = crate::spawn::preflight::write_empty_mcp_config_tempfile()?;
273
274 cmd.arg("-p")
275 .arg(prompt)
276 .arg("--strict-mcp-config")
277 .arg("--mcp-config")
278 .arg(mcp_config_path.as_os_str())
279 .arg("--dangerously-skip-permissions")
280 .arg("--settings")
281 .arg(r#"{"hooks":{}}"#)
282 .arg("--output-format")
283 .arg("json")
284 .arg("--json-schema")
285 .arg(json_schema)
286 .arg("--max-turns")
287 .arg(max_turns.to_string())
288 .arg("--no-session-persistence");
289
290 if let Some(m) = model {
291 cmd.arg("--model").arg(m);
292 }
293
294 cmd.stdin(Stdio::null())
295 .stdout(Stdio::piped())
296 .stderr(Stdio::piped());
297
298 let argv_refs: Vec<std::ffi::OsString> = cmd.get_args().map(|s| s.to_os_string()).collect();
304 let preflight_args = crate::spawn::preflight::PreFlightArgs {
305 binary_path: binary,
306 argv: &argv_refs,
307 workspace_root: std::path::Path::new("."),
308 mcp_config_inline_json: None,
309 expected_output_bytes: 65_536,
310 spawner_name: "claude_runner",
311 };
312 if let Err(e) = crate::spawn::preflight::preflight_check(&preflight_args) {
313 return Err(crate::errors::AppError::from(e));
319 }
320
321 Ok(cmd)
322}
323
324pub fn parse_claude_output(stdout: &str) -> Result<ClaudeResult, AppError> {
329 parse_claude_output_opts(stdout, false)
330}
331
332pub fn parse_claude_output_opts(
338 stdout: &str,
339 tolerate_max_turns: bool,
340) -> Result<ClaudeResult, AppError> {
341 let elements: Vec<ClaudeOutputElement> = serde_json::from_str(stdout).map_err(|e| {
342 AppError::Validation(format!("failed to parse claude output as JSON array: {e}"))
343 })?;
344
345 let is_oauth = elements
346 .iter()
347 .find(|e| e.r#type.as_deref() == Some("system") && e.subtype.as_deref() == Some("init"))
348 .and_then(|e| e.api_key_source.as_deref())
349 .map(|s| s == "none")
350 .unwrap_or(false);
351
352 let result_elem = elements
353 .iter()
354 .find(|e| e.r#type.as_deref() == Some("result"))
355 .ok_or_else(|| {
356 AppError::Validation("claude output missing 'result' element".to_string())
357 })?;
358
359 if !tolerate_max_turns && result_elem.terminal_reason.as_deref() == Some("max_turns") {
361 tracing::warn!(
362 target: "claude_runner",
363 "claude -p hit max_turns limit — hooks may have consumed turns"
364 );
365 return Err(AppError::Validation(
366 "claude -p hit max_turns: hooks may be consuming turns; increase --max-turns or disable hooks".to_string(),
367 ));
368 }
369
370 if result_elem.is_error {
371 let err_msg = result_elem
372 .error
373 .as_deref()
374 .or(result_elem.result.as_deref())
375 .unwrap_or("unknown error");
376 if err_msg.contains("rate_limit") || err_msg.contains("overloaded") {
377 return Err(AppError::RateLimited {
378 detail: err_msg.to_string(),
379 });
380 }
381 if err_msg.contains("Not logged in") || err_msg.contains("authentication") {
382 tracing::warn!(
383 target: "claude_runner",
384 "Claude Code authentication failed. Re-authenticate interactively with: claude"
385 );
386 }
387 return Err(AppError::Validation(format!(
388 "claude extraction failed: {err_msg}"
389 )));
390 }
391
392 let value = if let Some(v) = result_elem.structured_output.clone() {
393 v
394 } else if let Some(text) = &result_elem.result {
395 serde_json::from_str(text).map_err(|e| {
396 AppError::Validation(format!("failed to parse claude result field as JSON: {e}"))
397 })?
398 } else {
399 return Err(AppError::Validation(
400 "claude result missing structured_output and result field".into(),
401 ));
402 };
403
404 let cost = result_elem.total_cost_usd.unwrap_or(0.0);
405 Ok(ClaudeResult {
406 value,
407 cost_usd: cost,
408 is_oauth,
409 })
410}
411
412pub fn run_claude(
418 binary: &Path,
419 prompt: &str,
420 json_schema: &str,
421 input_text: &str,
422 model: Option<&str>,
423 timeout_secs: u64,
424 max_turns: u32,
425) -> Result<ClaudeResult, AppError> {
426 use wait_timeout::ChildExt;
427
428 let full_prompt = format!("{prompt}\n\n{input_text}");
429 let mut cmd = build_claude_command(binary, &full_prompt, json_schema, model, max_turns)?;
430
431 let mut child = spawn_with_memory_limit(&mut cmd).map_err(|e| {
432 AppError::Io(std::io::Error::new(
433 e.kind(),
434 format!("failed to spawn claude: {e}"),
435 ))
436 })?;
437
438 let start = std::time::Instant::now();
439 let timeout = std::time::Duration::from_secs(timeout_secs);
440 let status = child.wait_timeout(timeout).map_err(AppError::Io)?;
441
442 if status.is_none() {
443 #[cfg(unix)]
449 unsafe {
450 libc::kill(child.id() as i32, libc::SIGTERM);
451 }
452 let _ = child.kill();
453 let _ = child.wait();
454 }
455
456 match status {
457 Some(exit_status) => {
458 tracing::debug!(
459 target: "process",
460 exit_code = ?exit_status.code(),
461 elapsed_ms = start.elapsed().as_millis() as u64,
462 "external process completed"
463 );
464
465 let mut stdout_buf = Vec::new();
466 let mut stderr_buf = Vec::new();
467 if let Some(mut out) = child.stdout.take() {
468 std::io::Read::read_to_end(&mut out, &mut stdout_buf).map_err(AppError::Io)?;
469 }
470 if let Some(mut err) = child.stderr.take() {
471 std::io::Read::read_to_end(&mut err, &mut stderr_buf).map_err(AppError::Io)?;
472 }
473
474 let stdout_str = String::from_utf8(stdout_buf)
475 .map_err(|_| AppError::Validation("claude -p stdout is not valid UTF-8".into()))?;
476
477 if !exit_status.success() {
479 if let Ok(result) = parse_claude_output(&stdout_str) {
480 return Ok(result);
481 }
482 let stderr_str = String::from_utf8_lossy(&stderr_buf);
483 if stderr_str.contains("auth") || stderr_str.contains("login") {
484 tracing::warn!(
485 target: "claude_runner",
486 "Claude Code authentication may have failed. Re-authenticate with: claude"
487 );
488 }
489 return Err(AppError::Validation(format!(
490 "claude -p exited with code {:?}: {}",
491 exit_status.code(),
492 stderr_str.trim()
493 )));
494 }
495
496 parse_claude_output(&stdout_str)
497 }
498 None => {
499 tracing::warn!(target: "claude_runner", timeout_secs, "claude -p timed out, terminating");
500 terminate_gracefully(&mut child, 3);
501 Err(AppError::Validation(format!(
502 "claude -p timed out after {timeout_secs} seconds"
503 )))
504 }
505 }
506}
507
508#[cfg(unix)]
510pub fn terminate_gracefully(child: &mut std::process::Child, grace_secs: u64) {
511 use wait_timeout::ChildExt;
512 unsafe {
513 libc::kill(child.id() as i32, libc::SIGTERM);
514 }
515 match child.wait_timeout(std::time::Duration::from_secs(grace_secs)) {
516 Ok(Some(_)) => {}
517 _ => {
518 tracing::warn!(target: "process", pid = child.id(), "child ignored SIGTERM, sending SIGKILL");
519 let _ = child.kill();
520 let _ = child.wait();
521 }
522 }
523}
524
525#[cfg(not(unix))]
527pub fn terminate_gracefully(child: &mut std::process::Child, _grace_secs: u64) {
528 let _ = child.kill();
529 let _ = child.wait();
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535
536 #[test]
537 fn parse_output_detects_max_turns() {
538 let stdout = r#"[{"type":"system","subtype":"init","apiKeySource":"none"},{"type":"result","is_error":false,"terminal_reason":"max_turns","structured_output":{"name":"t"}}]"#;
539 let err = parse_claude_output(stdout).unwrap_err();
540 assert!(
541 format!("{err}").contains("max_turns"),
542 "must detect max_turns in output"
543 );
544 }
545
546 #[test]
547 fn parse_output_extracts_structured_value() {
548 let stdout = r#"[{"type":"system","subtype":"init","apiKeySource":"none"},{"type":"result","is_error":false,"structured_output":{"key":"val"},"total_cost_usd":0.01}]"#;
549 let result = parse_claude_output(stdout).unwrap();
550 assert_eq!(result.value["key"], "val");
551 assert!((result.cost_usd - 0.01).abs() < f64::EPSILON);
552 assert!(result.is_oauth);
553 }
554
555 #[test]
556 fn parse_output_detects_rate_limit() {
557 let stdout = r#"[{"type":"result","is_error":true,"error":"rate_limit exceeded"}]"#;
558 let err = parse_claude_output(stdout).unwrap_err();
559 assert!(
560 matches!(err, AppError::RateLimited { .. }),
561 "expected AppError::RateLimited, got: {err}"
562 );
563 }
564
565 #[test]
569 #[serial_test::serial(env)]
570 fn build_command_oauth_only_mandatory_flags() {
571 unsafe {
573 std::env::remove_var("ANTHROPIC_API_KEY");
574 std::env::remove_var("CLAUDE_CONFIG_DIR");
577 }
578 let cmd = build_claude_command(
579 std::path::Path::new("/usr/bin/false"),
580 "test prompt",
581 "{}",
582 Some("sonnet"),
583 4,
584 )
585 .expect("preflight gate accepts valid args");
586 let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
587 assert!(args.contains(&"-p"), "must have -p");
589 assert!(
590 args.contains(&"--strict-mcp-config"),
591 "must have --strict-mcp-config (gaps.md:206)"
592 );
593 assert!(
594 args.contains(&"--mcp-config"),
595 "must have --mcp-config (gaps.md:207)"
596 );
597 assert!(
598 args.contains(&"--dangerously-skip-permissions"),
599 "must have --dangerously-skip-permissions (gaps.md:208)"
600 );
601 assert!(
602 args.contains(&"--settings"),
603 "must have --settings (gaps.md:209)"
604 );
605 assert!(
606 args.contains(&"--output-format"),
607 "must have --output-format json (gaps.md:213)"
608 );
609 assert!(args.contains(&"--json-schema"), "must have --json-schema");
610 assert!(
611 args.contains(&"--max-turns"),
612 "must have --max-turns (gaps.md:212)"
613 );
614 assert!(
615 args.contains(&"--no-session-persistence"),
616 "must have --no-session-persistence"
617 );
618 assert!(
619 args.contains(&"--model"),
620 "must have --model when model is Some"
621 );
622 assert!(
624 !args.contains(&"--bare"),
625 "--bare is PROHIBITED (gaps.md:49)"
626 );
627 }
628
629 #[test]
633 #[serial_test::serial(env)]
634 fn build_command_aborts_when_anthropic_api_key_set() {
635 unsafe {
637 std::env::set_var("ANTHROPIC_API_KEY", "sk-test-violation");
638 std::env::remove_var("CLAUDE_CONFIG_DIR");
642 }
643 let cmd = build_claude_command(
644 std::path::Path::new("/usr/bin/claude"),
645 "test prompt",
646 "{}",
647 Some("sonnet"),
648 4,
649 )
650 .expect("preflight gate accepts valid args");
651 let program = cmd.get_program().to_string_lossy().to_string();
652 let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
653 assert_eq!(
654 program, "false",
655 "when ANTHROPIC_API_KEY is set, build_claude_command must abort"
656 );
657 assert!(
658 args.contains(&"--oauth-only-violation-anthropic-api-key-set"),
659 "aborted command must carry violation marker"
660 );
661 unsafe {
662 std::env::remove_var("ANTHROPIC_API_KEY");
663 }
664 }
665}