Skip to main content

sqlite_graphrag/commands/
claude_runner.rs

1//! Shared module for spawning Claude Code (`claude -p`) subprocesses.
2//!
3//! Eliminates duplication between `enrich.rs` and `ingest_claude.rs` (G02).
4//! Detects `terminal_reason: "max_turns"` in the JSON output (G03).
5//!
6//! v1.0.83 (ADR-0041): env whitelist now delegates to
7//! `crate::spawn::env_whitelist::apply_env_whitelist` so the canonical list
8//! lives in one place. `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` remain
9//! INTENTIONALLY ABSENT (defence-in-depth alongside the OAuth-only guards).
10
11use crate::errors::AppError;
12use crate::spawn::env_whitelist::apply_env_whitelist;
13use std::path::Path;
14use std::process::{Command, Stdio};
15
16/// Minimum Claude Code version required for structured JSON output.
17const MIN_CLAUDE_VERSION: &str = "2.1.0";
18
19/// Default virtual memory limit for LLM subprocesses (4 GiB).
20#[cfg(target_os = "linux")]
21const DEFAULT_SUBPROCESS_MEMORY_LIMIT_MB: u64 = 4096;
22
23// G28-C (v1.0.69): process lifecycle. The G28 gap asks for
24// `tokio::process::Command::kill_on_drop(true)`. This codebase uses
25// `std::process::Command` (synchronous) so the tokio helper is not
26// available. Equivalent defence-in-depth is provided by:
27//
28// 1. `SIGTERM` via `libc::kill` in the timeout branch of `run_claude`
29//    and `run_codex` (graceful — gives the child a chance to clean up
30//    MCP children and write logs).
31// 2. `child.kill()` (SIGKILL) if SIGTERM was ignored.
32// 3. `reaper::scan_and_kill_orphans()` at startup, which walks `/proc`
33//    and reaps any `claude`/`codex` processes that were orphaned by a
34//    previous crash.
35//
36// SIGKILL on drop is intentionally NOT used because (a) the gaps.md
37// Passo C warning flags it as risky per tokio-rs/tokio#7082, and (b)
38// the SIGTERM-then-SIGKILL pair covers the same threat model with
39// better cleanup behaviour.
40
41/// Spawns a command with a virtual memory limit via `setrlimit(RLIMIT_AS)`.
42///
43/// On Linux, applies the limit in a `pre_exec` hook before the child process
44/// starts.  On non-Linux platforms, falls back to an unlimited spawn.
45/// The limit is read from `SQLITE_GRAPHRAG_SUBPROCESS_MEMORY_LIMIT_MB`
46/// (default: 4096 MiB).
47#[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 = crate::runtime_config::resolve_u64(
51        None,
52        "spawn.subprocess_memory_limit_mb",
53        DEFAULT_SUBPROCESS_MEMORY_LIMIT_MB,
54    );
55    let max_bytes = max_mb * 1024 * 1024;
56    // SAFETY: pre_exec closure runs between fork() and exec() in the
57    // single-threaded child process — no other threads exist.
58    // libc::setsid and libc::setrlimit are async-signal-safe per POSIX.1-2008 §2.4.3.
59    // RLIMIT_AS limits virtual address space, not physical RSS.
60    // setsid failure with EPERM is tolerated (process already a session leader).
61    // On setrlimit failure, Err(last_os_error()) prevents exec.
62    unsafe {
63        cmd.pre_exec(move || {
64            let sid = libc::setsid();
65            if sid == -1 {
66                let err = std::io::Error::last_os_error();
67                if err.raw_os_error() != Some(libc::EPERM) {
68                    return Err(err);
69                }
70            }
71            let limit = libc::rlimit {
72                rlim_cur: max_bytes,
73                rlim_max: max_bytes,
74            };
75            if libc::setrlimit(libc::RLIMIT_AS, &limit) != 0 {
76                return Err(std::io::Error::last_os_error());
77            }
78            Ok(())
79        });
80    }
81    tracing::debug!(
82        target: "process",
83        program = ?cmd.get_program(),
84        args = ?cmd.get_args().collect::<Vec<_>>(),
85        "spawning external process"
86    );
87    cmd.spawn()
88}
89
90/// Spawns a command without memory limits (non-Linux fallback).
91/// On Unix (macOS, FreeBSD), applies setsid for process group isolation.
92#[cfg(not(target_os = "linux"))]
93pub fn spawn_with_memory_limit(cmd: &mut Command) -> std::io::Result<std::process::Child> {
94    #[cfg(unix)]
95    {
96        use std::os::unix::process::CommandExt;
97        // SAFETY: setsid() is async-signal-safe per POSIX.1-2008 §2.4.3.
98        // Creates independent session for cascade termination.
99        unsafe {
100            cmd.pre_exec(|| {
101                let sid = libc::setsid();
102                if sid == -1 {
103                    let err = std::io::Error::last_os_error();
104                    if err.raw_os_error() != Some(libc::EPERM) {
105                        return Err(err);
106                    }
107                }
108                Ok(())
109            });
110        }
111    }
112    tracing::debug!(
113        target: "process",
114        program = ?cmd.get_program(),
115        args = ?cmd.get_args().collect::<Vec<_>>(),
116        "spawning external process"
117    );
118    cmd.spawn()
119}
120
121/// Parsed output element from `claude -p --output-format json`.
122#[derive(Debug, serde::Deserialize)]
123pub struct ClaudeOutputElement {
124    pub r#type: Option<String>,
125    pub subtype: Option<String>,
126    #[serde(default)]
127    pub is_error: bool,
128    pub structured_output: Option<serde_json::Value>,
129    pub result: Option<String>,
130    pub total_cost_usd: Option<f64>,
131    pub error: Option<String>,
132    pub terminal_reason: Option<String>,
133    #[serde(rename = "apiKeySource")]
134    pub api_key_source: Option<String>,
135}
136
137/// Result of a successful Claude invocation.
138#[derive(Debug)]
139pub struct ClaudeResult {
140    pub value: serde_json::Value,
141    pub cost_usd: f64,
142    pub is_oauth: bool,
143}
144
145/// Validates that the Claude binary meets the minimum version requirement.
146pub fn validate_claude_version(binary: &Path) -> Result<String, AppError> {
147    let resolved = which::which(binary).map_err(|_| {
148        AppError::Validation(format!(
149            "executable '{}' not found in PATH; ensure it is installed and accessible",
150            binary.display()
151        ))
152    })?;
153    let output = Command::new(&resolved)
154        .arg("--version")
155        .stdin(Stdio::null())
156        .stdout(Stdio::piped())
157        .stderr(Stdio::piped())
158        .output()
159        .map_err(AppError::Io)?;
160
161    if !output.status.success() {
162        return Err(AppError::Validation(
163            "failed to run 'claude --version'".to_string(),
164        ));
165    }
166
167    let version_str = String::from_utf8(output.stdout)
168        .map_err(|_| AppError::Validation("claude --version output is not UTF-8".to_string()))?;
169    let version = version_str.trim().to_string();
170    let numeric = version.split([' ', '(']).next().unwrap_or("").trim();
171
172    fn parse_semver(s: &str) -> Option<(u64, u64, u64)> {
173        let parts: Vec<&str> = s.splitn(3, '.').collect();
174        if parts.len() < 2 {
175            return None;
176        }
177        let major = parts[0].parse::<u64>().ok()?;
178        let minor = parts[1].parse::<u64>().ok()?;
179        let patch = parts
180            .get(2)
181            .and_then(|p| p.parse::<u64>().ok())
182            .unwrap_or(0);
183        Some((major, minor, patch))
184    }
185
186    if let (Some(actual), Some(min)) = (parse_semver(numeric), parse_semver(MIN_CLAUDE_VERSION)) {
187        if actual < min {
188            return Err(AppError::Validation(format!(
189                "Claude Code version {numeric} is below minimum required {MIN_CLAUDE_VERSION}"
190            )));
191        }
192    }
193
194    Ok(version)
195}
196
197/// Builds a `Command` for `claude -p` with least-privilege environment.
198///
199/// G28-A (v1.0.68) + OAuth-only hardening (v1.0.69, mandated by gaps.md
200/// lines 41-49): the command ALWAYS uses the OAuth flow. The flag set
201/// is the canonical one documented in gaps.md Fix A:
202///
203/// ```text
204/// claude -p "TAREFA" \
205///   --strict-mcp-config \
206///   --mcp-config '{}' \
207///   --dangerously-skip-permissions \
208///   --settings '{"hooks":{}}' \
209///   --model <X> \
210///   --max-turns <N> \
211///   --output-format json \
212///   --no-session-persistence
213/// ```
214///
215/// The combination cuts the typical 8-10 MCP process tree to zero and
216/// disables user hooks. The reaper sweep at startup (see `reaper::scan_and_kill_orphans`)
217/// is the last line of defence for any process that ignored the flags.
218///
219/// **`--bare` is FORBIDDEN** (gaps.md:49 and operator policy):
220/// `--bare` cuts MCPs but disables OAuth and demands `ANTHROPIC_API_KEY`,
221/// which is PROHIBITED in this project. We also ABORT the spawn if
222/// `ANTHROPIC_API_KEY` is set in the environment, because that is the
223/// gateway to the prohibited API-key path.
224///
225/// GitHub issue [anthropics/claude-code#10787] documents that earlier
226/// Claude Code CLI builds sometimes ignored `--strict-mcp-config` and
227/// fell back to `~/.mcp.json`. We still pass the flags as defence-in-depth
228/// and ALSO honour `SQLITE_GRAPHRAG_CLAUDE_EMPTY_CONFIG_DIR` so users
229/// who need belt-and-suspenders isolation can point Claude at an empty
230/// config directory (no MCP, no hooks, no settings).
231///
232/// [anthropics/claude-code#10787]: https://github.com/anthropics/claude-code/issues/10787
233pub fn build_claude_command(
234    binary: &Path,
235    prompt: &str,
236    json_schema: &str,
237    model: Option<&str>,
238    max_turns: u32,
239) -> Result<Command, crate::errors::AppError> {
240    // OAuth-only guard (gaps.md:47, ADR-0011). If `ANTHROPIC_API_KEY` is
241    // set in the environment we MUST abort — that is the API-key path
242    // which is explicitly PROHIBITED. Use the OAuth flow exclusively.
243    if let Ok(_key) = std::env::var("ANTHROPIC_API_KEY") {
244        // Return a command that will fail loudly at spawn time. We
245        // intentionally do NOT pass `--bare` (PROHIBITED) and we do NOT
246        // allow the API-key path at all. The second marker arg is the
247        // orientative hint surfaced via the diagnostic pipeline (ADR-0041).
248        let mut cmd = Command::new("false");
249        cmd.env_clear();
250        cmd.env("PATH", "/nonexistent");
251        cmd.arg("--oauth-only-violation-anthropic-api-key-set");
252        cmd.arg("--oauth-only-resolution-use-anthropic-auth-token");
253        return Ok(cmd);
254    }
255
256    let mut cmd = Command::new(binary);
257
258    // v1.0.83 (ADR-0041): env whitelist delegated to
259    // `crate::spawn::env_whitelist::apply_env_whitelist`. The single source of
260    // truth lives in `src/spawn/env_whitelist.rs`; do NOT reintroduce a
261    // local whitelist here.
262    apply_env_whitelist(&mut cmd, crate::spawn::env_whitelist::is_strict_env_clear());
263    crate::spawn::apply_cwd_isolation(&mut cmd)?;
264
265    // Canonical OAuth-only command line (gaps.md:201-208). Every flag is
266    // mandatory; do NOT pass `--bare` (PROHIBITED, gaps.md:49).
267    //
268    // GAP-META-005 (v1.0.87, ADR-0045): `--mcp-config '{}'` inline JSON is
269    // rejected by Claude Code 2.1.177 — the flag expects a filepath.
270    // Substitute the inline literal for a tempfile path containing
271    // `{"mcpServers":{}}`. The pre-flight check rejects the inline form
272    // when `mcp_config_inline_json: Some("{}")` is passed.
273    let mcp_config_path = crate::spawn::preflight::write_empty_mcp_config_tempfile()?;
274
275    cmd.arg("-p")
276        .arg(prompt)
277        .arg("--strict-mcp-config")
278        .arg("--mcp-config")
279        .arg(mcp_config_path.as_os_str())
280        .arg("--dangerously-skip-permissions")
281        .arg("--settings")
282        .arg(r#"{"hooks":{}}"#)
283        .arg("--output-format")
284        .arg("json")
285        .arg("--json-schema")
286        .arg(json_schema)
287        .arg("--max-turns")
288        .arg(max_turns.to_string())
289        .arg("--no-session-persistence");
290
291    if let Some(m) = model {
292        cmd.arg("--model").arg(m);
293    }
294
295    cmd.stdin(Stdio::null())
296        .stdout(Stdio::piped())
297        .stderr(Stdio::piped());
298
299    // GAP-META-005 (v1.0.87, ADR-0045): pre-flight validation gate runs
300    // AFTER argv is fully built so binary, argv-size, walk-up of
301    // `.mcp.json`, and `CLAUDE_CONFIG_DIR` cleanliness are all checked.
302    // Pre-flight failure is a configuration error — panic with a clear
303    // message rather than spawn a misconfigured subprocess.
304    let argv_refs: Vec<std::ffi::OsString> = cmd.get_args().map(|s| s.to_os_string()).collect();
305    let preflight_args = crate::spawn::preflight::PreFlightArgs {
306        binary_path: binary,
307        argv: &argv_refs,
308        workspace_root: std::path::Path::new("."),
309        mcp_config_inline_json: None,
310        expected_output_bytes: 65_536,
311        spawner_name: "claude_runner",
312    };
313    if let Err(e) = crate::spawn::preflight::preflight_check(&preflight_args) {
314        // v1.0.88 (BUG-6 fix, ADR-0046): propagate the structured
315        // `PreFlightError` via the `From` impl in `errors.rs` so callers
316        // receive `AppError::PreFlightFailed` (exit 16) instead of a
317        // bare `std::process::exit(16)` that discards the variant name,
318        // tracing context, and PT-BR i18n.
319        return Err(crate::errors::AppError::from(e));
320    }
321
322    Ok(cmd)
323}
324
325/// Parses `claude -p --output-format json` output array.
326///
327/// G03: detects `terminal_reason: "max_turns"` and returns a specific error
328/// instead of a generic failure message.
329pub fn parse_claude_output(stdout: &str) -> Result<ClaudeResult, AppError> {
330    parse_claude_output_opts(stdout, false)
331}
332
333/// Like [`parse_claude_output`] but lets the caller decide whether a
334/// `terminal_reason: "max_turns"` result is fatal. `ingest` passes `true`
335/// (a partial extraction with a usable structured value is acceptable); `enrich`
336/// and the default keep `false` (max_turns means hooks are consuming turns — a
337/// misconfiguration to surface rather than silently accept).
338pub fn parse_claude_output_opts(
339    stdout: &str,
340    tolerate_max_turns: bool,
341) -> Result<ClaudeResult, AppError> {
342    let elements: Vec<ClaudeOutputElement> = serde_json::from_str(stdout).map_err(|e| {
343        AppError::Validation(format!("failed to parse claude output as JSON array: {e}"))
344    })?;
345
346    let is_oauth = elements
347        .iter()
348        .find(|e| e.r#type.as_deref() == Some("system") && e.subtype.as_deref() == Some("init"))
349        .and_then(|e| e.api_key_source.as_deref())
350        .map(|s| s == "none")
351        .unwrap_or(false);
352
353    let result_elem = elements
354        .iter()
355        .find(|e| e.r#type.as_deref() == Some("result"))
356        .ok_or_else(|| {
357            AppError::Validation("claude output missing 'result' element".to_string())
358        })?;
359
360    // G03: detect max_turns exhaustion before checking is_error
361    if !tolerate_max_turns && result_elem.terminal_reason.as_deref() == Some("max_turns") {
362        tracing::warn!(
363            target: "claude_runner",
364            "claude -p hit max_turns limit — hooks may have consumed turns"
365        );
366        return Err(AppError::Validation(
367            "claude -p hit max_turns: hooks may be consuming turns; increase --max-turns or disable hooks".to_string(),
368        ));
369    }
370
371    if result_elem.is_error {
372        let err_msg = result_elem
373            .error
374            .as_deref()
375            .or(result_elem.result.as_deref())
376            .unwrap_or("unknown error");
377        if err_msg.contains("rate_limit") || err_msg.contains("overloaded") {
378            return Err(AppError::RateLimited {
379                detail: err_msg.to_string(),
380            });
381        }
382        if err_msg.contains("Not logged in") || err_msg.contains("authentication") {
383            tracing::warn!(
384                target: "claude_runner",
385                "Claude Code authentication failed. Re-authenticate interactively with: claude"
386            );
387        }
388        return Err(AppError::Validation(format!(
389            "claude extraction failed: {err_msg}"
390        )));
391    }
392
393    let value = if let Some(v) = result_elem.structured_output.clone() {
394        v
395    } else if let Some(text) = &result_elem.result {
396        serde_json::from_str(text).map_err(|e| {
397            AppError::Validation(format!("failed to parse claude result field as JSON: {e}"))
398        })?
399    } else {
400        return Err(AppError::Validation(
401            "claude result missing structured_output and result field".into(),
402        ));
403    };
404
405    let cost = result_elem.total_cost_usd.unwrap_or(0.0);
406    Ok(ClaudeResult {
407        value,
408        cost_usd: cost,
409        is_oauth,
410    })
411}
412
413/// Calls `claude -p` with prompt and schema, waits with timeout, and parses output.
414///
415/// G03: parses stdout even on non-zero exit to detect `terminal_reason: "max_turns"`.
416/// G28-C (v1.0.69): the child is killed explicitly on timeout to avoid
417/// leaving a `claude -p` zombie with its MCP children behind.
418pub fn run_claude(
419    binary: &Path,
420    prompt: &str,
421    json_schema: &str,
422    input_text: &str,
423    model: Option<&str>,
424    timeout_secs: u64,
425    max_turns: u32,
426) -> Result<ClaudeResult, AppError> {
427    use wait_timeout::ChildExt;
428
429    let full_prompt = format!("{prompt}\n\n{input_text}");
430    let mut cmd = build_claude_command(binary, &full_prompt, json_schema, model, max_turns)?;
431
432    let mut child = spawn_with_memory_limit(&mut cmd).map_err(|e| {
433        AppError::Io(std::io::Error::new(
434            e.kind(),
435            format!("failed to spawn claude: {e}"),
436        ))
437    })?;
438
439    let start = std::time::Instant::now();
440    let timeout = std::time::Duration::from_secs(timeout_secs);
441    let status = child.wait_timeout(timeout).map_err(AppError::Io)?;
442
443    if status.is_none() {
444        // G28-C: timeout hit — send SIGTERM to the child so the MCP
445        // children it spawned (and their npm/node tree) are also
446        // reaped. SIGTERM gives the child a chance to clean up; the
447        // reaper sweep in main.rs is the last line of defence for
448        // anything that ignored it.
449        #[cfg(unix)]
450        unsafe {
451            libc::kill(child.id() as i32, libc::SIGTERM);
452        }
453        let _ = child.kill();
454        let _ = child.wait();
455    }
456
457    match status {
458        Some(exit_status) => {
459            tracing::debug!(
460                target: "process",
461                exit_code = ?exit_status.code(),
462                elapsed_ms = start.elapsed().as_millis() as u64,
463                "external process completed"
464            );
465
466            let mut stdout_buf = Vec::new();
467            let mut stderr_buf = Vec::new();
468            if let Some(mut out) = child.stdout.take() {
469                std::io::Read::read_to_end(&mut out, &mut stdout_buf).map_err(AppError::Io)?;
470            }
471            if let Some(mut err) = child.stderr.take() {
472                std::io::Read::read_to_end(&mut err, &mut stderr_buf).map_err(AppError::Io)?;
473            }
474
475            let stdout_str = String::from_utf8(stdout_buf)
476                .map_err(|_| AppError::Validation("claude -p stdout is not valid UTF-8".into()))?;
477
478            // G03: parse stdout even on failure to detect terminal_reason
479            if !exit_status.success() {
480                if let Ok(result) = parse_claude_output(&stdout_str) {
481                    return Ok(result);
482                }
483                let stderr_str = String::from_utf8_lossy(&stderr_buf);
484                if stderr_str.contains("auth") || stderr_str.contains("login") {
485                    tracing::warn!(
486                        target: "claude_runner",
487                        "Claude Code authentication may have failed. Re-authenticate with: claude"
488                    );
489                }
490                return Err(AppError::Validation(format!(
491                    "claude -p exited with code {:?}: {}",
492                    exit_status.code(),
493                    stderr_str.trim()
494                )));
495            }
496
497            parse_claude_output(&stdout_str)
498        }
499        None => {
500            tracing::warn!(target: "claude_runner", timeout_secs, "claude -p timed out, terminating");
501            terminate_gracefully(&mut child, 3);
502            Err(AppError::Validation(format!(
503                "claude -p timed out after {timeout_secs} seconds"
504            )))
505        }
506    }
507}
508
509/// Terminates a child process gracefully: SIGTERM first, SIGKILL after grace period.
510#[cfg(unix)]
511pub fn terminate_gracefully(child: &mut std::process::Child, grace_secs: u64) {
512    use wait_timeout::ChildExt;
513    unsafe {
514        libc::kill(child.id() as i32, libc::SIGTERM);
515    }
516    match child.wait_timeout(std::time::Duration::from_secs(grace_secs)) {
517        Ok(Some(_)) => {}
518        _ => {
519            tracing::warn!(target: "process", pid = child.id(), "child ignored SIGTERM, sending SIGKILL");
520            let _ = child.kill();
521            let _ = child.wait();
522        }
523    }
524}
525
526/// Non-Unix fallback: kill immediately (Windows TerminateProcess).
527#[cfg(not(unix))]
528pub fn terminate_gracefully(child: &mut std::process::Child, _grace_secs: u64) {
529    let _ = child.kill();
530    let _ = child.wait();
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536
537    #[test]
538    fn parse_output_detects_max_turns() {
539        let stdout = r#"[{"type":"system","subtype":"init","apiKeySource":"none"},{"type":"result","is_error":false,"terminal_reason":"max_turns","structured_output":{"name":"t"}}]"#;
540        let err = parse_claude_output(stdout).unwrap_err();
541        assert!(
542            format!("{err}").contains("max_turns"),
543            "must detect max_turns in output"
544        );
545    }
546
547    #[test]
548    fn parse_output_extracts_structured_value() {
549        let stdout = r#"[{"type":"system","subtype":"init","apiKeySource":"none"},{"type":"result","is_error":false,"structured_output":{"key":"val"},"total_cost_usd":0.01}]"#;
550        let result = parse_claude_output(stdout).unwrap();
551        assert_eq!(result.value["key"], "val");
552        assert!((result.cost_usd - 0.01).abs() < f64::EPSILON);
553        assert!(result.is_oauth);
554    }
555
556    #[test]
557    fn parse_output_detects_rate_limit() {
558        let stdout = r#"[{"type":"result","is_error":true,"error":"rate_limit exceeded"}]"#;
559        let err = parse_claude_output(stdout).unwrap_err();
560        assert!(
561            matches!(err, AppError::RateLimited { .. }),
562            "expected AppError::RateLimited, got: {err}"
563        );
564    }
565
566    /// OAuth-only conformance test (gaps.md:41-49, v1.0.69 mandate).
567    /// Verifies that `build_claude_command` always emits the canonical
568    /// flag set and NEVER emits `--bare` or any API-key path.
569    #[test]
570    #[serial_test::serial(env)]
571    fn build_command_oauth_only_mandatory_flags() {
572        // SAFETY: this is a unit test, no concurrent env mutation
573        unsafe {
574            std::env::remove_var("ANTHROPIC_API_KEY");
575            // GAP-META-005 (v1.0.87): clear CLAUDE_CONFIG_DIR so the new
576            // pre-flight check does not exit 16 on the test host.
577            std::env::remove_var("CLAUDE_CONFIG_DIR");
578        }
579        let cmd = build_claude_command(
580            std::path::Path::new("/usr/bin/false"),
581            "test prompt",
582            "{}",
583            Some("sonnet"),
584            4,
585        )
586        .expect("preflight gate accepts valid args");
587        let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
588        // Mandatory OAuth-only flags from gaps.md lines 201-208
589        assert!(args.contains(&"-p"), "must have -p");
590        assert!(
591            args.contains(&"--strict-mcp-config"),
592            "must have --strict-mcp-config (gaps.md:206)"
593        );
594        assert!(
595            args.contains(&"--mcp-config"),
596            "must have --mcp-config (gaps.md:207)"
597        );
598        assert!(
599            args.contains(&"--dangerously-skip-permissions"),
600            "must have --dangerously-skip-permissions (gaps.md:208)"
601        );
602        assert!(
603            args.contains(&"--settings"),
604            "must have --settings (gaps.md:209)"
605        );
606        assert!(
607            args.contains(&"--output-format"),
608            "must have --output-format json (gaps.md:213)"
609        );
610        assert!(args.contains(&"--json-schema"), "must have --json-schema");
611        assert!(
612            args.contains(&"--max-turns"),
613            "must have --max-turns (gaps.md:212)"
614        );
615        assert!(
616            args.contains(&"--no-session-persistence"),
617            "must have --no-session-persistence"
618        );
619        assert!(
620            args.contains(&"--model"),
621            "must have --model when model is Some"
622        );
623        // PROHIBITED flags (gaps.md:49)
624        assert!(
625            !args.contains(&"--bare"),
626            "--bare is PROHIBITED (gaps.md:49)"
627        );
628    }
629
630    /// OAuth-only guard: when `ANTHROPIC_API_KEY` is in the environment,
631    /// `build_claude_command` MUST abort the spawn (return a `false`
632    /// command), NOT silently fall back to the API-key path.
633    #[test]
634    #[serial_test::serial(env)]
635    fn build_command_aborts_when_anthropic_api_key_set() {
636        // SAFETY: unit test
637        unsafe {
638            std::env::set_var("ANTHROPIC_API_KEY", "sk-test-violation");
639            // GAP-META-005 (v1.0.87): clear CLAUDE_CONFIG_DIR so the
640            // pre-flight check (when it does run on the abort path)
641            // does not exit 16 prematurely.
642            std::env::remove_var("CLAUDE_CONFIG_DIR");
643        }
644        let cmd = build_claude_command(
645            std::path::Path::new("/usr/bin/claude"),
646            "test prompt",
647            "{}",
648            Some("sonnet"),
649            4,
650        )
651        .expect("preflight gate accepts valid args");
652        let program = cmd.get_program().to_string_lossy().to_string();
653        let args: Vec<&str> = cmd.get_args().filter_map(|a| a.to_str()).collect();
654        assert_eq!(
655            program, "false",
656            "when ANTHROPIC_API_KEY is set, build_claude_command must abort"
657        );
658        assert!(
659            args.contains(&"--oauth-only-violation-anthropic-api-key-set"),
660            "aborted command must carry violation marker"
661        );
662        unsafe {
663            std::env::remove_var("ANTHROPIC_API_KEY");
664        }
665    }
666}