claude-wrapper 0.14.0

A type-safe Claude Code CLI wrapper for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
//! A type-safe Claude Code CLI wrapper for Rust.
//!
//! `claude-wrapper` provides a builder-pattern interface for invoking the
//! `claude` CLI programmatically. Each subcommand is a typed builder that
//! produces typed output. The design follows the same shape as
//! [`docker-wrapper`](https://crates.io/crates/docker-wrapper) and
//! [`terraform-wrapper`](https://crates.io/crates/terraform-wrapper).
//!
//! # Feature flags
//!
//! | Feature | Default | Purpose |
//! |---|---|---|
//! | `async` | yes | tokio-backed async API. Disabling drops tokio from the runtime dep tree. |
//! | `json` | yes | JSON output parsing and the JSON-backed surface ([`QueryCommand::execute_json`], [`streaming`], [`session::Session`], [`duplex`], [`conversation`], and the [`history`] / [`jobs`] / [`settings`] introspection modules). |
//! | `tempfile` | yes | [`TempMcpConfig`] for one-shot MCP config files. |
//! | `sync` | no | Blocking API: `*_sync` methods on [`exec`], [`retry`], every command builder, and [`Claude`]. |
//!
//! Sync-only (tokio-free) build:
//!
//! ```toml
//! claude-wrapper = { version = "0.13", default-features = false, features = ["json", "sync"] }
//! ```
//!
//! # Quick start (async)
//!
//! ```no_run
//! # #[cfg(feature = "async")] {
//! use claude_wrapper::{Claude, ClaudeCommand, QueryCommand};
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let claude = Claude::builder().build()?;
//! let output = QueryCommand::new("explain this error: file not found")
//!     .model("sonnet")
//!     .execute(&claude)
//!     .await?;
//! println!("{}", output.stdout);
//! # Ok(()) }
//! # }
//! ```
//!
//! # Quick start (sync)
//!
//! Enable the `sync` feature and bring [`ClaudeCommandSyncExt`] into scope:
//!
//! ```no_run
//! # #[cfg(feature = "sync")] {
//! use claude_wrapper::{Claude, ClaudeCommandSyncExt, QueryCommand};
//!
//! # fn example() -> claude_wrapper::Result<()> {
//! let claude = Claude::builder().build()?;
//! let output = QueryCommand::new("explain this error")
//!     .execute_sync(&claude)?;
//! println!("{}", output.stdout);
//! # Ok(()) }
//! # }
//! ```
//!
//! # Two-layer builder
//!
//! The [`Claude`] client holds shared config (binary path, env, timeout,
//! default retry policy). Command builders hold per-invocation options
//! and call `execute(&claude)` (or `execute_sync`).
//!
//! ```no_run
//! # #[cfg(feature = "async")] {
//! use claude_wrapper::{Claude, ClaudeCommand, Effort, PermissionMode, QueryCommand};
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let claude = Claude::builder()
//!     .env("AWS_REGION", "us-west-2")
//!     .timeout_secs(300)
//!     .build()?;
//!
//! let output = QueryCommand::new("review src/main.rs")
//!     .model("opus")
//!     .system_prompt("You are a senior Rust developer")
//!     .permission_mode(PermissionMode::Plan)
//!     .effort(Effort::High)
//!     .max_turns(5)
//!     .no_session_persistence()
//!     .execute(&claude)
//!     .await?;
//! # Ok(()) }
//! # }
//! ```
//!
//! # JSON output
//!
//! ```no_run
//! # #[cfg(all(feature = "async", feature = "json"))] {
//! use claude_wrapper::{Claude, QueryCommand};
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let claude = Claude::builder().build()?;
//! let result = QueryCommand::new("what is 2+2?")
//!     .execute_json(&claude)
//!     .await?;
//! println!("answer: {}", result.result);
//! println!("cost: ${:.4}", result.cost_usd.unwrap_or(0.0));
//! # Ok(()) }
//! # }
//! ```
//!
//! # Multi-turn conversations
//!
//! Two shapes for multi-turn work, each suited to a different
//! process model. [`DuplexSession`] is the recommended choice for
//! long-running hosts; [`Session`] is the right fit for short-lived
//! processes.
//!
//! | | [`DuplexSession`] | [`Session`] |
//! |---|---|---|
//! | Process model | one child held open across turns | new subprocess per turn, `--resume` continuity |
//! | Mid-turn interrupt | yes ([`DuplexSession::interrupt`](duplex::DuplexSession::interrupt)) | no (only `child.kill()` via SIGKILL) |
//! | Mid-turn permission prompts | yes ([`PermissionHandler`]) | no |
//! | Broadcast event subscribers | yes ([`DuplexSession::subscribe`](duplex::DuplexSession::subscribe)) | no (per-turn `stream_query`) |
//! | Built-in cost / history tracking | no ([`TurnResult`] is per-turn) | yes ([`Session::total_cost_usd`], [`Session::history`], [`BudgetTracker`]) |
//! | Right for | long-running hosts (IDE backends, daemons, agent servers, chat UIs) | short-lived processes (CLIs, build scripts, batch jobs, lambdas) |
//!
//! ## `DuplexSession` (recommended for long-running hosts)
//!
//! ```no_run
//! # #[cfg(all(feature = "async", feature = "json"))] {
//! use claude_wrapper::Claude;
//! use claude_wrapper::duplex::{DuplexOptions, DuplexSession};
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let claude = Claude::builder().build()?;
//! let session = DuplexSession::spawn(
//!     &claude,
//!     DuplexOptions::default().model("haiku"),
//! ).await?;
//!
//! let turn = session.send("what's 2 + 2?").await?;
//! println!("answer: {}", turn.result_text().unwrap_or(""));
//!
//! session.close().await?;
//! # Ok(()) }
//! # }
//! ```
//!
//! See the [duplex module docs](duplex) for the full API including
//! `subscribe`, `interrupt`, and `respond_to_permission`.
//!
//! For host-side bookkeeping (history, cumulative cost, optional
//! [`BudgetTracker`] hard stop) on top of a [`DuplexSession`], wrap
//! it in a [`Conversation`]. See the
//! [conversation module docs](conversation).
//!
//! ## `Session` (for short-lived processes)
//!
//! ```no_run
//! # #[cfg(all(feature = "async", feature = "json"))] {
//! use std::sync::Arc;
//! use claude_wrapper::Claude;
//! use claude_wrapper::session::Session;
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let claude = Arc::new(Claude::builder().build()?);
//! let mut session = Session::new(claude);
//! let _first = session.send("what's 2 + 2?").await?;
//! let _second = session.send("and squared?").await?;
//! println!("cost: ${:.4}", session.total_cost_usd());
//! # Ok(()) }
//! # }
//! ```
//!
//! See the [session module docs](session) for the full API.
//!
//! # Budget tracking
//!
//! Attach a [`BudgetTracker`] to a session (or share one across several
//! sessions) to enforce a cumulative USD ceiling. Callbacks fire
//! exactly once when thresholds are crossed; pre-turn checks
//! short-circuit with [`Error::BudgetExceeded`]
//! once the ceiling is hit.
//!
//! ```no_run
//! # #[cfg(all(feature = "async", feature = "json"))] {
//! use std::sync::Arc;
//! use claude_wrapper::{BudgetTracker, Claude};
//! use claude_wrapper::session::Session;
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let budget = BudgetTracker::builder()
//!     .max_usd(5.00)
//!     .warn_at_usd(4.00)
//!     .on_warning(|t| eprintln!("warning: ${t:.2}"))
//!     .on_exceeded(|t| eprintln!("budget hit: ${t:.2}"))
//!     .build();
//!
//! let claude = Arc::new(Claude::builder().build()?);
//! let mut session = Session::new(claude).with_budget(budget.clone());
//! session.send("hello").await?;
//! println!("spent: ${:.4}", budget.total_usd());
//! # Ok(()) }
//! # }
//! ```
//!
//! # Tool permissions
//!
//! Use [`ToolPattern`] for typed `--allowed-tools` / `--disallowed-tools`
//! entries. Typed constructors always produce valid patterns; loose
//! `From<&str>` keeps bare strings working for back-compat.
//!
//! ```
//! use claude_wrapper::{QueryCommand, ToolPattern};
//!
//! let cmd = QueryCommand::new("review")
//!     .allowed_tool(ToolPattern::tool("Read"))
//!     .allowed_tool(ToolPattern::tool_with_args("Bash", "git log:*"))
//!     .allowed_tool(ToolPattern::all("Write"))
//!     .allowed_tool(ToolPattern::mcp("my-server", "*"))
//!     .disallowed_tool(ToolPattern::tool_with_args("Bash", "rm*"));
//! ```
//!
//! # Streaming
//!
//! Process NDJSON events in real time with [`streaming::stream_query`]
//! (async) or [`streaming::stream_query_sync`] (blocking; non-`Send`
//! handler supported).
//!
//! ```no_run
//! # #[cfg(all(feature = "async", feature = "json"))] {
//! use claude_wrapper::{Claude, OutputFormat, QueryCommand};
//! use claude_wrapper::streaming::{StreamEvent, stream_query};
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let claude = Claude::builder().build()?;
//! let cmd = QueryCommand::new("explain quicksort")
//!     .output_format(OutputFormat::StreamJson);
//!
//! stream_query(&claude, &cmd, |event: StreamEvent| {
//!     if event.is_result() {
//!         println!("result: {}", event.result_text().unwrap_or(""));
//!     }
//! }).await?;
//! # Ok(()) }
//! # }
//! ```
//!
//! # MCP config generation
//!
//! Generate `.mcp.json` files for `--mcp-config`:
//!
//! ```no_run
//! # #[cfg(feature = "async")] {
//! use claude_wrapper::{Claude, ClaudeCommand, McpConfigBuilder, QueryCommand};
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! McpConfigBuilder::new()
//!     .http_server("hub", "http://127.0.0.1:9090")
//!     .stdio_server("tool", "npx", ["my-server"])
//!     .write_to("/tmp/my-project/.mcp.json")?;
//!
//! let claude = Claude::builder().build()?;
//! QueryCommand::new("list tools")
//!     .mcp_config("/tmp/my-project/.mcp.json")
//!     .execute(&claude)
//!     .await?;
//! # Ok(()) }
//! # }
//! ```
//!
//! # On-disk introspection
//!
//! A family of read-only modules parses Claude Code's on-disk state
//! under `~/.claude` directly, without spawning the CLI. Each exposes a
//! root/loader with `list` / `get` accessors and degrades to an empty
//! result when the directory is absent: [`history`] (sessions and
//! transcripts), [`artifacts`] (agents), [`skills`], [`commands`]
//! (custom slash commands), [`settings`] (the four merged layers),
//! [`jobs`] (background-agent state), and [`worktrees`]. See the
//! `inspect_state` example for an end-to-end tour.
//!
//! ```no_run
//! # #[cfg(feature = "json")] {
//! use claude_wrapper::history::HistoryRoot;
//!
//! # fn example() -> claude_wrapper::Result<()> {
//! let history = HistoryRoot::home()?;
//! for project in history.list_projects()? {
//!     println!(
//!         "{} ({} sessions)",
//!         project.decoded_path.display(),
//!         project.session_count,
//!     );
//! }
//! # Ok(()) }
//! # }
//! ```
//!
//! # Dangerous: bypass mode
//!
//! `--permission-mode bypassPermissions` is isolated behind
//! [`dangerous::DangerousClient`], which requires an env-var
//! acknowledgement ([`dangerous::ALLOW_ENV`] = `"1"`) at process start.
//! See the [dangerous module docs](dangerous) for details.
//!
//! # Escape hatch
//!
//! For subcommands not yet wrapped, use [`RawCommand`]:
//!
//! ```no_run
//! # #[cfg(feature = "async")] {
//! use claude_wrapper::{Claude, ClaudeCommand, RawCommand};
//!
//! # async fn example() -> claude_wrapper::Result<()> {
//! let claude = Claude::builder().build()?;
//! let output = RawCommand::new("some-future-command")
//!     .arg("--new-flag")
//!     .arg("value")
//!     .execute(&claude)
//!     .await?;
//! # Ok(()) }
//! # }
//! ```
#![warn(missing_docs)]

pub mod artifacts;
pub mod auth;
pub mod budget;
/// Per-subcommand builders and the [`command::ClaudeCommand`] trait.
pub mod command;
pub mod commands;
#[cfg(all(feature = "json", feature = "async"))]
pub mod conversation;
pub mod dangerous;
#[cfg(all(feature = "json", feature = "async"))]
pub mod duplex;
pub mod error;
pub mod exec;
#[cfg(feature = "json")]
pub mod history;
#[cfg(feature = "json")]
pub mod jobs;
pub mod mcp_config;
pub mod memory;
pub mod plans;
pub mod retry;
#[cfg(all(feature = "json", feature = "async"))]
pub mod session;
#[cfg(feature = "json")]
pub mod sessions;
#[cfg(feature = "json")]
pub mod settings;
pub mod skills;
pub mod slash;
pub mod streaming;
#[cfg(feature = "json")]
pub mod tasks;
pub mod tool_pattern;
pub mod types;
pub mod version;
pub mod worktrees;

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

pub use budget::{BudgetBuilder, BudgetTracker};
pub use command::ClaudeCommand;
#[cfg(feature = "sync")]
pub use command::ClaudeCommandSyncExt;
#[allow(deprecated)]
pub use command::agents::AgentsCommand;
pub use command::auth::{
    AuthLoginCommand, AuthLogoutCommand, AuthStatusCommand, LoginMode, SetupTokenCommand,
};
pub use command::auto_mode::{
    AutoModeConfigCommand, AutoModeCritiqueCommand, AutoModeDefaultsCommand,
};
pub use command::doctor::DoctorCommand;
pub use command::install::InstallCommand;
pub use command::marketplace::{
    MarketplaceAddCommand, MarketplaceListCommand, MarketplaceRemoveCommand,
    MarketplaceUpdateCommand,
};
pub use command::mcp::{
    McpAddCommand, McpAddFromDesktopCommand, McpAddJsonCommand, McpGetCommand, McpListCommand,
    McpLoginCommand, McpLogoutCommand, McpRemoveCommand, McpResetProjectChoicesCommand,
    McpServeCommand,
};
pub use command::plugin::{
    PluginDetailsCommand, PluginDisableCommand, PluginEnableCommand, PluginInstallCommand,
    PluginListCommand, PluginPruneCommand, PluginTagCommand, PluginUninstallCommand,
    PluginUpdateCommand, PluginValidateCommand,
};
pub use command::project::ProjectPurgeCommand;
pub use command::query::QueryCommand;
pub use command::raw::RawCommand;
pub use command::ultrareview::UltrareviewCommand;
pub use command::update::UpdateCommand;
pub use command::version::VersionCommand;
#[cfg(all(feature = "json", feature = "async"))]
pub use conversation::Conversation;
#[cfg(all(feature = "json", feature = "async"))]
pub use duplex::{
    DuplexOptions, DuplexSession, InboundEvent, PermissionDecision, PermissionHandler,
    PermissionRequest, TurnResult,
};
pub use error::{Error, Result};
pub use exec::CommandOutput;
#[cfg(feature = "tempfile")]
pub use mcp_config::TempMcpConfig;
pub use mcp_config::{McpConfigBuilder, McpServerConfig};
pub use retry::{BackoffStrategy, RetryPolicy};
#[cfg(all(feature = "json", feature = "async"))]
pub use session::Session;
pub use tool_pattern::{PatternError, ToolPattern};
pub use types::*;
pub use version::{
    CliVersion, CliVersionStatus, TESTED_CLI_VERSION_MAX, TESTED_CLI_VERSION_MIN, VersionParseError,
};

/// What the crate knows about a child the moment it is spawned.
///
/// Delivered to the [`ClaudeBuilder::on_spawn`] observer before the run can
/// produce output, which is the point: a supervisor that records the pid only
/// after a run *finishes* has nothing to reconcile when it crashes mid-run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct SpawnInfo {
    /// The child's process id.
    pub pid: u32,
    /// The child's process group id, when it leads its own group.
    ///
    /// `None` when [`ClaudeBuilder::process_group`] is disabled, in which case
    /// the child shares the parent's group and its pid must never be passed to
    /// `killpg`: that would signal the caller's own process group.
    pub pgid: Option<u32>,
}

/// Called with [`SpawnInfo`] each time the crate spawns a CLI child.
///
/// Must not block: it runs inline on the spawning thread, between `spawn` and
/// the first read of the child's output.
pub type SpawnObserver = std::sync::Arc<dyn Fn(SpawnInfo) + Send + Sync>;

/// The Claude CLI client. Holds shared configuration applied to all commands.
///
/// Create one via [`Claude::builder()`] and reuse it across commands.
#[derive(Clone)]
pub struct Claude {
    pub(crate) binary: PathBuf,
    pub(crate) working_dir: Option<PathBuf>,
    // env, timeout, and retry_policy are written by the builder under
    // every feature combination but read only by the feature-gated
    // exec paths, so they are "never read" with neither `async` nor
    // `sync` feature.
    #[allow(dead_code)]
    pub(crate) env: HashMap<String, String>,
    pub(crate) global_args: Vec<String>,
    #[allow(dead_code)]
    pub(crate) timeout: Option<Duration>,
    #[allow(dead_code)]
    pub(crate) retry_policy: Option<RetryPolicy>,
    pub(crate) tested_cli_version_range: Option<(CliVersion, CliVersion)>,
    // Read only by the feature-gated exec paths, like env/timeout.
    #[allow(dead_code)]
    pub(crate) process_group: bool,
    #[allow(dead_code)]
    pub(crate) kill_grace: Option<Duration>,
    #[allow(dead_code)]
    pub(crate) on_spawn: Option<SpawnObserver>,
    #[allow(dead_code)]
    pub(crate) die_with_parent: bool,
}

impl std::fmt::Debug for Claude {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Claude")
            .field("binary", &self.binary)
            .field("working_dir", &self.working_dir)
            .field("global_args", &self.global_args)
            .field("timeout", &self.timeout)
            .field("process_group", &self.process_group)
            .field("kill_grace", &self.kill_grace)
            // A closure cannot be rendered, and env may hold credentials, so
            // neither is printed: only whether an observer is installed.
            .field("on_spawn", &self.on_spawn.is_some())
            .finish_non_exhaustive()
    }
}

impl Claude {
    /// Create a new builder for configuring the Claude client.
    #[must_use]
    pub fn builder() -> ClaudeBuilder {
        ClaudeBuilder::default()
    }

    /// Get the path to the claude binary.
    #[must_use]
    pub fn binary(&self) -> &Path {
        &self.binary
    }

    /// Get the working directory, if set.
    #[must_use]
    pub fn working_dir(&self) -> Option<&Path> {
        self.working_dir.as_deref()
    }

    /// Create a clone of this client with a different working directory.
    #[must_use]
    pub fn with_working_dir(&self, dir: impl Into<PathBuf>) -> Self {
        let mut clone = self.clone();
        clone.working_dir = Some(dir.into());
        clone
    }

    /// Query the installed CLI version.
    ///
    /// Runs `claude --version` and parses the output into a [`CliVersion`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> claude_wrapper::Result<()> {
    /// let claude = claude_wrapper::Claude::builder().build()?;
    /// let version = claude.cli_version().await?;
    /// println!("Claude CLI {version}");
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "async")]
    pub async fn cli_version(&self) -> Result<CliVersion> {
        let output = VersionCommand::new().execute(self).await?;
        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
            message: format!("failed to parse CLI version: {e}"),
            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
            working_dir: None,
        })
    }

    /// Check that the installed CLI version meets a minimum requirement.
    ///
    /// Returns the detected version on success, or an error if the version
    /// is below the minimum.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use claude_wrapper::CliVersion;
    ///
    /// # async fn example() -> claude_wrapper::Result<()> {
    /// let claude = claude_wrapper::Claude::builder().build()?;
    /// let version = claude.check_version(&CliVersion::new(2, 1, 0)).await?;
    /// println!("CLI version {version} meets minimum requirement");
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "async")]
    pub async fn check_version(&self, minimum: &CliVersion) -> Result<CliVersion> {
        let version = self.cli_version().await?;
        if version.satisfies_minimum(minimum) {
            Ok(version)
        } else {
            Err(Error::VersionMismatch {
                found: version,
                minimum: *minimum,
            })
        }
    }

    /// Blocking mirror of [`Claude::cli_version`]. Requires the
    /// `sync` feature.
    #[cfg(feature = "sync")]
    pub fn cli_version_sync(&self) -> Result<CliVersion> {
        let output = VersionCommand::new().execute_sync(self)?;
        CliVersion::parse_version_output(&output.stdout).map_err(|e| Error::Io {
            message: format!("failed to parse CLI version: {e}"),
            source: std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
            working_dir: None,
        })
    }

    /// Blocking mirror of [`Claude::check_version`]. Requires the
    /// `sync` feature.
    #[cfg(feature = "sync")]
    pub fn check_version_sync(&self, minimum: &CliVersion) -> Result<CliVersion> {
        let version = self.cli_version_sync()?;
        if version.satisfies_minimum(minimum) {
            Ok(version)
        } else {
            Err(Error::VersionMismatch {
                found: version,
                minimum: *minimum,
            })
        }
    }

    /// The tested-against `[min, max]` range declared at build time
    /// via [`ClaudeBuilder::tested_cli_version_range`], if any.
    ///
    /// `None` means no override was set, in which case version checks
    /// use the crate's own [`TESTED_CLI_VERSION_MIN`] /
    /// [`TESTED_CLI_VERSION_MAX`]; see [`Self::effective_tested_range`].
    #[must_use]
    pub fn tested_cli_version_range(&self) -> Option<(CliVersion, CliVersion)> {
        self.tested_cli_version_range
    }

    /// The range version checks actually use: the caller's override when one
    /// was set, otherwise the crate's own declared range.
    #[must_use]
    pub fn effective_tested_range(&self) -> (CliVersion, CliVersion) {
        self.tested_cli_version_range
            .unwrap_or((TESTED_CLI_VERSION_MIN, TESTED_CLI_VERSION_MAX))
    }

    /// Classify the installed CLI against the tested-against range.
    /// Logs a `tracing::warn!` when outside the range; returns the
    /// typed status either way.
    ///
    /// The range defaults to the crate's own
    /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`],
    /// because only the crate knows what it was built and tested
    /// against. [`ClaudeBuilder::tested_cli_version_range`] overrides
    /// it for hosts that have verified a different range themselves.
    ///
    /// Intended for one-shot use at startup, not on every command.
    #[cfg(feature = "async")]
    pub async fn cli_version_status(&self) -> Result<CliVersionStatus> {
        let (min, max) = self.effective_tested_range();
        let found = self.cli_version().await?;
        let status = found.status_within(&min, &max);
        warn_on_drift(&status);
        Ok(status)
    }

    /// Blocking mirror of [`Claude::cli_version_status`]. Requires
    /// the `sync` feature.
    #[cfg(feature = "sync")]
    pub fn cli_version_status_sync(&self) -> Result<CliVersionStatus> {
        let (min, max) = self.effective_tested_range();
        let found = self.cli_version_sync()?;
        let status = found.status_within(&min, &max);
        warn_on_drift(&status);
        Ok(status)
    }

    /// Refuse to proceed against a CLI outside the tested range.
    ///
    /// The opt-in hard gate. [`Claude::cli_version_status`] is the
    /// reporting path and keeps its behavior: it returns a typed
    /// status and warns. This one turns the same condition into
    /// [`Error::UntestedCliVersion`], for hosts that would rather fail
    /// at startup than run on an unverified binary.
    ///
    /// Returns the detected version on success. The drift warning
    /// still fires on the failure path, so a host that logs and a host
    /// that gates see the same line.
    ///
    /// # Why this is a method and not a builder option
    ///
    /// [`ClaudeBuilder::build`] is synchronous and never spawns the
    /// binary. Enforcing a version there would mean running a
    /// subprocess inside a constructor, so the check lives where the
    /// caller can await it.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> claude_wrapper::Result<()> {
    /// let claude = claude_wrapper::Claude::builder().build()?;
    /// // Run once at startup; returns Err on an untested CLI.
    /// let version = claude.ensure_tested_cli_version().await?;
    /// println!("running against {version}");
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "async")]
    pub async fn ensure_tested_cli_version(&self) -> Result<CliVersion> {
        let (min, max) = self.effective_tested_range();
        let found = self.cli_version().await?;
        self.gate_version(found, min, max)
    }

    /// Blocking mirror of [`Claude::ensure_tested_cli_version`].
    /// Requires the `sync` feature.
    #[cfg(feature = "sync")]
    pub fn ensure_tested_cli_version_sync(&self) -> Result<CliVersion> {
        let (min, max) = self.effective_tested_range();
        let found = self.cli_version_sync()?;
        self.gate_version(found, min, max)
    }

    /// Shared decision for the async and sync gates, so the two cannot
    /// disagree about what "outside the range" means.
    #[cfg(any(feature = "async", feature = "sync"))]
    fn gate_version(
        &self,
        found: CliVersion,
        min: CliVersion,
        max: CliVersion,
    ) -> Result<CliVersion> {
        let status = found.status_within(&min, &max);
        warn_on_drift(&status);
        if status.is_tested() {
            Ok(found)
        } else {
            Err(Error::UntestedCliVersion {
                found,
                tested_min: min,
                tested_max: max,
            })
        }
    }
}

#[allow(dead_code)] // unused with neither `async` nor `sync` feature
fn warn_on_drift(status: &CliVersionStatus) {
    match status {
        CliVersionStatus::Tested => {}
        CliVersionStatus::NewerUntested {
            found, tested_max, ..
        } => {
            tracing::warn!(
                found = %found,
                tested_max = %tested_max,
                "claude CLI is newer than the wrapper's tested-against range; \
                 semantics may have drifted -- proceed with caution"
            );
        }
        CliVersionStatus::OlderThanMinimum { found, minimum, .. } => {
            tracing::warn!(
                found = %found,
                minimum = %minimum,
                "claude CLI is older than the wrapper's declared minimum; \
                 incorrect behavior is likely (missing flags, different shapes)"
            );
        }
    }
}

/// Builder for creating a [`Claude`] client.
///
/// # Example
///
/// ```no_run
/// use claude_wrapper::Claude;
///
/// # fn example() -> claude_wrapper::Result<()> {
/// let claude = Claude::builder()
///     .env("AWS_REGION", "us-west-2")
///     .timeout_secs(120)
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Default)]
pub struct ClaudeBuilder {
    binary: Option<PathBuf>,
    working_dir: Option<PathBuf>,
    env: HashMap<String, String>,
    global_args: Vec<String>,
    timeout: Option<Duration>,
    retry_policy: Option<RetryPolicy>,
    tested_cli_version_range: Option<(CliVersion, CliVersion)>,
    process_group: Option<bool>,
    kill_grace: Option<Duration>,
    on_spawn: Option<SpawnObserver>,
    die_with_parent: bool,
}

impl std::fmt::Debug for ClaudeBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Mirrors Claude's Debug: a closure cannot be rendered and env may
        // hold credentials, so neither is printed.
        f.debug_struct("ClaudeBuilder")
            .field("binary", &self.binary)
            .field("working_dir", &self.working_dir)
            .field("global_args", &self.global_args)
            .field("timeout", &self.timeout)
            .field("process_group", &self.process_group)
            .field("kill_grace", &self.kill_grace)
            .field("on_spawn", &self.on_spawn.is_some())
            .finish_non_exhaustive()
    }
}

impl ClaudeBuilder {
    /// Set the path to the claude binary.
    ///
    /// If not set, the binary is resolved from PATH using `which`.
    #[must_use]
    pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
        self.binary = Some(path.into());
        self
    }

    /// Set the working directory for all commands.
    ///
    /// The spawned process will use this as its current directory.
    #[must_use]
    pub fn working_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.working_dir = Some(path.into());
        self
    }

    /// Add an environment variable to pass to all commands.
    #[must_use]
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }

    /// Add multiple environment variables.
    #[must_use]
    pub fn envs(
        mut self,
        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (k, v) in vars {
            self.env.insert(k.into(), v.into());
        }
        self
    }

    /// Set a default timeout for all commands (in seconds).
    #[must_use]
    pub fn timeout_secs(mut self, seconds: u64) -> Self {
        self.timeout = Some(Duration::from_secs(seconds));
        self
    }

    /// Set a default timeout for all commands.
    #[must_use]
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.timeout = Some(duration);
        self
    }

    /// Add a global argument applied to all commands.
    ///
    /// This is an escape hatch for flags not yet covered by the API.
    #[must_use]
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.global_args.push(arg.into());
        self
    }

    /// Enable verbose output for all commands (`--verbose`).
    #[must_use]
    pub fn verbose(mut self) -> Self {
        self.global_args.push("--verbose".into());
        self
    }

    /// Enable debug output for all commands (`--debug`).
    #[must_use]
    pub fn debug(mut self) -> Self {
        self.global_args.push("--debug".into());
        self
    }

    /// Set a default retry policy for all commands.
    ///
    /// Individual commands can override this via their own retry settings.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use claude_wrapper::{Claude, RetryPolicy};
    /// use std::time::Duration;
    ///
    /// # fn example() -> claude_wrapper::Result<()> {
    /// let claude = Claude::builder()
    ///     .retry(RetryPolicy::new()
    ///         .max_attempts(3)
    ///         .initial_backoff(Duration::from_secs(2))
    ///         .exponential()
    ///         .retry_on_timeout(true))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn retry(mut self, policy: RetryPolicy) -> Self {
        self.retry_policy = Some(policy);
        self
    }

    /// Declare the inclusive `[min, max]` range of `claude` CLI
    /// versions this client has been tested against.
    ///
    /// The wrapper does not enforce the range -- nothing errors when
    /// it's set wrong. Use [`Claude::cli_version_status`] (or its
    /// sync mirror) at startup to classify the actually-installed CLI
    /// against this declaration; that call returns a typed
    /// [`CliVersionStatus`] AND emits a `tracing::warn!` when
    /// outside the range. Hosts (claude-server, application code)
    /// can additionally surface the status to operators.
    ///
    /// # Why this exists
    ///
    /// CLI semantics drift across minor / patch releases (e.g.
    /// `claude agents` was repurposed in 2.1.143). The min floor
    /// lets us say "we know it's broken below this"; the max ceiling
    /// lets us say "we haven't verified above this -- proceed but
    /// expect surprises."
    ///
    /// # You usually do not need this
    ///
    /// The crate declares its own range in
    /// [`TESTED_CLI_VERSION_MIN`] / [`TESTED_CLI_VERSION_MAX`], and
    /// version checks use it by default, because only the crate knows
    /// what it was built and tested against. Set this only when a host
    /// has verified a different range itself.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use claude_wrapper::{Claude, CliVersion};
    ///
    /// # async fn example() -> claude_wrapper::Result<()> {
    /// let claude = Claude::builder()
    ///     .tested_cli_version_range(CliVersion::new(2, 1, 0), CliVersion::new(2, 1, 999))
    ///     .build()?;
    /// // Run once at startup to log a warning if the CLI is out of range.
    /// let _status = claude.cli_version_status().await?;
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub fn tested_cli_version_range(mut self, min: CliVersion, max: CliVersion) -> Self {
        self.tested_cli_version_range = Some((min, max));
        self
    }

    /// Control whether spawned `claude` children are placed in their
    /// own process group on Unix. Defaults to `true`.
    ///
    /// Own group (the default): cancellation and timeouts kill the
    /// child's whole process tree, but the child no longer shares the
    /// host terminal's process group, so terminal-generated signals
    /// (Ctrl-C) do not reach it; terminating a run is the wrapper's
    /// job via drop, timeout, or explicit kill. This is the right
    /// contract for supervisors (daemons, MCP servers, worker queues).
    ///
    /// Shared group (`false`): the child stays in the host's process
    /// group, so a terminal Ctrl-C reaches the whole run directly, but
    /// a wrapper-side kill only reaches the direct child and any
    /// subprocesses it spawned for tool use survive it. This is the
    /// right contract for terminal-attached hosts that shell out
    /// synchronously and rely on the terminal as the supervisor.
    ///
    /// No effect on non-Unix targets.
    #[must_use]
    pub fn process_group(mut self, enabled: bool) -> Self {
        self.process_group = Some(enabled);
        self
    }

    /// Grace period between SIGTERM and SIGKILL when a run is killed
    /// by a timeout or a duplex shutdown overrun (Unix). Default:
    /// none; kills are immediate SIGKILL.
    ///
    /// With a grace set, the child's whole process group gets SIGTERM
    /// first so `claude` can flush its transcript and session state,
    /// and SIGKILL follows once the grace elapses. The full grace is
    /// waited before the timeout error returns, so keep it short
    /// (500ms to 2s). Dropping a future cannot wait, so drop-path
    /// cancellation stays immediate SIGKILL, and the grace applies
    /// only while the child is in its own process group (see
    /// [`process_group`](Self::process_group)).
    #[must_use]
    pub fn kill_grace(mut self, grace: Duration) -> Self {
        self.kill_grace = Some(grace);
        self
    }

    /// Observe every child this client spawns, at spawn time.
    ///
    /// The observer receives a [`SpawnInfo`] before the run produces output,
    /// which is what makes it useful to a supervisor: recording the pid only
    /// once a run *finishes* leaves nothing to reconcile after a crash
    /// mid-run. Fires for one-shot runs, streaming runs, and duplex sessions
    /// alike, and on retry it fires once per attempt, since each attempt is a
    /// distinct process.
    ///
    /// The observer runs inline on the spawning thread, so it must not block.
    /// Write a pidfile or push to a channel; do not do I/O that can stall.
    ///
    /// # Why a callback rather than a return value
    ///
    /// The crash case needs the pid to be durable *before* the run can be
    /// orphaned. A pid on the result type arrives too late for exactly the
    /// scenario that motivates recording it.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use claude_wrapper::Claude;
    ///
    /// # fn example() -> claude_wrapper::Result<()> {
    /// let claude = Claude::builder()
    ///     .on_spawn(Arc::new(|info| {
    ///         eprintln!("spawned pid {} (group {:?})", info.pid, info.pgid);
    ///     }))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn on_spawn(mut self, observer: SpawnObserver) -> Self {
        self.on_spawn = Some(observer);
        self
    }

    /// Ask the kernel to kill spawned children when this process dies.
    ///
    /// **Linux only.** Check [`die_with_parent_supported`](crate::exec::die_with_parent_supported)
    /// rather than assuming; elsewhere this is accepted and does nothing.
    ///
    /// # The problem it addresses
    ///
    /// Every other cleanup path in this crate is a destructor: `kill_on_drop`,
    /// and the process-group kill on drop, timeout, or stream error. None of
    /// them run when *this* process is SIGKILLed. The child is then reparented
    /// to init, and because it leads its own process group (see
    /// [`process_group`](Self::process_group)) terminal signals cannot reach it
    /// either. It keeps running, keeps billing, and keeps appending to the
    /// session transcript, so a restarted supervisor that resumes the same
    /// session id can find itself interleaving with an orphan still writing.
    ///
    /// On Linux `PR_SET_PDEATHSIG` closes that: the kernel delivers SIGKILL to
    /// the child the moment its parent dies, with no cooperation from either
    /// side.
    ///
    /// # What it does not cover
    ///
    /// - **Non-Linux targets.** macOS has no equivalent. A supervisor that
    ///   needs the guarantee there has to poll and kill by pid; recording the
    ///   pid is what [`on_spawn`](Self::on_spawn) is for.
    /// - **Re-parenting.** The signal fires when the *immediate* parent dies.
    ///   If the crate's caller is itself an intermediate process that exits
    ///   normally, the child dies then, which is usually what you want but is
    ///   worth knowing if you daemonize between building the client and
    ///   spawning.
    /// - **The fork/prctl window.** Handled: the hook re-checks `getppid()`
    ///   after arming and exits if the parent already changed. Without that
    ///   check a parent dying in that window leaves exactly the orphan this
    ///   option exists to prevent.
    ///
    /// Off by default, because killing children on parent exit is the right
    /// default for a supervisor and the wrong one for a CLI that deliberately
    /// backgrounds work.
    #[must_use]
    pub fn die_with_parent(mut self, enabled: bool) -> Self {
        self.die_with_parent = enabled;
        self
    }

    /// Build the Claude client, resolving the binary path.
    pub fn build(self) -> Result<Claude> {
        let binary = match self.binary {
            Some(path) => path,
            None => which::which("claude").map_err(|_| Error::NotFound)?,
        };

        Ok(Claude {
            binary,
            working_dir: self.working_dir,
            env: self.env,
            global_args: self.global_args,
            timeout: self.timeout,
            retry_policy: self.retry_policy,
            tested_cli_version_range: self.tested_cli_version_range,
            process_group: self.process_group.unwrap_or(true),
            kill_grace: self.kill_grace,
            on_spawn: self.on_spawn,
            die_with_parent: self.die_with_parent,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builder_process_group_defaults_on_and_can_opt_out() {
        let on = Claude::builder()
            .binary("/nonexistent/claude")
            .build()
            .unwrap();
        assert!(on.process_group);

        let off = Claude::builder()
            .binary("/nonexistent/claude")
            .process_group(false)
            .build()
            .unwrap();
        assert!(!off.process_group);
    }

    #[test]
    fn builder_kill_grace_defaults_off_and_can_be_set() {
        let off = Claude::builder()
            .binary("/nonexistent/claude")
            .build()
            .unwrap();
        assert!(off.kill_grace.is_none());

        let on = Claude::builder()
            .binary("/nonexistent/claude")
            .kill_grace(Duration::from_millis(750))
            .build()
            .unwrap();
        assert_eq!(on.kill_grace, Some(Duration::from_millis(750)));
    }

    // -- the version gate ------------------------------------------
    //
    // `gate_version` is the decision both the async and sync gates
    // share, and it takes the version rather than fetching it, so the
    // policy is testable without spawning a binary.

    #[cfg(any(feature = "async", feature = "sync"))]
    fn gate(found: (u32, u32, u32)) -> Result<CliVersion> {
        let claude = Claude::builder()
            .binary("/nonexistent/claude")
            .build()
            .unwrap();
        let (min, max) = claude.effective_tested_range();
        claude.gate_version(CliVersion::new(found.0, found.1, found.2), min, max)
    }

    #[cfg(any(feature = "async", feature = "sync"))]
    #[test]
    fn gate_accepts_a_version_inside_the_declared_range() {
        let found = gate((
            TESTED_CLI_VERSION_MIN.major,
            TESTED_CLI_VERSION_MIN.minor,
            TESTED_CLI_VERSION_MIN.patch,
        ))
        .expect("the declared minimum must pass its own gate");
        assert_eq!(found, TESTED_CLI_VERSION_MIN);
    }

    #[cfg(any(feature = "async", feature = "sync"))]
    #[test]
    fn gate_rejects_older_than_minimum_with_both_bounds() {
        let err = gate((1, 0, 0)).expect_err("1.0.0 is below any supported floor");
        match err {
            Error::UntestedCliVersion {
                found,
                tested_min,
                tested_max,
            } => {
                assert_eq!(found, CliVersion::new(1, 0, 0));
                assert_eq!(tested_min, TESTED_CLI_VERSION_MIN);
                assert_eq!(tested_max, TESTED_CLI_VERSION_MAX);
                // The message must say which side it fell off, since
                // "too old" and "too new" call for opposite fixes.
                assert!(err_text(&err).contains("older"), "{}", err_text(&err));
            }
            other => panic!("expected UntestedCliVersion, got {other:?}"),
        }
    }

    #[cfg(any(feature = "async", feature = "sync"))]
    #[test]
    fn gate_rejects_newer_than_maximum() {
        let err = gate((99, 0, 0)).expect_err("99.0.0 is above the tested ceiling");
        assert!(matches!(err, Error::UntestedCliVersion { .. }));
        assert!(err_text(&err).contains("newer"), "{}", err_text(&err));
    }

    #[cfg(any(feature = "async", feature = "sync"))]
    #[test]
    fn gate_honours_a_caller_supplied_range_over_the_crate_default() {
        // A host that has verified a narrower window should be able to
        // enforce it, including rejecting versions the crate itself
        // considers fine.
        let claude = Claude::builder()
            .binary("/nonexistent/claude")
            .tested_cli_version_range(CliVersion::new(3, 0, 0), CliVersion::new(3, 0, 9))
            .build()
            .unwrap();
        let (min, max) = claude.effective_tested_range();
        assert_eq!(min, CliVersion::new(3, 0, 0));
        assert!(
            claude
                .gate_version(CliVersion::new(3, 0, 5), min, max)
                .is_ok()
        );
        assert!(
            claude
                .gate_version(TESTED_CLI_VERSION_MIN, min, max)
                .is_err(),
            "the caller's range must win over the crate's"
        );
    }

    #[cfg(any(feature = "async", feature = "sync"))]
    fn err_text(e: &Error) -> String {
        e.to_string()
    }

    #[test]
    fn test_builder_with_binary() {
        let claude = Claude::builder()
            .binary("/usr/local/bin/claude")
            .env("FOO", "bar")
            .timeout_secs(60)
            .build()
            .unwrap();

        assert_eq!(claude.binary, PathBuf::from("/usr/local/bin/claude"));
        assert_eq!(claude.env.get("FOO").unwrap(), "bar");
        assert_eq!(claude.timeout, Some(Duration::from_secs(60)));
    }

    #[test]
    fn test_builder_global_args() {
        let claude = Claude::builder()
            .binary("/usr/local/bin/claude")
            .arg("--verbose")
            .build()
            .unwrap();

        assert_eq!(claude.global_args, vec!["--verbose"]);
    }

    #[test]
    fn test_builder_verbose() {
        let claude = Claude::builder()
            .binary("/usr/local/bin/claude")
            .verbose()
            .build()
            .unwrap();
        assert!(claude.global_args.contains(&"--verbose".to_string()));
    }

    #[test]
    fn test_builder_debug() {
        let claude = Claude::builder()
            .binary("/usr/local/bin/claude")
            .debug()
            .build()
            .unwrap();
        assert!(claude.global_args.contains(&"--debug".to_string()));
    }
}