Skip to main content

claude_wrapper/command/
query.rs

1//! The `claude -p` query builder.
2//!
3//! [`QueryCommand`] is the crate's workhorse: a builder for oneshot
4//! print-mode queries covering the full `claude -p` flag surface, with
5//! typed output ([`execute`](QueryCommand::execute) /
6//! [`execute_json`](QueryCommand::execute_json)) and, under the `sync`
7//! feature, blocking peers. Spawn-time flags shared with
8//! [`DuplexOptions`](crate::duplex::DuplexOptions) live in a common
9//! internal `SharedSpawnArgs`, so the two builders cannot drift.
10
11use crate::Claude;
12use crate::command::ClaudeCommand;
13use crate::command::spawn_args::{SharedSpawnArgs, shell_quote};
14use crate::error::Result;
15use crate::exec::{self, CommandOutput};
16use crate::tool_pattern::ToolPattern;
17use crate::types::{Effort, HermeticScope, InputFormat, OutputFormat, PermissionMode};
18
19/// Builder for `claude -p <prompt>` (oneshot print-mode queries).
20///
21/// This is the primary command for programmatic use. It runs a single
22/// prompt through Claude and returns the result.
23///
24/// # Example
25///
26/// ```no_run
27/// use claude_wrapper::{Claude, ClaudeCommand, QueryCommand, OutputFormat};
28///
29/// # async fn example() -> claude_wrapper::Result<()> {
30/// let claude = Claude::builder().build()?;
31///
32/// let output = QueryCommand::new("explain this error: file not found")
33///     .model("sonnet")
34///     .output_format(OutputFormat::Json)
35///     .max_turns(1)
36///     .execute(&claude)
37///     .await?;
38/// # Ok(())
39/// # }
40/// ```
41#[derive(Debug, Clone)]
42pub struct QueryCommand {
43    prompt: String,
44    // Spawn-time knobs shared with DuplexOptions; the flag emission
45    // lives on SharedSpawnArgs so the two builders cannot drift.
46    shared: SharedSpawnArgs,
47    output_format: Option<OutputFormat>,
48    include_partial_messages: bool,
49    input_format: Option<InputFormat>,
50    retry_policy: Option<crate::retry::RetryPolicy>,
51    brief: bool,
52    from_pr: Option<String>,
53    prompt_via_stdin: bool,
54    verbose: bool,
55    prompt_suggestions: bool,
56    replay_user_messages: bool,
57}
58
59impl QueryCommand {
60    /// Create a new query command with the given prompt.
61    #[must_use]
62    pub fn new(prompt: impl Into<String>) -> Self {
63        Self {
64            prompt: prompt.into(),
65            shared: SharedSpawnArgs::default(),
66            output_format: None,
67            include_partial_messages: false,
68            input_format: None,
69            retry_policy: None,
70            brief: false,
71            from_pr: None,
72            prompt_via_stdin: false,
73            verbose: false,
74            prompt_suggestions: false,
75            replay_user_messages: false,
76        }
77    }
78
79    /// Set the model to use (e.g. "sonnet", "opus", or a full model ID).
80    #[must_use]
81    pub fn model(mut self, model: impl Into<String>) -> Self {
82        self.shared.model = Some(model.into());
83        self
84    }
85
86    /// Set a custom system prompt (replaces the default).
87    #[must_use]
88    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
89        self.shared.system_prompt = Some(prompt.into());
90        self
91    }
92
93    /// Append to the default system prompt.
94    #[must_use]
95    pub fn append_system_prompt(mut self, prompt: impl Into<String>) -> Self {
96        self.shared.append_system_prompt = Some(prompt.into());
97        self
98    }
99
100    /// Set the output format.
101    #[must_use]
102    pub fn output_format(mut self, format: OutputFormat) -> Self {
103        self.output_format = Some(format);
104        self
105    }
106
107    /// Set the maximum budget in USD.
108    #[must_use]
109    pub fn max_budget_usd(mut self, budget: f64) -> Self {
110        self.shared.max_budget_usd = Some(budget);
111        self
112    }
113
114    /// Set the permission mode.
115    #[must_use]
116    pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
117        self.shared.permission_mode = Some(mode);
118        self
119    }
120
121    /// Add allowed tool patterns.
122    ///
123    /// Accepts anything convertible into [`ToolPattern`], including
124    /// bare strings (e.g. `"Bash"`, `"Bash(git log:*)"`,
125    /// `"mcp__my-server__*"`) and values produced by
126    /// [`ToolPattern`]'s constructors.
127    ///
128    /// ```
129    /// use claude_wrapper::{QueryCommand, ToolPattern};
130    ///
131    /// let cmd = QueryCommand::new("hi")
132    ///     .allowed_tools(["Bash", "Read"]) // raw strings still work
133    ///     .allowed_tool(ToolPattern::tool_with_args("Bash", "git log:*"))
134    ///     .allowed_tool(ToolPattern::all("Write"));
135    /// ```
136    #[must_use]
137    pub fn allowed_tools<I, T>(mut self, tools: I) -> Self
138    where
139        I: IntoIterator<Item = T>,
140        T: Into<ToolPattern>,
141    {
142        self.shared
143            .allowed_tools
144            .extend(tools.into_iter().map(Into::into));
145        self
146    }
147
148    /// Add a single allowed tool pattern.
149    #[must_use]
150    pub fn allowed_tool(mut self, tool: impl Into<ToolPattern>) -> Self {
151        self.shared.allowed_tools.push(tool.into());
152        self
153    }
154
155    /// Add disallowed tool patterns.
156    #[must_use]
157    pub fn disallowed_tools<I, T>(mut self, tools: I) -> Self
158    where
159        I: IntoIterator<Item = T>,
160        T: Into<ToolPattern>,
161    {
162        self.shared
163            .disallowed_tools
164            .extend(tools.into_iter().map(Into::into));
165        self
166    }
167
168    /// Add a single disallowed tool pattern.
169    #[must_use]
170    pub fn disallowed_tool(mut self, tool: impl Into<ToolPattern>) -> Self {
171        self.shared.disallowed_tools.push(tool.into());
172        self
173    }
174
175    /// Add an MCP config file path.
176    #[must_use]
177    pub fn mcp_config(mut self, path: impl Into<String>) -> Self {
178        self.shared.mcp_config.push(path.into());
179        self
180    }
181
182    /// Add an additional directory for tool access.
183    #[must_use]
184    pub fn add_dir(mut self, dir: impl Into<String>) -> Self {
185        self.shared.add_dir.push(dir.into());
186        self
187    }
188
189    /// Set the effort level.
190    #[must_use]
191    pub fn effort(mut self, effort: Effort) -> Self {
192        self.shared.effort = Some(effort);
193        self
194    }
195
196    /// Set the maximum number of turns.
197    #[must_use]
198    pub fn max_turns(mut self, turns: u32) -> Self {
199        self.shared.max_turns = Some(turns);
200        self
201    }
202
203    /// Set a JSON schema for structured output validation.
204    #[must_use]
205    pub fn json_schema(mut self, schema: impl Into<String>) -> Self {
206        self.shared.json_schema = Some(schema.into());
207        self
208    }
209
210    /// Continue the most recent conversation.
211    #[must_use]
212    pub fn continue_session(mut self) -> Self {
213        self.shared.continue_session = true;
214        self
215    }
216
217    /// Resume a specific session by ID.
218    #[must_use]
219    pub fn resume(mut self, session_id: impl Into<String>) -> Self {
220        self.shared.resume = Some(session_id.into());
221        self
222    }
223
224    /// Use a specific session ID.
225    #[must_use]
226    pub fn session_id(mut self, id: impl Into<String>) -> Self {
227        self.shared.session_id = Some(id.into());
228        self
229    }
230
231    /// Clear every session-related flag and set `--resume` to the given id.
232    ///
233    /// Used by `Session::execute` to override whatever session flags the
234    /// caller may have set on their command (including a stale `--resume`,
235    /// `--continue`, `--session-id`, or `--fork-session`). Keeping the
236    /// override logic in one place prevents conflicting flags from reaching
237    /// the CLI.
238    #[cfg(all(feature = "json", feature = "async"))]
239    pub(crate) fn replace_session(mut self, id: impl Into<String>) -> Self {
240        self.shared.continue_session = false;
241        self.shared.resume = Some(id.into());
242        self.shared.session_id = None;
243        self.shared.fork_session = false;
244        self
245    }
246
247    /// Set a fallback model for when the primary model is overloaded.
248    #[must_use]
249    pub fn fallback_model(mut self, model: impl Into<String>) -> Self {
250        self.shared.fallback_model = Some(model.into());
251        self
252    }
253
254    /// Disable session persistence (sessions won't be saved to disk).
255    #[must_use]
256    pub fn no_session_persistence(mut self) -> Self {
257        self.shared.no_session_persistence = true;
258        self
259    }
260
261    /// Bypass all permission checks. Only use in sandboxed environments.
262    #[must_use]
263    pub fn dangerously_skip_permissions(mut self) -> Self {
264        self.shared.dangerously_skip_permissions = true;
265        self
266    }
267
268    /// Pin the session to a named subagent (`--agent <name>`).
269    ///
270    /// `name` is resolved by the CLI in this order: inline
271    /// definitions from [`Self::agents_json`], then user-level
272    /// `~/.claude/agents/<name>.md` files, then project-level dirs
273    /// loaded by the active `--setting-sources`.
274    ///
275    /// **Caveat**: as of Claude Code 2.1.143, the CLI silently
276    /// ignores an unknown `name` and falls back to the default
277    /// behavior -- no warning, no error. Callers that want a hard
278    /// "agent must exist" semantics should validate the name out of
279    /// band (e.g. via [`crate::artifacts::AgentsRoot::get`]) before
280    /// passing it here.
281    #[must_use]
282    pub fn agent(mut self, agent: impl Into<String>) -> Self {
283        self.shared.agent = Some(agent.into());
284        self
285    }
286
287    /// Inline subagent definitions for this session
288    /// (`--agents <json>`).
289    ///
290    /// `json` is a JSON object keyed by agent name, with each value
291    /// carrying at least `description` and `prompt`. Inline
292    /// definitions take precedence over on-disk
293    /// `~/.claude/agents/*.md` of the same name. Pass [`Self::agent`]
294    /// to select which one to use as the session's persona.
295    ///
296    /// Example: `{"reviewer": {"description": "Reviews code",
297    /// "prompt": "You are a code reviewer"}}`.
298    #[must_use]
299    pub fn agents_json(mut self, json: impl Into<String>) -> Self {
300        self.shared.agents_json = Some(json.into());
301        self
302    }
303
304    /// Set the list of available built-in tools.
305    ///
306    /// Use `""` to disable all tools, `"default"` for all tools, or
307    /// specific tool names like `["Bash", "Edit", "Read"]`.
308    /// This is different from `allowed_tools` which controls MCP tool permissions.
309    #[must_use]
310    pub fn tools(mut self, tools: impl IntoIterator<Item = impl Into<String>>) -> Self {
311        self.shared.tools.extend(tools.into_iter().map(Into::into));
312        self
313    }
314
315    /// Add a file resource to download at startup.
316    ///
317    /// Format: `file_id:relative_path` (e.g. `file_abc:doc.txt`).
318    #[must_use]
319    pub fn file(mut self, spec: impl Into<String>) -> Self {
320        self.shared.file.push(spec.into());
321        self
322    }
323
324    /// Include partial message chunks as they arrive.
325    ///
326    /// Only works with `--output-format stream-json`.
327    #[must_use]
328    pub fn include_partial_messages(mut self) -> Self {
329        self.include_partial_messages = true;
330        self
331    }
332
333    /// Set the input format.
334    #[must_use]
335    pub fn input_format(mut self, format: InputFormat) -> Self {
336        self.input_format = Some(format);
337        self
338    }
339
340    /// Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations.
341    #[must_use]
342    pub fn strict_mcp_config(mut self) -> Self {
343        self.shared.strict_mcp_config = true;
344        self
345    }
346
347    /// Path to a settings JSON file or a JSON string.
348    #[must_use]
349    pub fn settings(mut self, settings: impl Into<String>) -> Self {
350        self.shared.settings = Some(settings.into());
351        self
352    }
353
354    /// When resuming, create a new session ID instead of reusing the original.
355    #[must_use]
356    pub fn fork_session(mut self) -> Self {
357        self.shared.fork_session = true;
358        self
359    }
360
361    /// Create a new git worktree for this session, providing an isolated working directory.
362    #[must_use]
363    pub fn worktree(mut self) -> Self {
364        self.shared.worktree = true;
365        self
366    }
367
368    /// Create a new git worktree with an explicit name, providing an
369    /// isolated working directory.
370    ///
371    /// Equivalent to [`Self::worktree`] but emits `--worktree NAME`,
372    /// pinning the worktree's directory/branch name rather than
373    /// letting the CLI auto-generate one.
374    ///
375    /// # Example
376    ///
377    /// ```no_run
378    /// use claude_wrapper::{Claude, ClaudeCommand, QueryCommand};
379    ///
380    /// # async fn example() -> claude_wrapper::Result<()> {
381    /// let claude = Claude::builder().build()?;
382    ///
383    /// let output = QueryCommand::new("refactor the parser")
384    ///     .worktree_named("parser-refactor")
385    ///     .execute(&claude)
386    ///     .await?;
387    /// # Ok(())
388    /// # }
389    /// ```
390    #[must_use]
391    pub fn worktree_named(mut self, name: impl Into<String>) -> Self {
392        self.shared.worktree = true;
393        self.shared.worktree_name = Some(name.into());
394        self
395    }
396
397    /// Enable brief mode, which activates the SendUserMessage tool for agent-to-user communication.
398    #[must_use]
399    pub fn brief(mut self) -> Self {
400        self.brief = true;
401        self
402    }
403
404    /// Enable debug logging with an optional filter (e.g., "api,hooks").
405    #[must_use]
406    pub fn debug_filter(mut self, filter: impl Into<String>) -> Self {
407        self.shared.debug_filter = Some(filter.into());
408        self
409    }
410
411    /// Write debug logs to the specified file path.
412    #[must_use]
413    pub fn debug_file(mut self, path: impl Into<String>) -> Self {
414        self.shared.debug_file = Some(path.into());
415        self
416    }
417
418    /// Beta feature headers for API key authentication.
419    #[must_use]
420    pub fn betas(mut self, betas: impl Into<String>) -> Self {
421        self.shared.betas = Some(betas.into());
422        self
423    }
424
425    /// Load plugins from the specified directory for this session.
426    #[must_use]
427    pub fn plugin_dir(mut self, dir: impl Into<String>) -> Self {
428        self.shared.plugin_dirs.push(dir.into());
429        self
430    }
431
432    /// Fetch a plugin `.zip` from a URL for this session only
433    /// (`--plugin-url`). Repeatable; the URL-based counterpart to
434    /// [`Self::plugin_dir`].
435    #[must_use]
436    pub fn plugin_url(mut self, url: impl Into<String>) -> Self {
437        self.shared.plugin_urls.push(url.into());
438        self
439    }
440
441    /// Comma-separated list of setting sources to load (e.g., "user,project,local").
442    #[must_use]
443    pub fn setting_sources(mut self, sources: impl Into<String>) -> Self {
444        self.shared.setting_sources = Some(sources.into());
445        self
446    }
447
448    /// Seal the ambient `~/.claude` config for a reproducible run
449    /// ([`HermeticScope::Full`]).
450    ///
451    /// Equivalent to `hermetic_scoped(HermeticScope::Full)`: drops all
452    /// ambient setting sources (`--setting-sources ""`), restricts MCP
453    /// to `--mcp-config` servers (`--strict-mcp-config`), and moves
454    /// per-machine sections out of the system prompt
455    /// (`--exclude-dynamic-system-prompt-sections`). Provide everything
456    /// the run needs explicitly via [`Self::append_system_prompt`],
457    /// [`Self::mcp_config`], [`Self::add_dir`], and friends.
458    ///
459    /// This is not [`Self::bare`]: a hermetic seal leaves OAuth and
460    /// keychain auth working, whereas `--bare` forces API-key billing.
461    /// A later [`Self::setting_sources`] call overrides the seal scope.
462    #[must_use]
463    pub fn hermetic(mut self) -> Self {
464        self.shared.apply_hermetic(HermeticScope::Full);
465        self
466    }
467
468    /// Seal the ambient `~/.claude` config at an explicit
469    /// [`HermeticScope`].
470    ///
471    /// See [`Self::hermetic`] for the flag set. Use
472    /// [`HermeticScope::Project`] to keep the user's global `~/.claude`
473    /// while sealing project and local ambient config.
474    #[must_use]
475    pub fn hermetic_scoped(mut self, scope: HermeticScope) -> Self {
476        self.shared.apply_hermetic(scope);
477        self
478    }
479
480    /// Create a tmux session for the worktree.
481    #[must_use]
482    pub fn tmux(mut self) -> Self {
483        self.shared.tmux = true;
484        self
485    }
486
487    /// Run in minimal mode (`--bare`).
488    ///
489    /// Skips hooks, LSP, plugin sync, attribution, auto-memory,
490    /// background prefetches, keychain reads, and CLAUDE.md
491    /// auto-discovery. Sets `CLAUDE_CODE_SIMPLE=1` inside the child.
492    /// Anthropic auth is restricted to `ANTHROPIC_API_KEY` or
493    /// `apiKeyHelper` via `--settings`; OAuth and keychain are never
494    /// read. Third-party providers (Bedrock/Vertex/Foundry) use their
495    /// own credentials as normal.
496    ///
497    /// Intended for headless/CI use where you want deterministic
498    /// context: provide everything explicitly via `--system-prompt`,
499    /// `--append-system-prompt`, `--add-dir`, `--mcp-config`,
500    /// `--settings`, `--agents`, and `--plugin-dir`. Skills still
501    /// resolve via explicit `/skill-name` references.
502    #[must_use]
503    pub fn bare(mut self) -> Self {
504        self.shared.bare = true;
505        self
506    }
507
508    /// Disable all slash-command skills (`--disable-slash-commands`).
509    #[must_use]
510    pub fn disable_slash_commands(mut self) -> Self {
511        self.shared.disable_slash_commands = true;
512        self
513    }
514
515    /// Start with all customizations disabled (`--safe-mode`).
516    ///
517    /// Disables CLAUDE.md, skills, plugins, hooks, MCP servers, custom
518    /// commands and agents, output styles, and other customizations for
519    /// troubleshooting a broken configuration. Admin-managed (policy)
520    /// settings still apply. Auth, model selection, built-in tools, and
521    /// permissions work normally. Sets `CLAUDE_CODE_SAFE_MODE=1` inside
522    /// the child.
523    #[must_use]
524    pub fn safe_mode(mut self) -> Self {
525        self.shared.safe_mode = true;
526        self
527    }
528
529    /// Include every hook lifecycle event in the stream-json output
530    /// (`--include-hook-events`). Only meaningful with
531    /// `OutputFormat::StreamJson`.
532    #[must_use]
533    pub fn include_hook_events(mut self) -> Self {
534        self.shared.include_hook_events = true;
535        self
536    }
537
538    /// Move per-machine sections (cwd, env info, memory paths, git
539    /// status) out of the system prompt and into the first user
540    /// message (`--exclude-dynamic-system-prompt-sections`). Improves
541    /// cross-user prompt-cache reuse. Only applies with the default
542    /// system prompt; ignored with `--system-prompt`.
543    #[must_use]
544    pub fn exclude_dynamic_system_prompt_sections(mut self) -> Self {
545        self.shared.exclude_dynamic_system_prompt_sections = true;
546        self
547    }
548
549    /// Set a display name for this session (`--name`). Shown in the
550    /// prompt box, `/resume` picker, and terminal title.
551    #[must_use]
552    pub fn name(mut self, name: impl Into<String>) -> Self {
553        self.shared.name = Some(name.into());
554        self
555    }
556
557    /// Resume a session linked to a PR by number or URL
558    /// (`--from-pr <value>`).
559    ///
560    /// This wrapper only supports the valued form; the CLI's
561    /// no-value mode opens an interactive picker and would hang a
562    /// headless caller.
563    #[must_use]
564    pub fn from_pr(mut self, pr: impl Into<String>) -> Self {
565        self.from_pr = Some(pr.into());
566        self
567    }
568
569    /// Enable verbose logging (`--verbose`), overriding the CLI's
570    /// configured verbose-mode setting.
571    ///
572    /// Note: [`OutputFormat::StreamJson`] already forces `--verbose`
573    /// on (the CLI requires it alongside `--print`), so this builder
574    /// only changes behavior for the text and JSON output formats.
575    /// Either path emits the flag at most once.
576    #[must_use]
577    pub fn verbose(mut self, value: bool) -> Self {
578        self.verbose = value;
579        self
580    }
581
582    /// Emit a predicted next-user-prompt after each turn
583    /// (`--prompt-suggestions`).
584    ///
585    /// In print/SDK mode the CLI emits a `prompt_suggestion` message
586    /// alongside the normal result. Off by default.
587    #[must_use]
588    pub fn prompt_suggestions(mut self, value: bool) -> Self {
589        self.prompt_suggestions = value;
590        self
591    }
592
593    /// Re-emit user messages from stdin back on stdout
594    /// (`--replay-user-messages`).
595    ///
596    /// Only meaningful for bidirectional stream-json flows: the CLI
597    /// requires both [`InputFormat::StreamJson`] and
598    /// [`OutputFormat::StreamJson`] for this to take effect. Off by
599    /// default.
600    #[must_use]
601    pub fn replay_user_messages(mut self, value: bool) -> Self {
602        self.replay_user_messages = value;
603        self
604    }
605
606    /// Set a per-command retry policy, overriding the client default.
607    ///
608    /// # Example
609    ///
610    /// ```no_run
611    /// use claude_wrapper::{Claude, ClaudeCommand, QueryCommand, RetryPolicy};
612    /// use std::time::Duration;
613    ///
614    /// # async fn example() -> claude_wrapper::Result<()> {
615    /// let claude = Claude::builder().build()?;
616    ///
617    /// let output = QueryCommand::new("explain quicksort")
618    ///     .retry(RetryPolicy::new()
619    ///         .max_attempts(5)
620    ///         .initial_backoff(Duration::from_secs(2))
621    ///         .exponential()
622    ///         .retry_on_timeout(true))
623    ///     .execute(&claude)
624    ///     .await?;
625    /// # Ok(())
626    /// # }
627    /// ```
628    #[must_use]
629    pub fn retry(mut self, policy: crate::retry::RetryPolicy) -> Self {
630        self.retry_policy = Some(policy);
631        self
632    }
633
634    /// Return the full command as a string that could be run in a shell.
635    ///
636    /// Constructs a command string using the binary path from the Claude instance,
637    /// the client's global args, and the arguments from this query -- the same
638    /// assembly the exec path performs, so the preview matches what actually
639    /// runs. Arguments containing spaces or special shell characters are
640    /// shell-quoted to be safe for shell execution.
641    ///
642    /// # Example
643    ///
644    /// ```no_run
645    /// use claude_wrapper::{Claude, QueryCommand};
646    ///
647    /// # async fn example() -> claude_wrapper::Result<()> {
648    /// let claude = Claude::builder().build()?;
649    ///
650    /// let cmd = QueryCommand::new("explain quicksort")
651    ///     .model("sonnet");
652    ///
653    /// let command_str = cmd.to_command_string(&claude);
654    /// println!("Would run: {}", command_str);
655    /// # Ok(())
656    /// # }
657    /// ```
658    pub fn to_command_string(&self, claude: &Claude) -> String {
659        let args = exec::full_command_args(claude, self.build_args());
660        let quoted_args = args.iter().map(|arg| shell_quote(arg)).collect::<Vec<_>>();
661        format!("{} {}", claude.binary().display(), quoted_args.join(" "))
662    }
663
664    /// Execute the query and parse the JSON result.
665    ///
666    /// This is a convenience method that sets `OutputFormat::Json` and
667    /// deserializes the response into a [`QueryResult`](crate::types::QueryResult).
668    #[cfg(all(feature = "json", feature = "async"))]
669    pub async fn execute_json(&self, claude: &Claude) -> Result<crate::types::QueryResult> {
670        let args = self.build_args_with_forced_json();
671
672        let output = if self.prompt_via_stdin {
673            // Retry is skipped for stdin mode: the stdin pipe is consumed
674            // after the first attempt and cannot be rewound.
675            exec::run_claude_with_stdin_prompt(claude, args, self.prompt.clone()).await?
676        } else {
677            exec::run_claude_with_retry(claude, args, self.retry_policy.as_ref()).await?
678        };
679
680        serde_json::from_str(&output.stdout).map_err(|e| crate::error::Error::Json {
681            message: format!("failed to parse query result: {e}"),
682            source: e,
683        })
684    }
685
686    /// Blocking analog of [`QueryCommand::execute`] that honours the
687    /// configured [`RetryPolicy`](crate::retry::RetryPolicy).
688    ///
689    /// Overrides the blanket
690    /// [`ClaudeCommandSyncExt::execute_sync`](crate::ClaudeCommandSyncExt)
691    /// impl so retries still fire on the sync path.
692    #[cfg(feature = "sync")]
693    pub fn execute_sync(&self, claude: &Claude) -> Result<CommandOutput> {
694        if self.prompt_via_stdin {
695            // Retry is skipped for stdin mode: the stdin pipe is consumed
696            // after the first attempt and cannot be rewound.
697            exec::run_claude_with_stdin_prompt_sync(claude, self.build_args(), self.prompt.clone())
698        } else {
699            exec::run_claude_with_retry_sync(claude, self.args(), self.retry_policy.as_ref())
700        }
701    }
702
703    /// Blocking mirror of [`QueryCommand::execute_json`].
704    #[cfg(all(feature = "sync", feature = "json"))]
705    pub fn execute_json_sync(&self, claude: &Claude) -> Result<crate::types::QueryResult> {
706        let args = self.build_args_with_forced_json();
707
708        let output = if self.prompt_via_stdin {
709            // Retry is skipped for stdin mode: the stdin pipe is consumed
710            // after the first attempt and cannot be rewound.
711            exec::run_claude_with_stdin_prompt_sync(claude, args, self.prompt.clone())?
712        } else {
713            exec::run_claude_with_retry_sync(claude, args, self.retry_policy.as_ref())?
714        };
715
716        serde_json::from_str(&output.stdout).map_err(|e| crate::error::Error::Json {
717            message: format!("failed to parse query result: {e}"),
718            source: e,
719        })
720    }
721
722    /// Route the prompt through stdin rather than argv.
723    ///
724    /// When set, the prompt body does not appear in the spawned
725    /// process's argument list (`ps`, `/proc/PID/cmdline`, APM
726    /// agents). Use this for any prompt that contains sensitive
727    /// content: private code, internal design notes, orchestrator
728    /// dispatch specs.
729    ///
730    /// Requires that `claude --print` read from stdin when no
731    /// positional prompt is supplied (verified as of claude 2.1.x).
732    ///
733    /// Note: retry is skipped when stdin mode is active -- the stdin
734    /// pipe is consumed after the first attempt and cannot be rewound.
735    ///
736    /// # Example
737    /// ```no_run
738    /// use claude_wrapper::{Claude, ClaudeCommand, QueryCommand};
739    /// # async fn example() -> claude_wrapper::Result<()> {
740    /// let claude = Claude::builder().build()?;
741    /// let out = QueryCommand::new("my secret prompt")
742    ///     .prompt_via_stdin(true)
743    ///     .execute(&claude)
744    ///     .await?;
745    /// # Ok(()) }
746    /// ```
747    #[must_use]
748    pub fn prompt_via_stdin(mut self, value: bool) -> Self {
749        self.prompt_via_stdin = value;
750        self
751    }
752
753    /// Like [`Self::build_args`], but if `output_format` is unset on
754    /// this command, force it to `json`. The naive approach -- call
755    /// `build_args` then `args.push("--output-format")` -- breaks
756    /// because `build_args` already appended `--` and the prompt at
757    /// the end, so the late flag becomes positional and is eaten as
758    /// part of the prompt. We clone-and-set instead so the flag
759    /// lands in its proper slot before `--`.
760    fn build_args_with_forced_json(&self) -> Vec<String> {
761        if self.output_format.is_some() {
762            return self.build_args();
763        }
764        let mut effective = self.clone();
765        effective.output_format = Some(OutputFormat::Json);
766        effective.build_args()
767    }
768
769    fn build_args(&self) -> Vec<String> {
770        let mut args = vec!["--print".to_string()];
771
772        if let Some(ref format) = self.output_format {
773            args.push("--output-format".to_string());
774            args.push(format.as_arg().to_string());
775        }
776
777        // --verbose: explicit opt-in via `.verbose(true)`, or forced
778        // for stream-json (CLI v2.1.72+ requires it with --print).
779        // Emitted once so the two paths can't double up the flag.
780        if self.verbose || matches!(self.output_format, Some(OutputFormat::StreamJson)) {
781            args.push("--verbose".to_string());
782        }
783
784        self.shared.append_to(&mut args);
785
786        if self.include_partial_messages {
787            args.push("--include-partial-messages".to_string());
788        }
789
790        if let Some(ref format) = self.input_format {
791            args.push("--input-format".to_string());
792            args.push(format.as_arg().to_string());
793        }
794
795        if self.brief {
796            args.push("--brief".to_string());
797        }
798
799        if self.prompt_suggestions {
800            args.push("--prompt-suggestions".to_string());
801        }
802
803        if self.replay_user_messages {
804            args.push("--replay-user-messages".to_string());
805        }
806
807        if let Some(ref pr) = self.from_pr {
808            args.push("--from-pr".to_string());
809            args.push(pr.clone());
810        }
811
812        // Separator to prevent flags like --allowed-tools from consuming the prompt.
813        // When prompt_via_stdin is set, the prompt is sent via stdin after spawn
814        // rather than appearing in argv (avoids ps/APM/crash-dump leakage).
815        if !self.prompt_via_stdin {
816            args.push("--".to_string());
817            args.push(self.prompt.clone());
818        }
819
820        args
821    }
822}
823
824impl ClaudeCommand for QueryCommand {
825    type Output = CommandOutput;
826
827    fn args(&self) -> Vec<String> {
828        self.build_args()
829    }
830
831    #[cfg(feature = "async")]
832    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
833        if self.prompt_via_stdin {
834            // Retry is skipped for stdin mode: the stdin pipe is consumed
835            // after the first attempt and cannot be rewound.
836            let args = self.build_args(); // prompt not in args
837            exec::run_claude_with_stdin_prompt(claude, args, self.prompt.clone()).await
838        } else {
839            exec::run_claude_with_retry(claude, self.args(), self.retry_policy.as_ref()).await
840        }
841    }
842}
843
844#[cfg(test)]
845mod tests {
846    use super::*;
847
848    #[test]
849    fn test_basic_query_args() {
850        let cmd = QueryCommand::new("hello world");
851        let args = cmd.args();
852        assert_eq!(args, vec!["--print", "--", "hello world"]);
853    }
854
855    #[test]
856    fn prompt_via_stdin_omits_prompt_from_args() {
857        let cmd = QueryCommand::new("secret payload").prompt_via_stdin(true);
858        let args = cmd.args();
859        assert!(
860            !args.contains(&"secret payload".to_string()),
861            "prompt must not appear in args when prompt_via_stdin is set"
862        );
863        assert!(
864            !args.contains(&"--".to_string()),
865            "-- separator must be absent when prompt_via_stdin is set"
866        );
867    }
868
869    #[test]
870    fn prompt_via_stdin_false_keeps_prompt_in_args() {
871        let cmd = QueryCommand::new("visible prompt").prompt_via_stdin(false);
872        let args = cmd.args();
873        assert!(
874            args.contains(&"visible prompt".to_string()),
875            "prompt must still appear in args when prompt_via_stdin is false"
876        );
877        assert!(
878            args.contains(&"--".to_string()),
879            "-- separator must be present when prompt_via_stdin is false"
880        );
881    }
882
883    #[test]
884    #[cfg(feature = "async")] // uses tokio + the async-only execute()
885    #[ignore = "requires a real claude binary"]
886    fn prompt_via_stdin_integration() {
887        // Verify round-trip: prompt sent via stdin produces a valid response.
888        // Run with: cargo test --lib -p claude-wrapper -- --ignored prompt_via_stdin_integration
889        use crate::{Claude, ClaudeCommand};
890        let rt = tokio::runtime::Runtime::new().unwrap();
891        rt.block_on(async {
892            let claude = Claude::builder().build().unwrap();
893            let out = QueryCommand::new("reply with: STDIN_OK")
894                .prompt_via_stdin(true)
895                .execute(&claude)
896                .await
897                .unwrap();
898            assert!(
899                !out.stdout.is_empty(),
900                "expected non-empty output from stdin-mode query"
901            );
902        });
903    }
904
905    #[test]
906    fn build_args_with_forced_json_inserts_flag_before_separator() {
907        // Regression: prior to this fix, execute_json appended
908        // --output-format json AFTER build_args's `-- prompt` tail,
909        // so the flag was treated as positional and eaten as part
910        // of the prompt. With the fix the flag must land BEFORE the
911        // `--` separator.
912        let cmd = QueryCommand::new("hello");
913        let args = cmd.build_args_with_forced_json();
914
915        // The trailing pair must still be the separator + prompt.
916        assert_eq!(
917            &args[args.len() - 2..],
918            &["--".to_string(), "hello".to_string()],
919        );
920
921        // --output-format json must appear BEFORE `--`.
922        let sep = args.iter().position(|a| a == "--").expect("`--` present");
923        let fmt = args
924            .iter()
925            .position(|a| a == "--output-format")
926            .expect("--output-format present");
927        assert!(
928            fmt < sep,
929            "--output-format must come before `--` separator; got {args:?}"
930        );
931        assert_eq!(args[fmt + 1], "json");
932    }
933
934    #[test]
935    fn build_args_with_forced_json_respects_explicit_format() {
936        // If the caller already set output_format on the builder,
937        // the helper must NOT override it.
938        let cmd = QueryCommand::new("hello").output_format(OutputFormat::Text);
939        let args = cmd.build_args_with_forced_json();
940        let fmt = args
941            .iter()
942            .position(|a| a == "--output-format")
943            .expect("--output-format present");
944        assert_eq!(args[fmt + 1], "text");
945        // Just one occurrence -- not double-pushed.
946        assert_eq!(args.iter().filter(|a| *a == "--output-format").count(), 1);
947    }
948
949    #[test]
950    #[allow(deprecated)] // exercises PermissionMode::BypassPermissions directly; prefer dangerous::DangerousClient in new code
951    fn test_full_query_args() {
952        let cmd = QueryCommand::new("explain this")
953            .model("sonnet")
954            .system_prompt("be concise")
955            .output_format(OutputFormat::Json)
956            .max_budget_usd(0.50)
957            .permission_mode(PermissionMode::BypassPermissions)
958            .allowed_tools(["Bash", "Read"])
959            .mcp_config("/tmp/mcp.json")
960            .effort(Effort::High)
961            .max_turns(3)
962            .no_session_persistence();
963
964        let args = cmd.args();
965        assert!(args.contains(&"--print".to_string()));
966        assert!(args.contains(&"--model".to_string()));
967        assert!(args.contains(&"sonnet".to_string()));
968        assert!(args.contains(&"--system-prompt".to_string()));
969        assert!(args.contains(&"--output-format".to_string()));
970        assert!(args.contains(&"json".to_string()));
971        // json format should NOT include --verbose (only stream-json needs it)
972        assert!(!args.contains(&"--verbose".to_string()));
973        assert!(args.contains(&"--max-budget-usd".to_string()));
974        assert!(args.contains(&"--permission-mode".to_string()));
975        assert!(args.contains(&"bypassPermissions".to_string()));
976        assert!(args.contains(&"--allowed-tools".to_string()));
977        assert!(args.contains(&"Bash,Read".to_string()));
978        assert!(args.contains(&"--effort".to_string()));
979        assert!(args.contains(&"high".to_string()));
980        assert!(args.contains(&"--max-turns".to_string()));
981        assert!(args.contains(&"--no-session-persistence".to_string()));
982        // Prompt is last, preceded by -- separator
983        assert_eq!(args.last().unwrap(), "explain this");
984        assert_eq!(args[args.len() - 2], "--");
985    }
986
987    #[test]
988    fn typed_patterns_render_in_allowed_tools() {
989        use crate::ToolPattern;
990
991        let cmd = QueryCommand::new("hi")
992            .allowed_tool(ToolPattern::tool("Read"))
993            .allowed_tool(ToolPattern::tool_with_args("Bash", "git log:*"))
994            .allowed_tool(ToolPattern::all("Write"))
995            .allowed_tool(ToolPattern::mcp("srv", "*"));
996
997        let args = cmd.args();
998        let joined = args
999            .iter()
1000            .position(|a| a == "--allowed-tools")
1001            .map(|i| &args[i + 1])
1002            .unwrap();
1003        assert_eq!(joined, "Read,Bash(git log:*),Write(*),mcp__srv__*");
1004    }
1005
1006    #[test]
1007    fn disallowed_tool_singular_appends() {
1008        use crate::ToolPattern;
1009
1010        let cmd = QueryCommand::new("hi")
1011            .disallowed_tool("Write")
1012            .disallowed_tool(ToolPattern::tool_with_args("Bash", "rm*"));
1013
1014        let args = cmd.args();
1015        let joined = args
1016            .iter()
1017            .position(|a| a == "--disallowed-tools")
1018            .map(|i| &args[i + 1])
1019            .unwrap();
1020        assert_eq!(joined, "Write,Bash(rm*)");
1021    }
1022
1023    #[test]
1024    fn mixed_string_and_typed_patterns_both_accepted() {
1025        use crate::ToolPattern;
1026
1027        // Smoke test for API ergonomics: one plural call with mixed
1028        // inputs should compile even though the builder is generic
1029        // over T: Into<ToolPattern>.
1030        let strs: Vec<ToolPattern> = vec!["Bash".into(), ToolPattern::all("Read")];
1031        let cmd = QueryCommand::new("hi").allowed_tools(strs);
1032        assert!(cmd.args().contains(&"--allowed-tools".to_string()));
1033    }
1034
1035    #[test]
1036    fn new_bool_flags_emit_correct_cli_args() {
1037        let args = QueryCommand::new("hi")
1038            .bare()
1039            .disable_slash_commands()
1040            .include_hook_events()
1041            .exclude_dynamic_system_prompt_sections()
1042            .args();
1043        assert!(args.contains(&"--bare".to_string()));
1044        assert!(args.contains(&"--disable-slash-commands".to_string()));
1045        assert!(args.contains(&"--include-hook-events".to_string()));
1046        assert!(args.contains(&"--exclude-dynamic-system-prompt-sections".to_string()));
1047    }
1048
1049    #[test]
1050    fn name_flag_renders_with_value() {
1051        let args = QueryCommand::new("hi").name("my session").args();
1052        let pos = args.iter().position(|a| a == "--name").unwrap();
1053        assert_eq!(args[pos + 1], "my session");
1054    }
1055
1056    #[test]
1057    fn from_pr_flag_renders_with_value() {
1058        let args = QueryCommand::new("hi").from_pr("42").args();
1059        let pos = args.iter().position(|a| a == "--from-pr").unwrap();
1060        assert_eq!(args[pos + 1], "42");
1061    }
1062
1063    #[test]
1064    fn new_bool_flags_default_to_off() {
1065        let args = QueryCommand::new("hi").args();
1066        assert!(!args.contains(&"--bare".to_string()));
1067        assert!(!args.contains(&"--disable-slash-commands".to_string()));
1068        assert!(!args.contains(&"--include-hook-events".to_string()));
1069        assert!(!args.contains(&"--exclude-dynamic-system-prompt-sections".to_string()));
1070        assert!(!args.contains(&"--name".to_string()));
1071    }
1072
1073    #[test]
1074    fn test_separator_before_prompt_prevents_greedy_flag_parsing() {
1075        // Regression: --allowed-tools was consuming the prompt as a tool name
1076        // when the prompt appeared after it without a -- separator.
1077        let cmd = QueryCommand::new("fix the bug")
1078            .allowed_tools(["Read", "Edit", "Bash(cargo *)"])
1079            .output_format(OutputFormat::StreamJson);
1080        let args = cmd.args();
1081        // -- separator must appear before the prompt
1082        let sep_pos = args.iter().position(|a| a == "--").unwrap();
1083        let prompt_pos = args.iter().position(|a| a == "fix the bug").unwrap();
1084        assert_eq!(prompt_pos, sep_pos + 1, "prompt must follow -- separator");
1085        // --allowed-tools value must appear before the separator
1086        let tools_pos = args
1087            .iter()
1088            .position(|a| a.contains("Bash(cargo *)"))
1089            .unwrap();
1090        assert!(
1091            tools_pos < sep_pos,
1092            "allowed-tools must come before -- separator"
1093        );
1094    }
1095
1096    #[test]
1097    fn test_stream_json_includes_verbose() {
1098        let cmd = QueryCommand::new("test").output_format(OutputFormat::StreamJson);
1099        let args = cmd.args();
1100        assert!(args.contains(&"--output-format".to_string()));
1101        assert!(args.contains(&"stream-json".to_string()));
1102        assert!(args.contains(&"--verbose".to_string()));
1103    }
1104
1105    #[test]
1106    fn verbose_flag_emitted_when_set() {
1107        let args = QueryCommand::new("test").verbose(true).args();
1108        assert!(args.contains(&"--verbose".to_string()));
1109    }
1110
1111    #[test]
1112    fn verbose_absent_by_default_and_when_false() {
1113        assert!(
1114            !QueryCommand::new("test")
1115                .args()
1116                .contains(&"--verbose".to_string())
1117        );
1118        assert!(
1119            !QueryCommand::new("test")
1120                .verbose(false)
1121                .args()
1122                .contains(&"--verbose".to_string())
1123        );
1124    }
1125
1126    #[test]
1127    fn verbose_not_duplicated_with_stream_json() {
1128        // stream-json forces --verbose; an explicit .verbose(true) must
1129        // not push a second copy.
1130        let cmd = QueryCommand::new("test")
1131            .verbose(true)
1132            .output_format(OutputFormat::StreamJson);
1133        let count = cmd.args().iter().filter(|a| *a == "--verbose").count();
1134        assert_eq!(count, 1, "--verbose must appear exactly once");
1135    }
1136
1137    #[test]
1138    fn prompt_suggestions_flag_emitted_when_set() {
1139        let args = QueryCommand::new("test").prompt_suggestions(true).args();
1140        assert!(args.contains(&"--prompt-suggestions".to_string()));
1141        // Must land before the `--` separator, not be eaten as part of
1142        // the prompt.
1143        let sep = args.iter().position(|a| a == "--").unwrap();
1144        let flag = args
1145            .iter()
1146            .position(|a| a == "--prompt-suggestions")
1147            .unwrap();
1148        assert!(flag < sep, "--prompt-suggestions must precede `--`");
1149    }
1150
1151    #[test]
1152    fn prompt_suggestions_absent_by_default_and_when_false() {
1153        assert!(
1154            !QueryCommand::new("test")
1155                .args()
1156                .contains(&"--prompt-suggestions".to_string())
1157        );
1158        assert!(
1159            !QueryCommand::new("test")
1160                .prompt_suggestions(false)
1161                .args()
1162                .contains(&"--prompt-suggestions".to_string())
1163        );
1164    }
1165
1166    #[test]
1167    fn replay_user_messages_flag_emitted_when_set() {
1168        let args = QueryCommand::new("test").replay_user_messages(true).args();
1169        assert!(args.contains(&"--replay-user-messages".to_string()));
1170    }
1171
1172    #[test]
1173    fn replay_user_messages_absent_by_default_and_when_false() {
1174        assert!(
1175            !QueryCommand::new("test")
1176                .args()
1177                .contains(&"--replay-user-messages".to_string())
1178        );
1179        assert!(
1180            !QueryCommand::new("test")
1181                .replay_user_messages(false)
1182                .args()
1183                .contains(&"--replay-user-messages".to_string())
1184        );
1185    }
1186
1187    #[test]
1188    fn test_to_command_string_simple() {
1189        let claude = Claude::builder()
1190            .binary("/usr/local/bin/claude")
1191            .build()
1192            .unwrap();
1193
1194        let cmd = QueryCommand::new("hello");
1195        let command_str = cmd.to_command_string(&claude);
1196
1197        assert!(command_str.starts_with("/usr/local/bin/claude"));
1198        assert!(command_str.contains("--print"));
1199        assert!(command_str.contains("hello"));
1200    }
1201
1202    #[test]
1203    fn test_to_command_string_with_spaces() {
1204        let claude = Claude::builder()
1205            .binary("/usr/local/bin/claude")
1206            .build()
1207            .unwrap();
1208
1209        let cmd = QueryCommand::new("hello world").model("sonnet");
1210        let command_str = cmd.to_command_string(&claude);
1211
1212        assert!(command_str.starts_with("/usr/local/bin/claude"));
1213        assert!(command_str.contains("--print"));
1214        // Prompt with spaces should be quoted
1215        assert!(command_str.contains("'hello world'"));
1216        assert!(command_str.contains("--model"));
1217        assert!(command_str.contains("sonnet"));
1218    }
1219
1220    #[test]
1221    fn test_to_command_string_with_special_chars() {
1222        let claude = Claude::builder()
1223            .binary("/usr/local/bin/claude")
1224            .build()
1225            .unwrap();
1226
1227        let cmd = QueryCommand::new("test $VAR and `cmd`");
1228        let command_str = cmd.to_command_string(&claude);
1229
1230        // Arguments with special shell characters should be quoted
1231        assert!(command_str.contains("'test $VAR and `cmd`'"));
1232    }
1233
1234    #[test]
1235    fn test_to_command_string_with_single_quotes() {
1236        let claude = Claude::builder()
1237            .binary("/usr/local/bin/claude")
1238            .build()
1239            .unwrap();
1240
1241        let cmd = QueryCommand::new("it's");
1242        let command_str = cmd.to_command_string(&claude);
1243
1244        // Single quotes should be escaped in shell
1245        assert!(command_str.contains("'it'\\''s'"));
1246    }
1247
1248    #[test]
1249    fn to_command_string_includes_global_args() {
1250        // The exec path prepends the client's global args; the preview
1251        // must show them too (#705).
1252        let claude = Claude::builder()
1253            .binary("/usr/local/bin/claude")
1254            .arg("--debug")
1255            .build()
1256            .unwrap();
1257
1258        let command_str = QueryCommand::new("hello").to_command_string(&claude);
1259
1260        assert!(
1261            command_str.starts_with("/usr/local/bin/claude --debug --print"),
1262            "global args must precede command args; got {command_str}"
1263        );
1264    }
1265
1266    #[test]
1267    fn test_worktree_flag() {
1268        let cmd = QueryCommand::new("test").worktree();
1269        let args = cmd.args();
1270        assert!(args.contains(&"--worktree".to_string()));
1271    }
1272
1273    #[test]
1274    fn test_worktree_named() {
1275        let cmd = QueryCommand::new("test").worktree_named("feature-x");
1276        let args = cmd.args();
1277        assert!(
1278            args.windows(2).any(|w| w == ["--worktree", "feature-x"]),
1279            "missing --worktree feature-x in {args:?}"
1280        );
1281    }
1282
1283    #[test]
1284    fn test_brief_flag() {
1285        let cmd = QueryCommand::new("test").brief();
1286        let args = cmd.args();
1287        assert!(args.contains(&"--brief".to_string()));
1288    }
1289
1290    #[test]
1291    fn test_debug_filter() {
1292        let cmd = QueryCommand::new("test").debug_filter("api,hooks");
1293        let args = cmd.args();
1294        assert!(args.contains(&"--debug".to_string()));
1295        assert!(args.contains(&"api,hooks".to_string()));
1296    }
1297
1298    #[test]
1299    fn test_debug_file() {
1300        let cmd = QueryCommand::new("test").debug_file("/tmp/debug.log");
1301        let args = cmd.args();
1302        assert!(args.contains(&"--debug-file".to_string()));
1303        assert!(args.contains(&"/tmp/debug.log".to_string()));
1304    }
1305
1306    #[test]
1307    fn test_betas() {
1308        let cmd = QueryCommand::new("test").betas("feature-x");
1309        let args = cmd.args();
1310        assert!(args.contains(&"--betas".to_string()));
1311        assert!(args.contains(&"feature-x".to_string()));
1312    }
1313
1314    #[test]
1315    fn test_plugin_dir_single() {
1316        let cmd = QueryCommand::new("test").plugin_dir("/plugins/foo");
1317        let args = cmd.args();
1318        assert!(args.contains(&"--plugin-dir".to_string()));
1319        assert!(args.contains(&"/plugins/foo".to_string()));
1320    }
1321
1322    #[test]
1323    fn test_plugin_dir_multiple() {
1324        let cmd = QueryCommand::new("test")
1325            .plugin_dir("/plugins/foo")
1326            .plugin_dir("/plugins/bar");
1327        let args = cmd.args();
1328        let plugin_dir_count = args.iter().filter(|a| *a == "--plugin-dir").count();
1329        assert_eq!(plugin_dir_count, 2);
1330        assert!(args.contains(&"/plugins/foo".to_string()));
1331        assert!(args.contains(&"/plugins/bar".to_string()));
1332    }
1333
1334    #[test]
1335    fn test_plugin_url_single() {
1336        let cmd = QueryCommand::new("test").plugin_url("https://example.com/p.zip");
1337        let args = cmd.args();
1338        assert!(args.contains(&"--plugin-url".to_string()));
1339        assert!(args.contains(&"https://example.com/p.zip".to_string()));
1340    }
1341
1342    #[test]
1343    fn test_plugin_url_multiple() {
1344        let cmd = QueryCommand::new("test")
1345            .plugin_url("https://example.com/a.zip")
1346            .plugin_url("https://example.com/b.zip");
1347        let args = cmd.args();
1348        let plugin_url_count = args.iter().filter(|a| *a == "--plugin-url").count();
1349        assert_eq!(plugin_url_count, 2);
1350        assert!(args.contains(&"https://example.com/a.zip".to_string()));
1351        assert!(args.contains(&"https://example.com/b.zip".to_string()));
1352    }
1353
1354    #[test]
1355    fn test_safe_mode_flag() {
1356        let cmd = QueryCommand::new("test").safe_mode();
1357        let args = cmd.args();
1358        assert!(args.contains(&"--safe-mode".to_string()));
1359    }
1360
1361    #[test]
1362    fn test_safe_mode_absent_by_default() {
1363        let cmd = QueryCommand::new("test");
1364        let args = cmd.args();
1365        assert!(!args.contains(&"--safe-mode".to_string()));
1366    }
1367
1368    #[test]
1369    fn hermetic_emits_full_seal_flags() {
1370        let args = QueryCommand::new("test").hermetic().args();
1371        assert!(
1372            args.windows(2)
1373                .any(|w| w[0] == "--setting-sources" && w[1].is_empty()),
1374            "got {args:?}"
1375        );
1376        assert!(args.contains(&"--strict-mcp-config".to_string()));
1377        assert!(args.contains(&"--exclude-dynamic-system-prompt-sections".to_string()));
1378        assert!(!args.contains(&"--bare".to_string()));
1379    }
1380
1381    #[test]
1382    fn hermetic_scoped_project_keeps_user() {
1383        let args = QueryCommand::new("test")
1384            .hermetic_scoped(HermeticScope::Project)
1385            .args();
1386        assert!(args.windows(2).any(|w| w == ["--setting-sources", "user"]));
1387        assert!(args.contains(&"--strict-mcp-config".to_string()));
1388    }
1389
1390    #[test]
1391    fn setting_sources_overrides_hermetic_scope() {
1392        // The escape hatch: a later setting_sources call wins over the
1393        // scope the hermetic preset chose.
1394        let args = QueryCommand::new("test")
1395            .hermetic()
1396            .setting_sources("user,project")
1397            .args();
1398        assert!(
1399            args.windows(2)
1400                .any(|w| w == ["--setting-sources", "user,project"]),
1401            "got {args:?}"
1402        );
1403        assert_eq!(
1404            args.iter().filter(|a| *a == "--setting-sources").count(),
1405            1,
1406            "--setting-sources must not be duplicated"
1407        );
1408    }
1409
1410    #[test]
1411    fn test_setting_sources() {
1412        let cmd = QueryCommand::new("test").setting_sources("user,project,local");
1413        let args = cmd.args();
1414        assert!(args.contains(&"--setting-sources".to_string()));
1415        assert!(args.contains(&"user,project,local".to_string()));
1416    }
1417
1418    #[test]
1419    fn test_tmux_flag() {
1420        let cmd = QueryCommand::new("test").tmux();
1421        let args = cmd.args();
1422        assert!(args.contains(&"--tmux".to_string()));
1423    }
1424}