eggup-curl 0.2.0

External curl acquisition adapter for Eggup (bounded, no release policy)
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
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![doc = "External curl acquisition adapter with explicit bounded policy."]
#![doc = ""]
#![doc = "Implements `eggup-acquisition::AcquisitionTransport` without an embedded"]
#![doc = "HTTP/TLS stack. See `README.md` for the single policy configuration point."]
#![doc = ""]
#![doc = "Transport fallback (curl <-> Eggfetch for the same exact URL) lives in"]
#![doc = "`eggup-acquisition::ComposedTransport` and is never release/source fallback."]

use eggup_acquisition::{
    AcquisitionError, AcquisitionRequest, AcquisitionTransport, CancelFlag, FetchLimits,
    FetchOutcome,
};
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Default connect deadline ceiling.
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// Default total wall-clock deadline ceiling.
pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
/// Default redirect bound when following is enabled.
pub const DEFAULT_MAX_REDIRECTS: usize = 10;
/// Maximum accepted outbound `User-Agent` length, in bytes.
///
/// The bound keeps the outbound header value a bounded HTTP field value. It
/// matches the 512-byte magnitude this adapter already uses for bounded
/// diagnostics. A longer value is rejected with
/// [`AcquisitionError::InvalidInput`]; see
/// [`CurlTransport::with_executable_and_user_agent`] for the full accepted
/// grammar.
pub const MAX_USER_AGENT_BYTES: usize = 512;
/// Bound for captured curl stdout (`-w "%{http_code}"` plus slack).
const MAX_WRITE_OUT_BYTES: u64 = 64;
/// Parent polling granularity while waiting for the owned child.
const POLL_INTERVAL: Duration = Duration::from_millis(5);

/// Explicit proxy decision. Routing is never inherited accidentally.
#[derive(Debug, Clone, Default)]
pub enum CurlProxy {
    /// No proxy is used. The child environment is cleared and
    /// `--noproxy "*"` is passed as defense-in-depth.
    #[default]
    Disabled,
    /// Use an explicit snapshot of the current process proxy environment.
    FromEnvironment,
    /// Use explicit `KEY=value` pairs (e.g. `HTTPS_PROXY`, `NO_PROXY`).
    Custom(Vec<(String, String)>),
}

/// Strict transport configuration. All policy lives here.
#[derive(Debug, Clone)]
pub struct CurlConfig {
    /// Connect deadline ceiling.
    pub connect_timeout: Duration,
    /// Total deadline ceiling.
    pub total_timeout: Duration,
    /// Redirect bound when following is enabled.
    pub max_redirects: usize,
    /// Whether HTTP redirects are followed.
    pub follow_redirects: bool,
    /// Allowed URL protocols (default `http`, `https`).
    ///
    /// This list bounds the *initial* request. The redirect target set is
    /// narrowed further: an `https` request never follows a redirect down to
    /// `http`, so a `302 Location: http://...` is refused rather than followed
    /// in cleartext.
    pub allowed_protocols: Vec<String>,
    /// Proxy routing decision.
    pub proxy: CurlProxy,
}

impl Default for CurlConfig {
    fn default() -> Self {
        Self {
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
            total_timeout: DEFAULT_TOTAL_TIMEOUT,
            max_redirects: DEFAULT_MAX_REDIRECTS,
            follow_redirects: true,
            allowed_protocols: vec!["http".to_string(), "https".to_string()],
            proxy: CurlProxy::Disabled,
        }
    }
}

impl CurlConfig {
    /// Strict default: bounded timeouts, redirect bound, explicit proxy.
    pub fn strict() -> Self {
        Self::default()
    }

    /// Sets connect/total adapter ceilings.
    ///
    /// These are ceilings, not defaults: the effective deadline for one fetch
    /// is `min(request, adapter ceiling)` (see [`FetchLimits::effective`]).
    pub fn timeouts(mut self, connect: Duration, total: Duration) -> Self {
        self.connect_timeout = connect;
        self.total_timeout = total;
        self
    }

    /// Sets the redirect bound.
    pub fn max_redirects(mut self, max: usize) -> Self {
        self.max_redirects = max;
        self
    }

    /// Sets whether redirects are followed.
    pub fn follow_redirects(mut self, follow: bool) -> Self {
        self.follow_redirects = follow;
        self
    }

    /// Sets the allowed protocols.
    pub fn allowed_protocols(mut self, protocols: Vec<String>) -> Self {
        self.allowed_protocols = protocols;
        self
    }

    /// Sets the proxy decision.
    pub fn proxy(mut self, proxy: CurlProxy) -> Self {
        self.proxy = proxy;
        self
    }

    /// Derives the authoritative effective deadlines for one fetch.
    pub fn effective_timeouts(&self, limits: FetchLimits) -> (Duration, Duration) {
        limits.effective(self.connect_timeout, self.total_timeout)
    }

    fn validate(&self) -> Result<(), AcquisitionError> {
        if self.connect_timeout.is_zero() || self.total_timeout.is_zero() {
            return Err(AcquisitionError::InvalidInput(bound(
                "adapter timeouts must be positive".to_string(),
            )));
        }
        if self.connect_timeout > self.total_timeout {
            return Err(AcquisitionError::InvalidInput(bound(
                "adapter connect timeout must not exceed total timeout".to_string(),
            )));
        }
        if self.max_redirects > 50 {
            return Err(AcquisitionError::InvalidInput(bound(
                "adapter redirect bound out of range".to_string(),
            )));
        }
        if self.allowed_protocols.is_empty() || self.allowed_protocols.len() > 8 {
            return Err(AcquisitionError::InvalidInput(bound(
                "adapter protocol list out of range".to_string(),
            )));
        }
        for p in &self.allowed_protocols {
            if p.is_empty() || p.len() > 16 || !p.chars().all(|c| c.is_ascii_alphanumeric()) {
                return Err(AcquisitionError::InvalidInput(bound(
                    "adapter protocol names must be alphanumeric".to_string(),
                )));
            }
        }
        Ok(())
    }
}

/// External curl adapter implementing the acquisition seam.
///
/// No release, version, fallback, destination, or service policy lives here.
/// Only exact 404 becomes `NotFound`; TLS/5xx/timeout are hard failures and
/// missing/spawn failures become `Unavailable` for safe composition.
#[derive(Debug)]
pub struct CurlTransport {
    executable: PathBuf,
    config: CurlConfig,
    user_agent: Option<String>,
}

impl CurlTransport {
    /// Builds an adapter from an explicit executable path plus config.
    ///
    /// The path is the strongest selection; discovery via
    /// [`discover_curl_executable`] is opt-in only. Config validation happens
    /// here; executable existence/spawn is classified per-request as
    /// `Unavailable` so composition can fall back.
    ///
    /// The constructed adapter sends **no** `User-Agent`: no `--user-agent`
    /// element reaches `curl`, so `curl` applies its own default. Use
    /// [`CurlTransport::with_executable_and_user_agent`] to set one.
    pub fn with_executable(
        executable: impl Into<PathBuf>,
        config: CurlConfig,
    ) -> Result<Self, AcquisitionError> {
        config.validate()?;
        let executable = executable.into();
        if executable.as_os_str().is_empty() {
            return Err(AcquisitionError::InvalidInput(bound(
                "curl executable path must not be empty".to_string(),
            )));
        }
        Ok(Self {
            executable,
            config,
            user_agent: None,
        })
    }

    /// Builds an adapter from an explicit executable path plus config and a
    /// caller-supplied outbound `User-Agent` value.
    ///
    /// The value is validated here and is used for **every** request this
    /// adapter makes. It reaches `curl` as the literal argv element following
    /// `--user-agent`, positioned before the `--` separator and the URL. No
    /// shell is involved, so the value is never re-parsed or interpolated.
    ///
    /// # Accepted grammar
    ///
    /// ```text
    /// user-agent = 1*( VCHAR / SP / obs-text )
    /// VCHAR      = %x21-7E          ; printable ASCII, excluding SP
    /// SP         = %x20            ; permitted inside the value; a run of SP is
    ///                              ; permitted, but a leading or trailing SP is not
    /// obs-text   = %xA0-10FFFF     ; any non-ASCII scalar value (C1 excluded)
    /// ```
    ///
    /// A run of interior `SP` is permitted because the HTTP field-value grammar
    /// permits it: RFC 7230 §3.2 defines `field-content` as
    /// `field-vchar [ 1*( SP / HTAB ) field-vchar ]`, whose interior run is
    /// `1*`. The accepted set is therefore a subset of a well-formed HTTP field
    /// value, and the rules that actually protect the request head — no C0 or
    /// C1 control character, no `DEL`, no leading or trailing `SP` — are
    /// enforced exactly.
    ///
    /// The value is rejected with [`AcquisitionError::InvalidInput`] when it is
    /// empty, when its UTF-8 length exceeds [`MAX_USER_AGENT_BYTES`], when it
    /// contains any C0 control character (including `CR`, `LF`, `NUL`, and
    /// `HTAB`), `DEL` (`U+007F`), or any C1 control character
    /// (`U+0080`-`U+009F`), or when it begins or ends with a space.
    ///
    /// `InvalidInput` is terminal: unlike `Unavailable` it never causes a
    /// composed transport to fall back to another adapter.
    ///
    /// The control characters are refused because `curl` does not sanitize
    /// `--user-agent`: a value containing `CR LF` would be written into the
    /// request head verbatim and inject an additional header.
    pub fn with_executable_and_user_agent(
        executable: impl Into<PathBuf>,
        config: CurlConfig,
        user_agent: impl Into<String>,
    ) -> Result<Self, AcquisitionError> {
        config.validate()?;
        let executable = executable.into();
        if executable.as_os_str().is_empty() {
            return Err(AcquisitionError::InvalidInput(bound(
                "curl executable path must not be empty".to_string(),
            )));
        }
        let user_agent = user_agent.into();
        validate_user_agent(&user_agent)?;
        Ok(Self {
            executable,
            config,
            user_agent: Some(user_agent),
        })
    }

    /// Returns the configured executable path.
    pub fn executable(&self) -> &Path {
        &self.executable
    }

    /// Returns the transport configuration.
    pub fn config(&self) -> &CurlConfig {
        &self.config
    }

    /// Returns the outbound `User-Agent` value this adapter will send.
    ///
    /// `None` means no `--user-agent` element is emitted and `curl` applies
    /// its own default. See
    /// [`CurlTransport::with_executable_and_user_agent`] for the accepted
    /// grammar.
    pub fn user_agent(&self) -> Option<&str> {
        self.user_agent.as_deref()
    }
}

/// Validates a caller-supplied outbound `User-Agent` value.
///
/// The accepted grammar is the one documented on
/// [`CurlTransport::with_executable_and_user_agent`]. Every rejection is
/// `InvalidInput`, which is terminal: it never lets a composed transport fall
/// back to another adapter because of a malformed caller input.
fn validate_user_agent(user_agent: &str) -> Result<(), AcquisitionError> {
    if user_agent.is_empty() {
        return Err(AcquisitionError::InvalidInput(bound(
            "user agent must not be empty".to_string(),
        )));
    }
    if user_agent.len() > MAX_USER_AGENT_BYTES {
        return Err(AcquisitionError::InvalidInput(bound(
            "user agent exceeds the maximum length".to_string(),
        )));
    }
    let mut chars = user_agent.chars();
    let first = chars.next();
    let last = user_agent.chars().next_back();
    // An HTTP field value is delimited by optional whitespace that a recipient
    // may strip, so a value with surrounding spaces would not be transmitted
    // faithfully.
    if first == Some(' ') || last == Some(' ') {
        return Err(AcquisitionError::InvalidInput(bound(
            "user agent must not begin or end with a space".to_string(),
        )));
    }
    for ch in user_agent.chars() {
        let permitted = match ch {
            // VCHAR: printable ASCII, excluding SP.
            '\u{21}'..='\u{7E}' => true,
            // SP: interior only; the surrounding-space case is refused above.
            '\u{20}' => true,
            // obs-text: any non-ASCII scalar value, C1 controls excluded.
            '\u{A0}'..='\u{10FFFF}' => true,
            // Everything else is a C0 control (CR, LF, NUL, HTAB, ...), DEL, or
            // a C1 control.
            _ => false,
        };
        if !permitted {
            return Err(AcquisitionError::InvalidInput(bound(
                "user agent must not contain control characters".to_string(),
            )));
        }
    }
    Ok(())
}

impl AcquisitionTransport for CurlTransport {
    fn fetch_metadata(
        &self,
        request: &AcquisitionRequest,
        limits: FetchLimits,
        cancel: &CancelFlag,
    ) -> Result<FetchOutcome<eggup_acquisition::MetadataBytes>, AcquisitionError> {
        limits.validate()?;
        self.config.validate()?;
        if cancel.is_cancelled() {
            return Err(AcquisitionError::Cancelled);
        }
        let (eff_connect, eff_total) = self.config.effective_timeouts(limits);
        let max = limits.max_metadata_bytes;
        // Owned private temp in the system temp dir; same exclusive/0600
        // machinery as artifact staging, cleaned unconditionally.
        let parent = std::env::temp_dir();
        let _ = fs::create_dir_all(&parent);
        let (mut file, tmp) =
            eggup_acquisition::__acquire_exclusive_temp(&parent, "eggup-curl-meta")?;
        struct Guard {
            path: PathBuf,
            disarm: bool,
        }
        impl Drop for Guard {
            fn drop(&mut self) {
                if !self.disarm {
                    eggup_acquisition::__remove_owned_temp(&self.path);
                }
            }
        }
        let mut guard = Guard {
            path: tmp.clone(),
            disarm: false,
        };
        let outcome = run_curl_to_file(
            &self.executable,
            &self.config,
            self.user_agent.as_deref(),
            request,
            &tmp,
            &mut file,
            max as u64,
            eff_connect,
            eff_total,
            cancel,
        )?;
        match outcome {
            CurlOutcome::Success => {
                if cancel.is_cancelled() {
                    return Err(AcquisitionError::Cancelled);
                }
                let bytes = fs::read(&tmp)
                    .map_err(|e| AcquisitionError::__adapter_io("reading part file", e))?;
                eggup_acquisition::__remove_owned_temp(&tmp);
                guard.disarm = true;
                if bytes.len() > max {
                    return Err(AcquisitionError::TooLarge { limit: max as u64 });
                }
                Ok(FetchOutcome::Success(
                    eggup_acquisition::__adapter_metadata(bytes),
                ))
            }
            CurlOutcome::NotFound => {
                eggup_acquisition::__remove_owned_temp(&tmp);
                guard.disarm = true;
                Ok(FetchOutcome::NotFound)
            }
        }
    }

    fn fetch_artifact(
        &self,
        request: &AcquisitionRequest,
        dest: &Path,
        limits: FetchLimits,
        cancel: &CancelFlag,
    ) -> Result<FetchOutcome<eggup_acquisition::ArtifactEvidence>, AcquisitionError> {
        limits.validate()?;
        self.config.validate()?;
        if cancel.is_cancelled() {
            return Err(AcquisitionError::Cancelled);
        }
        let parent = dest.parent().ok_or_else(|| {
            AcquisitionError::InvalidInput(bound("destination has no parent".into()))
        })?;
        let parent_meta = fs::symlink_metadata(parent)
            .map_err(|e| AcquisitionError::__adapter_io("reading artifact parent", e))?;
        if !parent_meta.is_dir() || parent_meta.file_type().is_symlink() {
            return Err(AcquisitionError::InvalidInput(bound(
                "artifact parent must be an existing real directory".into(),
            )));
        }
        if fs::symlink_metadata(dest).is_ok() {
            return Err(AcquisitionError::InvalidInput(bound(
                "artifact destination already exists; refusing to overwrite".into(),
            )));
        }
        let (eff_connect, eff_total) = self.config.effective_timeouts(limits);
        let max_artifact = limits.max_artifact_bytes;
        let (mut file, tmp) = eggup_acquisition::__acquire_exclusive_temp(parent, "eggup-curl")?;
        struct Guard {
            path: PathBuf,
            disarm: bool,
        }
        impl Drop for Guard {
            fn drop(&mut self) {
                if !self.disarm {
                    eggup_acquisition::__remove_owned_temp(&self.path);
                }
            }
        }
        let mut guard = Guard {
            path: tmp.clone(),
            disarm: false,
        };
        let outcome = run_curl_to_file(
            &self.executable,
            &self.config,
            self.user_agent.as_deref(),
            request,
            &tmp,
            &mut file,
            max_artifact,
            eff_connect,
            eff_total,
            cancel,
        )?;
        match outcome {
            CurlOutcome::NotFound => {
                eggup_acquisition::__remove_owned_temp(&tmp);
                guard.disarm = true;
                Ok(FetchOutcome::NotFound)
            }
            CurlOutcome::Success => {
                if cancel.is_cancelled() {
                    return Err(AcquisitionError::Cancelled);
                }
                let size = fs::metadata(&tmp)
                    .map_err(|e| AcquisitionError::__adapter_io("reading part file", e))?
                    .len();
                if size > max_artifact {
                    eggup_acquisition::__remove_owned_temp(&tmp);
                    guard.disarm = true;
                    return Err(AcquisitionError::TooLarge {
                        limit: max_artifact,
                    });
                }
                match eggup_acquisition::__promote_no_clobber(&tmp, dest) {
                    Ok(()) => {
                        guard.disarm = true;
                        Ok(FetchOutcome::Success(
                            eggup_acquisition::__adapter_artifact(size),
                        ))
                    }
                    Err(e) => {
                        eggup_acquisition::__remove_owned_temp(&tmp);
                        guard.disarm = true;
                        Err(e)
                    }
                }
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CurlOutcome {
    Success,
    NotFound,
}

/// Opt-in discovery of a `curl` executable via `PATH`.
///
/// Searches `PATH` for `curl` (plus `curl.exe` on Windows) and returns the
/// first existing regular file. Returns `Unavailable` when nothing is found.
/// Callers that require an explicit path should use
/// [`CurlTransport::with_executable`] directly instead.
pub fn discover_curl_executable() -> Result<PathBuf, AcquisitionError> {
    discover_in(std::env::var_os("PATH"))
}

fn discover_in(path_var: Option<std::ffi::OsString>) -> Result<PathBuf, AcquisitionError> {
    let path_var = path_var
        .ok_or_else(|| AcquisitionError::__adapter_unavailable("curl not found: PATH is unset"))?;
    #[cfg(windows)]
    let names = vec!["curl", "curl.exe"];
    #[cfg(not(windows))]
    let names = vec!["curl"];
    for dir in std::env::split_paths(&path_var) {
        if dir.as_os_str().is_empty() {
            continue;
        }
        for name in &names {
            let candidate = dir.join(name);
            if let Ok(meta) = fs::symlink_metadata(&candidate) {
                if meta.is_file() {
                    return Ok(candidate);
                }
            }
        }
    }
    Err(AcquisitionError::__adapter_unavailable(
        "curl not found on PATH",
    ))
}

/// Bounds a diagnostic detail to 512 bytes, truncating only at a UTF-8
/// character boundary.
///
/// The implementation lives in the seam (`eggup-acquisition`), which owns the
/// bounded-detail rule. This adapter deliberately keeps no local copy of the
/// truncation logic; it only delegates.
fn bound(s: String) -> String {
    eggup_acquisition::__adapter_bound_detail(s)
}

/// Renders the diagnostic detail for a failed `spawn()`.
///
/// The cause segment is derived **only** from the [`std::io::ErrorKind`]
/// discriminant and the numeric raw OS code. The OS-provided message text is
/// deliberately **not** rendered: it is free-form, platform-specific, and can
/// echo a path, so rendering it would risk carrying caller-supplied material
/// into a diagnostic that this crate's redaction rule governs.
///
/// Exact format:
///
/// ```text
/// curl spawn failed for {redacted}: {kind}[ (os error {code})]
/// ```
///
/// `{redacted}` is the **already redacted** URL; this helper must never be
/// given the raw URL. `{kind}` is the `ErrorKind` in its `Debug` form (for
/// example `NotFound`, `PermissionDenied`, `WouldBlock`). The ` (os error
/// {code})` suffix is present only when the error carries a raw OS code.
///
/// The caller keeps the `Unavailable` classification: the cause is evidence in
/// the detail, never a change of variant, because `Unavailable` is the only
/// hard failure that falls back under `CompositionPolicy::UnavailableOnly`.
fn spawn_failure_detail(redacted: &str, error: &std::io::Error) -> String {
    let kind = format!("{:?}", error.kind());
    match error.raw_os_error() {
        Some(code) => format!("curl spawn failed for {redacted}: {kind} (os error {code})"),
        None => format!("curl spawn failed for {redacted}: {kind}"),
    }
}

/// Serializes a positive Rust `Duration` as locale-independent decimal seconds
/// suitable for curl `--connect-timeout` and `--max-time`.
///
/// Curl accepts decimal seconds with a dot separator. We format at
/// microsecond resolution and strip trailing fractional zeros, so
/// `100 ms -> "0.1"`, `250 ms -> "0.25"`, `1.5 s -> "1.5"`, and
/// `2 s -> "2"`. Whole-second callers observe exact equality.
///
/// Sub-second values never round upward: truncation to whole microseconds
/// always produces a value `<=` the input. A positive Rust `Duration` whose
/// precision truncates below one microsecond cannot be expressed without
/// widening; we reject it rather than silently extending the caller's
/// ceiling.
fn duration_decimal_seconds(d: Duration) -> Result<String, AcquisitionError> {
    if d.is_zero() {
        return Err(AcquisitionError::InvalidInput(bound(
            "duration must be positive".to_string(),
        )));
    }
    let total_micros = d.as_micros();
    if total_micros == 0 {
        return Err(AcquisitionError::InvalidInput(bound(
            "duration below microsecond precision cannot be represented without widening"
                .to_string(),
        )));
    }
    let secs = total_micros / 1_000_000;
    let micros = total_micros % 1_000_000;
    if micros == 0 {
        Ok(secs.to_string())
    } else {
        let mut frac = format!("{:06}", micros);
        while frac.ends_with('0') {
            frac.pop();
        }
        Ok(format!("{secs}.{frac}"))
    }
}

fn proxy_env_snapshot(proxy: &CurlProxy) -> Vec<(String, String)> {
    const KEYS: &[&str] = &[
        "HTTP_PROXY",
        "http_proxy",
        "HTTPS_PROXY",
        "https_proxy",
        "ALL_PROXY",
        "all_proxy",
        "NO_PROXY",
        "no_proxy",
    ];
    match proxy {
        CurlProxy::Disabled => Vec::new(),
        CurlProxy::FromEnvironment => KEYS
            .iter()
            .filter_map(|k| {
                std::env::var_os(k).map(|v| ((*k).to_string(), v.to_string_lossy().into_owned()))
            })
            .collect(),
        CurlProxy::Custom(pairs) => pairs.clone(),
    }
}

/// Protocols a redirect may target.
///
/// The initial request's own scheme bounds the redirect target set: an `https`
/// request never follows a redirect down to `http`. Without this, a
/// `302 Location: http://attacker/...` would be followed in cleartext with no
/// error and no diagnostic, and the cleartext body would be promoted to the
/// destination as a normal success. This matches the strict downgrade denial
/// the native eggfetch adapter already enforces.
fn redirect_protocols(config: &CurlConfig, url: &str) -> Vec<String> {
    let starts_https = url
        .split_once("://")
        .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("https"));
    if !starts_https {
        return config.allowed_protocols.clone();
    }
    let narrowed: Vec<String> = config
        .allowed_protocols
        .iter()
        .filter(|proto| !proto.eq_ignore_ascii_case("http"))
        .cloned()
        .collect();
    if narrowed.is_empty() {
        // An https request with no non-http protocol allowed cannot succeed at
        // all; `--proto` already rejects the initial scheme. Emit a well-formed
        // list rather than an empty `--proto-redir`.
        return config.allowed_protocols.clone();
    }
    narrowed
}

#[allow(clippy::too_many_arguments)]
fn build_curl_args(
    config: &CurlConfig,
    user_agent: Option<&str>,
    url: &str,
    max_bytes: u64,
    eff_connect: Duration,
    eff_total: Duration,
) -> Result<Vec<String>, AcquisitionError> {
    // The caller-supplied value is re-validated here, before a single element
    // is pushed, so an invalid value can never produce an argv and can never
    // reach the wire.
    if let Some(agent) = user_agent {
        validate_user_agent(agent)?;
    }
    // Ignore ~/.curlrc so ambient config cannot smuggle proxy/auth policy.
    let mut args: Vec<String> = vec![
        "--disable".to_string(),
        "--silent".to_string(),
        "--show-error".to_string(),
        "--no-progress-meter".to_string(),
    ];
    if config.follow_redirects {
        args.push("--location".to_string());
        args.push("--max-redirs".to_string());
        args.push(config.max_redirects.to_string());
    }
    let connect_arg = duration_decimal_seconds(eff_connect)?;
    let total_arg = duration_decimal_seconds(eff_total)?;
    args.push("--connect-timeout".to_string());
    args.push(connect_arg);
    args.push("--max-time".to_string());
    args.push(total_arg);
    args.push("--max-filesize".to_string());
    args.push(max_bytes.to_string());
    if !config.allowed_protocols.is_empty() {
        let list = format!("={}", config.allowed_protocols.join(","));
        args.push("--proto".to_string());
        args.push(list);
        args.push("--proto-redir".to_string());
        args.push(format!("={}", redirect_protocols(config, url).join(",")));
    }
    if matches!(proxy_kind(config), ProxyKind::Disabled) {
        args.push("--noproxy".to_string());
        args.push("*".to_string());
    }
    if let Some(agent) = user_agent {
        // A literal argv element: the child is spawned without a shell, so the
        // value is transmitted exactly as given and cannot be re-parsed as an
        // option (curl takes the element after `--user-agent` as the value).
        args.push("--user-agent".to_string());
        args.push(agent.to_string());
    }
    args.push("--output".to_string());
    args.push("-".to_string());
    args.push("--write-out".to_string());
    args.push("%{stderr}%{http_code}".to_string());
    args.push("--".to_string());
    args.push(url.to_string());
    Ok(args)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProxyKind {
    Disabled,
    Enabled,
}

fn proxy_kind(config: &CurlConfig) -> ProxyKind {
    match &config.proxy {
        CurlProxy::Disabled => ProxyKind::Disabled,
        CurlProxy::FromEnvironment | CurlProxy::Custom(_) => ProxyKind::Enabled,
    }
}

#[allow(clippy::too_many_arguments)]
fn run_curl_to_file(
    executable: &Path,
    config: &CurlConfig,
    user_agent: Option<&str>,
    request: &AcquisitionRequest,
    output: &Path,
    output_file: &mut File,
    max_bytes: u64,
    eff_connect: Duration,
    eff_total: Duration,
    cancel: &CancelFlag,
) -> Result<CurlOutcome, AcquisitionError> {
    let url = request.url().to_string();
    let redacted = request.redacted();
    let args = build_curl_args(config, user_agent, &url, max_bytes, eff_connect, eff_total)?;
    let proxy_env = proxy_env_snapshot(&config.proxy);
    let start = Instant::now();
    let deadline = start + eff_total;
    let owned_file = output_file
        .try_clone()
        .map_err(|e| AcquisitionError::__adapter_io("cloning owned output handle", e))?;

    let mut cmd = Command::new(executable);
    cmd.args(&args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .env_clear();
    for (k, v) in &proxy_env {
        cmd.env(k, v);
    }
    let mut child = cmd.spawn().map_err(|e| {
        AcquisitionError::__adapter_unavailable(spawn_failure_detail(&redacted, &e))
    })?;
    // Curl streams the body on stdout. A duplicate of Eggup's exclusive open
    // file handle is moved to the reader thread; no pathname is reopened.
    let stdout = child.stdout.take().expect("piped stdout");
    let mut owned_file = owned_file;
    let overflow = Arc::new(AtomicBool::new(false));
    let overflow_reader = Arc::clone(&overflow);
    let body_reader = std::thread::spawn(move || {
        use std::io::{Read, Write};
        let mut reader = stdout.take(max_bytes.saturating_add(1));
        let mut written = 0u64;
        let mut buf = [0u8; 16 * 1024];
        loop {
            let n = reader.read(&mut buf).map_err(|_| ())?;
            if n == 0 {
                break;
            }
            written = written.saturating_add(n as u64);
            if written > max_bytes {
                overflow_reader.store(true, Ordering::Release);
            }
            owned_file.write_all(&buf[..n]).map_err(|_| ())?;
        }
        owned_file.flush().map_err(|_| ())?;
        Ok::<u64, ()>(written)
    });
    let stderr = child.stderr.take().expect("piped stderr");
    let status_reader = std::thread::spawn(move || {
        use std::io::Read;
        let mut reader = stderr;
        let mut kept = Vec::with_capacity(MAX_WRITE_OUT_BYTES as usize);
        let mut buf = [0u8; 128];
        loop {
            let n = reader.read(&mut buf).map_err(|_| ())?;
            if n == 0 {
                break;
            }
            let room = (MAX_WRITE_OUT_BYTES as usize).saturating_sub(kept.len());
            kept.extend_from_slice(&buf[..n.min(room)]);
        }
        Ok::<Vec<u8>, ()>(kept)
    });

    let exit_code: Option<i32> = loop {
        if overflow.load(Ordering::Acquire) {
            let _ = child.kill();
            let _ = child.wait();
            let _ = body_reader.join();
            let _ = status_reader.join();
            eggup_acquisition::__remove_owned_temp(output);
            return Err(AcquisitionError::TooLarge { limit: max_bytes });
        }
        if cancel.is_cancelled() {
            let _ = child.kill();
            let _ = child.wait();
            let _ = body_reader.join();
            let _ = status_reader.join();
            eggup_acquisition::__remove_owned_temp(output);
            return Err(AcquisitionError::Cancelled);
        }
        match child.try_wait() {
            Ok(Some(status)) => break status.code(),
            Ok(None) => {
                if Instant::now() >= deadline {
                    let _ = child.kill();
                    let _ = child.wait();
                    let _ = body_reader.join();
                    let _ = status_reader.join();
                    eggup_acquisition::__remove_owned_temp(output);
                    return Err(AcquisitionError::Timeout { phase: "total" });
                }
                std::thread::sleep(POLL_INTERVAL);
            }
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                let _ = body_reader.join();
                let _ = status_reader.join();
                eggup_acquisition::__remove_owned_temp(output);
                return Err(AcquisitionError::__adapter_io("waiting for curl", e));
            }
        }
    };
    let _ = child.wait();
    let bytes_written = body_reader
        .join()
        .map_err(|_| {
            AcquisitionError::__adapter_io(
                "joining curl body reader",
                std::io::Error::other("curl body reader failed"),
            )
        })?
        .map_err(|_| {
            AcquisitionError::__adapter_io(
                "writing curl body",
                std::io::Error::other("writing curl body failed"),
            )
        })?;
    if bytes_written > max_bytes {
        eggup_acquisition::__remove_owned_temp(output);
        return Err(AcquisitionError::TooLarge { limit: max_bytes });
    }
    output_file
        .flush()
        .map_err(|e| AcquisitionError::__adapter_io("flushing owned output", e))?;
    let code_bytes = status_reader
        .join()
        .map_err(|_| {
            AcquisitionError::__adapter_io(
                "joining curl status reader",
                std::io::Error::other("curl status reader failed"),
            )
        })?
        .map_err(|_| {
            AcquisitionError::__adapter_io(
                "reading curl status",
                std::io::Error::other("reading curl status failed"),
            )
        })?;
    classify_curl_result(
        exit_code,
        &code_bytes,
        output,
        &redacted,
        start,
        eff_connect,
        eff_total,
        max_bytes,
    )
}

#[allow(clippy::too_many_arguments)]
fn classify_curl_result(
    exit_code: Option<i32>,
    code_bytes: &[u8],
    output: &Path,
    redacted: &str,
    start: Instant,
    eff_connect: Duration,
    eff_total: Duration,
    max_bytes: u64,
) -> Result<CurlOutcome, AcquisitionError> {
    let elapsed = start.elapsed();
    let code_text = String::from_utf8_lossy(code_bytes).trim().to_string();
    let http_code: Option<u16> = code_text.parse().ok();
    // Tolerance covers one parent polling interval plus a small scheduling
    // margin for kill/reap latency. It must never extend the caller's
    // deadline; it only labels an already-enforced timeout.
    let tolerance = POLL_INTERVAL + Duration::from_millis(5);
    match exit_code {
        // curl operation timeout (connect or total). Distinguish by elapsed
        // against the effective connect ceiling using only the parent
        // scheduling tolerance, not whole-second slack.
        Some(28) => {
            // When the effective connect and total ceilings are equal the two
            // are indistinguishable, and `elapsed <= eff_connect + tolerance`
            // would hold for every exit 28 — including one caused by the total
            // deadline. Claim only the weaker fact in that case rather than
            // misattributing a total timeout to connection setup.
            let phase = if eff_connect < eff_total && elapsed <= eff_connect + tolerance {
                "connect"
            } else {
                "total"
            };
            return Err(AcquisitionError::Timeout { phase });
        }
        // curl --max-filesize exceeded.
        Some(63) => {
            eggup_acquisition::__remove_owned_temp(output);
            return Err(AcquisitionError::TooLarge { limit: max_bytes });
        }
        Some(0) => {}
        failure @ (Some(_) | None) => {
            // Any non-zero curl exit means the transfer did not complete
            // (partial body, TLS, connect, resolve). Even when curl still
            // prints an HTTP code, the body is incomplete and must not be
            // promoted. Report an ordinary transport failure.
            eggup_acquisition::__remove_owned_temp(output);
            return Err(AcquisitionError::Transport(bound(format!(
                "curl transfer failed (exit {}) for {redacted}",
                failure.map_or_else(|| "unknown".to_string(), |code| code.to_string())
            ))));
        }
    }
    match http_code {
        Some(200..=299) => Ok(CurlOutcome::Success),
        Some(404) => Ok(CurlOutcome::NotFound),
        Some(status) => {
            eggup_acquisition::__remove_owned_temp(output);
            Err(AcquisitionError::Transport(bound(format!(
                "HTTP {status} from {redacted}"
            ))))
        }
        None => {
            eggup_acquisition::__remove_owned_temp(output);
            Err(AcquisitionError::Transport(bound(format!(
                "curl status capture failed for {redacted}"
            ))))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use eggup_acquisition::{FixtureResponse, FixtureTransport};
    #[cfg(not(windows))]
    use std::io::{Read, Write};
    #[cfg(not(windows))]
    use std::net::TcpListener;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    #[cfg(not(windows))]
    use std::thread;

    // Platform gate note (M013, Defect A): the `#[cfg(not(windows))]` gate on
    // the loopback-server tests below is a **known, deliberate** platform
    // difference, not a silent coverage gap. Those tests drive a real `curl`
    // subprocess against an in-process loopback HTTP server; the Windows lane
    // exercises the same transport paths through the real `curl.exe`
    // integration tests instead. The gate is recorded here, at the point of
    // use, so a reader sees the exclusion and its reason.

    #[test]
    fn exit_28_is_labelled_total_when_connect_and_total_ceilings_coincide() {
        let dir = temp_dir("curl-phase");
        let output = dir.join("body");
        std::fs::write(&output, b"partial").unwrap();

        let timed_out = |eff_connect: Duration, elapsed: Duration| {
            let start = Instant::now() - elapsed;
            match classify_curl_result(
                Some(28),
                b"",
                &output,
                "https://example.com/app",
                start,
                eff_connect,
                Duration::from_secs(5),
                1024,
            ) {
                Err(AcquisitionError::Timeout { phase }) => phase,
                other => panic!("expected a timeout, got {other:?}"),
            }
        };

        // Equal ceilings: a timeout past the total deadline is not a connect
        // timeout, and must not be reported as one.
        let equal = Duration::from_secs(1);
        assert_eq!(
            timed_out(equal, Duration::from_secs(5)),
            "total",
            "coincident ceilings must not label a total timeout as connect"
        );

        // Genuinely tighter connect ceiling, expired: still a connect timeout.
        assert_eq!(
            timed_out(Duration::from_secs(1), Duration::from_millis(1)),
            "connect"
        );

        // Connect ceiling not expired: the total deadline is what expired.
        assert_eq!(
            timed_out(Duration::from_secs(1), Duration::from_secs(5)),
            "total"
        );
    }

    #[test]
    fn diagnostic_bound_never_splits_multibyte_code_points() {
        for ch in ["é", "€", "🦀"] {
            let prefix = "x".repeat(511);
            let bounded = bound(format!("{prefix}{ch}tail"));
            assert_eq!(bounded, prefix);
            assert!(bounded.len() <= 512);
        }
    }

    fn req(url: &str) -> AcquisitionRequest {
        AcquisitionRequest::new(url).unwrap()
    }

    fn limits() -> FetchLimits {
        FetchLimits {
            max_metadata_bytes: 64 * 1024,
            max_artifact_bytes: 256 * 1024,
            connect_timeout: Duration::from_secs(2),
            total_timeout: Duration::from_secs(10),
        }
    }

    fn temp_dir(prefix: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let p = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
        let _ = fs::create_dir_all(&p);
        p
    }

    fn real_curl() -> Option<PathBuf> {
        discover_curl_executable().ok()
    }

    /// Requires a discoverable system `curl` executable.
    ///
    /// M013, Defect A, treatment (a): the tests that use this helper drive the
    /// **real** curl subprocess. There is no fixture or stub that can stand in
    /// for it, so when no `curl` is discoverable the test must fail loudly with
    /// the missing prerequisite and the remedy. It must never report a pass
    /// while asserting nothing.
    fn require_curl_executable() -> PathBuf {
        match real_curl() {
            Some(exe) => exe,
            None => panic!(
                "no `curl` executable was discoverable on PATH. This test drives the real curl \
                 subprocess and has nothing to assert without one. Install curl (for example \
                 `brew install curl`) or put a curl executable on PATH, then re-run \
                 `cargo test -p eggup-curl`."
            ),
        }
    }

    /// Builds a strict transport over the discovered system `curl`, failing
    /// loudly when no `curl` is discoverable (M013, Defect A, treatment (a)).
    fn require_transport() -> CurlTransport {
        let exe = require_curl_executable();
        CurlTransport::with_executable(exe, CurlConfig::strict())
            .expect("strict curl transport must build from a discovered curl executable")
    }

    #[cfg(not(windows))]
    fn serve_once(
        status: u16,
        headers: Vec<(String, String)>,
        body: Vec<u8>,
        stall_before_body_ms: u64,
        abort_after_headers: bool,
    ) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let addr = listener.local_addr().unwrap();
        thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
                let mut buf = [0u8; 8192];
                let _ = stream.read(&mut buf);
                let reason = match status {
                    200 => "OK",
                    302 => "Found",
                    404 => "Not Found",
                    500 => "Internal Server Error",
                    _ => "OK",
                };
                let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
                for (k, v) in headers {
                    head.push_str(&format!("{k}: {v}\r\n"));
                }
                head.push_str("Connection: close\r\n\r\n");
                let _ = stream.write_all(head.as_bytes());
                if abort_after_headers {
                    return;
                }
                if stall_before_body_ms > 0 {
                    thread::sleep(Duration::from_millis(stall_before_body_ms));
                }
                let _ = stream.write_all(&body);
            }
        });
        format!("http://{addr}")
    }

    #[cfg(not(windows))]
    fn ok_server(body: Vec<u8>) -> String {
        serve_once(
            200,
            vec![
                ("Content-Length".into(), body.len().to_string()),
                ("Content-Type".into(), "application/octet-stream".into()),
            ],
            body,
            0,
            false,
        )
    }

    /// Serves one request and records the raw request head the client sent.
    ///
    /// `serve_once` proves the adapter's behavior; this variant additionally
    /// captures what the peer actually received, so a header the adapter sets
    /// can be asserted on the wire rather than only in the child's argv.
    /// The head is written before the response is sent, so a client that has
    /// received the response is guaranteed to find the record on disk.
    #[cfg(not(windows))]
    fn serve_once_recording_head(status: u16, body: Vec<u8>, record: &Path) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let addr = listener.local_addr().unwrap();
        let record = record.to_path_buf();
        thread::spawn(move || {
            if let Ok((mut stream, _)) = listener.accept() {
                stream.set_read_timeout(Some(Duration::from_secs(5))).ok();
                stream.set_write_timeout(Some(Duration::from_secs(5))).ok();
                let mut buf = [0u8; 8192];
                let read = stream.read(&mut buf).unwrap_or(0);
                let _ = fs::write(&record, &buf[..read]);
                let reason = match status {
                    200 => "OK",
                    404 => "Not Found",
                    500 => "Internal Server Error",
                    _ => "OK",
                };
                let mut head = format!("HTTP/1.1 {status} {reason}\r\n");
                head.push_str(&format!("Content-Length: {}\r\n", body.len()));
                head.push_str("Content-Type: application/octet-stream\r\n");
                head.push_str("Connection: close\r\n\r\n");
                let _ = stream.write_all(head.as_bytes());
                let _ = stream.write_all(&body);
            }
        });
        format!("http://{addr}")
    }

    /// Minimal fake curl executable (Unix-only): writes a fixed body to stdout
    /// and a fixed HTTP code to stderr. Records
    /// argv/env for policy assertions.
    ///
    /// Unix-only because it relies on `sh` + `xxd` and Unix executable-mode
    /// setup. Windows exercises the same transport paths through the real
    /// `curl.exe` integration tests and the platform-neutral unit tests below;
    /// shell-dependent fake-child tests are `#[cfg(unix)]`-gated, never the
    /// whole module.
    #[cfg(unix)]
    fn fake_curl_script(body: &[u8], code: &str, exit: i32, record_dir: &Path) -> PathBuf {
        let dir = record_dir.to_path_buf();
        let script = dir.join(format!(
            "fake-curl-{}-{}.sh",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        let body_hex: String = body.iter().map(|b| format!("{b:02x}")).collect();
        let content = format!(
            "#!/bin/sh\n\
             echo \"$@\" > \"{rec}/argv\"\n\
             env > \"{rec}/env\"\n\
             printf '{hex}' | xxd -r -p\n\\
             printf '{code}' >&2\n\\
             exit {exit}\n",
            rec = dir.display(),
            hex = body_hex,
            code = code,
            exit = exit,
        );
        fs::write(&script, content).unwrap();
        let mut perms = fs::metadata(&script).unwrap().permissions();
        perms.set_mode(0o700);
        fs::set_permissions(&script, perms).unwrap();
        script
    }

    #[test]
    fn executable_selection_and_discovery_are_explicit() {
        // Empty path is invalid input, not unavailable.
        let err = CurlTransport::with_executable("", CurlConfig::strict()).unwrap_err();
        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
        // Invalid config fails closed at construction.
        let bad = CurlConfig::strict().timeouts(Duration::ZERO, Duration::from_secs(1));
        let err = CurlTransport::with_executable("/usr/bin/curl", bad).unwrap_err();
        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
        // Discovery is opt-in and returns a real file when curl exists.
        if let Ok(path) = discover_curl_executable() {
            assert!(fs::symlink_metadata(&path).unwrap().is_file());
        }
        // Absent PATH entry yields typed Unavailable, never Transport.
        // Uses the injectable helper so parallel tests never mutate process PATH.
        let err = discover_in(Some("/nonexistent-eggup-curl-path-xyz".into())).unwrap_err();
        assert!(matches!(err, AcquisitionError::Unavailable(_)));
        assert!(err.is_unavailable());
        let err = discover_in(None).unwrap_err();
        assert!(matches!(err, AcquisitionError::Unavailable(_)));
    }

    #[test]
    fn missing_executable_and_spawn_failure_are_unavailable() {
        let t = CurlTransport::with_executable(
            "/nonexistent-eggup-curl-binary-xyz",
            CurlConfig::strict(),
        )
        .unwrap();
        let err = t
            .fetch_metadata(&req("http://127.0.0.1:1/x"), limits(), &CancelFlag::new())
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Unavailable(_)));
        let dir = temp_dir("curl-unavail");
        let dest = dir.join("app");
        let err = t
            .fetch_artifact(
                &req("http://127.0.0.1:1/x"),
                &dest,
                limits(),
                &CancelFlag::new(),
            )
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Unavailable(_)));
        assert!(!dest.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    /// M015 (§6.1, §10): a spawn failure keeps the `Unavailable`
    /// classification **and** now carries the OS cause.
    ///
    /// Before this milestone the `io::Error` returned by `Command::spawn()` was
    /// discarded by a `map_err(|_| …)`, so a missing executable (`ENOENT`), a
    /// non-executable file (`EACCES`), and a transient resource failure
    /// (`EAGAIN`) all rendered the identical, cause-free string
    /// `curl spawn failed for {redacted}`. A hosted CI run failed with exactly
    /// that message and could not be attributed, because the diagnostic carried
    /// no way to tell the causes apart.
    ///
    /// The expected cause is observed **independently** here — this test
    /// performs its own spawn of the same missing path and reads the platform's
    /// own error — so the assertion is not circular with the adapter's
    /// rendering and does not hard-code a platform-specific errno.
    ///
    /// Deterministic by construction: no network, no wall-clock budget, no
    /// `PATH` dependency, and no real `curl` required.
    #[test]
    fn spawn_failure_detail_names_the_os_cause_and_stays_unavailable() {
        const MISSING: &str = "/nonexistent-eggup-curl-binary-m015";
        const USERINFO: &str = "S3CR3T-USERINFO-9917";
        const QUERY: &str = "TOKEN-QUERY-5523";
        const FRAGMENT: &str = "FRAG-SENTINEL-7788";
        let url = format!("https://user:{USERINFO}@example.com/x?token={QUERY}#{FRAGMENT}");

        // The platform's own error for this spawn, observed independently.
        let observed = std::process::Command::new(MISSING)
            .spawn()
            .expect_err("spawning a missing executable must fail");
        let expected_kind = format!("{:?}", observed.kind());

        let t = CurlTransport::with_executable(MISSING, CurlConfig::strict()).unwrap();
        let err = t
            .fetch_metadata(&req(&url), limits(), &CancelFlag::new())
            .unwrap_err();

        // (a) The classification is unchanged: still `Unavailable`, still
        // eligible for fallback under `CompositionPolicy::UnavailableOnly`.
        assert!(matches!(err, AcquisitionError::Unavailable(_)));
        assert!(err.is_unavailable());

        let detail = match &err {
            AcquisitionError::Unavailable(detail) => detail.clone(),
            other => panic!("expected Unavailable, got {other:?}"),
        };

        // (b) The detail now names the OS cause.
        assert!(
            detail.contains(&expected_kind),
            "detail does not name the ErrorKind {expected_kind}: {detail}"
        );
        match observed.raw_os_error() {
            Some(code) => assert!(
                detail.contains(&format!("os error {code}")),
                "detail does not carry the raw OS code {code}: {detail}"
            ),
            None => assert!(
                !detail.contains("os error"),
                "detail carries an OS code the platform did not produce: {detail}"
            ),
        }
        assert!(
            detail.starts_with("curl spawn failed for "),
            "detail lost the established prefix: {detail}"
        );

        // (b') The exact documented format is pinned, so it cannot drift
        // silently: `curl spawn failed for {redacted}: {kind}[ (os error {code})]`.
        let redacted = eggup_acquisition::redact_url(&url);
        let expected_detail = match observed.raw_os_error() {
            Some(code) => {
                format!("curl spawn failed for {redacted}: {expected_kind} (os error {code})")
            }
            None => format!("curl spawn failed for {redacted}: {expected_kind}"),
        };
        assert_eq!(detail, expected_detail);

        // (c) The detail carries no URL or credential material, and the
        // redaction of the URL is preserved.
        assert!(!detail.contains(USERINFO), "userinfo leaked: {detail}");
        assert!(!detail.contains(QUERY), "query leaked: {detail}");
        assert!(!detail.contains(FRAGMENT), "fragment leaked: {detail}");
        assert!(detail.contains("<redacted>"), "redaction lost: {detail}");

        // (d) The detail stays bounded by the seam's shared rule.
        assert!(detail.len() <= 512, "detail is not bounded: {detail}");
    }

    #[test]
    #[cfg(not(windows))]
    fn metadata_success_not_found_and_server_error() {
        let t = require_transport();
        let base = ok_server(b"hello-curl-meta".to_vec());
        let out = t
            .fetch_metadata(&req(&format!("{base}/meta")), limits(), &CancelFlag::new())
            .unwrap();
        assert_eq!(out.success().unwrap().bytes(), b"hello-curl-meta");

        let base = serve_once(404, vec![], b"nope".to_vec(), 0, false);
        let out = t
            .fetch_metadata(&req(&format!("{base}/m")), limits(), &CancelFlag::new())
            .unwrap();
        assert!(out.is_not_found());

        let base = serve_once(500, vec![], b"boom".to_vec(), 0, false);
        let err = t
            .fetch_metadata(&req(&format!("{base}/e")), limits(), &CancelFlag::new())
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Transport(_)));
        assert!(!matches!(err, AcquisitionError::Unavailable(_)));
    }

    #[test]
    #[cfg(not(windows))]
    fn artifact_success_not_found_and_server_error() {
        let t = require_transport();
        let body: Vec<u8> = (0..4096).map(|i| (i % 251) as u8).collect();
        let base = ok_server(body.clone());
        let dir = temp_dir("curl-artifact");
        let dest = dir.join("app");
        let out = t
            .fetch_artifact(
                &req(&format!("{base}/app")),
                &dest,
                limits(),
                &CancelFlag::new(),
            )
            .unwrap();
        assert_eq!(out.success().unwrap().bytes_written, 4096);
        assert_eq!(fs::read(&dest).unwrap(), body);

        let base = serve_once(404, vec![], b"no".to_vec(), 0, false);
        let dest2 = dir.join("missing");
        let out = t
            .fetch_artifact(
                &req(&format!("{base}/m")),
                &dest2,
                limits(),
                &CancelFlag::new(),
            )
            .unwrap();
        assert!(out.is_not_found());
        assert!(!dest2.exists());

        let base = serve_once(500, vec![], b"boom".to_vec(), 0, false);
        let dest3 = dir.join("err");
        let err = t
            .fetch_artifact(
                &req(&format!("{base}/e")),
                &dest3,
                limits(),
                &CancelFlag::new(),
            )
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Transport(_)));
        assert!(!dest3.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn tls_like_process_failure_is_transport_not_unavailable() {
        let dir = temp_dir("curl-tls");
        let script = fake_curl_script(b"", "", 35, &dir);
        let t =
            CurlTransport::with_executable(&script, CurlConfig::strict()).expect("fake transport");
        let err = t
            .fetch_metadata(&req("https://example.com/x"), limits(), &CancelFlag::new())
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Transport(_)));
        assert!(!err.is_unavailable());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn truncated_transfer_is_hard_failure_without_promotion() {
        let t = require_transport();
        let body = vec![5u8; 4096];
        let base = serve_once(
            200,
            vec![("Content-Length".into(), "4096".into())],
            body,
            0,
            true,
        );
        let dir = temp_dir("curl-trunc");
        let dest = dir.join("app");
        let err = t
            .fetch_artifact(
                &req(&format!("{base}/app")),
                &dest,
                limits(),
                &CancelFlag::new(),
            )
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Transport(_)));
        assert!(!dest.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn metadata_and_artifact_size_overflow() {
        let t = require_transport();
        let big = vec![9u8; 128 * 1024];
        let base = ok_server(big);
        let err = t
            .fetch_metadata(&req(&format!("{base}/big")), limits(), &CancelFlag::new())
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::TooLarge { .. }));

        let body = vec![1u8; 8192];
        let base = ok_server(body);
        let dir = temp_dir("curl-overflow");
        let dest = dir.join("app");
        let small = FetchLimits {
            max_metadata_bytes: 64 * 1024,
            max_artifact_bytes: 1024,
            connect_timeout: Duration::from_secs(2),
            total_timeout: Duration::from_secs(10),
        };
        let err = t
            .fetch_artifact(
                &req(&format!("{base}/app")),
                &dest,
                small,
                &CancelFlag::new(),
            )
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::TooLarge { .. }));
        assert!(!dest.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    /// Total-phase timeout, proven end to end against a real `curl`.
    ///
    /// M013, Defect A, treatment (a): the fixture must exist, so a missing
    /// `curl` fails loudly instead of reporting a vacuous pass.
    #[test]
    #[cfg(not(windows))]
    fn total_phase_timeout_is_typed_end_to_end() {
        let t = require_transport();
        // Slow body with a short total ceiling.
        let body = vec![2u8; 1024];
        let base = serve_once(
            200,
            vec![("Content-Length".into(), body.len().to_string())],
            body,
            5000,
            false,
        );
        let short_total = FetchLimits {
            max_metadata_bytes: 64 * 1024,
            max_artifact_bytes: 256 * 1024,
            connect_timeout: Duration::from_millis(500),
            total_timeout: Duration::from_secs(2),
        };
        let err = t
            .fetch_metadata(
                &req(&format!("{base}/slow")),
                short_total,
                &CancelFlag::new(),
            )
            .unwrap_err();
        assert!(
            matches!(err, AcquisitionError::Timeout { phase: "total" }),
            "expected a total-phase timeout, got {err}"
        );
    }

    /// Connect-phase timeout, proven end to end — **environment-conditional**.
    ///
    /// M013, Defect A, treatment (b): this proof needs a host that blackholes
    /// the route to the probe address so the connect ceiling expires. Most
    /// hosts and CI runners reject the connection immediately with
    /// `ENETUNREACH`/`EHOSTUNREACH`, which is an ordinary transport failure,
    /// not a timeout. The test is therefore marked as ignored with a recorded
    /// reason and is reported as *ignored*, never as *passed*, and it never
    /// exits silently: when it is run explicitly it asserts the exact
    /// connect-phase label. The connect/total **label** is proven
    /// deterministically, with no subprocess and no network, by
    /// `classify_curl_result_labels_connect_and_total_without_a_subprocess`.
    #[test]
    #[cfg(not(windows))]
    #[ignore = "environment-conditional: needs a host that blackholes the route to 10.255.255.1:81 so the connect ceiling expires instead of failing fast with ENETUNREACH/EHOSTUNREACH; the connect/total label itself is proven without a network by classify_curl_result_labels_connect_and_total_without_a_subprocess"]
    fn connect_phase_timeout_is_typed_end_to_end() {
        let t = require_transport();
        // Unroutable connect with a short connect ceiling.
        let short_connect = FetchLimits {
            max_metadata_bytes: 64 * 1024,
            max_artifact_bytes: 256 * 1024,
            connect_timeout: Duration::from_millis(500),
            total_timeout: Duration::from_secs(10),
        };
        let err = t
            .fetch_metadata(
                &req("http://10.255.255.1:81/unreachable"),
                short_connect,
                &CancelFlag::new(),
            )
            .unwrap_err();
        assert!(
            matches!(err, AcquisitionError::Timeout { phase: "connect" }),
            "expected a connect-phase timeout, got {err}"
        );
    }

    /// The connect/total timeout label, proven without a subprocess and
    /// without a network.
    ///
    /// M013, Defect A: because the end-to-end connect-phase proof is
    /// environment-conditional, the *label* is pinned here at the
    /// `classify_curl_result` layer by injecting `start`. The injected
    /// elapsed times are whole seconds, so the assertion never depends on a
    /// sub-second wall-clock budget.
    #[test]
    fn classify_curl_result_labels_connect_and_total_without_a_subprocess() {
        let dir = temp_dir("curl-phase-label");
        let output = dir.join("body");
        fs::write(&output, b"partial").unwrap();

        let phase_for = |eff_connect: Duration, eff_total: Duration, elapsed: Duration| {
            let start = Instant::now() - elapsed;
            match classify_curl_result(
                Some(28),
                b"",
                &output,
                "https://example.com/app",
                start,
                eff_connect,
                eff_total,
                1024,
            ) {
                Err(AcquisitionError::Timeout { phase }) => phase,
                other => panic!("expected a timeout, got {other:?}"),
            }
        };

        // A strictly tighter connect ceiling that has expired labels the
        // failure as a connect timeout.
        assert_eq!(
            phase_for(
                Duration::from_secs(2),
                Duration::from_secs(20),
                Duration::from_secs(2),
            ),
            "connect",
            "an expired, strictly tighter connect ceiling must label a connect timeout"
        );
        // The same ceilings with the elapsed time past the connect ceiling
        // label the failure as a total timeout.
        assert_eq!(
            phase_for(
                Duration::from_secs(2),
                Duration::from_secs(20),
                Duration::from_secs(5),
            ),
            "total",
            "an elapsed time past the connect ceiling must label a total timeout"
        );
        // Coincident ceilings are indistinguishable, so the weaker total
        // claim is the only honest one.
        assert_eq!(
            phase_for(
                Duration::from_secs(2),
                Duration::from_secs(2),
                Duration::from_secs(5),
            ),
            "total",
            "coincident ceilings must not label a total timeout as connect"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn duration_decimal_seconds_serializes_sub_second_inputs_truthfully() {
        // Sub-second positive durations produce decimal-second text that
        // never exceeds the input when curl parses it back.
        let cases = [
            (Duration::from_micros(1), "0.000001"),
            (Duration::from_micros(500), "0.0005"),
            (Duration::from_millis(1), "0.001"),
            (Duration::from_millis(100), "0.1"),
            (Duration::from_millis(250), "0.25"),
            (Duration::from_millis(500), "0.5"),
            (Duration::from_millis(1500), "1.5"),
            (Duration::from_secs(2), "2"),
            (Duration::from_secs(120), "120"),
        ];
        for (input, expected) in cases {
            let rendered = duration_decimal_seconds(input).expect("serializes");
            assert_eq!(rendered, expected, "input {input:?}");
        }
        // Whole-second values never gain a spurious fractional part.
        let rendered = duration_decimal_seconds(Duration::from_secs(7)).unwrap();
        assert_eq!(rendered, "7");
        // Zero is rejected.
        assert!(duration_decimal_seconds(Duration::ZERO).is_err());
        // Positive durations that truncate below one microsecond cannot be
        // represented without widening and must be rejected.
        let sub_micros = Duration::from_nanos(500);
        assert!(duration_decimal_seconds(sub_micros).is_err());
    }

    #[test]
    fn https_request_never_allows_a_cleartext_redirect_target() {
        let cfg = CurlConfig::strict();
        let value_after = |args: &[String], flag: &str| -> String {
            let idx = args.iter().position(|a| a == flag).expect("flag present");
            args[idx + 1].clone()
        };

        // The initial request may still use http; only the redirect target set
        // is narrowed.
        let https = build_curl_args(
            &cfg,
            None,
            "https://example.com/artifact",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(5),
        )
        .expect("builds");
        assert_eq!(value_after(&https, "--proto"), "=http,https");
        assert_eq!(value_after(&https, "--proto-redir"), "=https");

        // A cleartext request may still be redirected to either scheme.
        let http = build_curl_args(
            &cfg,
            None,
            "http://example.com/artifact",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(5),
        )
        .expect("builds");
        assert_eq!(value_after(&http, "--proto"), "=http,https");
        assert_eq!(value_after(&http, "--proto-redir"), "=http,https");

        // Scheme comparison is case-insensitive, as URLs are.
        let upper = build_curl_args(
            &cfg,
            None,
            "HTTPS://example.com/artifact",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(5),
        )
        .expect("builds");
        assert_eq!(value_after(&upper, "--proto-redir"), "=https");

        // A configuration that allows only http cannot fetch https at all; the
        // list stays well-formed rather than becoming empty.
        let http_only = CurlConfig::strict().allowed_protocols(vec!["http".to_string()]);
        let denied = build_curl_args(
            &http_only,
            None,
            "https://example.com/artifact",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(5),
        )
        .expect("builds");
        assert_eq!(value_after(&denied, "--proto-redir"), "=http");
    }

    #[test]
    fn build_curl_args_passes_decimal_deadlines_never_above_ceiling() {
        let cfg = CurlConfig::strict();
        let cases = [
            (
                Duration::from_millis(100),
                Duration::from_secs(1),
                "0.1",
                "1",
            ),
            (
                Duration::from_millis(250),
                Duration::from_millis(1500),
                "0.25",
                "1.5",
            ),
            (Duration::from_secs(2), Duration::from_secs(5), "2", "5"),
            (
                Duration::from_micros(500),
                Duration::from_micros(750),
                "0.0005",
                "0.00075",
            ),
        ];
        for (connect, total, expected_connect, expected_total) in cases {
            let args = build_curl_args(&cfg, None, "https://example.com/x", 1024, connect, total)
                .expect("builds");
            let connect_idx = args
                .iter()
                .position(|a| a == "--connect-timeout")
                .expect("connect-timeout present");
            let total_idx = args
                .iter()
                .position(|a| a == "--max-time")
                .expect("max-time present");
            assert_eq!(args[connect_idx + 1], expected_connect);
            assert_eq!(args[total_idx + 1], expected_total);
        }
        // Sub-microsecond positive durations must fail validation rather
        // than widen to a second.
        let err = build_curl_args(
            &cfg,
            None,
            "https://example.com/x",
            1024,
            Duration::from_nanos(500),
            Duration::from_millis(500),
        );
        assert!(matches!(err, Err(AcquisitionError::InvalidInput(_))));
    }

    /// M012 (§6.2): the deterministic half of the sub-second serialization
    /// proof.
    ///
    /// A sub-second `--max-time` cannot be proven end-to-end, because the
    /// parent's deadline *is* the effective total ceiling — proving it would
    /// need a sub-second wall-clock budget. It is proven here instead, at the
    /// layer where the rule lives: `build_curl_args`, with no subprocess, no
    /// network, and no wall clock at all. This retains the coverage that
    /// `build_curl_args_passes_sub_second_deadlines_to_fake_curl` had to give
    /// up in order to become deterministic.
    #[test]
    fn sub_second_deadlines_serialize_truthfully_without_a_subprocess() {
        let cfg = CurlConfig::strict();
        let value_after = |args: &[String], flag: &str| -> String {
            let idx = args.iter().position(|a| a == flag).expect("flag present");
            args[idx + 1].clone()
        };
        let sub_second_pair = FetchLimits {
            max_metadata_bytes: 64 * 1024,
            max_artifact_bytes: 256 * 1024,
            connect_timeout: Duration::from_millis(250),
            total_timeout: Duration::from_millis(750),
        };

        // A sub-second connect *and* sub-second total pair serializes to
        // truthful decimal seconds.
        let (eff_connect, eff_total) = cfg.effective_timeouts(sub_second_pair);
        assert_eq!(eff_connect, Duration::from_millis(250));
        assert_eq!(eff_total, Duration::from_millis(750));
        let args = build_curl_args(
            &cfg,
            None,
            "https://example.com/x",
            1024,
            eff_connect,
            eff_total,
        )
        .expect("builds");
        assert_eq!(value_after(&args, "--connect-timeout"), "0.25");
        assert_eq!(value_after(&args, "--max-time"), "0.75");

        // `--max-time` is the *effective* total ceiling, never the raw
        // request, when the adapter ceiling is the lower of the two.
        let capped =
            CurlConfig::strict().timeouts(Duration::from_millis(100), Duration::from_millis(400));
        let (capped_connect, capped_total) = capped.effective_timeouts(sub_second_pair);
        assert_eq!(capped_connect, Duration::from_millis(100));
        assert_eq!(capped_total, Duration::from_millis(400));
        let capped_args = build_curl_args(
            &capped,
            None,
            "https://example.com/x",
            1024,
            capped_connect,
            capped_total,
        )
        .expect("builds");
        assert_eq!(value_after(&capped_args, "--connect-timeout"), "0.1");
        assert_eq!(value_after(&capped_args, "--max-time"), "0.4");
        assert_ne!(
            value_after(&capped_args, "--max-time"),
            "0.75",
            "--max-time must be the effective ceiling, never the raw request"
        );

        // Sub-microsecond positive durations still fail validation rather
        // than widen to a second.
        let err = build_curl_args(
            &cfg,
            None,
            "https://example.com/x",
            1024,
            Duration::from_nanos(500),
            Duration::from_millis(500),
        );
        assert!(matches!(err, Err(AcquisitionError::InvalidInput(_))));
    }

    /// M012 (§6.1): the *asserted* serialization is decoupled from the
    /// *enforced* wall-clock budget.
    ///
    /// The invariant under test is that a sub-second `FetchLimits` deadline is
    /// serialized truthfully into the spawned child's argv. The former
    /// version also made those same sub-second values the live parent
    /// deadline, so the assertion doubled as a claim about host scheduling
    /// and failed whenever the host was loaded: the parent deadline was the
    /// only enforcement (the fake child ignores `--connect-timeout` and
    /// `--max-time`), so a busy host expired the deadline the test was
    /// trying to succeed inside.
    ///
    /// Here the connect deadline stays sub-second and is still proven
    /// end-to-end through a real spawn, while the total budget is generous,
    /// so no host scheduling decision can expire it.
    ///
    /// A sub-second `--max-time` cannot be proven end-to-end at all: the
    /// parent's deadline *is* the effective total ceiling, so proving it
    /// would require a sub-second wall-clock budget. That half is proven
    /// deterministically, with no subprocess and no wall clock, by
    /// `sub_second_deadlines_serialize_truthfully_without_a_subprocess`.
    #[cfg(unix)]
    #[test]
    fn build_curl_args_passes_sub_second_deadlines_to_fake_curl() {
        let dir = temp_dir("curl-decode-args");
        let script = fake_curl_script(b"", "200", 0, &dir);
        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
        let cfg = FetchLimits {
            max_metadata_bytes: 64 * 1024,
            max_artifact_bytes: 256 * 1024,
            connect_timeout: Duration::from_millis(250),
            // Generous on purpose: the total budget is not the thing under
            // test, and a sub-second value here would re-couple the
            // assertion to the host's scheduler.
            total_timeout: Duration::from_secs(30),
        };
        t.fetch_metadata(&req("https://example.com/x"), cfg, &CancelFlag::new())
            .expect("fake curl completes well inside the 30s budget");
        let argv = fs::read_to_string(dir.join("argv")).unwrap();
        assert!(
            argv.contains("--connect-timeout 0.25"),
            "argv missing 0.25: {argv}"
        );
        assert!(argv.contains("--max-time 30"), "argv missing 30: {argv}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn sub_second_total_timeout_kills_child_promptly() {
        let t = require_transport();
        let body = vec![7u8; 8192];
        let base = serve_once(
            200,
            vec![("Content-Length".into(), body.len().to_string())],
            body,
            4000,
            false,
        );
        let short_total = FetchLimits {
            max_metadata_bytes: 64 * 1024,
            max_artifact_bytes: 256 * 1024,
            connect_timeout: Duration::from_millis(100),
            total_timeout: Duration::from_millis(250),
        };
        let dir = temp_dir("curl-subsec-total");
        let dest = dir.join("app");
        let started = Instant::now();
        let err = t
            .fetch_artifact(
                &req(&format!("{base}/app")),
                &dest,
                short_total,
                &CancelFlag::new(),
            )
            .unwrap_err();
        let elapsed = started.elapsed();
        assert!(matches!(err, AcquisitionError::Timeout { phase: "total" }));

        // M012 (§6.3): promptness is proven against the deadline and against
        // the server's stall, not against an absolute wall-clock constant.
        //
        // The deadline was actually reached: the fetch did not succeed early.
        // Without this half, an upper bound alone would also pass if the
        // fetch failed immediately.
        assert!(
            elapsed >= short_total.total_timeout,
            "elapsed {elapsed:?} is below the {:?} total deadline",
            short_total.total_timeout
        );

        // The child was killed rather than left to stall: comfortably inside
        // the server's 4000 ms body stall. This proves the deadline fired; it
        // does not claim the OS reaped within a fixed number of
        // milliseconds, and the headroom absorbs the kill/reap/join latency
        // that the transport's deadline contract does not govern.
        assert!(
            elapsed < Duration::from_secs(2),
            "elapsed {elapsed:?} is not below the 2 s bound"
        );
        assert!(!dest.exists());
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn cancellation_before_spawn_cleans_temp() {
        let t = require_transport();
        let dir = temp_dir("curl-cancel");
        let dest = dir.join("app");
        let cancel = CancelFlag::new();
        cancel.cancel();
        let err = t
            .fetch_artifact(&req("http://127.0.0.1:1/app"), &dest, limits(), &cancel)
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Cancelled));
        assert!(!dest.exists());
        let leftovers: Vec<_> = fs::read_dir(&dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_name().to_string_lossy().ends_with(".part"))
            .collect();
        assert!(leftovers.is_empty());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn cancellation_during_body_stream_kills_and_reaps_child() {
        let t = require_transport();
        let base = serve_once(
            200,
            vec![("Content-Length".into(), "65536".into())],
            vec![3u8; 65536],
            5000,
            false,
        );
        let dir = temp_dir("curl-cancel-stream");
        let dest = dir.join("app");
        let cancel = Arc::new(CancelFlag::new());
        let child_cancel = Arc::clone(&cancel);
        let child_transport = t;
        let url = format!("{base}/app");
        let child = thread::spawn(move || {
            child_transport.fetch_artifact(&req(&url), &dest, limits(), &child_cancel)
        });
        thread::sleep(Duration::from_millis(150));
        cancel.cancel();
        assert!(matches!(
            child.join().unwrap(),
            Err(AcquisitionError::Cancelled)
        ));
        assert!(!dir.join("app").exists());
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn redirect_follow_and_reject() {
        let curl_exe = require_curl_executable();
        let target_body = b"redirect-target".to_vec();
        let target = ok_server(target_body.clone());
        let redirect = serve_once(
            302,
            vec![("Location".into(), format!("{target}/final"))],
            b"".to_vec(),
            0,
            false,
        );
        let follow = CurlTransport::with_executable(
            curl_exe.clone(),
            CurlConfig::strict()
                .follow_redirects(true)
                .max_redirects(10),
        )
        .unwrap();
        let out = follow
            .fetch_metadata(&req(&format!("{redirect}/r")), limits(), &CancelFlag::new())
            .unwrap();
        assert_eq!(out.success().unwrap().bytes(), b"redirect-target");

        let nofollow =
            CurlTransport::with_executable(curl_exe, CurlConfig::strict().follow_redirects(false))
                .unwrap();
        let err = nofollow
            .fetch_metadata(&req(&format!("{redirect}/r")), limits(), &CancelFlag::new())
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::Transport(_)));
    }

    #[cfg(unix)]
    #[test]
    fn proxy_disabled_uses_noproxy_and_cleared_env() {
        let dir = temp_dir("curl-proxy");
        let script = fake_curl_script(b"ok", "200", 0, &dir);
        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
        let out = t
            .fetch_metadata(&req("http://example.com/x"), limits(), &CancelFlag::new())
            .unwrap();
        assert_eq!(out.success().unwrap().bytes(), b"ok");
        let argv = fs::read_to_string(dir.join("argv")).unwrap();
        assert!(argv.contains("--noproxy"));
        assert!(argv.contains("--disable"));
        assert!(argv.contains("--output -"));
        assert!(!argv.contains("eggup-curl-meta"));
        let env = fs::read_to_string(dir.join("env")).unwrap();
        assert!(!env.contains("HTTP_PROXY=hunter"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn proxy_custom_env_is_explicit() {
        let dir = temp_dir("curl-proxy-custom");
        let script = fake_curl_script(b"ok", "200", 0, &dir);
        let t = CurlTransport::with_executable(
            &script,
            CurlConfig::strict().proxy(CurlProxy::Custom(vec![(
                "HTTPS_PROXY".to_string(),
                "http://proxy.example:8080".to_string(),
            )])),
        )
        .unwrap();
        t.fetch_metadata(&req("http://example.com/x"), limits(), &CancelFlag::new())
            .unwrap();
        let argv = fs::read_to_string(dir.join("argv")).unwrap();
        assert!(!argv.contains("--noproxy"));
        let env = fs::read_to_string(dir.join("env")).unwrap();
        assert!(env.contains("HTTPS_PROXY=http://proxy.example:8080"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn artifact_temp_is_owner_private_and_no_clobber() {
        let dir = temp_dir("curl-perms");
        let script = fake_curl_script(b"owned-bytes", "200", 0, &dir);
        // Use a separate work dir for the destination so the fake script dir
        // (which holds argv/env records) does not interfere.
        let work = temp_dir("curl-perms-work");
        // Fake curl writes directly to the Eggup-owned temp; verify promotion
        // preserves foreign destinations and cleans only owned temps.
        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
        let dest = work.join("app");
        let out = t
            .fetch_artifact(
                &req("http://example.com/app"),
                &dest,
                limits(),
                &CancelFlag::new(),
            )
            .unwrap();
        assert_eq!(
            out.success().unwrap().bytes_written,
            b"owned-bytes".len() as u64
        );
        #[cfg(unix)]
        {
            let mode = fs::metadata(&dest).unwrap().permissions().mode() & 0o777;
            // Promoted artifact inherits the owner-private temp mode via
            // hard-link promotion (0600), never a world-readable default.
            assert_eq!(mode, 0o600);
        }
        // Existing destination is never overwritten.
        fs::write(&dest, b"FOREIGN").unwrap();
        let dest2 = work.join("app");
        let err = t
            .fetch_artifact(
                &req("http://example.com/app"),
                &dest2,
                limits(),
                &CancelFlag::new(),
            )
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
        assert_eq!(fs::read(&dest2).unwrap(), b"FOREIGN");
        let _ = fs::remove_dir_all(&dir);
        let _ = fs::remove_dir_all(&work);
    }

    #[cfg(unix)]
    #[test]
    fn credential_material_is_redacted() {
        let dir = temp_dir("curl-redact");
        let script = fake_curl_script(b"", "", 7, &dir);
        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
        let url = "https://user:S3CR3T-USERINFO-9917@example.com/app?token=TOKEN-QUERY-5523#FRAG-SENTINEL-7788";
        let err = t
            .fetch_metadata(&req(url), limits(), &CancelFlag::new())
            .unwrap_err();
        let msg = format!("{err}");
        assert!(!msg.contains("S3CR3T-USERINFO-9917"));
        assert!(!msg.contains("TOKEN-QUERY-5523"));
        assert!(!msg.contains("FRAG-SENTINEL-7788"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn invalid_limits_fail_before_spawn() {
        let dir = temp_dir("curl-invalid");
        let script = fake_curl_script(b"ok", "200", 0, &dir);
        let t = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
        let bad = FetchLimits {
            max_metadata_bytes: 0,
            ..limits()
        };
        let err = t
            .fetch_metadata(&req("http://example.com/x"), bad, &CancelFlag::new())
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
        // Fake was never invoked (no argv record beyond setup is acceptable;
        // assert no artifact side effects).
        let dest = dir.join("app");
        let err = t
            .fetch_artifact(&req("http://example.com/x"), &dest, bad, &CancelFlag::new())
            .unwrap_err();
        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
        assert!(!dest.exists());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn composition_with_fixture_falls_back_from_unavailable_curl() {
        use eggup_acquisition::{ComposedTransport, CompositionPolicy};
        let dir = temp_dir("curl-composed");
        let script = dir.join("missing-curl");
        let curl = CurlTransport::with_executable(&script, CurlConfig::strict()).unwrap();
        let fixture = FixtureTransport::new();
        fixture.route(
            "https://example.com/meta",
            FixtureResponse::body(b"via-fixture".to_vec()),
        );
        let composed = ComposedTransport::new(&curl, &fixture, CompositionPolicy::UnavailableOnly);
        let out = composed
            .fetch_metadata(
                &req("https://example.com/meta"),
                limits(),
                &CancelFlag::new(),
            )
            .unwrap();
        assert_eq!(out.success().unwrap().bytes(), b"via-fixture");
        let _ = fs::remove_dir_all(&dir);
    }

    /// M014 (§6.2, §6.4): a configured `User-Agent` reaches `curl` as a
    /// literal argv element, positioned before the `--` separator and the URL.
    ///
    /// The position matters: `--` is what isolates the URL from the options,
    /// so an option emitted after it would be read as part of the URL rather
    /// than as an option.
    #[test]
    fn user_agent_is_emitted_as_a_literal_argv_element_before_the_url() {
        let cfg = CurlConfig::strict();
        let agent = "eggup-curl-test/1.0 (Macintosh; x86_64)";
        let args = build_curl_args(
            &cfg,
            Some(agent),
            "https://example.com/x",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(2),
        )
        .expect("builds");
        let flag = args
            .iter()
            .position(|a| a == "--user-agent")
            .expect("the user agent flag is present");
        assert_eq!(
            args[flag + 1],
            agent,
            "the value must be the exact element following the flag"
        );
        assert_eq!(
            args.iter().filter(|a| *a == "--user-agent").count(),
            1,
            "the flag must appear exactly once"
        );
        let separator = args.iter().position(|a| a == "--").expect("separator");
        let url = args
            .iter()
            .position(|a| a == "https://example.com/x")
            .expect("url");
        assert!(
            flag < separator,
            "--user-agent must be emitted before the -- separator"
        );
        assert!(separator < url, "the -- separator must precede the URL");
        assert_eq!(url, args.len() - 1, "the URL stays the last element");
    }

    /// M014 (§6.3, R3-R5): a value carrying a control character is rejected
    /// as `InvalidInput`, and no argv is produced for it.
    ///
    /// `curl` does not sanitize `--user-agent`: a `CR LF` inside the value is
    /// written into the request head verbatim and injects a second header.
    /// The adapter therefore refuses the value before it can reach the wire.
    #[test]
    fn user_agent_rejects_control_characters_without_producing_argv() {
        let cfg = CurlConfig::strict();
        let rejected = [
            "eggup\r\nX-Injected: 1",
            "eggup\rvalue",
            "eggup\nvalue",
            "eggup\u{0}value",
            "eggup\tvalue",
            "eggup\u{7F}value",
            "eggup\u{85}value",
            "eggup\u{9F}value",
        ];
        for bad in rejected {
            let err = build_curl_args(
                &cfg,
                Some(bad),
                "https://example.com/x",
                1024,
                Duration::from_secs(1),
                Duration::from_secs(2),
            )
            .expect_err("a control character must be rejected");
            assert!(
                matches!(err, AcquisitionError::InvalidInput(_)),
                "expected InvalidInput for {bad:?}, got {err:?}"
            );
            // The constructor refuses it too, so no transport can carry it.
            let ctor = CurlTransport::with_executable_and_user_agent(
                "/usr/bin/curl",
                CurlConfig::strict(),
                bad,
            )
            .expect_err("a control character must be refused at construction");
            assert!(
                matches!(ctor, AcquisitionError::InvalidInput(_)),
                "expected InvalidInput for {bad:?}, got {ctor:?}"
            );
        }
    }

    /// M014 (§6.3, R1-R2): the empty value and an over-bound value are
    /// rejected, and a value exactly at the bound is accepted.
    #[test]
    fn user_agent_rejects_empty_and_over_bound_values() {
        let cfg = CurlConfig::strict();
        let empty = build_curl_args(
            &cfg,
            Some(""),
            "https://example.com/x",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(2),
        )
        .expect_err("an empty value must be rejected");
        assert!(matches!(empty, AcquisitionError::InvalidInput(_)));

        let at_bound = "a".repeat(MAX_USER_AGENT_BYTES);
        let ok = build_curl_args(
            &cfg,
            Some(&at_bound),
            "https://example.com/x",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(2),
        )
        .expect("a value exactly at the bound must be accepted");
        let flag = ok
            .iter()
            .position(|a| a == "--user-agent")
            .expect("the user agent flag is present");
        assert_eq!(ok[flag + 1], at_bound);

        let over_bound = "a".repeat(MAX_USER_AGENT_BYTES + 1);
        let err = build_curl_args(
            &cfg,
            Some(&over_bound),
            "https://example.com/x",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(2),
        )
        .expect_err("an over-bound value must be rejected");
        assert!(matches!(err, AcquisitionError::InvalidInput(_)));

        // The constructor applies the same bound.
        let ctor = CurlTransport::with_executable_and_user_agent(
            "/usr/bin/curl",
            CurlConfig::strict(),
            over_bound.clone(),
        )
        .expect_err("an over-bound value must be refused at construction");
        assert!(matches!(ctor, AcquisitionError::InvalidInput(_)));
    }

    /// M014 (§6.5): the default transport sends no `User-Agent`, and its argv
    /// is element-for-element what it was before the control existed.
    ///
    /// The published `eggup-curl 0.1.2` behavior is what a consumer already
    /// observes on the wire, so the default path must not change silently.
    #[test]
    fn default_transport_emits_no_user_agent_and_keeps_the_previous_argv() {
        let cfg = CurlConfig::strict();
        let transport = CurlTransport::with_executable("/usr/bin/curl", cfg.clone())
            .expect("the transport builds");
        assert_eq!(
            transport.user_agent(),
            None,
            "the default transport must not carry a user agent"
        );

        let args = build_curl_args(
            &cfg,
            None,
            "https://example.com/x",
            1024,
            Duration::from_secs(1),
            Duration::from_secs(2),
        )
        .expect("builds");
        assert!(
            !args.iter().any(|a| a == "--user-agent"),
            "the default argv must not carry --user-agent"
        );
        assert_eq!(
            args,
            vec![
                "--disable",
                "--silent",
                "--show-error",
                "--no-progress-meter",
                "--location",
                "--max-redirs",
                "10",
                "--connect-timeout",
                "1",
                "--max-time",
                "2",
                "--max-filesize",
                "1024",
                "--proto",
                "=http,https",
                "--proto-redir",
                "=https",
                "--noproxy",
                "*",
                "--output",
                "-",
                "--write-out",
                "%{stderr}%{http_code}",
                "--",
                "https://example.com/x",
            ],
            "the default argv must be unchanged"
        );
    }

    /// M014 (§6.3): a rejected caller value is a terminal `InvalidInput`, and
    /// a composed transport does not fall back on it.
    ///
    /// `Unavailable` is the only outcome the seam falls back on. A malformed
    /// caller input must therefore never be classified as `Unavailable`, or a
    /// composed transport would silently serve the request from another
    /// adapter.
    #[test]
    fn rejected_user_agent_is_a_terminal_invalid_input_not_unavailable() {
        use eggup_acquisition::{ComposedTransport, CompositionPolicy};
        let err = CurlTransport::with_executable_and_user_agent(
            "/usr/bin/curl",
            CurlConfig::strict(),
            "bad\rvalue",
        )
        .expect_err("a control character must be refused at construction");
        assert!(matches!(err, AcquisitionError::InvalidInput(_)));
        assert!(
            !err.is_unavailable(),
            "a rejected caller value must never be classified as unavailable"
        );

        // The same terminality at the composition layer: a curl adapter that
        // fails with `InvalidInput` is not retried on the secondary transport.
        let curl = CurlTransport::with_executable_and_user_agent(
            "/usr/bin/curl",
            CurlConfig::strict(),
            "eggup-curl-test/1.0",
        )
        .expect("builds");
        let fixture = FixtureTransport::new();
        fixture.route(
            "https://example.com/meta",
            FixtureResponse::body(b"via-fixture".to_vec()),
        );
        let composed = ComposedTransport::new(&curl, &fixture, CompositionPolicy::UnavailableOnly);
        let bad_limits = FetchLimits {
            max_metadata_bytes: 0,
            ..limits()
        };
        let composed_err = composed
            .fetch_metadata(
                &req("https://example.com/meta"),
                bad_limits,
                &CancelFlag::new(),
            )
            .expect_err("a terminal failure must not fall back to the fixture");
        assert!(
            matches!(composed_err, AcquisitionError::InvalidInput(_)),
            "the composed transport must surface the terminal failure, got {composed_err:?}"
        );
    }

    /// M014 (§6.1): the configured value reaches the wire as the outbound
    /// `User-Agent` header.
    ///
    /// The argv assertions prove what the adapter asks `curl` to do; this
    /// proves what the peer actually receives.
    #[cfg(not(windows))]
    #[test]
    fn user_agent_reaches_the_wire_as_the_configured_header() {
        let dir = temp_dir("curl-ua-wire");
        let record = dir.join("request-head");
        let base = serve_once_recording_head(200, b"ok".to_vec(), &record);
        let curl_exe = require_curl_executable();
        let transport = CurlTransport::with_executable_and_user_agent(
            curl_exe,
            CurlConfig::strict(),
            "eggup-curl-test/1.0",
        )
        .expect("builds");
        assert_eq!(transport.user_agent(), Some("eggup-curl-test/1.0"));
        let out = transport
            .fetch_metadata(&req(&format!("{base}/x")), limits(), &CancelFlag::new())
            .expect("the loopback fetch must succeed");
        assert_eq!(out.success().unwrap().bytes(), b"ok");
        let head = fs::read_to_string(&record).expect("the request head was recorded");
        assert!(
            head.contains("User-Agent: eggup-curl-test/1.0\r\n"),
            "the configured user agent must reach the wire; the head was {head:?}"
        );
        let _ = fs::remove_dir_all(&dir);
    }
}