claude-wrapper 0.14.1

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
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
//! Process spawning and execution for the `claude` CLI.
//!
//! Builds and runs the child process behind every command: applies the
//! [`Claude`] client's binary path, working directory, environment, and
//! timeout, scrubs the `CLAUDECODE` env var so nested runs are not
//! detected as recursive, drains stdout/stderr without deadlocking, and
//! maps failures onto [`Error`] via
//! [`from_command_failure`](crate::error::Error::from_command_failure).
//! Both the async (tokio) and blocking (`sync` feature) paths live here.
//!
//! Every spawn places the child in its own process group on Unix, and
//! every async spawn sets `kill_on_drop(true)`. Dropping an in-flight
//! execute future (a lost `tokio::select!` race, a caller-side timeout)
//! SIGKILLs the whole group (via the crate-internal `GroupKillGuard`),
//! so subprocesses the
//! CLI spawned for tool use (shells, MCP servers, test runners) die
//! with it rather than being reparented and running on. The same
//! group-kill runs when a configured timeout fires, on both the async
//! and blocking paths. The blocking paths cannot be dropped mid-flight,
//! so they have no drop-side equivalent.
//!
//! Consequence of the group split: the child no longer shares the
//! host's terminal process group, so terminal-generated signals
//! (Ctrl-C) do not reach it directly; terminating a run is the
//! wrapper's job, via drop, timeout, or an explicit kill.
//! Terminal-attached hosts that want the terminal to stay the
//! supervisor can opt out with
//! [`ClaudeBuilder::process_group(false)`](crate::ClaudeBuilder::process_group),
//! trading the tree kill away: kills then reach only the direct child.

#[cfg(any(feature = "async", feature = "sync"))]
use std::time::Duration;

#[cfg(feature = "async")]
use tokio::io::AsyncReadExt;
#[cfg(feature = "async")]
use tokio::process::Command;
#[cfg(any(feature = "async", feature = "sync"))]
use tracing::{debug, warn};

use crate::Claude;
#[cfg(any(feature = "async", feature = "sync"))]
use crate::error::{Error, Result};

/// Assemble the full argv passed to the CLI binary: the client's
/// global args followed by the command's own args.
///
/// Single assembly path shared by every exec entry point and
/// [`QueryCommand::to_command_string`](crate::QueryCommand::to_command_string),
/// so a rendered preview cannot drift from what actually spawns.
pub(crate) fn full_command_args(claude: &Claude, args: Vec<String>) -> Vec<String> {
    let mut command_args = claude.global_args.clone();
    command_args.extend(args);
    command_args
}

/// Apply the client's environment policy to one CLI child command.
///
/// Kept as the single environment assembly point for buffered, streaming,
/// sync, timeout, retry, stdin, and duplex spawns. Explicit entries are
/// applied after clearing and after the nested-session scrub, so callers can
/// deliberately restore an entry when required.
#[cfg(any(feature = "async", feature = "sync"))]
pub(crate) fn apply_child_environment(
    cmd: &mut std::process::Command,
    clear_env: bool,
    env: &std::collections::HashMap<String, String>,
) {
    if clear_env {
        cmd.env_clear();
    }
    cmd.env_remove("CLAUDECODE");
    cmd.env_remove("CLAUDE_CODE_ENTRYPOINT");
    cmd.envs(env);
}

/// The subcommand label for a span, derived from the argv.
///
/// The first token is the subcommand for subcommand-style invocations
/// (`mcp`, `plugin`, `doctor`). For print-mode runs it is the leading
/// flag (`--print`), which is equally informative. Never a value:
/// values always follow a flag, and the first token cannot be one.
///
/// Deliberately not the whole argv. Prompts arrive as argv positionals
/// and must never reach a span field.
#[cfg(any(feature = "async", feature = "sync"))]
pub(crate) fn span_command(args: &[String]) -> &str {
    args.first().map(String::as_str).unwrap_or("<none>")
}

/// Open the span covering one CLI invocation.
///
/// `exit_code` and `duration_ms` are declared empty and recorded when
/// the call finishes, so a subscriber sees them on close. Carries the
/// binary and working directory, never the prompt and never the env.
#[cfg(any(feature = "async", feature = "sync"))]
pub(crate) fn exec_span(claude: &Claude, args: &[String], mode: &'static str) -> tracing::Span {
    tracing::debug_span!(
        "claude.exec",
        command = span_command(args),
        mode,
        binary = %claude.binary.display(),
        cwd = claude.working_dir.as_deref().map(|d| d.display().to_string()),
        exit_code = tracing::field::Empty,
        duration_ms = tracing::field::Empty,
    )
}

/// Record the outcome of an invocation on its span.
#[cfg(any(feature = "async", feature = "sync"))]
pub(crate) fn record_exec_outcome(
    span: &tracing::Span,
    exit_code: i32,
    started: std::time::Instant,
) {
    span.record("exit_code", exit_code);
    span.record("duration_ms", started.elapsed().as_millis() as u64);
}

/// Raw output from a claude CLI invocation.
#[derive(Debug, Clone)]
pub struct CommandOutput {
    /// Captured standard output.
    pub stdout: String,
    /// Captured standard error.
    pub stderr: String,
    /// Process exit code.
    pub exit_code: i32,
    /// Whether the process exited successfully (exit code 0).
    pub success: bool,
}

/// Kills the child's entire process group when dropped, unless disarmed.
///
/// Every spawn puts the child in its own process group on Unix
/// (`process_group(0)`), so the group id equals the child's pid.
/// `kill_on_drop` and `Child::kill` only reach the direct child; this
/// guard extends cancellation to the subprocesses the CLI spawns for
/// tool use (shells, MCP servers, test runners), which would otherwise
/// be reparented and keep running.
///
/// Callers must [`disarm`](Self::disarm) the guard once the child's
/// exit status has been observed: past that point the pid can be reaped
/// and recycled, and signalling a recycled group would hit unrelated
/// processes. While the child is unreaped (running or zombie) its pid
/// cannot be recycled, so firing is safe.
///
/// On non-Unix targets the guard is a no-op.
/// Arm the group-kill guard and tell the observer the child exists.
///
/// Kept together so the two cannot disagree about whether the child leads its
/// own group: the `pgid` reported is `Some` exactly when the guard is armed,
/// which is exactly when the pid is safe to `killpg`.
/// The spawn-policy knobs every spawn path carries together.
///
/// Bundled because they always travel as a set and because threading them
/// individually pushed the timeout paths past clippy's argument threshold:
/// whether the child leads its own group, how long to wait before escalating a
/// kill, whether the child should die with its parent, and who to tell that it
/// exists.
#[cfg(any(feature = "async", feature = "sync"))]
#[derive(Clone, Copy)]
pub(crate) struct SpawnPolicy<'a> {
    pub(crate) process_group: bool,
    pub(crate) kill_grace: Option<Duration>,
    pub(crate) die_with_parent: bool,
    pub(crate) on_spawn: Option<&'a crate::SpawnObserver>,
}

#[cfg(any(feature = "async", feature = "sync"))]
impl SpawnPolicy<'_> {
    /// The policy a [`Claude`] client describes.
    pub(crate) fn of(claude: &Claude) -> SpawnPolicy<'_> {
        SpawnPolicy {
            process_group: claude.process_group,
            kill_grace: claude.kill_grace,
            die_with_parent: claude.die_with_parent,
            on_spawn: claude.on_spawn.as_ref(),
        }
    }
}

#[cfg(any(feature = "async", feature = "sync"))]
pub(crate) fn arm_and_notify(
    process_group: bool,
    pid: Option<u32>,
    on_spawn: Option<&crate::SpawnObserver>,
) -> GroupKillGuard {
    if let (Some(pid), Some(observer)) = (pid, on_spawn) {
        observer(crate::SpawnInfo {
            pid,
            pgid: process_group.then_some(pid),
        });
    }
    GroupKillGuard::new_if(process_group, pid)
}

#[cfg(any(feature = "async", feature = "sync"))]
pub(crate) struct GroupKillGuard {
    #[cfg(unix)]
    pgid: Option<i32>,
}

#[cfg(any(feature = "async", feature = "sync"))]
impl GroupKillGuard {
    /// Arm a guard only when the child was placed in its own process
    /// group; otherwise the child's pid is not a group id and must
    /// never be signalled (see
    /// [`ClaudeBuilder::process_group`](crate::ClaudeBuilder::process_group)).
    pub(crate) fn new_if(enabled: bool, pid: Option<u32>) -> Self {
        Self::new(if enabled { pid } else { None })
    }

    /// Arm a guard for the child with the given pid (as returned by
    /// `Child::id`). A `None` pid (child already reaped) leaves the
    /// guard disarmed.
    pub(crate) fn new(pid: Option<u32>) -> Self {
        #[cfg(unix)]
        {
            Self {
                pgid: pid.and_then(|p| i32::try_from(p).ok()),
            }
        }
        #[cfg(not(unix))]
        {
            let _ = pid;
            Self {}
        }
    }

    /// Stop the guard from firing: the child's exit status has been
    /// observed, so the group id is no longer safe to signal.
    pub(crate) fn disarm(&mut self) {
        #[cfg(unix)]
        {
            self.pgid = None;
        }
    }

    /// True while the guard can still signal the group.
    pub(crate) fn is_armed(&self) -> bool {
        #[cfg(unix)]
        {
            self.pgid.is_some()
        }
        #[cfg(not(unix))]
        {
            false
        }
    }

    /// SIGTERM the whole group (Unix) so the CLI can flush its
    /// transcript and session state. Does not disarm: callers follow
    /// up with [`kill_now`](Self::kill_now) once the grace elapses.
    pub(crate) fn term_now(&self) {
        #[cfg(unix)]
        if let Some(pgid) = self.pgid {
            // SAFETY: plain FFI call with no pointers or invariants;
            // failure (e.g. ESRCH once the group is gone) is ignored.
            let _ = unsafe { libc::killpg(pgid, libc::SIGTERM) };
        }
    }

    /// SIGKILL the group immediately and disarm.
    pub(crate) fn kill_now(&mut self) {
        #[cfg(unix)]
        if let Some(pgid) = self.pgid.take() {
            // SAFETY: plain FFI call with no pointers or invariants;
            // failure (e.g. ESRCH once the group is gone) is ignored.
            let _ = unsafe { libc::killpg(pgid, libc::SIGKILL) };
        }
    }
}

#[cfg(any(feature = "async", feature = "sync"))]
impl Drop for GroupKillGuard {
    fn drop(&mut self) {
        self.kill_now();
    }
}

/// Whether [`ClaudeBuilder::die_with_parent`](crate::ClaudeBuilder::die_with_parent)
/// does anything on this platform.
///
/// `true` only on Linux, which is the only target with a kernel-level
/// parent-death signal (`PR_SET_PDEATHSIG`). Elsewhere the option is accepted
/// and has no effect, so a supervisor that needs the guarantee everywhere must
/// check this and run its own watchdog rather than assume coverage it does not
/// have.
#[must_use]
pub const fn die_with_parent_supported() -> bool {
    cfg!(target_os = "linux")
}

/// Ask the kernel to SIGKILL the child when this process dies.
///
/// Linux only. Two things make this correct rather than merely present:
///
/// - **The fork/prctl race.** `PR_SET_PDEATHSIG` is set by the child *after*
///   the fork. If the parent dies in that window the signal never arrives and
///   the child orphans anyway, which is the exact case this exists to prevent.
///   So the hook re-reads `getppid()` immediately afterwards and exits if the
///   parent already changed.
/// - **Async-signal-safety.** Everything called here (`prctl`, `getppid`,
///   `_exit`) is on the post-fork allowlist. Anything that allocates or takes a
///   lock would risk deadlocking the child.
///
/// The signal is also cleared across `execve` only for setuid binaries, which
/// `claude` is not, so it survives into the CLI itself.
#[cfg(all(unix, any(feature = "async", feature = "sync")))]
fn pdeathsig_hook() -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static {
    // Read the parent pid before the fork: inside the child, "the parent we
    // meant" is this value, not whatever getppid happens to return later.
    let parent = std::process::id();
    move || {
        #[cfg(target_os = "linux")]
        {
            // SAFETY: async-signal-safe calls only, as required post-fork.
            unsafe {
                if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
                    return Err(std::io::Error::last_os_error());
                }
                // Lost the race: the parent died before the signal was armed.
                if libc::getppid() as u32 != parent {
                    libc::_exit(1);
                }
            }
        }
        #[cfg(not(target_os = "linux"))]
        {
            let _ = parent;
        }
        Ok(())
    }
}

/// Apply the parent-death policy to an async spawn. No-op off Linux; see
/// [`die_with_parent_supported`].
#[cfg(feature = "async")]
pub(crate) fn apply_die_with_parent(cmd: &mut Command, enabled: bool) {
    #[cfg(unix)]
    if enabled {
        // SAFETY: the hook is async-signal-safe; see `pdeathsig_hook`.
        unsafe {
            cmd.pre_exec(pdeathsig_hook());
        }
    }
    #[cfg(not(unix))]
    {
        let _ = (cmd, enabled);
    }
}

/// Blocking mirror of [`apply_die_with_parent`].
#[cfg(feature = "sync")]
pub(crate) fn apply_die_with_parent_sync(cmd: &mut std::process::Command, enabled: bool) {
    #[cfg(unix)]
    if enabled {
        use std::os::unix::process::CommandExt;
        // SAFETY: the hook is async-signal-safe; see `pdeathsig_hook`.
        unsafe {
            cmd.pre_exec(pdeathsig_hook());
        }
    }
    #[cfg(not(unix))]
    {
        let _ = (cmd, enabled);
    }
}

/// Apply the client's process-group policy to an async spawn: place
/// the child in its own group (Unix) unless the builder opted out via
/// [`ClaudeBuilder::process_group`](crate::ClaudeBuilder::process_group).
#[cfg(feature = "async")]
pub(crate) fn apply_process_group(cmd: &mut Command, enabled: bool) {
    #[cfg(unix)]
    if enabled {
        cmd.process_group(0);
    }
    #[cfg(not(unix))]
    {
        let _ = (cmd, enabled);
    }
}

/// Blocking mirror of [`apply_process_group`].
#[cfg(feature = "sync")]
pub(crate) fn apply_process_group_sync(cmd: &mut std::process::Command, enabled: bool) {
    #[cfg(unix)]
    if enabled {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    #[cfg(not(unix))]
    {
        let _ = (cmd, enabled);
    }
}

/// Escalated group kill for the waitable paths: SIGTERM the group,
/// wait out `grace` without reaping (the zombie child keeps the group
/// id reserved, so a recycled pid can never be signalled), then
/// SIGKILL whatever remains. With no grace configured, or when the
/// child is not in its own process group, this is an immediate
/// SIGKILL. Drop-path cancellation cannot wait and always SIGKILLs
/// immediately via the guard's `Drop`.
#[cfg(feature = "async")]
pub(crate) async fn kill_group_with_grace(group: &mut GroupKillGuard, grace: Option<Duration>) {
    if let Some(g) = grace
        && !g.is_zero()
        && group.is_armed()
    {
        group.term_now();
        tokio::time::sleep(g).await;
    }
    group.kill_now();
}

/// Blocking mirror of [`kill_group_with_grace`].
#[cfg(feature = "sync")]
pub(crate) fn kill_group_with_grace_sync(group: &mut GroupKillGuard, grace: Option<Duration>) {
    if let Some(g) = grace
        && !g.is_zero()
        && group.is_armed()
    {
        group.term_now();
        std::thread::sleep(g);
    }
    group.kill_now();
}

/// Run a claude command with the given arguments.
///
/// If the [`Claude`] client has a retry policy set, transient errors will be
/// retried according to that policy. A per-command retry policy can be passed
/// to override the client default.
///
/// Dropping the returned future mid-flight kills the spawned `claude`
/// process and, on Unix, its whole process group (SIGKILL): an
/// abandoned run does not keep executing in the background, and the
/// subprocesses it spawned for tool use die with it.
#[cfg(feature = "async")]
pub async fn run_claude(claude: &Claude, args: Vec<String>) -> Result<CommandOutput> {
    run_claude_with_retry(claude, args, None).await
}

/// Run a claude command with an optional per-command retry policy override.
///
/// Dropping the returned future kills the child; see [`run_claude`].
#[cfg(feature = "async")]
pub async fn run_claude_with_retry(
    claude: &Claude,
    args: Vec<String>,
    retry_override: Option<&crate::retry::RetryPolicy>,
) -> Result<CommandOutput> {
    let policy = retry_override.or(claude.retry_policy.as_ref());

    match policy {
        Some(policy) => {
            crate::retry::with_retry(policy, || run_claude_once(claude, args.clone())).await
        }
        None => run_claude_once(claude, args).await,
    }
}

/// Run claude, writing `stdin_content` to the child's stdin rather than
/// passing the prompt as argv.
///
/// stdin mode does not retry -- the stdin pipe is consumed after the first
/// attempt and cannot be rewound for a subsequent try.
///
/// Dropping the returned future kills the child; see [`run_claude`].
#[cfg(feature = "async")]
pub async fn run_claude_with_stdin_prompt(
    claude: &Claude,
    args: Vec<String>,
    stdin_content: String,
) -> Result<CommandOutput> {
    run_claude_with_stdin_prompt_internal(claude, args, stdin_content).await
}

#[cfg(feature = "async")]
async fn run_claude_with_stdin_prompt_internal(
    claude: &Claude,
    args: Vec<String>,
    stdin_content: String,
) -> Result<CommandOutput> {
    let command_args = full_command_args(claude, args);

    let span = exec_span(claude, &command_args, "stdin");
    let _enter = span.enter();
    let started = std::time::Instant::now();
    debug!(binary = %claude.binary.display(), args = ?command_args, "executing claude command (stdin prompt)");

    let binary = &claude.binary;
    let env = &claude.env;
    let clear_env = claude.clear_env;
    let working_dir = claude.working_dir.as_deref();

    let result = if let Some(timeout) = claude.timeout {
        run_with_timeout_stdin(
            binary,
            &command_args,
            env,
            clear_env,
            working_dir,
            timeout,
            stdin_content,
            SpawnPolicy::of(claude),
        )
        .await
    } else {
        run_internal_stdin(
            binary,
            &command_args,
            env,
            clear_env,
            working_dir,
            stdin_content,
            SpawnPolicy::of(claude),
        )
        .await
    };

    if let Ok(output) = &result {
        record_exec_outcome(&span, output.exit_code, started);
    }
    result
}

#[cfg(feature = "async")]
async fn run_internal_stdin(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    stdin_content: String,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace: _, // no kill site on this path
        die_with_parent,
        on_spawn,
    } = policy;
    use tokio::io::AsyncWriteExt;

    let mut cmd = Command::new(binary);
    cmd.args(args);
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    // Dropping the in-flight future must kill the child, not leave the
    // CLI running unattended (see the module docs).
    cmd.kill_on_drop(true);
    // Own process group (Unix) so cancellation can signal the whole
    // tree, not just the direct child (see GroupKillGuard). Opt out
    // via ClaudeBuilder::process_group.
    apply_process_group(&mut cmd, process_group);
    apply_die_with_parent(&mut cmd, die_with_parent);
    apply_child_environment(cmd.as_std_mut(), clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    let mut child = spawn_retrying_txtbsy(&mut cmd)
        .await
        .map_err(|e| Error::Io {
            message: format!("failed to spawn claude: {e}"),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        })?;
    let mut group = arm_and_notify(process_group, child.id(), on_spawn);

    // Write the prompt to stdin, then drop the handle so the child sees EOF.
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(stdin_content.as_bytes())
            .await
            .map_err(|e| Error::Io {
                message: format!("failed to write to claude stdin: {e}"),
                source: e,
                working_dir: working_dir.map(|p| p.to_path_buf()),
            })?;
        // Drop stdin so the child sees EOF.
    }

    let mut stdout_handle = child.stdout.take().expect("stdout was piped");
    let mut stderr_handle = child.stderr.take().expect("stderr was piped");

    let (status, stdout_str, stderr_str) = tokio::join!(
        child.wait(),
        drain(&mut stdout_handle),
        drain(&mut stderr_handle),
    );

    let status = status.map_err(|e| Error::Io {
        message: "failed to wait for claude process".to_string(),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })?;
    group.disarm();

    let exit_code = status.code().unwrap_or(-1);

    if !status.success() {
        return Err(Error::from_command_failure(
            format!("{} {}", binary.display(), args.join(" ")),
            exit_code,
            stdout_str,
            stderr_str,
            working_dir.map(|p| p.to_path_buf()),
        ));
    }

    Ok(CommandOutput {
        stdout: stdout_str,
        stderr: stderr_str,
        exit_code,
        success: true,
    })
}

#[cfg(feature = "async")]
#[allow(clippy::too_many_arguments)]
async fn run_with_timeout_stdin(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    timeout: Duration,
    stdin_content: String,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace,
        die_with_parent,
        on_spawn,
    } = policy;
    use tokio::io::AsyncWriteExt;

    let mut cmd = Command::new(binary);
    cmd.args(args);
    cmd.stdin(std::process::Stdio::piped());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    // Dropping the in-flight future must kill the child, not leave the
    // CLI running unattended (see the module docs).
    cmd.kill_on_drop(true);
    // Own process group (Unix) so cancellation can signal the whole
    // tree, not just the direct child (see GroupKillGuard). Opt out
    // via ClaudeBuilder::process_group.
    apply_process_group(&mut cmd, process_group);
    apply_die_with_parent(&mut cmd, die_with_parent);
    apply_child_environment(cmd.as_std_mut(), clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    let mut child = spawn_retrying_txtbsy(&mut cmd)
        .await
        .map_err(|e| Error::Io {
            message: format!("failed to spawn claude: {e}"),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        })?;
    let mut group = arm_and_notify(process_group, child.id(), on_spawn);

    // Write the prompt to stdin, then drop the handle so the child sees EOF.
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(stdin_content.as_bytes())
            .await
            .map_err(|e| Error::Io {
                message: format!("failed to write to claude stdin: {e}"),
                source: e,
                working_dir: working_dir.map(|p| p.to_path_buf()),
            })?;
        // Drop stdin so the child sees EOF.
    }

    let mut stdout_handle = child.stdout.take().expect("stdout was piped");
    let mut stderr_handle = child.stderr.take().expect("stderr was piped");

    let wait_and_drain = async {
        let (status, stdout_str, stderr_str) = tokio::join!(
            child.wait(),
            drain(&mut stdout_handle),
            drain(&mut stderr_handle),
        );
        (status, stdout_str, stderr_str)
    };

    match tokio::time::timeout(timeout, wait_and_drain).await {
        Ok((Ok(status), stdout, stderr)) => {
            group.disarm();
            let exit_code = status.code().unwrap_or(-1);

            if !status.success() {
                return Err(Error::from_command_failure(
                    format!("{} {}", binary.display(), args.join(" ")),
                    exit_code,
                    stdout,
                    stderr,
                    working_dir.map(|p| p.to_path_buf()),
                ));
            }

            Ok(CommandOutput {
                stdout,
                stderr,
                exit_code,
                success: true,
            })
        }
        Ok((Err(e), _stdout, _stderr)) => Err(Error::Io {
            message: "failed to wait for claude process".to_string(),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        }),
        Err(_) => {
            // Timeout: take down the whole group first (subprocesses
            // may hold our pipe fds), honoring the optional SIGTERM
            // grace, then kill+reap the direct child.
            kill_group_with_grace(&mut group, kill_grace).await;
            let _ = child.kill().await;
            let drain_budget = Duration::from_millis(200);
            let stdout_str = tokio::time::timeout(drain_budget, drain(&mut stdout_handle))
                .await
                .unwrap_or_default();
            let stderr_str = tokio::time::timeout(drain_budget, drain(&mut stderr_handle))
                .await
                .unwrap_or_default();
            if !stdout_str.is_empty() || !stderr_str.is_empty() {
                warn!(
                    stdout = %stdout_str,
                    stderr = %stderr_str,
                    "partial output from timed-out process",
                );
            }
            Err(Error::Timeout {
                timeout_seconds: timeout.as_secs(),
            })
        }
    }
}

#[cfg(feature = "async")]
async fn run_claude_once(claude: &Claude, args: Vec<String>) -> Result<CommandOutput> {
    let command_args = full_command_args(claude, args);

    let span = exec_span(claude, &command_args, "oneshot");
    let _enter = span.enter();
    let started = std::time::Instant::now();
    debug!(binary = %claude.binary.display(), args = ?command_args, "executing claude command");

    let output = if let Some(timeout) = claude.timeout {
        run_with_timeout(
            &claude.binary,
            &command_args,
            &claude.env,
            claude.clear_env,
            claude.working_dir.as_deref(),
            timeout,
            SpawnPolicy::of(claude),
        )
        .await?
    } else {
        run_internal(
            &claude.binary,
            &command_args,
            &claude.env,
            claude.clear_env,
            claude.working_dir.as_deref(),
            SpawnPolicy::of(claude),
        )
        .await?
    };

    record_exec_outcome(&span, output.exit_code, started);
    Ok(output)
}

/// Run a claude command and allow specific non-zero exit codes.
///
/// Dropping the returned future kills the child; see [`run_claude`].
#[cfg(feature = "async")]
pub async fn run_claude_allow_exit_codes(
    claude: &Claude,
    args: Vec<String>,
    allowed_codes: &[i32],
) -> Result<CommandOutput> {
    let output = run_claude(claude, args).await;

    match output {
        Err(Error::CommandFailed {
            exit_code,
            stdout,
            stderr,
            ..
        }) if allowed_codes.contains(&exit_code) => Ok(CommandOutput {
            stdout,
            stderr,
            exit_code,
            success: false,
        }),
        other => other,
    }
}

#[cfg(feature = "async")]
async fn run_internal(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace: _, // no kill site on this path
        die_with_parent,
        on_spawn,
    } = policy;
    let mut cmd = Command::new(binary);
    cmd.args(args);

    // Prevent child from inheriting/blocking on parent's stdin.
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    // Dropping the in-flight future must kill the child, not leave the
    // CLI running unattended (see the module docs).
    cmd.kill_on_drop(true);
    // Own process group (Unix) so cancellation can signal the whole
    // tree, not just the direct child (see GroupKillGuard). Opt out
    // via ClaudeBuilder::process_group.
    apply_process_group(&mut cmd, process_group);
    apply_die_with_parent(&mut cmd, die_with_parent);

    apply_child_environment(cmd.as_std_mut(), clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    // Spawn explicitly (rather than `Command::output`) so the pid is
    // available to the group-kill guard while the run is in flight.
    let mut child = spawn_retrying_txtbsy(&mut cmd)
        .await
        .map_err(|e| Error::Io {
            message: format!("failed to spawn claude: {e}"),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        })?;
    let mut group = arm_and_notify(process_group, child.id(), on_spawn);

    let mut stdout_handle = child.stdout.take().expect("stdout was piped");
    let mut stderr_handle = child.stderr.take().expect("stderr was piped");

    let (status, stdout, stderr) = tokio::join!(
        child.wait(),
        drain(&mut stdout_handle),
        drain(&mut stderr_handle),
    );

    let status = status.map_err(|e| Error::Io {
        message: "failed to wait for claude process".to_string(),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })?;
    group.disarm();

    let exit_code = status.code().unwrap_or(-1);

    if !status.success() {
        return Err(Error::from_command_failure(
            format!("{} {}", binary.display(), args.join(" ")),
            exit_code,
            stdout,
            stderr,
            working_dir.map(|p| p.to_path_buf()),
        ));
    }

    Ok(CommandOutput {
        stdout,
        stderr,
        exit_code,
        success: true,
    })
}

/// Run a command with a timeout, killing the child's whole process
/// group (Unix) and reaping the child on expiration.
///
/// Spawns the child explicitly (rather than wrapping `Command::output()` in a
/// `tokio::time::timeout`) so that we retain the handle and can SIGKILL the
/// child and wait for it when the timeout fires. Stdout and stderr are drained
/// concurrently with `child.wait()` via `tokio::join!` so neither pipe buffer
/// can fill up and deadlock the child.
///
/// On timeout, partial stdout/stderr captured before the kill is logged at
/// warn level; the returned `Error::Timeout` itself does not carry the
/// partial output.
#[cfg(feature = "async")]
async fn run_with_timeout(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    timeout: Duration,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace,
        die_with_parent,
        on_spawn,
    } = policy;
    let mut cmd = Command::new(binary);
    cmd.args(args);
    cmd.stdin(std::process::Stdio::null());
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());
    // Dropping the in-flight future must kill the child, not leave the
    // CLI running unattended (see the module docs).
    cmd.kill_on_drop(true);
    // Own process group (Unix) so cancellation can signal the whole
    // tree, not just the direct child (see GroupKillGuard). Opt out
    // via ClaudeBuilder::process_group.
    apply_process_group(&mut cmd, process_group);
    apply_die_with_parent(&mut cmd, die_with_parent);
    apply_child_environment(cmd.as_std_mut(), clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    let mut child = spawn_retrying_txtbsy(&mut cmd)
        .await
        .map_err(|e| Error::Io {
            message: format!("failed to spawn claude: {e}"),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        })?;
    let mut group = arm_and_notify(process_group, child.id(), on_spawn);

    let mut stdout = child.stdout.take().expect("stdout was piped");
    let mut stderr = child.stderr.take().expect("stderr was piped");

    // Drain stdout and stderr concurrently with the process wait so
    // neither pipe buffer can fill up and deadlock the child.
    // tokio::join! polls all three on the same task; no tokio::spawn
    // (and therefore no `rt` feature) required.
    let wait_and_drain = async {
        let (status, stdout_str, stderr_str) =
            tokio::join!(child.wait(), drain(&mut stdout), drain(&mut stderr));
        (status, stdout_str, stderr_str)
    };

    match tokio::time::timeout(timeout, wait_and_drain).await {
        Ok((Ok(status), stdout, stderr)) => {
            group.disarm();
            let exit_code = status.code().unwrap_or(-1);

            if !status.success() {
                return Err(Error::from_command_failure(
                    format!("{} {}", binary.display(), args.join(" ")),
                    exit_code,
                    stdout,
                    stderr,
                    working_dir.map(|p| p.to_path_buf()),
                ));
            }

            Ok(CommandOutput {
                stdout,
                stderr,
                exit_code,
                success: true,
            })
        }
        Ok((Err(e), _stdout, _stderr)) => Err(Error::Io {
            message: "failed to wait for claude process".to_string(),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        }),
        Err(_) => {
            // Timeout: take down the whole group, honoring the
            // optional SIGTERM grace, then kill+reap the direct
            // child. The group kill takes down subprocesses that
            // could otherwise hold our pipe fds open forever; the
            // capped drain below stays as a backstop.
            kill_group_with_grace(&mut group, kill_grace).await;
            let _ = child.kill().await;
            let drain_budget = Duration::from_millis(200);
            let stdout_str = tokio::time::timeout(drain_budget, drain(&mut stdout))
                .await
                .unwrap_or_default();
            let stderr_str = tokio::time::timeout(drain_budget, drain(&mut stderr))
                .await
                .unwrap_or_default();
            if !stdout_str.is_empty() || !stderr_str.is_empty() {
                warn!(
                    stdout = %stdout_str,
                    stderr = %stderr_str,
                    "partial output from timed-out process",
                );
            }
            Err(Error::Timeout {
                timeout_seconds: timeout.as_secs(),
            })
        }
    }
}

#[cfg(feature = "async")]
async fn drain<R: AsyncReadExt + Unpin>(reader: &mut R) -> String {
    let mut buf = Vec::new();
    let _ = reader.read_to_end(&mut buf).await;
    String::from_utf8_lossy(&buf).into_owned()
}

/// Total wall-clock time to keep retrying a spawn that reports `ETXTBSY`.
///
/// Measured as elapsed time rather than a sum of backoffs so a saturated
/// host (a CI job running build + clippy + tests at once) still gets the
/// full window: the busy descriptor can stay open longer than the old
/// 500ms budget under that load, which surfaced as a spurious spawn
/// failure. This is only ever spent when a real `ETXTBSY` occurs, which
/// does not happen against an already-installed binary in production.
#[cfg(any(feature = "async", feature = "sync"))]
const TXTBSY_RETRY_BUDGET: Duration = Duration::from_secs(3);

/// Per-attempt backoff ceiling while retrying `ETXTBSY`.
///
/// Backoff grows exponentially but is capped so retries stay frequent for
/// the whole budget: the busy window can clear at any instant, and a large
/// tail sleep (the old loop reached 1-2s) would keep spawning stalled long
/// after the descriptor closed.
#[cfg(any(feature = "async", feature = "sync"))]
const TXTBSY_MAX_BACKOFF: Duration = Duration::from_millis(25);

/// Spawn `cmd`, retrying briefly on `ETXTBSY` (`ExecutableFileBusy`).
///
/// `execve` fails with `ETXTBSY` when another process holds the target file
/// open for writing. In a multithreaded program this happens transiently even
/// for a file this process has finished writing: if another thread `fork`s
/// while a writable descriptor to the binary is still open, the child inherits
/// that descriptor and holds it until its own `exec` completes. Any `execve`
/// of the file in that window sees a writer and fails. The condition always
/// clears on its own, so retry within a bounded wall-clock budget rather than
/// surfacing a spurious spawn failure.
#[cfg(feature = "async")]
async fn spawn_retrying_txtbsy(cmd: &mut Command) -> std::io::Result<tokio::process::Child> {
    let start = std::time::Instant::now();
    let mut backoff = Duration::from_millis(1);
    loop {
        match cmd.spawn() {
            Err(e)
                if e.kind() == std::io::ErrorKind::ExecutableFileBusy
                    && start.elapsed() < TXTBSY_RETRY_BUDGET =>
            {
                tokio::time::sleep(backoff).await;
                backoff = (backoff * 2).min(TXTBSY_MAX_BACKOFF);
            }
            other => return other,
        }
    }
}

// ---------- sync twins ----------

/// Blocking mirror of [`run_claude`]. Available with the `sync` feature.
#[cfg(feature = "sync")]
pub fn run_claude_sync(claude: &Claude, args: Vec<String>) -> Result<CommandOutput> {
    run_claude_with_retry_sync(claude, args, None)
}

/// Blocking mirror of [`run_claude_with_retry`].
#[cfg(feature = "sync")]
pub fn run_claude_with_retry_sync(
    claude: &Claude,
    args: Vec<String>,
    retry_override: Option<&crate::retry::RetryPolicy>,
) -> Result<CommandOutput> {
    let policy = retry_override.or(claude.retry_policy.as_ref());

    match policy {
        Some(policy) => {
            crate::retry::with_retry_sync(policy, || run_claude_once_sync(claude, args.clone()))
        }
        None => run_claude_once_sync(claude, args),
    }
}

/// Blocking mirror of [`run_claude_with_stdin_prompt`].
///
/// stdin mode does not retry -- the stdin pipe is consumed after the first
/// attempt and cannot be rewound.
#[cfg(feature = "sync")]
pub fn run_claude_with_stdin_prompt_sync(
    claude: &Claude,
    args: Vec<String>,
    stdin_content: String,
) -> Result<CommandOutput> {
    let command_args = full_command_args(claude, args);

    let span = exec_span(claude, &command_args, "stdin-sync");
    let _enter = span.enter();
    let started = std::time::Instant::now();
    debug!(binary = %claude.binary.display(), args = ?command_args, "executing claude command (stdin prompt, sync)");

    let result = if let Some(timeout) = claude.timeout {
        run_with_timeout_stdin_sync(
            &claude.binary,
            &command_args,
            &claude.env,
            claude.clear_env,
            claude.working_dir.as_deref(),
            timeout,
            stdin_content,
            SpawnPolicy::of(claude),
        )
    } else {
        run_internal_stdin_sync(
            &claude.binary,
            &command_args,
            &claude.env,
            claude.clear_env,
            claude.working_dir.as_deref(),
            stdin_content,
            SpawnPolicy::of(claude),
        )
    };

    if let Ok(output) = &result {
        record_exec_outcome(&span, output.exit_code, started);
    }
    result
}

#[cfg(feature = "sync")]
fn run_internal_stdin_sync(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    stdin_content: String,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace: _, // no kill site on this path
        die_with_parent,
        on_spawn,
    } = policy;
    use std::io::Write;
    use std::process::{Command as StdCommand, Stdio};

    let mut cmd = StdCommand::new(binary);
    cmd.args(args);
    cmd.stdin(Stdio::piped());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    // Own process group (Unix) so a kill can signal the whole tree,
    // not just the direct child (see GroupKillGuard). Opt out via
    // ClaudeBuilder::process_group.
    apply_process_group_sync(&mut cmd, process_group);
    apply_die_with_parent_sync(&mut cmd, die_with_parent);
    apply_child_environment(&mut cmd, clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    let mut child = spawn_retrying_txtbsy_sync(&mut cmd).map_err(|e| Error::Io {
        message: format!("failed to spawn claude: {e}"),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })?;
    let mut group = arm_and_notify(process_group, Some(child.id()), on_spawn);

    // Write the prompt to stdin, then drop the handle so the child sees EOF.
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(stdin_content.as_bytes())
            .map_err(|e| Error::Io {
                message: format!("failed to write to claude stdin: {e}"),
                source: e,
                working_dir: working_dir.map(|p| p.to_path_buf()),
            })?;
        stdin.flush().map_err(|e| Error::Io {
            message: format!("failed to flush claude stdin: {e}"),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        })?;
        // Drop stdin so the child sees EOF.
    }

    let output = child.wait_with_output().map_err(|e| Error::Io {
        message: "failed to wait for claude process".to_string(),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })?;
    group.disarm();

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let exit_code = output.status.code().unwrap_or(-1);

    if !output.status.success() {
        return Err(Error::from_command_failure(
            format!("{} {}", binary.display(), args.join(" ")),
            exit_code,
            stdout,
            stderr,
            working_dir.map(|p| p.to_path_buf()),
        ));
    }

    Ok(CommandOutput {
        stdout,
        stderr,
        exit_code,
        success: true,
    })
}

#[cfg(feature = "sync")]
#[allow(clippy::too_many_arguments)]
fn run_with_timeout_stdin_sync(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    timeout: Duration,
    stdin_content: String,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace,
        die_with_parent,
        on_spawn,
    } = policy;
    use std::io::Write;
    use std::process::{Command as StdCommand, Stdio};
    use std::thread;
    use wait_timeout::ChildExt;

    let mut cmd = StdCommand::new(binary);
    cmd.args(args);
    cmd.stdin(Stdio::piped());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    // Own process group (Unix) so a kill can signal the whole tree,
    // not just the direct child (see GroupKillGuard). Opt out via
    // ClaudeBuilder::process_group.
    apply_process_group_sync(&mut cmd, process_group);
    apply_die_with_parent_sync(&mut cmd, die_with_parent);
    apply_child_environment(&mut cmd, clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    let mut child = spawn_retrying_txtbsy_sync(&mut cmd).map_err(|e| Error::Io {
        message: format!("failed to spawn claude: {e}"),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })?;
    let mut group = arm_and_notify(process_group, Some(child.id()), on_spawn);

    // Write the prompt to stdin, then drop the handle so the child sees EOF.
    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(stdin_content.as_bytes())
            .map_err(|e| Error::Io {
                message: format!("failed to write to claude stdin: {e}"),
                source: e,
                working_dir: working_dir.map(|p| p.to_path_buf()),
            })?;
        stdin.flush().map_err(|e| Error::Io {
            message: format!("failed to flush claude stdin: {e}"),
            source: e,
            working_dir: working_dir.map(|p| p.to_path_buf()),
        })?;
        // Drop stdin so the child sees EOF.
    }

    let stdout = child.stdout.take().expect("stdout was piped");
    let stderr = child.stderr.take().expect("stderr was piped");

    let stdout_thread = thread::spawn(move || drain_sync(stdout));
    let stderr_thread = thread::spawn(move || drain_sync(stderr));

    match child.wait_timeout(timeout).map_err(|e| Error::Io {
        message: "failed to wait for claude process".to_string(),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })? {
        Some(status) => {
            group.disarm();
            let stdout = stdout_thread.join().unwrap_or_default();
            let stderr = stderr_thread.join().unwrap_or_default();
            let exit_code = status.code().unwrap_or(-1);

            if !status.success() {
                return Err(Error::from_command_failure(
                    format!("{} {}", binary.display(), args.join(" ")),
                    exit_code,
                    stdout,
                    stderr,
                    working_dir.map(|p| p.to_path_buf()),
                ));
            }

            Ok(CommandOutput {
                stdout,
                stderr,
                exit_code,
                success: true,
            })
        }
        None => {
            // Timeout: take down the whole group first (subprocesses
            // may hold our pipe fds), honoring the optional SIGTERM
            // grace, then kill+reap the direct child.
            kill_group_with_grace_sync(&mut group, kill_grace);
            let _ = child.kill();
            let _ = child.wait();
            let (stdout_str, stderr_str) =
                join_with_deadline(stdout_thread, stderr_thread, Duration::from_millis(200));
            if !stdout_str.is_empty() || !stderr_str.is_empty() {
                warn!(
                    stdout = %stdout_str,
                    stderr = %stderr_str,
                    "partial output from timed-out process",
                );
            }
            Err(Error::Timeout {
                timeout_seconds: timeout.as_secs(),
            })
        }
    }
}

#[cfg(feature = "sync")]
fn run_claude_once_sync(claude: &Claude, args: Vec<String>) -> Result<CommandOutput> {
    let command_args = full_command_args(claude, args);

    let span = exec_span(claude, &command_args, "oneshot-sync");
    let _enter = span.enter();
    let started = std::time::Instant::now();
    debug!(binary = %claude.binary.display(), args = ?command_args, "executing claude command (sync)");

    let result = if let Some(timeout) = claude.timeout {
        run_with_timeout_sync(
            &claude.binary,
            &command_args,
            &claude.env,
            claude.clear_env,
            claude.working_dir.as_deref(),
            timeout,
            SpawnPolicy::of(claude),
        )
    } else {
        run_internal_sync(
            &claude.binary,
            &command_args,
            &claude.env,
            claude.clear_env,
            claude.working_dir.as_deref(),
            SpawnPolicy::of(claude),
        )
    };

    if let Ok(output) = &result {
        record_exec_outcome(&span, output.exit_code, started);
    }
    result
}

/// Blocking mirror of [`run_claude_allow_exit_codes`].
#[cfg(feature = "sync")]
pub fn run_claude_allow_exit_codes_sync(
    claude: &Claude,
    args: Vec<String>,
    allowed_codes: &[i32],
) -> Result<CommandOutput> {
    match run_claude_sync(claude, args) {
        Err(Error::CommandFailed {
            exit_code,
            stdout,
            stderr,
            ..
        }) if allowed_codes.contains(&exit_code) => Ok(CommandOutput {
            stdout,
            stderr,
            exit_code,
            success: false,
        }),
        other => other,
    }
}

#[cfg(feature = "sync")]
fn run_internal_sync(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace: _, // no kill site on this path
        die_with_parent,
        on_spawn,
    } = policy;
    use std::process::{Command as StdCommand, Stdio};

    let mut cmd = StdCommand::new(binary);
    cmd.args(args);
    cmd.stdin(Stdio::null());
    // Own process group (Unix); see the module docs. This path has no
    // kill site (a blocking call cannot be cancelled mid-flight), so
    // there is no guard to arm -- but the child still exists and a
    // supervisor still wants its pid, so the spawn is observed below.
    apply_process_group_sync(&mut cmd, process_group);
    apply_die_with_parent_sync(&mut cmd, die_with_parent);
    apply_child_environment(&mut cmd, clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    let output =
        output_retrying_txtbsy_sync_observed(&mut cmd, process_group, on_spawn).map_err(|e| {
            Error::Io {
                message: format!("failed to spawn claude: {e}"),
                source: e,
                working_dir: working_dir.map(|p| p.to_path_buf()),
            }
        })?;

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let exit_code = output.status.code().unwrap_or(-1);

    if !output.status.success() {
        return Err(Error::from_command_failure(
            format!("{} {}", binary.display(), args.join(" ")),
            exit_code,
            stdout,
            stderr,
            working_dir.map(|p| p.to_path_buf()),
        ));
    }

    Ok(CommandOutput {
        stdout,
        stderr,
        exit_code,
        success: true,
    })
}

/// Blocking run with a timeout. Mirrors [`run_with_timeout`]: spawns
/// the child, drains stdout/stderr on dedicated threads so neither
/// pipe buffer can fill up while we wait, then uses
/// [`wait_timeout::ChildExt::wait_timeout`] to enforce the deadline.
/// On timeout, the child's whole process group (Unix) is SIGKILLed and
/// the child reaped; partial output is logged at warn but the returned
/// [`Error::Timeout`] does not carry it.
#[cfg(feature = "sync")]
fn run_with_timeout_sync(
    binary: &std::path::Path,
    args: &[String],
    env: &std::collections::HashMap<String, String>,
    clear_env: bool,
    working_dir: Option<&std::path::Path>,
    timeout: Duration,
    policy: SpawnPolicy<'_>,
) -> Result<CommandOutput> {
    let SpawnPolicy {
        process_group,
        kill_grace,
        die_with_parent,
        on_spawn,
    } = policy;
    use std::process::{Command as StdCommand, Stdio};
    use std::thread;
    use wait_timeout::ChildExt;

    let mut cmd = StdCommand::new(binary);
    cmd.args(args);
    cmd.stdin(Stdio::null());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    // Own process group (Unix) so a kill can signal the whole tree,
    // not just the direct child (see GroupKillGuard). Opt out via
    // ClaudeBuilder::process_group.
    apply_process_group_sync(&mut cmd, process_group);
    apply_die_with_parent_sync(&mut cmd, die_with_parent);
    apply_child_environment(&mut cmd, clear_env, env);

    if let Some(dir) = working_dir {
        cmd.current_dir(dir);
    }

    let mut child = spawn_retrying_txtbsy_sync(&mut cmd).map_err(|e| Error::Io {
        message: format!("failed to spawn claude: {e}"),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })?;
    let mut group = arm_and_notify(process_group, Some(child.id()), on_spawn);

    // Detach stdout/stderr onto their own threads so neither can block
    // the child by filling its pipe buffer. Each thread owns its half
    // and drops it on completion, which closes the parent's fd and
    // lets read_to_end() return EOF once the child exits.
    let stdout = child.stdout.take().expect("stdout was piped");
    let stderr = child.stderr.take().expect("stderr was piped");

    let stdout_thread = thread::spawn(move || drain_sync(stdout));
    let stderr_thread = thread::spawn(move || drain_sync(stderr));

    match child.wait_timeout(timeout).map_err(|e| Error::Io {
        message: "failed to wait for claude process".to_string(),
        source: e,
        working_dir: working_dir.map(|p| p.to_path_buf()),
    })? {
        Some(status) => {
            group.disarm();
            let stdout = stdout_thread.join().unwrap_or_default();
            let stderr = stderr_thread.join().unwrap_or_default();
            let exit_code = status.code().unwrap_or(-1);

            if !status.success() {
                return Err(Error::from_command_failure(
                    format!("{} {}", binary.display(), args.join(" ")),
                    exit_code,
                    stdout,
                    stderr,
                    working_dir.map(|p| p.to_path_buf()),
                ));
            }

            Ok(CommandOutput {
                stdout,
                stderr,
                exit_code,
                success: true,
            })
        }
        None => {
            // Timeout: take down the whole group, honoring the
            // optional SIGTERM grace, then kill+reap the direct
            // child. The group kill takes down subprocesses that
            // could otherwise hold our pipe fds open and block the
            // drain threads; the capped join below stays as a
            // backstop.
            kill_group_with_grace_sync(&mut group, kill_grace);
            let _ = child.kill();
            let _ = child.wait();

            let (stdout_str, stderr_str) =
                join_with_deadline(stdout_thread, stderr_thread, Duration::from_millis(200));

            if !stdout_str.is_empty() || !stderr_str.is_empty() {
                warn!(
                    stdout = %stdout_str,
                    stderr = %stderr_str,
                    "partial output from timed-out process",
                );
            }

            Err(Error::Timeout {
                timeout_seconds: timeout.as_secs(),
            })
        }
    }
}

#[cfg(feature = "sync")]
fn drain_sync<R: std::io::Read>(mut reader: R) -> String {
    let mut buf = Vec::new();
    let _ = reader.read_to_end(&mut buf);
    String::from_utf8_lossy(&buf).into_owned()
}

/// Blocking mirror of [`spawn_retrying_txtbsy`]. See that function for why
/// `ETXTBSY` is retried rather than surfaced.
#[cfg(feature = "sync")]
fn spawn_retrying_txtbsy_sync(
    cmd: &mut std::process::Command,
) -> std::io::Result<std::process::Child> {
    let start = std::time::Instant::now();
    let mut backoff = Duration::from_millis(1);
    loop {
        match cmd.spawn() {
            Err(e)
                if e.kind() == std::io::ErrorKind::ExecutableFileBusy
                    && start.elapsed() < TXTBSY_RETRY_BUDGET =>
            {
                std::thread::sleep(backoff);
                backoff = (backoff * 2).min(TXTBSY_MAX_BACKOFF);
            }
            other => return other,
        }
    }
}

/// Run `cmd` to completion, retrying on `ETXTBSY` like
/// [`spawn_retrying_txtbsy_sync`].
///
/// The blocking no-timeout capture path calls `Command::output` (spawn,
/// wait, and collect in one step) rather than holding a `Child`, so it
/// needs the same retry wrapped around `output` itself. The `ETXTBSY`
/// still occurs at the `execve` inside `output`.
#[cfg(feature = "sync")]
/// Run to completion, reporting the child to `on_spawn` first.
///
/// `Command::output` is `spawn` followed by `wait_with_output`, so splitting
/// the two is behaviour-identical and makes the pid observable on a path that
/// otherwise never exposes it.
#[cfg(feature = "sync")]
fn output_retrying_txtbsy_sync_observed(
    cmd: &mut std::process::Command,
    process_group: bool,
    on_spawn: Option<&crate::SpawnObserver>,
) -> std::io::Result<std::process::Output> {
    // `Command::output` pipes stdout and stderr implicitly; `spawn` does not,
    // so setting them here keeps this split behaviour-identical rather than
    // silently returning empty captures.
    cmd.stdout(std::process::Stdio::piped());
    cmd.stderr(std::process::Stdio::piped());

    let start = std::time::Instant::now();
    let mut backoff = Duration::from_millis(1);
    loop {
        let spawned = cmd.spawn().inspect(|child| {
            if let Some(observer) = on_spawn {
                let pid = child.id();
                observer(crate::SpawnInfo {
                    pid,
                    pgid: process_group.then_some(pid),
                });
            }
        });
        match spawned.and_then(std::process::Child::wait_with_output) {
            Err(e)
                if e.kind() == std::io::ErrorKind::ExecutableFileBusy
                    && start.elapsed() < TXTBSY_RETRY_BUDGET =>
            {
                std::thread::sleep(backoff);
                backoff = (backoff * 2).min(TXTBSY_MAX_BACKOFF);
            }
            other => return other,
        }
    }
}

/// Wait for both drain threads to finish, returning "" for any that
/// miss the deadline. Threads aren't cancellable in std; if the child's
/// subprocesses are still holding a pipe fd open after kill(), the
/// drain thread leaks. That's a pathological case; the common timeout
/// path with a responsive child joins in microseconds.
#[cfg(feature = "sync")]
fn join_with_deadline(
    stdout_thread: std::thread::JoinHandle<String>,
    stderr_thread: std::thread::JoinHandle<String>,
    budget: Duration,
) -> (String, String) {
    use std::sync::mpsc;
    use std::thread;

    let (tx, rx) = mpsc::channel::<(&'static str, String)>();

    let tx_out = tx.clone();
    let tx_err = tx;

    thread::spawn(move || {
        let s = stdout_thread.join().unwrap_or_default();
        let _ = tx_out.send(("stdout", s));
    });
    thread::spawn(move || {
        let s = stderr_thread.join().unwrap_or_default();
        let _ = tx_err.send(("stderr", s));
    });

    let mut stdout = String::new();
    let mut stderr = String::new();
    let deadline = std::time::Instant::now() + budget;

    for _ in 0..2 {
        let now = std::time::Instant::now();
        if now >= deadline {
            break;
        }
        match rx.recv_timeout(deadline - now) {
            Ok(("stdout", s)) => stdout = s,
            Ok(("stderr", s)) => stderr = s,
            Ok(_) => unreachable!(),
            Err(_) => break,
        }
    }

    (stdout, stderr)
}

// Fake-binary-driven tests for the spawn/execute paths. Unix-only: they
// write and run a small bash `claude` stand-in, which cannot execute on
// Windows. CI runs `cargo test --lib` on Windows too, so the module is
// gated on `unix` to compile out there; ubuntu/macOS (and `llvm-cov`)
// exercise it. `tempfile` is a dev-dependency, so it is always available
// under `#[cfg(test)]` regardless of the crate feature.
#[cfg(all(test, unix, any(feature = "async", feature = "sync")))]
mod tests {
    use super::*;
    use std::io::Write;
    use std::os::unix::fs::PermissionsExt;

    use crate::Claude;

    /// Write `body` as an executable bash `claude` stand-in in a fresh
    /// tempdir. Returns the dir (keep it bound so it outlives the run)
    /// and the script path.
    fn fake_script(body: &str) -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("fake-claude.sh");
        // Close the writable handle before returning so the window in which a
        // concurrent test's fork could inherit a writable fd to this script
        // (and make our later execve fail with ETXTBSY) is as short as
        // possible. Spawn itself retries ETXTBSY; this just makes it rarer.
        {
            let mut f = std::fs::File::create(&path).expect("create script");
            write!(f, "#!/usr/bin/env bash\n{body}\n").expect("write script");
            f.sync_all().expect("sync script");
        }
        let perms = std::fs::Permissions::from_mode(0o755);
        std::fs::set_permissions(&path, perms).expect("chmod");
        (dir, path)
    }

    fn client(path: &std::path::Path) -> Claude {
        Claude::builder()
            .binary(path)
            .build()
            .expect("build client")
    }

    #[test]
    fn full_command_args_puts_global_args_first() {
        let claude = Claude::builder()
            .binary("/usr/local/bin/claude")
            .arg("--debug")
            .arg("--verbose")
            .build()
            .expect("build client");
        let args = full_command_args(&claude, vec!["--print".to_string(), "hi".to_string()]);
        assert_eq!(args, ["--debug", "--verbose", "--print", "hi"]);
    }

    #[test]
    fn full_command_args_without_global_args_is_passthrough() {
        let claude = Claude::builder()
            .binary("/usr/local/bin/claude")
            .build()
            .expect("build client");
        let args = full_command_args(&claude, vec!["--print".to_string()]);
        assert_eq!(args, ["--print"]);
    }

    // Serializes the env-scrub tests, which mutate process-global env.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn set_scrub_vars() {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: the synchronous mutation is serialized by ENV_LOCK and
        // not held across any await; no other test reads these vars.
        unsafe {
            std::env::set_var("CLAUDECODE", "1");
            std::env::set_var("CLAUDE_CODE_ENTRYPOINT", "cli");
        }
    }

    fn clear_scrub_vars() {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: see set_scrub_vars.
        unsafe {
            std::env::remove_var("CLAUDECODE");
            std::env::remove_var("CLAUDE_CODE_ENTRYPOINT");
        }
    }

    // ---------- async ----------

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_success_maps_output() {
        let (_dir, path) = fake_script(r#"echo "hi there"; exit 0"#);
        let out = run_claude(&client(&path), vec!["--version".into()])
            .await
            .expect("success");
        assert!(out.success);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("hi there"));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_nonzero_exit_maps_command_failed() {
        let (_dir, path) = fake_script(r#"echo "boom" >&2; exit 3"#);
        let err = run_claude(&client(&path), vec![]).await.unwrap_err();
        match err {
            Error::CommandFailed {
                exit_code, stderr, ..
            } => {
                assert_eq!(exit_code, 3);
                assert!(stderr.contains("boom"));
            }
            other => panic!("expected CommandFailed, got {other:?}"),
        }
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_rail_stop_maps_max_turns() {
        let (_dir, path) = fake_script(
            r#"echo '{"type":"result","subtype":"error_max_turns","is_error":true,"errors":["Reached maximum number of turns (2)"]}'; exit 1"#,
        );
        let err = run_claude(&client(&path), vec![]).await.unwrap_err();
        assert!(
            matches!(
                err,
                Error::MaxTurnsExceeded {
                    max_turns: Some(2),
                    ..
                }
            ),
            "got: {err:?}"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_auth_shaped_stderr_maps_auth() {
        let (_dir, path) =
            fake_script(r#"echo "Not authenticated. Run `claude login`." >&2; exit 1"#);
        let err = run_claude(&client(&path), vec![]).await.unwrap_err();
        assert!(matches!(err, Error::Auth { .. }), "got: {err:?}");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_scrubs_claude_env_vars() {
        let (_dir, path) =
            fake_script(r#"echo "CC=[${CLAUDECODE:-}] EP=[${CLAUDE_CODE_ENTRYPOINT:-}]""#);
        // The child sees the vars scrubbed regardless; setting them in the
        // parent is what makes the assertion meaningful rather than
        // trivially empty. Correctness does not depend on the lock (the
        // scrub removes them either way), so it only wraps the synchronous
        // env mutations -- never held across the await, per clippy.
        set_scrub_vars();
        let out = run_claude(&client(&path), vec![]).await.expect("success");
        clear_scrub_vars();
        assert!(out.stdout.contains("CC=[]"), "got: {}", out.stdout);
        assert!(out.stdout.contains("EP=[]"), "got: {}", out.stdout);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_applies_working_dir() {
        let (_dir, path) = fake_script(r#"pwd"#);
        let workdir = tempfile::tempdir().expect("workdir");
        let claude = Claude::builder()
            .binary(&path)
            .working_dir(workdir.path())
            .build()
            .expect("build");
        let out = run_claude(&claude, vec![]).await.expect("success");
        let got = std::fs::canonicalize(out.stdout.trim()).expect("canonicalize pwd");
        let want = std::fs::canonicalize(workdir.path()).expect("canonicalize workdir");
        assert_eq!(got, want);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_stdin_prompt_round_trips() {
        let (_dir, path) = fake_script(r#"cat"#);
        let out = run_claude_with_stdin_prompt(&client(&path), vec![], "hello via stdin".into())
            .await
            .expect("success");
        assert!(out.stdout.contains("hello via stdin"));
    }

    // The retry loop in `spawn_retrying_txtbsy` must only absorb `ETXTBSY`;
    // every other spawn error has to surface promptly rather than be retried
    // until the budget elapses. A missing binary yields `NotFound`, which
    // must return on the first attempt.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_spawn_retry_passes_through_non_txtbsy_error() {
        let mut cmd = Command::new("/nonexistent/definitely-not-a-real-binary");
        let err = spawn_retrying_txtbsy(&mut cmd)
            .await
            .expect_err("spawn of missing binary should fail");
        assert_eq!(err.kind(), std::io::ErrorKind::NotFound, "got: {err:?}");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_allow_exit_codes_permits_listed_code() {
        let (_dir, path) = fake_script(r#"echo out; exit 2"#);
        let out = run_claude_allow_exit_codes(&client(&path), vec![], &[2])
            .await
            .expect("allowed code is Ok");
        assert!(!out.success);
        assert_eq!(out.exit_code, 2);
        assert!(out.stdout.contains("out"));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_allow_exit_codes_still_errors_on_unlisted_code() {
        let (_dir, path) = fake_script(r#"exit 2"#);
        let err = run_claude_allow_exit_codes(&client(&path), vec![], &[5])
            .await
            .unwrap_err();
        assert!(
            matches!(err, Error::CommandFailed { exit_code: 2, .. }),
            "got: {err:?}"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_timeout_fires_on_slow_child() {
        let (_dir, path) = fake_script(r#"sleep 3; echo done"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_millis(300))
            .build()
            .expect("build");
        let err = run_claude(&claude, vec![]).await.unwrap_err();
        assert!(matches!(err, Error::Timeout { .. }), "got: {err:?}");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_timeout_path_returns_output_when_fast() {
        let (_dir, path) = fake_script(r#"echo quick"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_secs(30))
            .build()
            .expect("build");
        let out = run_claude(&claude, vec![]).await.expect("success");
        assert!(out.stdout.contains("quick"));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_timeout_path_maps_command_failed() {
        let (_dir, path) = fake_script(r#"echo e >&2; exit 4"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_secs(30))
            .build()
            .expect("build");
        let err = run_claude(&claude, vec![]).await.unwrap_err();
        assert!(
            matches!(err, Error::CommandFailed { exit_code: 4, .. }),
            "got: {err:?}"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_stdin_with_timeout_round_trips() {
        let (_dir, path) = fake_script(r#"cat"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_secs(30))
            .build()
            .expect("build");
        let out = run_claude_with_stdin_prompt(&claude, vec![], "piped under timeout".into())
            .await
            .expect("success");
        assert!(out.stdout.contains("piped under timeout"));
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_stdin_timeout_fires_on_slow_child() {
        let (_dir, path) = fake_script(r#"sleep 3"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_millis(300))
            .build()
            .expect("build");
        let err = run_claude_with_stdin_prompt(&claude, vec![], "x".into())
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Timeout { .. }), "got: {err:?}");
    }

    /// Drive `fut` just long enough for the fake script to write its pid
    /// file, then drop it mid-flight (on return) and hand back the pid.
    #[cfg(feature = "async")]
    async fn drop_in_flight_and_capture_pid<F>(fut: F, pid_path: &std::path::Path) -> u32
    where
        F: std::future::Future,
        F::Output: std::fmt::Debug,
    {
        tokio::pin!(fut);
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        loop {
            if let Some(pid) = std::fs::read_to_string(pid_path)
                .ok()
                .and_then(|s| s.trim().parse().ok())
            {
                // Returning drops the pinned future here, mid-flight.
                return pid;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "child never wrote its pid file"
            );
            tokio::select! {
                out = &mut fut => panic!("future completed before drop: {out:?}"),
                _ = tokio::time::sleep(Duration::from_millis(10)) => {}
            }
        }
    }

    /// Poll until `pid` is dead or a zombie awaiting reap. The kill is
    /// delivered synchronously (killpg / kill_on_drop's start_kill), but
    /// reaping happens asynchronously, so a transient zombie counts as
    /// killed. Blocking on purpose: it runs after the kill has been
    /// issued, so nothing async needs to make progress.
    fn assert_pid_killed(pid: u32) {
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        loop {
            let out = std::process::Command::new("ps")
                .args(["-o", "stat=", "-p", &pid.to_string()])
                .output()
                .expect("run ps");
            let stat = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if !out.status.success() || stat.is_empty() || stat.starts_with('Z') {
                return;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "process {pid} still alive (stat {stat}) after kill"
            );
            std::thread::sleep(Duration::from_millis(25));
        }
    }

    /// Fake script that records its own pid, spawns a same-group
    /// grandchild that records its pid too, then sleeps far longer than
    /// any test deadline. The main shell waits for the grandchild pid
    /// to land before writing its own, so tests that poll for the pid
    /// file can rely on the grandchild pid being readable as well.
    /// Non-interactive bash does not create new process groups for
    /// background jobs, so a group kill must take down both.
    fn group_script(
        pid_path: &std::path::Path,
        gpid_path: &std::path::Path,
    ) -> (tempfile::TempDir, std::path::PathBuf) {
        // `bash -c` rather than a subshell because `$$` inside a
        // subshell still names the parent, and `$BASHPID` needs bash 4
        // (macOS ships 3.2). The path travels as `$0` so it needs no
        // extra quoting.
        fake_script(&format!(
            concat!(
                "bash -c 'echo $$ > \"$0\"; exec sleep 300' \"{g}\" &\n",
                "until [[ -s \"{g}\" ]]; do sleep 0.01; done\n",
                "echo $$ > \"{p}\"\n",
                "exec sleep 300",
            ),
            g = gpid_path.display(),
            p = pid_path.display(),
        ))
    }

    /// Read a pid recorded by `group_script`, if fully written yet.
    fn try_read_pid(path: &std::path::Path) -> Option<u32> {
        std::fs::read_to_string(path).ok()?.trim().parse().ok()
    }

    /// Read a pid recorded by `group_script`. Only the async tests use
    /// this unconditional variant; the sync timeout test reads through
    /// `try_read_pid`, so gate it to keep sync-only builds warning-free.
    #[cfg(feature = "async")]
    fn read_pid(path: &std::path::Path) -> u32 {
        try_read_pid(path).expect("pid file readable")
    }

    // Dropping an in-flight execute future must kill the spawned child:
    // every async spawn site sets kill_on_drop(true), so a caller racing
    // execute against cancellation (tokio::select!, timeout) cannot leak
    // a headless CLI run. `exec` keeps the recorded pid the direct child,
    // so the SIGKILL lands on the process the test watches.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_dropping_in_flight_future_kills_child() {
        let workdir = tempfile::tempdir().expect("workdir");
        let pid_path = workdir.path().join("pid");
        let (_dir, path) = fake_script(&format!(
            r#"echo $$ > "{}"; exec sleep 30"#,
            pid_path.display()
        ));
        let claude = client(&path);
        let pid = drop_in_flight_and_capture_pid(run_claude(&claude, vec![]), &pid_path).await;
        assert_pid_killed(pid);
    }

    // Same guarantee on the timeout path, which holds a Child from
    // spawn_retrying_txtbsy rather than going through Command::output.
    // The configured timeout is far longer than the test; the drop is
    // what kills the child.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_dropping_in_flight_future_kills_child_with_timeout() {
        let workdir = tempfile::tempdir().expect("workdir");
        let pid_path = workdir.path().join("pid");
        let (_dir, path) = fake_script(&format!(
            r#"echo $$ > "{}"; exec sleep 30"#,
            pid_path.display()
        ));
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_secs(120))
            .build()
            .expect("build");
        let pid = drop_in_flight_and_capture_pid(run_claude(&claude, vec![]), &pid_path).await;
        assert_pid_killed(pid);
    }

    // Dropping the future must kill the child's whole process group,
    // not just the direct child: the CLI spawns subprocesses for tool
    // use, and a cancelled run must leave none of them behind.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_dropping_in_flight_future_kills_process_group() {
        let workdir = tempfile::tempdir().expect("workdir");
        let pid_path = workdir.path().join("pid");
        let gpid_path = workdir.path().join("gpid");
        let (_dir, path) = group_script(&pid_path, &gpid_path);
        let claude = client(&path);
        let pid = drop_in_flight_and_capture_pid(run_claude(&claude, vec![]), &pid_path).await;
        assert_pid_killed(pid);
        assert_pid_killed(read_pid(&gpid_path));
    }

    // A fired timeout must also kill the whole group. Before the group
    // kill, the timeout path SIGKILLed only the direct child and the
    // grandchild survived. Retries on a heavily loaded host, where the
    // child can get killed before it records its pids: the kill still
    // happened, but there is nothing to observe, so run it again.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_timeout_kills_process_group() {
        let mut observed = false;
        for _ in 0..5 {
            let workdir = tempfile::tempdir().expect("workdir");
            let pid_path = workdir.path().join("pid");
            let gpid_path = workdir.path().join("gpid");
            let (_dir, path) = group_script(&pid_path, &gpid_path);
            let claude = Claude::builder()
                .binary(&path)
                .timeout(Duration::from_millis(1000))
                .build()
                .expect("build");
            let err = run_claude(&claude, vec![]).await.unwrap_err();
            assert!(matches!(err, Error::Timeout { .. }), "got: {err:?}");
            if let (Some(pid), Some(gpid)) = (try_read_pid(&pid_path), try_read_pid(&gpid_path)) {
                assert_pid_killed(pid);
                assert_pid_killed(gpid);
                observed = true;
                break;
            }
        }
        assert!(observed, "child never recorded pids within 5 timeout runs");
    }

    // With the process-group split opted out, dropping the future still
    // kills the direct child via kill_on_drop, but the grandchild is
    // deliberately left running: that is the pre-group contract #767
    // preserves for terminal-attached hosts, where the terminal is the
    // supervisor. The test reaps the survivor itself.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_process_group_opt_out_kills_only_direct_child() {
        let workdir = tempfile::tempdir().expect("workdir");
        let pid_path = workdir.path().join("pid");
        let gpid_path = workdir.path().join("gpid");
        let (_dir, path) = group_script(&pid_path, &gpid_path);
        let claude = Claude::builder()
            .binary(&path)
            .process_group(false)
            .build()
            .expect("build");
        let pid = drop_in_flight_and_capture_pid(run_claude(&claude, vec![]), &pid_path).await;
        assert_pid_killed(pid);

        // The grandchild must still be alive: no group kill happened.
        let gpid = read_pid(&gpid_path);
        let out = std::process::Command::new("ps")
            .args(["-o", "stat=", "-p", &gpid.to_string()])
            .output()
            .expect("run ps");
        let stat = String::from_utf8_lossy(&out.stdout).trim().to_string();
        assert!(
            out.status.success() && !stat.is_empty() && !stat.starts_with('Z'),
            "grandchild {gpid} should have survived the opt-out drop (stat {stat:?})"
        );

        // Reap the deliberate survivor so it does not idle for 300s.
        let _ = std::process::Command::new("kill")
            .args(["-9", &gpid.to_string()])
            .status();
    }

    /// Fake script that traps SIGTERM, records a marker, and exits
    /// cleanly. The marker can only exist if TERM arrived before the
    /// KILL: SIGKILL cannot be trapped. `sleep` runs as a background
    /// job with `wait` so bash stays alive to handle the signal
    /// (an `exec sleep` would replace bash and drop the trap).
    fn term_trap_script(marker: &std::path::Path) -> (tempfile::TempDir, std::path::PathBuf) {
        fake_script(&format!(
            concat!(
                "trap 'echo term > \"{m}\"; exit 0' TERM\n",
                "sleep 300 &\n",
                "wait $!",
            ),
            m = marker.display(),
        ))
    }

    // With a kill grace configured, a fired timeout SIGTERMs the group
    // before the SIGKILL, giving the child a chance to flush. Retries
    // on a heavily loaded host where the child is killed before it
    // installs its trap: the kill still happened, but there is nothing
    // to observe, so run it again.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_timeout_with_grace_delivers_sigterm_first() {
        let mut observed = false;
        for _ in 0..5 {
            let workdir = tempfile::tempdir().expect("workdir");
            let marker = workdir.path().join("term-marker");
            let (_dir, path) = term_trap_script(&marker);
            let claude = Claude::builder()
                .binary(&path)
                .timeout(Duration::from_millis(500))
                .kill_grace(Duration::from_secs(1))
                .build()
                .expect("build");
            let err = run_claude(&claude, vec![]).await.unwrap_err();
            assert!(matches!(err, Error::Timeout { .. }), "got: {err:?}");
            if marker.exists() {
                observed = true;
                break;
            }
        }
        assert!(observed, "TERM marker never appeared within 5 timeout runs");
    }

    // Blocking mirror of async_timeout_with_grace_delivers_sigterm_first.
    #[cfg(feature = "sync")]
    #[test]
    fn sync_timeout_with_grace_delivers_sigterm_first() {
        let mut observed = false;
        for _ in 0..5 {
            let workdir = tempfile::tempdir().expect("workdir");
            let marker = workdir.path().join("term-marker");
            let (_dir, path) = term_trap_script(&marker);
            let claude = Claude::builder()
                .binary(&path)
                .timeout(Duration::from_millis(500))
                .kill_grace(Duration::from_secs(1))
                .build()
                .expect("build");
            let err = run_claude_sync(&claude, vec![]).unwrap_err();
            assert!(matches!(err, Error::Timeout { .. }), "got: {err:?}");
            if marker.exists() {
                observed = true;
                break;
            }
        }
        assert!(observed, "TERM marker never appeared within 5 timeout runs");
    }

    // Same guarantee for the stdin-prompt path.
    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_dropping_in_flight_stdin_future_kills_child() {
        let workdir = tempfile::tempdir().expect("workdir");
        let pid_path = workdir.path().join("pid");
        let (_dir, path) = fake_script(&format!(
            r#"echo $$ > "{}"; exec sleep 30"#,
            pid_path.display()
        ));
        let claude = client(&path);
        let pid = drop_in_flight_and_capture_pid(
            run_claude_with_stdin_prompt(&claude, vec![], "x".into()),
            &pid_path,
        )
        .await;
        assert_pid_killed(pid);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_spawn_failure_maps_io() {
        let claude = Claude::builder()
            .binary("/nonexistent/definitely/not/here")
            .build()
            .expect("build");
        let err = run_claude(&claude, vec![]).await.unwrap_err();
        assert!(matches!(err, Error::Io { .. }), "got: {err:?}");
    }

    // ---------- sync ----------

    #[cfg(feature = "sync")]
    #[test]
    fn sync_success_maps_output() {
        let (_dir, path) = fake_script(r#"echo "hi sync"; exit 0"#);
        let out = run_claude_sync(&client(&path), vec![]).expect("success");
        assert!(out.success);
        assert!(out.stdout.contains("hi sync"));
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_nonzero_exit_maps_command_failed() {
        let (_dir, path) = fake_script(r#"echo "boom" >&2; exit 3"#);
        let err = run_claude_sync(&client(&path), vec![]).unwrap_err();
        match err {
            Error::CommandFailed {
                exit_code, stderr, ..
            } => {
                assert_eq!(exit_code, 3);
                assert!(stderr.contains("boom"));
            }
            other => panic!("expected CommandFailed, got {other:?}"),
        }
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_scrubs_claude_env_vars() {
        let (_dir, path) =
            fake_script(r#"echo "CC=[${CLAUDECODE:-}] EP=[${CLAUDE_CODE_ENTRYPOINT:-}]""#);
        set_scrub_vars();
        let out = run_claude_sync(&client(&path), vec![]).expect("success");
        clear_scrub_vars();
        assert!(out.stdout.contains("CC=[]"), "got: {}", out.stdout);
        assert!(out.stdout.contains("EP=[]"), "got: {}", out.stdout);
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_stdin_prompt_round_trips() {
        let (_dir, path) = fake_script(r#"cat"#);
        let out = run_claude_with_stdin_prompt_sync(&client(&path), vec![], "sync stdin".into())
            .expect("success");
        assert!(out.stdout.contains("sync stdin"));
    }

    // Sync mirror: only `ETXTBSY` is retried; a missing binary must surface
    // `NotFound` on the first attempt.
    #[cfg(feature = "sync")]
    #[test]
    fn sync_spawn_retry_passes_through_non_txtbsy_error() {
        let mut cmd = std::process::Command::new("/nonexistent/definitely-not-a-real-binary");
        let err =
            spawn_retrying_txtbsy_sync(&mut cmd).expect_err("spawn of missing binary should fail");
        assert_eq!(err.kind(), std::io::ErrorKind::NotFound, "got: {err:?}");
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_output_retry_passes_through_non_txtbsy_error() {
        let mut cmd = std::process::Command::new("/nonexistent/definitely-not-a-real-binary");
        let err = output_retrying_txtbsy_sync_observed(&mut cmd, false, None)
            .expect_err("output of missing binary should fail");
        assert_eq!(err.kind(), std::io::ErrorKind::NotFound, "got: {err:?}");
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_allow_exit_codes_permits_listed_code() {
        let (_dir, path) = fake_script(r#"echo out; exit 2"#);
        let out = run_claude_allow_exit_codes_sync(&client(&path), vec![], &[2])
            .expect("allowed code is Ok");
        assert!(!out.success);
        assert_eq!(out.exit_code, 2);
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_timeout_fires_on_slow_child() {
        let (_dir, path) = fake_script(r#"sleep 3; echo done"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_millis(300))
            .build()
            .expect("build");
        let err = run_claude_sync(&claude, vec![]).unwrap_err();
        assert!(matches!(err, Error::Timeout { .. }), "got: {err:?}");
    }

    // Blocking mirror of async_timeout_kills_process_group: a fired
    // timeout on the sync path must kill the whole group too. Same
    // retry rationale as the async variant.
    #[cfg(feature = "sync")]
    #[test]
    fn sync_timeout_kills_process_group() {
        let mut observed = false;
        for _ in 0..5 {
            let workdir = tempfile::tempdir().expect("workdir");
            let pid_path = workdir.path().join("pid");
            let gpid_path = workdir.path().join("gpid");
            let (_dir, path) = group_script(&pid_path, &gpid_path);
            let claude = Claude::builder()
                .binary(&path)
                .timeout(Duration::from_millis(1000))
                .build()
                .expect("build");
            let err = run_claude_sync(&claude, vec![]).unwrap_err();
            assert!(matches!(err, Error::Timeout { .. }), "got: {err:?}");
            if let (Some(pid), Some(gpid)) = (try_read_pid(&pid_path), try_read_pid(&gpid_path)) {
                assert_pid_killed(pid);
                assert_pid_killed(gpid);
                observed = true;
                break;
            }
        }
        assert!(observed, "child never recorded pids within 5 timeout runs");
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_timeout_path_returns_output_when_fast() {
        let (_dir, path) = fake_script(r#"echo quick"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_secs(30))
            .build()
            .expect("build");
        let out = run_claude_sync(&claude, vec![]).expect("success");
        assert!(out.stdout.contains("quick"));
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_stdin_with_timeout_round_trips() {
        let (_dir, path) = fake_script(r#"cat"#);
        let claude = Claude::builder()
            .binary(&path)
            .timeout(Duration::from_secs(30))
            .build()
            .expect("build");
        let out = run_claude_with_stdin_prompt_sync(&claude, vec![], "sync piped".into())
            .expect("success");
        assert!(out.stdout.contains("sync piped"));
    }
}