eggpack-core 0.1.2

Producer-side planning, qualification, local finalization, and manifest aggregation for Eggpack
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
//! Explicit Cargo build bindings, command descriptions, and bounded process execution.

use crate::{BuildStrategy, CompatibilityFloor, ReleasePlan};
use command_group::CommandGroup;
use eggpack_contract::{DistributionContract, ExpandedAssets};
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    ffi::OsString,
    fs,
    io::{Read, Write},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    sync::{Arc, Mutex},
    thread,
    time::{Duration, Instant},
};

/// Retained-output bound the builder commands request by default.
const MAX_OUTPUT: usize = 256 * 1024;
/// Ceiling for the retained-output bound of any bounded process.
///
/// This is the single output bound the shared runner enforces. The builder
/// commands keep their tighter default (`MAX_OUTPUT`); the ceiling is wide
/// enough to admit the consumer-validator case, whose configured bound is
/// larger and is validated by its own owner.
const MAX_PROCESS_OUTPUT: usize = 8 * 1024 * 1024;
/// Wall-time bound for the sanitized `git rev-parse` verification spawn.
const GIT_TIMEOUT: Duration = Duration::from_secs(30);
/// Retained-output bound for the `git` verification spawn: a bare object name.
const GIT_OUTPUT_LIMIT: usize = 4 * 1024;
/// Floor on the post-reap drain budget.
///
/// On the timeout, cancellation, and output-limit paths the caller's deadline
/// has already passed, but the killed process group's pipes still have to
/// reach EOF, so the drain budget never collapses to zero.
const MIN_DRAIN_GRACE: Duration = Duration::from_secs(1);
/// Ceiling on the post-reap drain budget, so a generous caller deadline does
/// not turn a parked reader into a long wait.
///
/// The group is killed on the failure paths, but a descendant that outlived a
/// normally-exited child keeps its own pipe open, and a longer wait would not
/// produce EOF. The pipes are either closed already or held open by a leaked
/// descendant, so the run fails closed instead.
const MAX_DRAIN_GRACE: Duration = Duration::from_secs(2);

/// Restore POSIX exec bits on a transferred candidate before spawning it.
///
/// Artifact transfer between jobs strips exec bits; the recorded
/// size/digest cover bytes only, so restoring mode cannot change identity.
fn ensure_candidate_executable(path: &Path) -> Result<(), BuildError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let meta =
            fs::symlink_metadata(path).map_err(|_| build_err("candidate is not executable"))?;
        if meta.file_type().is_symlink() || !meta.is_file() {
            return Err(build_err("candidate is not executable"));
        }
        let mut permissions = meta.permissions();
        permissions.set_mode(permissions.mode() | 0o111);
        fs::set_permissions(path, permissions)
            .map_err(|_| build_err("candidate is not executable"))?;
        Ok(())
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        Ok(())
    }
}

/// Contract logical location for one Cargo-produced executable.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum LogicalOutputSelector {
    /// Direct artifact executable.
    Direct,
    /// Bundle entry by its contract order index.
    BundleEntry {
        /// Zero-based contract entry index.
        index: usize,
    },
    /// Archive member by its exact contract source.
    ArchiveMember {
        /// Contract archive source.
        source: String,
    },
}

/// A Cargo package and binary target explicitly bound to a logical contract slot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildBinding {
    /// Logical contract output slot.
    pub selector: LogicalOutputSelector,
    /// Cargo package name.
    pub package: String,
    /// Cargo binary target name.
    pub binary: String,
}

/// Strict producer-side BuildBindings schema version 1.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildBindingsV1 {
    /// Schema version, exactly 1.
    pub schema_version: u32,
    /// Bindings for canonical target triple.
    pub targets: BTreeMap<String, Vec<BuildBinding>>,
}

/// Failure from producer build planning or execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildError(pub(crate) String);
impl std::fmt::Display for BuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}
impl std::error::Error for BuildError {}
fn build_err(s: &str) -> BuildError {
    BuildError(s.to_owned())
}

#[derive(Clone, Copy)]
enum ExecutableAllowance {
    Builder,
    Candidate,
    Qemu,
    Git,
    Interpreter,
}

/// Cancellation source observed by the bounded runner.
///
/// The runner polls it on the same cadence as the deadline, so a cancelled
/// run ends promptly instead of at some later point.
enum Cancellation<'a> {
    /// No cancellation source; only the deadline applies.
    None,
    /// The builder's own cancellation flag.
    Build(&'a BuildCancellation),
    /// A caller-owned atomic flag.
    Flag(&'a std::sync::atomic::AtomicBool),
}

impl Cancellation<'_> {
    fn is_cancelled(&self) -> bool {
        match self {
            Cancellation::None => false,
            Cancellation::Build(cancellation) => cancellation.is_cancelled(),
            Cancellation::Flag(flag) => flag.load(std::sync::atomic::Ordering::SeqCst),
        }
    }
}

/// Explicit shell-free process command. Executable and argv are separate OS arguments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandSpec {
    /// Executable path or tool name.
    pub executable: String,
    /// Ordered arguments.
    pub args: Vec<String>,
    /// Working directory.
    pub cwd: PathBuf,
    /// Explicit environment overrides only.
    pub env: BTreeMap<String, String>,
    /// Maximum wall time.
    pub timeout: Duration,
    /// Maximum retained stdout bytes.
    pub stdout_limit: usize,
    /// Maximum retained stderr bytes.
    pub stderr_limit: usize,
    /// Optional tool version substring checked internally and never returned.
    pub expected_stdout: Option<String>,
    /// Optional exact trimmed-stdout match checked internally and never returned.
    ///
    /// Used where containment would be weaker than the invariant: the tool must
    /// emit one exact value, not merely contain it among other output.
    pub expected_stdout_exact: Option<String>,
}

/// Exact source command associated with a logical output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoundCommand {
    /// Output selector.
    pub selector: LogicalOutputSelector,
    /// Cargo package.
    pub package: String,
    /// Cargo binary target.
    pub binary: String,
    /// Process description.
    pub command: CommandSpec,
}

/// Explicit shell-free interpreter command for a bounded consumer-validator run.
///
/// The argument vector is OS-native so a validated absolute path reaches the
/// interpreter byte-exact, and the executable stays inside the finite
/// interpreter allowlist the shared runner enforces.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterpreterCommandSpec {
    /// Interpreter executable name.
    pub executable: String,
    /// Ordered OS-native arguments.
    pub args: Vec<OsString>,
    /// Working directory.
    pub cwd: PathBuf,
    /// Explicit environment overrides only.
    pub env: BTreeMap<String, String>,
    /// Maximum wall time.
    pub timeout: Duration,
    /// Maximum retained stdout bytes.
    pub stdout_limit: usize,
    /// Maximum retained stderr bytes.
    pub stderr_limit: usize,
    /// Optional tool version substring checked internally and never returned.
    pub expected_stdout: Option<String>,
}

/// Command exit classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CommandOutcome {
    /// Process exited with success.
    Success,
    /// Process exited nonzero.
    Failed(i32),
    /// Deadline exceeded; process group cleanup completed.
    TimedOut,
    /// Caller cancelled execution; process-group cleanup completed.
    Cancelled,
    /// Output exceeded a configured bound.
    OutputLimitExceeded,
}

/// Cloneable caller cancellation flag for bounded builder work.
#[derive(Debug, Clone, Default)]
pub struct BuildCancellation(std::sync::Arc<std::sync::atomic::AtomicBool>);
impl BuildCancellation {
    /// Create an active cancellation flag.
    pub fn new() -> Self {
        Self::default()
    }
    /// Request cancellation; an active child process group is killed and waited for.
    pub fn cancel(&self) {
        self.0.store(true, std::sync::atomic::Ordering::SeqCst);
    }
    pub(crate) fn is_cancelled(&self) -> bool {
        self.0.load(std::sync::atomic::Ordering::SeqCst)
    }
}

/// Bounded process evidence with no environment dump.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessEvidence {
    /// Outcome classification.
    pub outcome: CommandOutcome,
    /// Number of retained stdout bytes.
    pub stdout_bytes: usize,
    /// Number of retained stderr bytes.
    pub stderr_bytes: usize,
}

/// Candidate bytes produced for a declared logical output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CandidateArtifact {
    /// Canonical target triple.
    pub target: String,
    /// Logical output slot.
    pub selector: LogicalOutputSelector,
    /// Explicit source package.
    pub package: String,
    /// Explicit binary target.
    pub binary: String,
    /// Private candidate path.
    pub path: PathBuf,
    /// Candidate size in bytes.
    pub size: u64,
}

/// Result of a single bounded build attempt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildAttempt {
    /// Release identity from the supplied ReleasePlan.
    pub release_id: String,
    /// Source revision from the supplied ReleasePlan.
    pub source_revision: String,
    /// Canonical target triple.
    pub target: String,
    /// Selected strategy.
    pub strategy: BuildStrategy,
    /// Tool summary, without environment values.
    pub tool_summary: String,
    /// Bounded process evidence.
    pub process: ProcessEvidence,
    /// Validated candidate outputs.
    pub candidates: Vec<CandidateArtifact>,
}

impl BuildBindingsV1 {
    /// Strictly parse TOML bindings.
    pub fn from_toml(text: &str) -> Result<Self, BuildError> {
        let value: Self =
            toml::from_str(text).map_err(|_| build_err("invalid BuildBindings TOML"))?;
        value.validate_shape()?;
        Ok(value)
    }
    fn validate_shape(&self) -> Result<(), BuildError> {
        if self.schema_version != 1 || self.targets.is_empty() || self.targets.len() > 256 {
            return Err(build_err("invalid BuildBindings version or target count"));
        }
        for (target, bindings) in &self.targets {
            if target.is_empty() || bindings.is_empty() || bindings.len() > 256 {
                return Err(build_err("invalid BuildBindings target or binding count"));
            }
            let mut slots = BTreeSet::new();
            for b in bindings {
                if !slots.insert(&b.selector)
                    || !valid_identifier(&b.package)
                    || !valid_identifier(&b.binary)
                {
                    return Err(build_err("duplicate slot or invalid Cargo identifier"));
                }
                if let LogicalOutputSelector::ArchiveMember { source } = &b.selector {
                    if source.is_empty()
                        || source.len() > 255
                        || source.starts_with('/')
                        || source
                            .split('/')
                            .any(|p| p.is_empty() || p == "." || p == "..")
                    {
                        return Err(build_err("invalid archive member source"));
                    }
                }
            }
        }
        Ok(())
    }
    /// Validate that each plan target's bindings exactly cover Cargo executable contract slots.
    pub fn validate_for(
        &self,
        contract: &DistributionContract,
        plan: &ReleasePlan,
    ) -> Result<(), BuildError> {
        self.validate_shape()?;
        for target in &plan.targets {
            let bindings = self
                .targets
                .get(&target.target)
                .ok_or_else(|| build_err("missing target bindings"))?;
            let expanded = contract
                .expand(&target.target, &plan.release_id)
                .map_err(|_| build_err("contract target expansion failed"))?;
            let expected: BTreeSet<LogicalOutputSelector> = match expanded.assets {
                ExpandedAssets::Direct(_) => [LogicalOutputSelector::Direct].into_iter().collect(),
                ExpandedAssets::Bundle(b) => (0..b.entries.len())
                    .map(|index| LogicalOutputSelector::BundleEntry { index })
                    .collect(),
                ExpandedAssets::Archive(a) => a
                    .members
                    .into_iter()
                    .map(|m| LogicalOutputSelector::ArchiveMember { source: m.source })
                    .collect(),
            };
            let actual: BTreeSet<_> = bindings.iter().map(|b| b.selector.clone()).collect();
            if actual != expected {
                return Err(build_err(
                    "bindings do not exactly cover contract Cargo slots",
                ));
            }
        }
        if self
            .targets
            .keys()
            .any(|k| !plan.targets.iter().any(|t| &t.target == k))
        {
            return Err(build_err("bindings include target outside ReleasePlan"));
        }
        Ok(())
    }
}
fn valid_identifier(s: &str) -> bool {
    !s.is_empty()
        && s.len() <= 128
        && s.bytes()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))
}

/// Construct the only supported Cargo command for a planned logical output.
pub fn cargo_command(
    target: &crate::PlannedTarget,
    binding: &BuildBinding,
    cwd: &Path,
    target_dir: &Path,
    timeout: Duration,
) -> Result<CommandSpec, BuildError> {
    if !valid_identifier(&binding.package) || !valid_identifier(&binding.binary) {
        return Err(build_err("invalid Cargo identifier"));
    }
    let rustup = target.policy.toolchain.rust.as_str();
    // Built by named position rather than index: the target triple is written
    // once and never patched afterwards, so inserting a flag can no longer
    // leave the floor override pointing at an unrelated argument.
    let mut args = vec!["+".to_owned() + rustup];
    args.push(
        match target.policy.strategy {
            BuildStrategy::NativeCargo => "build",
            BuildStrategy::CargoZigbuild => "zigbuild",
        }
        .into(),
    );
    args.extend(["--release".to_owned(), "--locked".to_owned()]);
    if target.policy.strategy == BuildStrategy::CargoZigbuild {
        let triple = match target.policy.floor {
            CompatibilityFloor::Glibc { major, minor } => {
                format!("{}.{major}.{minor}", target.target)
            }
            CompatibilityFloor::Macos { .. } => {
                // The canonical floor rule owns this refusal: a macOS floor
                // cannot be satisfied by a cargo-zigbuild build.
                crate::validate_floor_applicability(
                    &target.policy.floor,
                    target.policy.strategy,
                    &target.target,
                )
                .map_err(|_| build_err("macOS floor cannot use cargo-zigbuild"))?;
                target.target.clone()
            }
            CompatibilityFloor::None => target.target.clone(),
        };
        args.extend(["--target".to_owned(), triple]);
    } else {
        args.extend(["--target".to_owned(), target.target.clone()]);
    }
    args.extend([
        "--package".into(),
        binding.package.clone(),
        "--bin".into(),
        binding.binary.clone(),
    ]);
    let mut env = BTreeMap::new();
    env.insert(
        "CARGO_TARGET_DIR".into(),
        target_dir.to_string_lossy().into_owned(),
    );
    Ok(CommandSpec {
        executable: "cargo".into(),
        args,
        cwd: cwd.to_path_buf(),
        env,
        timeout,
        stdout_limit: MAX_OUTPUT,
        stderr_limit: MAX_OUTPUT,
        expected_stdout: None,
        expected_stdout_exact: None,
    })
}

/// Run a process with a deadline and caller cancellation, cleaning up its process group.
pub fn run_bounded_cancellable(
    spec: &CommandSpec,
    cancellation: &BuildCancellation,
) -> Result<ProcessEvidence, BuildError> {
    run_bounded_inner(
        spec,
        Cancellation::Build(cancellation),
        ExecutableAllowance::Builder,
    )
}

/// Run a bounded consumer-validator interpreter process group.
///
/// The supervised interpreter is terminated as a whole process group (or job
/// object) on every failure path, so no descendant outlives the run; the
/// reader-thread joins are bounded by the run's own remaining deadline, so a
/// descendant that inherited a pipe cannot park the run past its deadline;
/// and the environment is cleared except for the shared allowlist. Captured
/// output never crosses the boundary: the caller learns only the outcome and
/// the retained byte counts.
///
/// The interpreter is restricted to the finite Python 3 interpreter names.
/// A caller-supplied cancellation flag is observed on the same poll cadence
/// as the deadline.
pub fn run_interpreter_bounded(
    spec: &InterpreterCommandSpec,
    cancelled: Option<&std::sync::atomic::AtomicBool>,
) -> Result<ProcessEvidence, BuildError> {
    let cancellation = match cancelled {
        Some(flag) => Cancellation::Flag(flag),
        None => Cancellation::None,
    };
    let run = BoundedRun {
        executable: spec.executable.as_str(),
        args: &spec.args,
        cwd: spec.cwd.as_path(),
        env: &spec.env,
        timeout: spec.timeout,
        stdout_limit: spec.stdout_limit,
        stderr_limit: spec.stderr_limit,
        expected_stdout: spec.expected_stdout.as_deref(),
        expected_stdout_exact: None,
    };
    run_bounded(&run, cancellation, ExecutableAllowance::Interpreter)
}

/// Run a bounded `git` process group that must echo exactly `expected` on stdout.
///
/// The only sanctioned `git` spawn in the workspace: bounded time and output,
/// process-group cleanup, and a cleared environment. stdout is matched
/// internally and never returned, so the caller learns only pass or fail.
pub fn run_git_bounded(expected: &str, cwd: Option<&Path>) -> Result<ProcessEvidence, BuildError> {
    run_git_resolve_bounded(
        vec![
            "rev-parse".into(),
            "--verify".into(),
            "HEAD^{commit}".into(),
        ],
        expected,
        cwd,
    )
}

/// Verify an exact local tag peels to the expected commit using bounded git.
pub fn run_git_tag_bounded(
    tag: &str,
    expected: &str,
    cwd: Option<&Path>,
) -> Result<ProcessEvidence, BuildError> {
    // The canonical exact-tag safety rule owns this refusal: it carries the
    // union of the git-ref-path concerns and the shell-metacharacter concerns.
    if crate::validate_exact_tag_safety(tag).is_err() {
        return Err(build_err("invalid exact git tag"));
    }
    run_git_resolve_bounded(
        vec![
            "rev-parse".into(),
            "--verify".into(),
            format!("refs/tags/{tag}^{{commit}}"),
        ],
        expected,
        cwd,
    )
}

fn run_git_resolve_bounded(
    args: Vec<String>,
    expected: &str,
    cwd: Option<&Path>,
) -> Result<ProcessEvidence, BuildError> {
    let cwd = match cwd {
        Some(cwd) => cwd.to_path_buf(),
        None => std::env::current_dir().map_err(|_| build_err("working directory unavailable"))?,
    };
    let spec = CommandSpec {
        executable: "git".into(),
        args,
        cwd,
        env: BTreeMap::new(),
        timeout: GIT_TIMEOUT,
        stdout_limit: GIT_OUTPUT_LIMIT,
        stderr_limit: GIT_OUTPUT_LIMIT,
        expected_stdout: None,
        expected_stdout_exact: Some(expected.to_owned()),
    };
    run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Git)
}

pub(crate) fn run_qualification_process(
    spec: &CommandSpec,
    cancellation: &BuildCancellation,
) -> Result<ProcessEvidence, BuildError> {
    run_bounded_inner(
        spec,
        Cancellation::Build(cancellation),
        ExecutableAllowance::Candidate,
    )
}

pub(crate) fn run_qemu_process(
    spec: &CommandSpec,
    cancellation: &BuildCancellation,
) -> Result<ProcessEvidence, BuildError> {
    run_bounded_inner(
        spec,
        Cancellation::Build(cancellation),
        ExecutableAllowance::Qemu,
    )
}

/// Normalized bounded-run parameters, shared by every public entry point.
///
/// The runner has one implementation; the entry points differ only in the
/// executable allowance, the argument representation, and the cancellation
/// source they carry.
struct BoundedRun<'a> {
    executable: &'a str,
    args: &'a [OsString],
    cwd: &'a Path,
    env: &'a BTreeMap<String, String>,
    timeout: Duration,
    stdout_limit: usize,
    stderr_limit: usize,
    expected_stdout: Option<&'a str>,
    expected_stdout_exact: Option<&'a str>,
}

fn run_bounded_inner(
    spec: &CommandSpec,
    cancellation: Cancellation<'_>,
    allowance: ExecutableAllowance,
) -> Result<ProcessEvidence, BuildError> {
    let args: Vec<OsString> = spec.args.iter().map(OsString::from).collect();
    let run = BoundedRun {
        executable: spec.executable.as_str(),
        args: &args,
        cwd: spec.cwd.as_path(),
        env: &spec.env,
        timeout: spec.timeout,
        stdout_limit: spec.stdout_limit,
        stderr_limit: spec.stderr_limit,
        expected_stdout: spec.expected_stdout.as_deref(),
        expected_stdout_exact: spec.expected_stdout_exact.as_deref(),
    };
    run_bounded(&run, cancellation, allowance)
}

/// Whether a failed group signal is resolved by the kernel or a safe retry.
///
/// `ESRCH` proves the group is absent. For another error, an exited leader
/// must first be reaped and the whole group signalled again; only a successful
/// retry or retry `ESRCH` establishes that termination is complete.
///
/// The initial error is not proof that the group is empty. In particular,
/// macOS `EPERM` can mean a group member is unsignalable, not absent.
/// `try_wait` reports only the supervised leader and cannot inventory the
/// remaining process group.
///
/// The retry closure is lazy and runs only after the leader has exited and
/// been reaped. It sends the same group signal again, so live descendants are
/// still targeted. Any retry error other than `ESRCH` remains a hard failure.
/// Pipe EOF is not group inventory: descendants may close inherited pipes
/// and remain alive. This helper is used by each Unix termination path.
#[cfg(unix)]
fn group_signal_failure_is_benign(
    error: &std::io::Error,
    child_exited: bool,
    retry_group_signal: impl FnOnce() -> std::io::Result<()>,
) -> bool {
    if error.raw_os_error() == Some(libc::ESRCH) {
        return true;
    }
    if !child_exited {
        return false;
    }
    match retry_group_signal() {
        Ok(()) => true,
        Err(retry_error) => retry_error.raw_os_error() == Some(libc::ESRCH),
    }
}

/// Terminate the supervised process group, tolerating only proven completion.
///
/// On macOS, signalling a group containing an unreaped zombie can fail with
/// `EPERM`; reaping the leader may make the group empty, but it may also leave
/// live descendants. Therefore, after any non-`ESRCH` failure, the runner
/// reaps an exited leader and retries the group signal. A successful retry
/// reaches remaining members; retry `ESRCH` proves the group is empty. Every
/// other retry error remains a hard failure.
///
/// The drain budget detects a descendant that keeps a pipe open, but a
/// descendant that closes its pipes is not observable through that budget.
/// Group termination, not pipe state or leader status, is the authority here.
/// Existing timeout, cancellation, and output-limit classification is unchanged.
fn terminate_process_group(
    child: &mut command_group::GroupChild,
    message: &str,
) -> Result<(), BuildError> {
    match child.kill() {
        Ok(()) => Ok(()),
        Err(error) => {
            // Reap the leader before retrying; its exit alone says nothing
            // about other members that may still be in the process group.
            let child_wait = child.try_wait();
            #[cfg(unix)]
            let child_exited = child_wait.as_ref().is_ok_and(Option::is_some);
            #[cfg(unix)]
            if group_signal_failure_is_benign(&error, child_exited, || child.kill()) {
                return Ok(());
            }
            #[cfg(not(unix))]
            let _ = child_wait;
            Err(build_err(message))
        }
    }
}

fn run_bounded(
    run: &BoundedRun<'_>,
    cancellation: Cancellation<'_>,
    allowance: ExecutableAllowance,
) -> Result<ProcessEvidence, BuildError> {
    let executable_allowed = match allowance {
        ExecutableAllowance::Builder => {
            matches!(run.executable, "cargo" | "rustc" | "zig")
        }
        ExecutableAllowance::Candidate => Path::new(run.executable).is_absolute(),
        ExecutableAllowance::Qemu => {
            matches!(run.executable, "qemu-x86_64" | "qemu-aarch64" | "qemu-arm")
        }
        ExecutableAllowance::Git => run.executable == "git",
        ExecutableAllowance::Interpreter => matches!(run.executable, "python3" | "python"),
    };
    if !executable_allowed
        || run.timeout.is_zero()
        || run.timeout > Duration::from_secs(86_400)
        || run.stdout_limit == 0
        || run.stderr_limit == 0
        || run.stdout_limit > MAX_PROCESS_OUTPUT
        || run.stderr_limit > MAX_PROCESS_OUTPUT
    {
        return Err(build_err("invalid process bounds or executable"));
    }
    // F10a: artifact transfer between jobs strips POSIX exec bits
    // (upload-artifact documents 644 for all files). A transferred
    // candidate must be executable again before its smoke spawns it;
    // bytes (and therefore recorded size/digest) are unaffected by mode.
    if matches!(allowance, ExecutableAllowance::Candidate)
        && ensure_candidate_executable(Path::new(run.executable)).is_err()
    {
        return Err(build_err("candidate is not executable"));
    }
    let mut command = Command::new(run.executable);
    command
        .args(run.args)
        .current_dir(run.cwd)
        .env_clear()
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let environment = if matches!(allowance, ExecutableAllowance::Git) {
        // git resolves its helpers and DLLs from PATH, and reads the global
        // config from HOME/USERPROFILE; `safe.directory` is frequently set
        // there, so both must survive the environment clear.
        [
            "PATH",
            "HOME",
            "USERPROFILE",
            "SystemRoot",
            "WINDIR",
            "TEMP",
            "TMP",
        ]
        .as_slice()
    } else if !matches!(allowance, ExecutableAllowance::Builder) {
        ["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP"].as_slice()
    } else {
        [
            "PATH",
            "HOME",
            "USERPROFILE",
            "SystemRoot",
            "WINDIR",
            "TEMP",
            "TMP",
            "CARGO_HOME",
            "RUSTUP_HOME",
            "LIB",
            "LIBPATH",
            "INCLUDE",
            "VCToolsInstallDir",
            "VisualStudioVersion",
            "VCINSTALLDIR",
            "WindowsSdkDir",
            "WindowsSDKVersion",
            "UniversalCRTSdkDir",
            "UCRTVersion",
        ]
        .as_slice()
    };
    for key in environment {
        if let Some(value) = std::env::var_os(key) {
            command.env(key, value);
        }
    }
    #[cfg(windows)]
    if let Some(vc_tools) = std::env::var_os("VCToolsInstallDir") {
        let preferred_linker = PathBuf::from(vc_tools)
            .join("bin")
            .join("Hostx64")
            .join("x64");
        if let Some(path) = std::env::var_os("PATH") {
            let path = std::iter::once(preferred_linker).chain(std::env::split_paths(&path));
            if let Ok(path) = std::env::join_paths(path) {
                command.env("PATH", path);
            }
        }
    }
    command.envs(run.env);
    let mut child = command
        .group_spawn()
        .map_err(|_| build_err("process spawn failed"))?;
    let stdout = child
        .inner()
        .stdout
        .take()
        .ok_or_else(|| build_err("stdout pipe unavailable"))?;
    let stderr = child
        .inner()
        .stderr
        .take()
        .ok_or_else(|| build_err("stderr pipe unavailable"))?;
    let out = Arc::new(Mutex::new((Vec::new(), false)));
    let err = Arc::new(Mutex::new((Vec::new(), false)));
    let out2 = out.clone();
    let out_limit = run.stdout_limit;
    let t1 = thread::spawn(move || drain(stdout, out2, out_limit));
    let err2 = err.clone();
    let err_limit = run.stderr_limit;
    let t2 = thread::spawn(move || drain(stderr, err2, err_limit));
    let until = Instant::now() + run.timeout;
    let (timed_out, cancelled, over_limit) = loop {
        if cancellation.is_cancelled() {
            terminate_process_group(&mut child, "cancelled process-group termination failed")?;
            child
                .wait()
                .map_err(|_| build_err("cancelled process-group wait failed"))?;
            break (false, true, false);
        }
        if Instant::now() >= until {
            terminate_process_group(&mut child, "process-group termination failed")?;
            child
                .wait()
                .map_err(|_| build_err("process-group wait failed"))?;
            break (true, false, false);
        }
        // Prompt output-limit detection: a reader that has already seen more
        // than its bound ends the run now, at the moment of excess, instead
        // of letting a chatty process run until its deadline.
        if stream_over_limit(&out) || stream_over_limit(&err) {
            terminate_process_group(&mut child, "output-limit process-group termination failed")?;
            child
                .wait()
                .map_err(|_| build_err("output-limit process-group wait failed"))?;
            break (false, false, true);
        }
        if child
            .try_wait()
            .map_err(|_| build_err("process wait failed"))?
            .is_some()
        {
            break (false, false, false);
        }
        thread::sleep(Duration::from_millis(20));
    };
    // The child — and on the kill paths its whole process group — is reaped,
    // but the deadline must still bound the whole run: a drain thread returns
    // only at pipe EOF, which needs every write end closed, so a descendant
    // that inherited stdout and outlived the child would park the join for
    // that descendant's entire lifetime. The joins therefore get a bounded
    // budget taken from what is left of the caller's own deadline, and a
    // reader still parked at it is detached and failed closed below.
    let drain_budget = until
        .saturating_duration_since(Instant::now())
        .clamp(MIN_DRAIN_GRACE, MAX_DRAIN_GRACE);
    let drain_until = Instant::now() + drain_budget;
    let drained = join_drained(t1, drain_until, "stdout reader failed")?
        & join_drained(t2, drain_until, "stderr reader failed")?;
    if !drained {
        // A reader was still parked at its budget, so the write end it waits
        // on is held by a descendant that outlived the supervised child. The
        // run fails closed below, and the group is terminated here so that
        // descendant does not outlive the run either.
        let _ = child.kill();
    }
    let status = child
        .try_wait()
        .map_err(|_| build_err("process wait failed"))?
        .ok_or_else(|| build_err("process cleanup incomplete"))?;
    let (stdout, out_over) = out
        .lock()
        .map_err(|_| build_err("stdout state unavailable"))?
        .clone();
    let (stderr, err_over) = err
        .lock()
        .map_err(|_| build_err("stderr state unavailable"))?
        .clone();
    let expected_missing = run
        .expected_stdout
        .is_some_and(|expected| !String::from_utf8_lossy(&stdout).contains(expected))
        || run
            .expected_stdout_exact
            .is_some_and(|expected| String::from_utf8_lossy(&stdout).trim() != expected);
    let outcome = if timed_out {
        CommandOutcome::TimedOut
    } else if cancelled {
        CommandOutcome::Cancelled
    } else if over_limit || !drained || out_over || err_over {
        CommandOutcome::OutputLimitExceeded
    } else if expected_missing {
        CommandOutcome::Failed(-1)
    } else if status.success() {
        CommandOutcome::Success
    } else {
        CommandOutcome::Failed(status.code().unwrap_or(-1))
    };
    Ok(ProcessEvidence {
        outcome,
        stdout_bytes: stdout.len(),
        stderr_bytes: stderr.len(),
    })
}
/// Join one drain thread, bounded by `drain_until`.
///
/// Returns `false` when the reader is still parked at the budget — the write
/// end it is waiting on belongs to a process that outlived the supervised
/// child. The handle is then dropped, which detaches the thread rather than
/// blocking; the retained bytes are then incomplete and the caller reports
/// the run as failed.
fn join_drained(
    handle: thread::JoinHandle<()>,
    drain_until: Instant,
    reader_error: &'static str,
) -> Result<bool, BuildError> {
    while !handle.is_finished() {
        if Instant::now() >= drain_until {
            return Ok(false);
        }
        thread::sleep(Duration::from_millis(10));
    }
    handle.join().map_err(|_| build_err(reader_error))?;
    Ok(true)
}

/// Whether a drained stream has already passed its retained-output bound.
///
/// The bound is checked before the bytes are retained, so the accumulator
/// never grows past its limit even transiently; this reads the same flag so
/// the runner can end the run at the moment of excess.
fn stream_over_limit(capture: &Arc<Mutex<(Vec<u8>, bool)>>) -> bool {
    capture.lock().map(|state| state.1).unwrap_or(false)
}

fn drain<R: Read>(mut reader: R, capture: Arc<Mutex<(Vec<u8>, bool)>>, limit: usize) {
    let mut buffer = [0; 8192];
    loop {
        match reader.read(&mut buffer) {
            Ok(0) | Err(_) => break,
            Ok(n) => {
                if let Ok(mut state) = capture.lock() {
                    let keep = n.min(limit.saturating_sub(state.0.len()));
                    state.0.extend_from_slice(&buffer[..keep]);
                    if keep < n {
                        state.1 = true;
                    }
                }
            }
        }
    }
}

/// Confirm configured Rust/cargo-zigbuild versions before build execution.
fn preflight(
    target: &crate::PlannedTarget,
    cwd: &Path,
    cancellation: &BuildCancellation,
) -> Result<(), BuildError> {
    let rust = run_bounded_cancellable(
        &CommandSpec {
            executable: "rustc".into(),
            args: vec![
                "+".to_owned() + &target.policy.toolchain.rust,
                "--version".into(),
            ],
            cwd: cwd.into(),
            env: BTreeMap::new(),
            timeout: Duration::from_secs(10),
            stdout_limit: 1024,
            stderr_limit: 1024,
            expected_stdout: None,
            expected_stdout_exact: None,
        },
        cancellation,
    )?;
    if rust.outcome != CommandOutcome::Success {
        return Err(build_err("configured Rust toolchain preflight failed"));
    }
    let cargo = run_bounded_cancellable(
        &CommandSpec {
            executable: "cargo".into(),
            args: vec![
                "+".to_owned() + &target.policy.toolchain.rust,
                "--version".into(),
            ],
            cwd: cwd.into(),
            env: BTreeMap::new(),
            timeout: Duration::from_secs(10),
            stdout_limit: 1024,
            stderr_limit: 1024,
            expected_stdout: None,
            expected_stdout_exact: None,
        },
        cancellation,
    )?;
    if cargo.outcome != CommandOutcome::Success {
        return Err(build_err("configured Cargo toolchain preflight failed"));
    }
    if target.policy.strategy == BuildStrategy::CargoZigbuild {
        let expected = target
            .policy
            .toolchain
            .cargo_zigbuild
            .as_deref()
            .ok_or_else(|| build_err("cargo-zigbuild version missing"))?;
        let expected_zig = target
            .policy
            .toolchain
            .zig
            .as_deref()
            .ok_or_else(|| build_err("Zig version missing"))?;
        let actual = run_bounded_cancellable(
            &CommandSpec {
                executable: "cargo".into(),
                args: vec!["zigbuild".into(), "--version".into()],
                cwd: cwd.into(),
                env: BTreeMap::new(),
                timeout: Duration::from_secs(10),
                stdout_limit: 1024,
                stderr_limit: 1024,
                // Trimmed equality, not a substring test: a pin of `0.23.3`
                // must not be satisfied by a reported `0.23.30`.
                expected_stdout: None,
                expected_stdout_exact: Some(format!("cargo-zigbuild {expected}")),
            },
            cancellation,
        )?;
        if actual.outcome != CommandOutcome::Success {
            return Err(build_err("cargo-zigbuild version mismatch"));
        }
        let zig = run_bounded_cancellable(
            &CommandSpec {
                executable: "zig".into(),
                args: vec!["version".into()],
                cwd: cwd.into(),
                env: BTreeMap::new(),
                timeout: Duration::from_secs(10),
                stdout_limit: 1024,
                stderr_limit: 1024,
                // Same rule for Zig: the reported version must equal the pin.
                expected_stdout: None,
                expected_stdout_exact: Some(expected_zig.to_owned()),
            },
            cancellation,
        )?;
        if zig.outcome != CommandOutcome::Success {
            return Err(build_err("Zig version mismatch"));
        }
    }
    Ok(())
}

/// Execute one target using explicit bindings, private target storage, and exact output discovery.
pub fn execute_target(
    plan: &ReleasePlan,
    target: &crate::PlannedTarget,
    bindings: &[BuildBinding],
    repository_root: &Path,
    work_root: &Path,
    invocation: &str,
) -> Result<BuildAttempt, BuildError> {
    execute_target_cancellable(
        plan,
        target,
        bindings,
        repository_root,
        work_root,
        invocation,
        &BuildCancellation::new(),
    )
}

/// Execute a target with explicit caller cancellation and bounded cleanup.
pub fn execute_target_cancellable(
    plan: &ReleasePlan,
    target: &crate::PlannedTarget,
    bindings: &[BuildBinding],
    repository_root: &Path,
    work_root: &Path,
    invocation: &str,
    cancellation: &BuildCancellation,
) -> Result<BuildAttempt, BuildError> {
    if !plan.targets.iter().any(|planned| planned == target)
        || plan.schema_version != 1
        || plan.release_id.is_empty()
        || plan.source_revision.is_empty()
    {
        return Err(build_err(
            "target is not part of the supplied ReleasePlan identity",
        ));
    }
    if !repository_root.is_absolute() {
        return Err(build_err("repository root must be absolute"));
    }
    let repository =
        fs::canonicalize(repository_root).map_err(|_| build_err("repository root unavailable"))?;
    preflight(target, &repository, cancellation)?;
    let target_dir = private_target_dir(work_root, invocation, &target.target)?;
    fs::create_dir(&target_dir)
        .map_err(|_| build_err("private Cargo target directory creation failed"))?;
    let mut candidates = Vec::new();
    let mut last = ProcessEvidence {
        outcome: CommandOutcome::Success,
        stdout_bytes: 0,
        stderr_bytes: 0,
    };
    for binding in bindings {
        let spec = cargo_command(
            target,
            binding,
            &repository,
            &target_dir,
            Duration::from_secs(1800),
        )?;
        let evidence = run_bounded_cancellable(&spec, cancellation)?;
        if evidence.outcome != CommandOutcome::Success {
            return Ok(BuildAttempt {
                release_id: plan.release_id.clone(),
                source_revision: plan.source_revision.clone(),
                target: target.target.clone(),
                strategy: target.policy.strategy,
                tool_summary: format!("rust {}", target.policy.toolchain.rust),
                process: evidence,
                candidates: Vec::new(),
            });
        }
        let (path, size) = discover_candidate(&target_dir, &target.target, &binding.binary)?;
        candidates.push(CandidateArtifact {
            target: target.target.clone(),
            selector: binding.selector.clone(),
            package: binding.package.clone(),
            binary: binding.binary.clone(),
            path,
            size,
        });
        last = evidence;
    }
    if candidates.is_empty() {
        // A build that produced no candidate has produced nothing to finalize.
        // Reporting it as a success attempt with an empty candidate list would
        // leave the empty list as the only signal, so it fails closed here.
        return Err(build_err("build produced no candidates"));
    }
    Ok(BuildAttempt {
        release_id: plan.release_id.clone(),
        source_revision: plan.source_revision.clone(),
        target: target.target.clone(),
        strategy: target.policy.strategy,
        tool_summary: format!(
            "rust {}{}{}",
            target.policy.toolchain.rust,
            target
                .policy
                .toolchain
                .cargo_zigbuild
                .as_ref()
                .map(|v| format!(" cargo-zigbuild {v}"))
                .unwrap_or_default(),
            target
                .policy
                .toolchain
                .zig
                .as_ref()
                .map(|v| format!(" zig {v}"))
                .unwrap_or_default()
        ),
        process: last,
        candidates,
    })
}

/// Establish a caller-owned absolute work root and a unique target directory.
pub fn private_target_dir(
    work_root: &Path,
    invocation: &str,
    target: &str,
) -> Result<PathBuf, BuildError> {
    if !work_root.is_absolute()
        || invocation.is_empty()
        || invocation.len() > 128
        || target.is_empty()
    {
        return Err(build_err("invalid private work root identity"));
    }
    if fs::symlink_metadata(work_root)
        .map_err(|_| build_err("work root must pre-exist"))?
        .file_type()
        .is_symlink()
    {
        return Err(build_err("symlink work root rejected"));
    }
    let canonical =
        fs::canonicalize(work_root).map_err(|_| build_err("work root canonicalization failed"))?;
    let name = format!("{}-{}", safe_component(invocation), safe_component(target));
    let path = canonical.join(name);
    match fs::create_dir(&path) {
        Ok(()) => (),
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            return Err(build_err("private build directory already exists"))
        }
        Err(_) => return Err(build_err("private build directory creation failed")),
    }
    let check = fs::canonicalize(&path)
        .map_err(|_| build_err("private build path canonicalization failed"))?;
    if !check.starts_with(&canonical) {
        return Err(build_err("private build path escapes work root"));
    }
    let mut metadata = fs::File::create(path.join(".eggpack-owner"))
        .map_err(|_| build_err("ownership marker creation failed"))?;
    metadata
        .write_all(format!("1\n{}\n{}\n", invocation, target).as_bytes())
        .map_err(|_| build_err("ownership marker write failed"))?;
    Ok(path.join("target"))
}
fn safe_component(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Resolve and validate exactly the Cargo release output path.
pub fn discover_candidate(
    target_dir: &Path,
    target: &str,
    binary: &str,
) -> Result<(PathBuf, u64), BuildError> {
    if !valid_identifier(binary) {
        return Err(build_err("invalid binary name"));
    }
    let mut path = target_dir.join(target).join("release").join(binary);
    if target.contains("-windows-") {
        // Cargo appends the executable suffix to the full binary name; a binary
        // name containing `.` keeps it (`tool.cli` -> `tool.cli.exe`).
        path.set_file_name(format!("{binary}.exe"));
    }
    let metadata =
        fs::symlink_metadata(&path).map_err(|_| build_err("expected candidate missing"))?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_file() || metadata.len() == 0 {
        return Err(build_err("candidate is not a non-empty regular file"));
    }
    let canonical_root =
        fs::canonicalize(target_dir).map_err(|_| build_err("target directory unavailable"))?;
    let canonical_file =
        fs::canonicalize(&path).map_err(|_| build_err("candidate canonicalization failed"))?;
    if !canonical_file.starts_with(&canonical_root) {
        return Err(build_err("candidate escapes private target directory"));
    }
    let release_dir = target_dir.join(target).join("release");
    let target_meta = fs::symlink_metadata(target_dir.join(target))
        .map_err(|_| build_err("target output directory missing"))?;
    let release_meta = fs::symlink_metadata(&release_dir)
        .map_err(|_| build_err("release output directory missing"))?;
    if target_meta.file_type().is_symlink()
        || !target_meta.is_dir()
        || release_meta.file_type().is_symlink()
        || !release_meta.is_dir()
    {
        return Err(build_err(
            "candidate parent directory is not private regular directory",
        ));
    }
    Ok((path, metadata.len()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{HostArch, HostOs, Qualification, SupportTier, TargetPolicy, ToolchainRequirement};
    use std::sync::Mutex;

    static CARGO_FIXTURE_LOCK: Mutex<()> = Mutex::new(());

    fn target() -> crate::PlannedTarget {
        crate::PlannedTarget {
            target: "x86_64-unknown-linux-gnu".into(),
            policy: TargetPolicy {
                target: "x86_64-unknown-linux-gnu".into(),
                strategy: BuildStrategy::NativeCargo,
                host_os: HostOs::Linux,
                host_arch: HostArch::X86_64,
                qualification_host: None,
                toolchain: ToolchainRequirement {
                    rust: "1.89.0".into(),
                    cargo_zigbuild: None,
                    zig: None,
                },
                floor: CompatibilityFloor::None,
                qualification: Qualification::Native,
                support: SupportTier::Required,
            },
            artifact_form: crate::PlannedAssetForm::Direct,
            floor_status: crate::FloorVerificationStatus::NotDeclared,
        }
    }
    #[test]
    fn command_is_explicit_and_never_shell_based() {
        let b = BuildBinding {
            selector: LogicalOutputSelector::Direct,
            package: "demo".into(),
            binary: "demo-bin".into(),
        };
        let c = cargo_command(
            &target(),
            &b,
            Path::new("/repo"),
            Path::new("/private/target"),
            Duration::from_secs(10),
        )
        .unwrap();
        assert_eq!(c.executable, "cargo");
        assert_eq!(
            c.args,
            [
                "+1.89.0",
                "build",
                "--release",
                "--locked",
                "--target",
                "x86_64-unknown-linux-gnu",
                "--package",
                "demo",
                "--bin",
                "demo-bin"
            ]
        );
        assert_eq!(c.env["CARGO_TARGET_DIR"], "/private/target");
        let mut arbitrary = c;
        arbitrary.executable = "sh".into();
        assert!(
            run_bounded_inner(&arbitrary, Cancellation::None, ExecutableAllowance::Builder)
                .is_err()
        );
    }
    #[test]
    fn zigbuild_floor_uses_only_gnu_target_syntax() {
        let mut t = target();
        t.policy.strategy = BuildStrategy::CargoZigbuild;
        t.policy.toolchain.cargo_zigbuild = Some("0.19.8".into());
        t.policy.toolchain.zig = Some("0.14.1".into());
        t.policy.floor = CompatibilityFloor::Glibc {
            major: 2,
            minor: 17,
        };
        let binding = BuildBinding {
            selector: LogicalOutputSelector::Direct,
            package: "demo".into(),
            binary: "demo".into(),
        };
        let command = cargo_command(
            &t,
            &binding,
            Path::new("/repo"),
            Path::new("/target"),
            Duration::from_secs(10),
        )
        .unwrap();
        assert_eq!(command.args[1], "zigbuild");
        assert_eq!(command.args[5], "x86_64-unknown-linux-gnu.2.17");
        t.policy.floor = CompatibilityFloor::Macos {
            major: 13,
            minor: 0,
        };
        assert!(cargo_command(
            &t,
            &binding,
            Path::new("/repo"),
            Path::new("/target"),
            Duration::from_secs(10)
        )
        .is_err());
    }
    /// The compatibility-floor build behaviour is unchanged by the floor
    /// verification status: the cargo-zigbuild triple rewrite is pinned
    /// byte-for-byte, and the macOS-under-zigbuild refusal keeps its exact
    /// message. Recording a floor status must never move the refusal from
    /// build-command time to declaration time.
    #[test]
    fn the_cargo_zigbuild_floor_rewrite_and_macos_refusal_are_unchanged() {
        let mut t = target();
        t.policy.strategy = BuildStrategy::CargoZigbuild;
        t.policy.toolchain.cargo_zigbuild = Some("0.23.3".into());
        t.policy.toolchain.zig = Some("0.14.1".into());
        t.policy.floor = CompatibilityFloor::Glibc {
            major: 2,
            minor: 17,
        };
        let binding = BuildBinding {
            selector: LogicalOutputSelector::Direct,
            package: "demo".into(),
            binary: "demo".into(),
        };
        let command = cargo_command(
            &t,
            &binding,
            Path::new("/repo"),
            Path::new("/target"),
            Duration::from_secs(10),
        )
        .unwrap();
        assert_eq!(
            command.args,
            vec![
                "+1.89.0",
                "zigbuild",
                "--release",
                "--locked",
                "--target",
                "x86_64-unknown-linux-gnu.2.17",
                "--package",
                "demo",
                "--bin",
                "demo",
            ]
        );
        // A macOS floor under cargo-zigbuild is refused at build-command time
        // with the unchanged message.
        t.policy.floor = CompatibilityFloor::Macos {
            major: 13,
            minor: 0,
        };
        let refusal = cargo_command(
            &t,
            &binding,
            Path::new("/repo"),
            Path::new("/target"),
            Duration::from_secs(10),
        )
        .unwrap_err();
        assert_eq!(refusal.to_string(), "macOS floor cannot use cargo-zigbuild");
        // The refusal is not moved to declaration time: the policy still
        // resolves, because only the canonical floor rule refuses it.
        assert_eq!(
            t.policy.floor,
            CompatibilityFloor::Macos {
                major: 13,
                minor: 0
            }
        );
    }
    #[test]
    fn binding_document_rejects_duplicate_and_unknown_fields() {
        let good = r#"schema_version = 1
[targets]
"x86_64-unknown-linux-gnu" = [{ selector = { kind = "direct" }, package = "demo", binary = "demo" }]
"#;
        assert!(BuildBindingsV1::from_toml(good).is_ok());
        assert!(BuildBindingsV1::from_toml(
            &good.replace("schema_version = 1", "schema_version = 2")
        )
        .is_err());
        assert!(
            BuildBindingsV1::from_toml(&good.replace("package =", "extra = 1, package =")).is_err()
        );
    }
    #[test]
    fn bindings_must_match_direct_contract_slots_exactly() {
        let contract = DistributionContract::parse_toml_str(include_str!(
            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
        ))
        .unwrap();
        let plan = crate::PackConfig {
            schema_version: 1,
            targets: vec![target().policy],
        }
        .resolve(&contract, "1.0", "abc", &["linux-x64".into()])
        .unwrap();
        let bindings = BuildBindingsV1 {
            schema_version: 1,
            targets: [(
                "x86_64-unknown-linux-gnu".into(),
                vec![BuildBinding {
                    selector: LogicalOutputSelector::Direct,
                    package: "demo".into(),
                    binary: "demo".into(),
                }],
            )]
            .into_iter()
            .collect(),
        };
        assert!(bindings.validate_for(&contract, &plan).is_ok());
        let mut invalid = bindings;
        invalid.targets.get_mut("x86_64-unknown-linux-gnu").unwrap()[0].selector =
            LogicalOutputSelector::BundleEntry { index: 0 };
        assert!(invalid.validate_for(&contract, &plan).is_err());
    }
    #[test]
    fn candidate_lookup_is_exact_regular_and_nonempty() {
        let root = crate::test_temp_dir("builder-test");
        let out = root.join("x86_64-unknown-linux-gnu/release");
        fs::create_dir_all(&out).unwrap();
        fs::write(out.join("demo"), b"binary").unwrap();
        assert_eq!(
            discover_candidate(&root, "x86_64-unknown-linux-gnu", "demo")
                .unwrap()
                .1,
            6
        );
        fs::write(out.join("empty"), b"").unwrap();
        assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "empty").is_err());
        assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "other").is_err());
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn windows_candidate_appends_exe_and_preserves_dotted_names() {
        let root = crate::test_temp_dir("builder-exe-test");
        let target = "x86_64-pc-windows-msvc";
        let out = root.join(target).join("release");
        fs::create_dir_all(&out).unwrap();
        fs::write(out.join("demo.exe"), b"binary").unwrap();
        assert_eq!(discover_candidate(&root, target, "demo").unwrap().1, 6);
        fs::write(out.join("tool.cli.exe"), b"dotted").unwrap();
        // Cargo appends the suffix: a dotted name keeps its own extension
        // rather than having it replaced.
        let (path, size) = discover_candidate(&root, target, "tool.cli").unwrap();
        assert!(path.ends_with("tool.cli.exe"), "{path:?}");
        assert_eq!(size, 6);
        fs::remove_dir_all(root).unwrap();

        // A replaced-extension lookup must not resolve: with only `tool.exe`
        // present, `tool.cli` is a miss rather than a truncation match.
        let root = crate::test_temp_dir("builder-exe-test-2");
        let out = root.join(target).join("release");
        fs::create_dir_all(&out).unwrap();
        fs::write(out.join("tool.exe"), b"truncated").unwrap();
        assert!(discover_candidate(&root, target, "tool.cli").is_err());
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn windows_candidate_matching_is_not_a_substring_heuristic() {
        let root = crate::test_temp_dir("builder-triple-test");
        let target = "x86_64-unknown-notwindowsish";
        let out = root.join(target).join("release");
        fs::create_dir_all(&out).unwrap();
        fs::write(out.join("demo"), b"binary").unwrap();
        assert!(discover_candidate(&root, target, "demo").is_ok());
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn git_verification_is_bounded_and_exact() {
        let root = crate::test_temp_dir("builder-git-test");
        let git = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(&root)
                .env("GIT_AUTHOR_NAME", "t")
                .env("GIT_AUTHOR_EMAIL", "t@example.invalid")
                .env("GIT_COMMITTER_NAME", "t")
                .env("GIT_COMMITTER_EMAIL", "t@example.invalid")
                .output()
        };
        if !git(&["init", "--quiet"]).is_ok_and(|o| o.status.success()) {
            fs::remove_dir_all(root).unwrap();
            return; // git unavailable: nothing to verify
        }
        fs::write(root.join("f"), b"x").unwrap();
        if !git(&["add", "f"]).is_ok_and(|o| o.status.success())
            || !git(&["commit", "--quiet", "-m", "c"]).is_ok_and(|o| o.status.success())
        {
            fs::remove_dir_all(root).unwrap();
            return;
        }
        let head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
            .unwrap()
            .trim()
            .to_owned();
        assert_eq!(head.len(), 40);
        assert!(git(&["tag", "v1.2.3"]).is_ok_and(|o| o.status.success()));
        assert_eq!(
            run_git_tag_bounded("v1.2.3", &head, Some(&root))
                .unwrap()
                .outcome,
            CommandOutcome::Success
        );
        assert_ne!(
            run_git_tag_bounded("v1.2.4", &head, Some(&root))
                .unwrap()
                .outcome,
            CommandOutcome::Success
        );
        assert!(run_git_tag_bounded("v../evil", &head, Some(&root)).is_err());
        assert!(run_git_tag_bounded("v1.2.3^{}", &head, Some(&root)).is_err());
        fs::write(root.join("f"), b"second commit").unwrap();
        assert!(git(&["add", "f"]).is_ok_and(|o| o.status.success()));
        assert!(git(&["commit", "--quiet", "-m", "second"]).is_ok_and(|o| o.status.success()));
        assert!(git(&["tag", "v1.2.9"]).is_ok_and(|o| o.status.success()));
        let second_head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
            .unwrap()
            .trim()
            .to_owned();
        assert_ne!(
            run_git_tag_bounded("v1.2.9", &head, Some(&root))
                .unwrap()
                .outcome,
            CommandOutcome::Success,
            "another tag pointing at a different commit must fail"
        );
        assert_eq!(
            run_git_bounded(&second_head, Some(&root)).unwrap().outcome,
            CommandOutcome::Success
        );
        // The match is exact, not containment: surrounding noise fails closed.
        let noisy = format!(" {second_head} ");
        assert_ne!(
            run_git_bounded(&noisy, Some(&root)).unwrap().outcome,
            CommandOutcome::Success
        );
        assert_ne!(
            run_git_bounded(&second_head[..39], Some(&root))
                .unwrap()
                .outcome,
            CommandOutcome::Success
        );
        assert_ne!(
            run_git_bounded(&"0".repeat(40), Some(&root))
                .unwrap()
                .outcome,
            CommandOutcome::Success
        );
        // A non-repository working directory cannot resolve HEAD.
        let outside = crate::test_temp_dir("builder-git-outside");
        assert_ne!(
            run_git_bounded(&second_head, Some(&outside))
                .unwrap()
                .outcome,
            CommandOutcome::Success
        );
        fs::remove_dir_all(outside).unwrap();
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn private_workspace_rejects_relative_and_reused_invocations() {
        let root = crate::test_temp_dir("private-test");
        assert!(private_target_dir(Path::new("relative"), "run", "target").is_err());
        assert!(private_target_dir(&root, "run", "target").is_ok());
        assert!(private_target_dir(&root, "run", "target").is_err());
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn process_output_is_bounded_and_exit_status_explicit() {
        let spec = CommandSpec {
            executable: "rustc".into(),
            args: vec!["--version".into()],
            cwd: std::env::current_dir().unwrap(),
            env: BTreeMap::new(),
            timeout: Duration::from_secs(5),
            stdout_limit: 1024,
            stderr_limit: 1024,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        let result =
            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder).unwrap();
        assert_eq!(result.outcome, CommandOutcome::Success);
        assert!(result.stdout_bytes <= 1024);
    }
    /// A process group whose only member has already exited and been reaped
    /// holds no process, so terminating it is reported as "no such process
    /// group". That is not a failed termination — there is nothing left to
    /// terminate — and treating it as one turns a completed run into an
    /// error.
    ///
    /// Linux signals a zombie process group successfully while macOS refuses
    /// to signal a group that holds one and reports `EPERM` for the whole
    /// group, so the same run terminated cleanly on one platform and failed
    /// on the other, reporting an output-bound violation as a launch
    /// failure.
    #[cfg(unix)]
    #[test]
    fn terminating_an_already_exited_process_group_is_not_a_failure() {
        let mut command = Command::new("sh");
        command.args(["-c", "exit 0"]);
        let mut child = command.group_spawn().unwrap();
        // Reap the child: the group then holds no process at all.
        child.wait().unwrap();
        // The dependency reports the empty group as an error.
        assert!(child.kill().is_err());
        // The runner treats that as "nothing left to terminate".
        assert!(terminate_process_group(&mut child, "test termination").is_ok());
    }
    #[cfg(unix)]
    #[test]
    fn a_failed_group_signal_is_benign_only_after_recheck_proves_termination() {
        let no_such_group = std::io::Error::from_raw_os_error(libc::ESRCH);
        let not_permitted = std::io::Error::from_raw_os_error(libc::EPERM);

        assert!(group_signal_failure_is_benign(
            &no_such_group,
            false,
            || { panic!("ESRCH must not trigger a retry") }
        ));
        assert!(!group_signal_failure_is_benign(
            &not_permitted,
            false,
            || { panic!("a live or unverified child must not trigger a retry") }
        ));
        assert!(group_signal_failure_is_benign(&not_permitted, true, || Ok(
            ()
        )));
        assert!(group_signal_failure_is_benign(&not_permitted, true, || {
            Err(std::io::Error::from_raw_os_error(libc::ESRCH))
        }));
        assert!(!group_signal_failure_is_benign(
            &not_permitted,
            true,
            || { Err(std::io::Error::from_raw_os_error(libc::EPERM)) }
        ));
    }
    #[cfg(unix)]
    #[test]
    fn terminating_an_exited_leader_still_signals_a_live_group_descendant() {
        let root = crate::test_temp_dir("group-descendant-termination");
        let started = root.join("descendant-started");
        let release = root.join("descendant-release");
        let survived = root.join("descendant-survived");
        let started_arg = started.to_string_lossy().into_owned();
        let release_arg = release.to_string_lossy().into_owned();
        let survived_arg = survived.to_string_lossy().into_owned();
        let mut command = Command::new("sh");
        command.args([
            "-c",
            "sh -c 'printf started > \"$1\"; while [ ! -e \"$2\" ]; do sleep 0.01; done; printf survived > \"$3\"' sh \"$1\" \"$2\" \"$3\" >/dev/null 2>&1 & while [ ! -e \"$1\" ]; do sleep 0.01; done; exit 0",
            "group-fixture",
            started_arg.as_str(),
            release_arg.as_str(),
            survived_arg.as_str(),
        ]);
        let mut child = command.group_spawn().unwrap();

        let leader_deadline = Instant::now() + Duration::from_secs(3);
        let leader_status = loop {
            match child.try_wait() {
                Ok(Some(status)) => break Some(status),
                Ok(None) if Instant::now() < leader_deadline => {
                    thread::sleep(Duration::from_millis(10));
                }
                _ => break None,
            }
        };
        let descendant_deadline = Instant::now() + Duration::from_secs(1);
        while !started.is_file() && Instant::now() < descendant_deadline {
            thread::sleep(Duration::from_millis(10));
        }

        let terminated = terminate_process_group(&mut child, "test termination").is_ok();
        if !terminated {
            let _ = child.kill();
        }
        // If a live descendant was incorrectly left behind, releasing it makes
        // it write a marker rather than relying on an arbitrary sleep duration.
        fs::write(&release, "release").unwrap();
        let survivor_deadline = Instant::now() + Duration::from_secs(1);
        while !survived.is_file() && Instant::now() < survivor_deadline {
            thread::sleep(Duration::from_millis(10));
        }
        let descendant_started = started.is_file();
        let descendant_survived = survived.exists();
        let leader_succeeded = leader_status.is_some_and(|status| status.success());
        fs::remove_dir_all(root).unwrap();

        assert!(leader_succeeded, "the group leader must exit normally");
        assert!(descendant_started, "the live descendant fixture must start");
        assert!(terminated, "the process group must be terminated");
        assert!(
            !descendant_survived,
            "the descendant must not outlive group termination"
        );
    }
    #[test]
    fn nonzero_tool_exit_is_not_success() {
        let spec = CommandSpec {
            executable: "rustc".into(),
            args: vec!["--eggpack-invalid-option".into()],
            cwd: std::env::current_dir().unwrap(),
            env: BTreeMap::new(),
            timeout: Duration::from_secs(5),
            stdout_limit: 1024,
            stderr_limit: 1024,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        assert!(matches!(
            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
                .unwrap()
                .outcome,
            CommandOutcome::Failed(_)
        ));
    }
    #[test]
    fn stdout_overflow_is_bounded_and_not_success() {
        let root = crate::test_temp_dir("output-bound");
        let source = root.join("many-errors.rs");
        let body = (0..200)
            .map(|i| format!("fn f{i}() {{ absent_symbol_{i}(); }}\n"))
            .collect::<String>();
        fs::write(&source, body).unwrap();
        let spec = CommandSpec {
            executable: "rustc".into(),
            args: vec![
                "--crate-type".into(),
                "lib".into(),
                source.to_string_lossy().into_owned(),
            ],
            cwd: root.clone(),
            env: BTreeMap::new(),
            timeout: Duration::from_secs(10),
            stdout_limit: 128,
            stderr_limit: 128,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        assert_eq!(
            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
                .unwrap()
                .outcome,
            CommandOutcome::OutputLimitExceeded
        );
        fs::remove_dir_all(root).unwrap();
    }
    #[test]
    fn timeout_kills_and_waits_for_the_process_group() {
        let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
        let root = crate::test_temp_dir("timeout");
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("Cargo.toml"), "[package]\nname='timeout-fixture'\nversion='0.1.0'\nedition='2021'\nbuild='build.rs'\n").unwrap();
        fs::write(
            root.join("Cargo.lock"),
            "version = 3\n\n[[package]]\nname = \"timeout-fixture\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        fs::write(
            root.join("build.rs"),
            "fn main() { println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_STARTED\"); println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_SLEEP\"); if let Some(path) = std::env::var_os(\"EGGPACK_BUILD_STARTED\") { std::fs::write(path, b\"started\").unwrap(); } if std::env::var_os(\"EGGPACK_BUILD_SLEEP\").is_some() { std::thread::sleep(std::time::Duration::from_secs(30)); } }\n",
        )
        .unwrap();
        fs::write(root.join("src/lib.rs"), "pub fn fixture() {}\n").unwrap();
        let mut spec = CommandSpec {
            executable: "cargo".into(),
            args: vec![
                "build".into(),
                "--locked".into(),
                "--offline".into(),
                "--manifest-path".into(),
                root.join("Cargo.toml").to_string_lossy().into_owned(),
            ],
            cwd: root.clone(),
            env: BTreeMap::new(),
            timeout: Duration::from_secs(60),
            stdout_limit: 4096,
            stderr_limit: 4096,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        for iteration in 0..3 {
            spec.timeout = Duration::from_secs(60);
            spec.env.remove("EGGPACK_BUILD_SLEEP");
            let timeout_target = root.join(format!("cargo-target-timeout-{iteration}"));
            spec.env.insert(
                "CARGO_TARGET_DIR".into(),
                timeout_target.to_string_lossy().into_owned(),
            );
            let warm_timeout = root.join(format!("warm-timeout-{iteration}"));
            spec.env.insert(
                "EGGPACK_BUILD_STARTED".into(),
                warm_timeout.to_string_lossy().into_owned(),
            );
            assert_eq!(
                run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
                    .unwrap()
                    .outcome,
                CommandOutcome::Success
            );
            assert!(warm_timeout.is_file(), "timeout fixture warm-up failed");
            spec.timeout = Duration::from_secs(5);
            spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
            let timeout_started = root.join(format!("timeout-started-{iteration}"));
            spec.env.insert(
                "EGGPACK_BUILD_STARTED".into(),
                timeout_started.to_string_lossy().into_owned(),
            );
            assert_eq!(
                run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
                    .unwrap()
                    .outcome,
                CommandOutcome::TimedOut
            );
            assert!(timeout_started.is_file(), "build script never started");

            spec.timeout = Duration::from_secs(60);
            spec.env.remove("EGGPACK_BUILD_SLEEP");
            let cancel_target = root.join(format!("cargo-target-cancel-{iteration}"));
            spec.env.insert(
                "CARGO_TARGET_DIR".into(),
                cancel_target.to_string_lossy().into_owned(),
            );
            let warm_cancel = root.join(format!("warm-cancel-{iteration}"));
            spec.env.insert(
                "EGGPACK_BUILD_STARTED".into(),
                warm_cancel.to_string_lossy().into_owned(),
            );
            assert_eq!(
                run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
                    .unwrap()
                    .outcome,
                CommandOutcome::Success
            );
            assert!(warm_cancel.is_file(), "cancellation fixture warm-up failed");

            spec.timeout = Duration::from_secs(180);
            spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
            let cancellation = BuildCancellation::new();
            let request = cancellation.clone();
            let cancellation_started = root.join(format!("cancellation-started-{iteration}"));
            spec.env.insert(
                "EGGPACK_BUILD_STARTED".into(),
                cancellation_started.to_string_lossy().into_owned(),
            );
            let cancellation_started_by_thread = cancellation_started.clone();
            let canceller = thread::spawn(move || {
                let deadline = Instant::now() + Duration::from_secs(15);
                while !cancellation_started_by_thread.is_file() && Instant::now() < deadline {
                    thread::sleep(Duration::from_millis(10));
                }
                assert!(
                    cancellation_started_by_thread.is_file(),
                    "build script did not start before cancellation deadline"
                );
                request.cancel();
            });
            assert_eq!(
                run_bounded_cancellable(&spec, &cancellation)
                    .unwrap()
                    .outcome,
                CommandOutcome::Cancelled
            );
            canceller.join().unwrap();
            assert!(cancellation_started.is_file());
        }
        fs::remove_dir_all(root).unwrap();
    }
    // Not standalone coverage: this is a child fixture re-executed by
    // `parked_drain_reader_cannot_outlive_the_deadline` in this test binary.
    // It returns immediately after spawning a descendant that inherits the
    // stdout write end, so no EOF ever arrives on that pipe.
    #[test]
    #[ignore]
    // Detaching the grandchild is the behaviour under test: this fixture must
    // return while the descendant is still running, so waiting on it is exactly
    // what cannot happen here. The test harness exits immediately afterwards.
    #[allow(clippy::zombie_processes)]
    fn builder_child_leaves_parked_descendant() {
        std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "builder::tests::builder_child_holds_stdout",
                "--ignored",
                "--nocapture",
            ])
            .spawn()
            .unwrap();
    }

    /// Child fixture: outlives its parent, holding the inherited pipe open.
    #[test]
    #[ignore]
    fn builder_child_holds_stdout() {
        std::thread::sleep(Duration::from_secs(20));
    }

    /// A child that exits normally while a descendant still holds its stdout
    /// write end must not park the runner. Pipe EOF never arrives, so the
    /// drain join has to be bounded and the run has to fail closed.
    #[test]
    fn parked_drain_reader_cannot_outlive_the_deadline() {
        let spec = CommandSpec {
            executable: std::env::current_exe()
                .unwrap()
                .to_string_lossy()
                .into_owned(),
            args: vec![
                "--exact".into(),
                "builder::tests::builder_child_leaves_parked_descendant".into(),
                "--ignored".into(),
                "--nocapture".into(),
            ],
            cwd: std::env::current_dir().unwrap(),
            env: BTreeMap::new(),
            timeout: Duration::from_secs(10),
            stdout_limit: 4096,
            stderr_limit: 4096,
            expected_stdout: None,
            expected_stdout_exact: None,
        };
        let started = Instant::now();
        let evidence =
            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Candidate).unwrap();
        assert_eq!(
            evidence.outcome,
            CommandOutcome::OutputLimitExceeded,
            "a parked drain reader must fail the run closed, not report success"
        );
        assert!(
            started.elapsed() < Duration::from_secs(15),
            "bounded run took {:?}; the parked reader defeated the deadline",
            started.elapsed()
        );
    }
    #[test]
    fn real_local_cargo_fixture_builds_a_direct_candidate() {
        let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
        let base = crate::test_temp_dir("cargo-smoke");
        let repo = base.join("repo");
        let work = base.join("work");
        fs::create_dir_all(repo.join("src")).unwrap();
        fs::create_dir_all(&work).unwrap();
        fs::write(
            repo.join("Cargo.toml"),
            "[package]\nname='smoke-fixture'\nversion='0.1.0'\nedition='2021'\n",
        )
        .unwrap();
        fs::write(
            repo.join("Cargo.lock"),
            "version = 3\n\n[[package]]\nname = \"smoke-fixture\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        fs::write(repo.join("src/main.rs"), "fn main() {}\n").unwrap();
        let mut t = target();
        t.policy.toolchain.rust = "stable".into();
        let (triple, os, arch) = match (std::env::consts::OS, std::env::consts::ARCH) {
            ("windows", "x86_64") => ("x86_64-pc-windows-msvc", HostOs::Windows, HostArch::X86_64),
            ("macos", "x86_64") => ("x86_64-apple-darwin", HostOs::Macos, HostArch::X86_64),
            ("macos", "aarch64") => ("aarch64-apple-darwin", HostOs::Macos, HostArch::Aarch64),
            ("linux", "x86_64") => ("x86_64-unknown-linux-gnu", HostOs::Linux, HostArch::X86_64),
            ("linux", "aarch64") => (
                "aarch64-unknown-linux-gnu",
                HostOs::Linux,
                HostArch::Aarch64,
            ),
            other => panic!("unsupported hosted Cargo smoke platform: {other:?}"),
        };
        t.target = triple.into();
        t.policy.target = triple.into();
        t.policy.host_os = os;
        t.policy.host_arch = arch;
        let binding = BuildBinding {
            selector: LogicalOutputSelector::Direct,
            package: "smoke-fixture".into(),
            binary: "smoke-fixture".into(),
        };
        let plan = ReleasePlan {
            schema_version: 1,
            release_id: "test".into(),
            source_revision: "abc".into(),
            targets: vec![t.clone()],
        };
        let attempt = execute_target(&plan, &t, &[binding], &repo, &work, "smoke").unwrap();
        assert_eq!(attempt.process.outcome, CommandOutcome::Success);
        assert_eq!(attempt.release_id, plan.release_id);
        assert_eq!(attempt.source_revision, plan.source_revision);
        assert_eq!(attempt.candidates.len(), 1);
        assert!(attempt.candidates[0].size > 0);
        fs::remove_dir_all(base).unwrap();
    }
}