1use 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#[derive(Debug, Clone)]
42pub struct QueryCommand {
43 prompt: String,
44 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 #[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 #[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 #[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 #[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 #[must_use]
102 pub fn output_format(mut self, format: OutputFormat) -> Self {
103 self.output_format = Some(format);
104 self
105 }
106
107 #[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 #[must_use]
116 pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
117 self.shared.permission_mode = Some(mode);
118 self
119 }
120
121 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
191 pub fn effort(mut self, effort: Effort) -> Self {
192 self.shared.effort = Some(effort);
193 self
194 }
195
196 #[must_use]
198 pub fn max_turns(mut self, turns: u32) -> Self {
199 self.shared.max_turns = Some(turns);
200 self
201 }
202
203 #[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 #[must_use]
212 pub fn continue_session(mut self) -> Self {
213 self.shared.continue_session = true;
214 self
215 }
216
217 #[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 #[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 #[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 #[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 #[must_use]
256 pub fn no_session_persistence(mut self) -> Self {
257 self.shared.no_session_persistence = true;
258 self
259 }
260
261 #[must_use]
263 pub fn dangerously_skip_permissions(mut self) -> Self {
264 self.shared.dangerously_skip_permissions = true;
265 self
266 }
267
268 #[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 #[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 #[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 #[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 #[must_use]
328 pub fn include_partial_messages(mut self) -> Self {
329 self.include_partial_messages = true;
330 self
331 }
332
333 #[must_use]
335 pub fn input_format(mut self, format: InputFormat) -> Self {
336 self.input_format = Some(format);
337 self
338 }
339
340 #[must_use]
342 pub fn strict_mcp_config(mut self) -> Self {
343 self.shared.strict_mcp_config = true;
344 self
345 }
346
347 #[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 #[must_use]
356 pub fn fork_session(mut self) -> Self {
357 self.shared.fork_session = true;
358 self
359 }
360
361 #[must_use]
363 pub fn worktree(mut self) -> Self {
364 self.shared.worktree = true;
365 self
366 }
367
368 #[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 #[must_use]
399 pub fn brief(mut self) -> Self {
400 self.brief = true;
401 self
402 }
403
404 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
463 pub fn hermetic(mut self) -> Self {
464 self.shared.apply_hermetic(HermeticScope::Full);
465 self
466 }
467
468 #[must_use]
475 pub fn hermetic_scoped(mut self, scope: HermeticScope) -> Self {
476 self.shared.apply_hermetic(scope);
477 self
478 }
479
480 #[must_use]
482 pub fn tmux(mut self) -> Self {
483 self.shared.tmux = true;
484 self
485 }
486
487 #[must_use]
503 pub fn bare(mut self) -> Self {
504 self.shared.bare = true;
505 self
506 }
507
508 #[must_use]
510 pub fn disable_slash_commands(mut self) -> Self {
511 self.shared.disable_slash_commands = true;
512 self
513 }
514
515 #[must_use]
524 pub fn safe_mode(mut self) -> Self {
525 self.shared.safe_mode = true;
526 self
527 }
528
529 #[must_use]
533 pub fn include_hook_events(mut self) -> Self {
534 self.shared.include_hook_events = true;
535 self
536 }
537
538 #[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 #[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 #[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 #[must_use]
577 pub fn verbose(mut self, value: bool) -> Self {
578 self.verbose = value;
579 self
580 }
581
582 #[must_use]
588 pub fn prompt_suggestions(mut self, value: bool) -> Self {
589 self.prompt_suggestions = value;
590 self
591 }
592
593 #[must_use]
601 pub fn replay_user_messages(mut self, value: bool) -> Self {
602 self.replay_user_messages = value;
603 self
604 }
605
606 #[must_use]
629 pub fn retry(mut self, policy: crate::retry::RetryPolicy) -> Self {
630 self.retry_policy = Some(policy);
631 self
632 }
633
634 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 #[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 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 #[cfg(feature = "sync")]
693 pub fn execute_sync(&self, claude: &Claude) -> Result<CommandOutput> {
694 if self.prompt_via_stdin {
695 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 #[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 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 #[must_use]
748 pub fn prompt_via_stdin(mut self, value: bool) -> Self {
749 self.prompt_via_stdin = value;
750 self
751 }
752
753 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 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 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 let args = self.build_args(); 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")] #[ignore = "requires a real claude binary"]
886 fn prompt_via_stdin_integration() {
887 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 let cmd = QueryCommand::new("hello");
913 let args = cmd.build_args_with_forced_json();
914
915 assert_eq!(
917 &args[args.len() - 2..],
918 &["--".to_string(), "hello".to_string()],
919 );
920
921 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 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 assert_eq!(args.iter().filter(|a| *a == "--output-format").count(), 1);
947 }
948
949 #[test]
950 #[allow(deprecated)] 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 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 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 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 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 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 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 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 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 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 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 assert!(command_str.contains("'it'\\''s'"));
1246 }
1247
1248 #[test]
1249 fn to_command_string_includes_global_args() {
1250 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 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}